import { useState, useEffect } from "react";
import api from "../../../api/client";
import {
  ORDER_STATUS_LABELS,
  TIMELINE_TYPE_LABELS, OrderStatusChip, fmtDateFull,
} from "./shared";

const labelStyle = { fontSize: 11, fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.06em" };
const inputStyle = { backgroundColor: "var(--bg-input)", borderColor: "var(--border-primary)", color: "var(--text-primary)", border: "1px solid var(--border-primary)", borderRadius: 6, padding: "6px 10px", fontSize: 13, width: "100%" };

const STATUSES = Object.entries(ORDER_STATUS_LABELS);
const TIMELINE_TYPES = Object.entries(TIMELINE_TYPE_LABELS);

const STATUS_DEFAULT_NOTES = {
  negotiating:                    "Just started Negotiating with the customer on a possible new order",
  awaiting_quotation:             "We agreed on what the customer needs, and currently drafting a Quote for them",
  awaiting_customer_confirmation: "The Quotation has been sent to the Customer. Awaiting their Confirmation",
  awaiting_fulfilment:            "Customer has accepted the Quotation, and no further action is needed from them. First Chance possible we are going to build their device",
  awaiting_payment:               "Customer has accepted the Quotation, but a payment|advance is due before we proceed",
  manufacturing:                  "We have begun manufacturing the Customer's Device",
  shipped:                        "The order has been Shipped ! Awaiting Customer Feedback",
  installed:                      "Customer has informed us that the device has been successfully Installed !",
  declined:                       "Customer sadly declined our offer",
  complete:                       "Customer has successfully installed, and operated their product. No further action needed ! The order is complete !",
};

const VERBOSE_DATE_FMT = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "long", year: "numeric" });
const TIME_FMT = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", hour12: true });

function fmtVerboseDateTime(iso) {
  if (!iso) return "—";
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "—";
  return `${VERBOSE_DATE_FMT.format(d)}, ${TIME_FMT.format(d).toLowerCase()}`;
}

// ── Delete confirm modal ──────────────────────────────────────────────────────
function DeleteConfirm({ message, onConfirm, onCancel, deleting }) {
  return (
    <div style={{ position: "fixed", inset: 0, backgroundColor: "rgba(0,0,0,0.6)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1001 }}>
      <div style={{ backgroundColor: "var(--bg-card)", borderRadius: 10, padding: 24, width: 340, border: "1px solid var(--border-primary)" }}>
        <p style={{ fontSize: 14, color: "var(--text-primary)", marginBottom: 18 }}>{message || "Delete this item? This cannot be undone."}</p>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <button type="button" onClick={onCancel} style={{ fontSize: 13, padding: "5px 14px", borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>Cancel</button>
          <button type="button" onClick={onConfirm} disabled={deleting}
            style={{ fontSize: 13, fontWeight: 600, padding: "5px 14px", borderRadius: 6, border: "none", backgroundColor: "var(--danger)", color: "#fff", cursor: "pointer", opacity: deleting ? 0.6 : 1 }}>
            {deleting ? "Deleting..." : "Delete"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Timeline event row ────────────────────────────────────────────────────────
function TimelineEventRow({ event, index, canEdit, onEdit, onDelete }) {
  const [hovered, setHovered] = useState(false);
  return (
    <div
      style={{ display: "flex", gap: 10, paddingBottom: 10, position: "relative" }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flexShrink: 0 }}>
        <div style={{ width: 8, height: 8, borderRadius: "50%", backgroundColor: "var(--accent)", marginTop: 4 }} />
        <div style={{ flex: 1, width: 1, backgroundColor: "var(--border-secondary)" }} />
      </div>
      <div style={{ flex: 1, paddingBottom: 4 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text-heading)" }}>
          {TIMELINE_TYPE_LABELS[event.type] || event.type}
        </div>
        {event.note && <div style={{ fontSize: 12, color: "var(--text-primary)", marginTop: 3, whiteSpace: "pre-wrap" }}>{event.note}</div>}
        <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 3 }}>
          {fmtVerboseDateTime(event.date)}
          {event.updated_by && <span style={{ opacity: 0.55 }}> · {event.updated_by}</span>}
        </div>
      </div>
      {canEdit && hovered && (
        <div style={{ display: "flex", gap: 4, flexShrink: 0, alignSelf: "flex-start" }}>
          <button type="button" onClick={() => onEdit(index, event)}
            style={{ fontSize: 11, padding: "2px 8px", borderRadius: 4, border: "1px solid var(--border-primary)", backgroundColor: "var(--bg-card)", color: "var(--text-secondary)", cursor: "pointer" }}>
            Edit
          </button>
          <button type="button" onClick={() => onDelete(index)}
            style={{ fontSize: 11, padding: "2px 8px", borderRadius: 4, border: "1px solid var(--danger)", backgroundColor: "var(--bg-card)", color: "var(--danger)", cursor: "pointer" }}>
            Delete
          </button>
        </div>
      )}
    </div>
  );
}

// ── Order card ────────────────────────────────────────────────────────────────
function OrderCard({ order, customerId, canEdit, user, onReload, isOpen, onToggle, onDeleteOrder }) {
  const [showTimelineForm, setShowTimelineForm] = useState(false);
  const [showEditForm, setShowEditForm] = useState(false);
  const [showStatusUpdate, setShowStatusUpdate] = useState(false);
  const [deleteTlIndex, setDeleteTlIndex] = useState(null);
  const [deletingTl, setDeletingTl] = useState(false);

  // Timeline edit state
  const [editTimelineIndex, setEditTimelineIndex] = useState(null);
  const [editTimelineForm, setEditTimelineForm] = useState({ type: "note", note: "", date: "" });

  const [timelineForm, setTimelineForm] = useState({ type: "note", note: "", date: new Date().toISOString().slice(0, 16) });
  const [editForm, setEditForm] = useState({
    order_number: order.order_number || "",
    title: order.title || "",
    status: order.status || "negotiating",
    notes: order.notes || "",
  });
  const [statusUpdateForm, setStatusUpdateForm] = useState({
    newStatus: order.status || "negotiating",
    title: order.title || "",
    note: "",
    datetime: new Date().toISOString().slice(0, 16),
  });
  const [saving, setSaving] = useState(false);
  const [savingTl, setSavingTl] = useState(false);
  const [savingStatus, setSavingStatus] = useState(false);
  const [savingTlEdit, setSavingTlEdit] = useState(false);

  const timeline = [...(order.timeline || [])].sort((a, b) => (b.date || "").localeCompare(a.date || ""));

  const handleAddTimeline = async () => {
    if (!timelineForm.type) return;
    setSavingTl(true);
    try {
      await api.post(`/crm/customers/${customerId}/orders/${order.id}/timeline`, {
        ...timelineForm,
        date: timelineForm.date ? new Date(timelineForm.date).toISOString() : new Date().toISOString(),
        updated_by: user?.name || "Staff",
      });
      setTimelineForm({ type: "note", note: "", date: new Date().toISOString().slice(0, 16) });
      setShowTimelineForm(false);
      onReload();
    } catch (err) {
      alert(err.message);
    } finally {
      setSavingTl(false);
    }
  };

  const handleSaveEdit = async () => {
    setSaving(true);
    try {
      await api.patch(`/crm/customers/${customerId}/orders/${order.id}`, {
        order_number: editForm.order_number || null,
        title: editForm.title || null,
        status: editForm.status,
        status_updated_date: new Date().toISOString(),
        status_updated_by: user?.name || "Staff",
        notes: editForm.notes || null,
      });
      setShowEditForm(false);
      onReload();
    } catch (err) {
      alert(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleUpdateStatus = async () => {
    setSavingStatus(true);
    try {
      // Step 1: archive current status as a timeline event with the correct type and date
      const existingMatch = (order.timeline || []).some(
        (e) => e.archived_status === order.status &&
               e.date === (order.status_updated_date || order.created_at)
      );
      if (!existingMatch) {
        const statusToType = {
          negotiating: "negotiations_started",
          awaiting_quotation: "quote_request",
          awaiting_customer_confirmation: "quote_sent",
          awaiting_fulfilment: "quote_accepted",
          awaiting_payment: "invoice_sent",
          manufacturing: "mfg_started",
          shipped: "order_shipped",
          installed: "installed",
          declined: "note",
          complete: "payment_received",
        };
        const tlType = statusToType[order.status] || "note";
        await api.post(`/crm/customers/${customerId}/orders/${order.id}/timeline`, {
          type: tlType,
          note: order.notes || "",
          date: order.status_updated_date || order.created_at || new Date().toISOString(),
          updated_by: order.status_updated_by || order.created_by || "System",
          archived_status: order.status,
        });
      }
      // Step 2: update to new status — if note is left empty, save as empty (not the old note)
      await api.patch(`/crm/customers/${customerId}/orders/${order.id}`, {
        status: statusUpdateForm.newStatus,
        title: statusUpdateForm.title || order.title || null,
        status_updated_date: new Date(statusUpdateForm.datetime).toISOString(),
        status_updated_by: user?.name || "Staff",
        notes: statusUpdateForm.note,
      });
      setShowStatusUpdate(false);
      setStatusUpdateForm({ newStatus: order.status || "negotiating", title: order.title || "", note: "", datetime: new Date().toISOString().slice(0, 16) });
      onReload();
    } catch (err) {
      alert(err.message);
    } finally {
      setSavingStatus(false);
    }
  };

  const startEditTimeline = (index, event) => {
    setEditTimelineIndex(index);
    setEditTimelineForm({
      type: event.type || "note",
      note: event.note || "",
      date: event.date ? new Date(event.date).toISOString().slice(0, 16) : new Date().toISOString().slice(0, 16),
    });
  };

  const handleSaveTimelineEdit = async () => {
    setSavingTlEdit(true);
    try {
      const origIdx = (order.timeline || []).findIndex((e) =>
        e.date === timeline[editTimelineIndex].date && e.note === timeline[editTimelineIndex].note && e.type === timeline[editTimelineIndex].type
      );
      await api.patch(`/crm/customers/${customerId}/orders/${order.id}/timeline/${origIdx}`, {
        type: editTimelineForm.type,
        note: editTimelineForm.note,
        date: new Date(editTimelineForm.date).toISOString(),
      });
      setEditTimelineIndex(null);
      onReload();
    } catch (err) {
      alert(err.message);
    } finally {
      setSavingTlEdit(false);
    }
  };

  const handleDeleteTimeline = async () => {
    setDeletingTl(true);
    try {
      const origIdx = (order.timeline || []).findIndex((e) =>
        e.date === timeline[deleteTlIndex].date && e.note === timeline[deleteTlIndex].note && e.type === timeline[deleteTlIndex].type
      );
      await api.delete(`/crm/customers/${customerId}/orders/${order.id}/timeline/${origIdx}`);
      setDeleteTlIndex(null);
      onReload();
    } catch (err) {
      alert(err.message);
    } finally {
      setDeletingTl(false);
    }
  };

  return (
    <div className="ui-section-card mb-3">
      {/* Order header — clickable to toggle timeline */}
      <div
        style={{ display: "flex", alignItems: "flex-start", gap: 12, flexWrap: "wrap", cursor: "pointer" }}
        onClick={(e) => {
          if (e.target.closest("button")) return;
          onToggle(order.id);
        }}
      >
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            <span style={{ fontFamily: "monospace", fontSize: 12, color: "var(--text-muted)" }}>{order.order_number}</span>
            <OrderStatusChip status={order.status} />
          </div>
          <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-heading)", marginTop: 4 }}>
            {order.title || <span style={{ color: "var(--text-muted)", fontStyle: "italic" }}>Untitled order</span>}
          </div>
          {order.notes && <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 4, whiteSpace: "pre-wrap" }}>{order.notes}</div>}
          <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 4 }}>
            Created <strong>{fmtDateFull(order.created_at)}</strong>{order.created_by ? ` by ${order.created_by}` : ""}
            {order.status_updated_date && order.status_updated_by && (
              <> · Status updated <strong>{fmtDateFull(order.status_updated_date)}</strong> by {order.status_updated_by}</>
            )}
          </div>
        </div>

        {/* Actions */}
        <div style={{ display: "flex", gap: 6, flexShrink: 0, flexWrap: "wrap" }}>
          {/* Update Status button — neutral style */}
          {canEdit && (
            <button type="button"
              onClick={(e) => {
                e.stopPropagation();
                setShowStatusUpdate((v) => {
                  if (!v) {
                    // Reset datetime to NOW and pre-fill default note each time panel opens
                    setStatusUpdateForm((f) => ({
                      ...f,
                      datetime: new Date().toISOString().slice(0, 16),
                      note: STATUS_DEFAULT_NOTES[f.newStatus] || "",
                    }));
                  }
                  return !v;
                });
                setShowEditForm(false);
              }}
              style={{
                fontSize: 12, padding: "4px 12px", borderRadius: 6,
                border: "1px solid var(--border-primary)",
                backgroundColor: showStatusUpdate ? "var(--bg-card-hover)" : "transparent",
                color: "var(--text-secondary)",
                cursor: "pointer",
                display: "flex", alignItems: "center", gap: 5,
              }}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/>
              </svg>
              Update Status
            </button>
          )}
          <button type="button"
            onClick={(e) => { e.stopPropagation(); onToggle(order.id); }}
            style={{ fontSize: 12, padding: "4px 12px", borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: isOpen ? "var(--bg-card-hover)" : "transparent", color: "var(--text-secondary)", cursor: "pointer" }}>
            {isOpen ? "Hide Timeline" : "Timeline"} ({(order.timeline || []).length})
          </button>
          {canEdit && (
            <button type="button"
              onClick={(e) => { e.stopPropagation(); setShowEditForm((v) => !v); setShowStatusUpdate(false); }}
              style={{ fontSize: 12, padding: "4px 12px", borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: showEditForm ? "var(--bg-card-hover)" : "transparent", color: "var(--text-secondary)", cursor: "pointer" }}>
              Edit
            </button>
          )}
          {canEdit && (
            <button type="button"
              onClick={(e) => { e.stopPropagation(); onDeleteOrder(order.id); }}
              style={{ fontSize: 12, padding: "4px 8px", borderRadius: 6, border: "1px solid var(--danger)", backgroundColor: "transparent", color: "var(--danger)", cursor: "pointer", display: "flex", alignItems: "center" }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M5.755,20.283,4,8H20L18.245,20.283A2,2,0,0,1,16.265,22H7.735A2,2,0,0,1,5.755,20.283ZM21,4H16V3a1,1,0,0,0-1-1H9A1,1,0,0,0,8,3V4H3A1,1,0,0,0,3,6H21a1,1,0,0,0,0-2Z"/></svg>
            </button>
          )}
        </div>
      </div>

      {/* Update Status form */}
      {showStatusUpdate && (
        <div style={{ marginTop: 12, padding: 12, borderRadius: 8, backgroundColor: "var(--bg-primary)", border: "1px solid var(--border-primary)" }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text-heading)", marginBottom: 10 }}>Update Order Status</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
            <div>
              <div style={{ ...labelStyle, marginBottom: 4 }}>New Status</div>
              <select value={statusUpdateForm.newStatus} onChange={(e) => setStatusUpdateForm((f) => ({ ...f, newStatus: e.target.value, note: STATUS_DEFAULT_NOTES[e.target.value] || "" }))} style={inputStyle}>
                {STATUSES.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
              </select>
            </div>
            <div style={{ display: "flex", gap: 6, alignItems: "flex-end" }}>
              <div style={{ flex: 1 }}>
                <div style={{ ...labelStyle, marginBottom: 4 }}>Date & Time</div>
                <input type="datetime-local" value={statusUpdateForm.datetime} onChange={(e) => setStatusUpdateForm((f) => ({ ...f, datetime: e.target.value }))} style={inputStyle} />
              </div>
              <button type="button" onClick={() => setStatusUpdateForm((f) => ({ ...f, datetime: new Date().toISOString().slice(0, 16) }))}
                style={{ fontSize: 11, padding: "6px 8px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-secondary)", cursor: "pointer", whiteSpace: "nowrap", marginBottom: 0 }}>
                Now
              </button>
            </div>
            <div style={{ gridColumn: "1 / -1" }}>
              <div style={{ ...labelStyle, marginBottom: 4 }}>Order Title</div>
              <input type="text" value={statusUpdateForm.title} onChange={(e) => setStatusUpdateForm((f) => ({ ...f, title: e.target.value }))} style={inputStyle} placeholder="Update order title (optional)..." />
            </div>
            <div style={{ gridColumn: "1 / -1" }}>
              <div style={{ ...labelStyle, marginBottom: 4 }}>Note</div>
              <textarea rows={2} value={statusUpdateForm.note} onChange={(e) => setStatusUpdateForm((f) => ({ ...f, note: e.target.value }))} style={{ ...inputStyle, resize: "vertical" }} placeholder="Optional note about this status change..." />
            </div>
          </div>
          <div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: 10, padding: "6px 10px", borderRadius: 6, backgroundColor: "var(--bg-card-hover)" }}>
            Current status "<strong>{ORDER_STATUS_LABELS[order.status] || order.status}</strong>" will be archived as a timeline event, then replaced with "{ORDER_STATUS_LABELS[statusUpdateForm.newStatus] || statusUpdateForm.newStatus}".
          </div>
          <div className="flex gap-2 justify-end">
            <button type="button" onClick={() => setShowStatusUpdate(false)}
              style={{ fontSize: 12, padding: "4px 12px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>Cancel</button>
            <button type="button" onClick={handleUpdateStatus} disabled={savingStatus}
              style={{ fontSize: 12, fontWeight: 600, padding: "4px 14px", borderRadius: 5, border: "none", backgroundColor: "var(--btn-primary)", color: "#fff", cursor: "pointer", opacity: savingStatus ? 0.6 : 1 }}>
              {savingStatus ? "Updating..." : "Update Status"}
            </button>
          </div>
        </div>
      )}

      {/* Edit form */}
      {showEditForm && (
        <div style={{ marginTop: 12, padding: 12, borderRadius: 8, backgroundColor: "var(--bg-primary)", border: "1px solid var(--border-primary)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
            <div>
              <div style={{ ...labelStyle, marginBottom: 4 }}>Order Number</div>
              <input type="text" value={editForm.order_number} onChange={(e) => setEditForm((f) => ({ ...f, order_number: e.target.value }))} style={inputStyle} />
            </div>
            <div>
              <div style={{ ...labelStyle, marginBottom: 4 }}>Title</div>
              <input type="text" value={editForm.title} onChange={(e) => setEditForm((f) => ({ ...f, title: e.target.value }))} style={inputStyle} />
            </div>
            <div>
              <div style={{ ...labelStyle, marginBottom: 4 }}>Status</div>
              <select value={editForm.status} onChange={(e) => setEditForm((f) => ({ ...f, status: e.target.value }))} style={inputStyle}>
                {STATUSES.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
              </select>
            </div>
            <div style={{ gridColumn: "1 / -1" }}>
              <div style={{ ...labelStyle, marginBottom: 4 }}>Notes</div>
              <textarea rows={2} value={editForm.notes} onChange={(e) => setEditForm((f) => ({ ...f, notes: e.target.value }))} style={{ ...inputStyle, resize: "vertical" }} />
            </div>
          </div>
          <div className="flex gap-2 justify-end">
            <button type="button" onClick={() => setShowEditForm(false)}
              style={{ fontSize: 12, padding: "4px 12px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>Cancel</button>
            <button type="button" onClick={handleSaveEdit} disabled={saving}
              style={{ fontSize: 12, fontWeight: 600, padding: "4px 14px", borderRadius: 5, border: "none", backgroundColor: "var(--btn-primary)", color: "#fff", cursor: "pointer", opacity: saving ? 0.6 : 1 }}>
              {saving ? "Saving..." : "Save"}
            </button>
          </div>
        </div>
      )}

      {/* Timeline */}
      {isOpen && (
        <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--border-secondary)" }}>
          {timeline.length === 0 ? (
            <p style={{ fontSize: 12, color: "var(--text-muted)", fontStyle: "italic" }}>No timeline events yet.</p>
          ) : (
            <div>
              {timeline.map((ev, i) => (
                <TimelineEventRow
                  key={i}
                  event={ev}
                  index={i}
                  canEdit={canEdit}
                  onEdit={startEditTimeline}
                  onDelete={(idx) => setDeleteTlIndex(idx)}
                />
              ))}
            </div>
          )}

          {/* Timeline item edit form */}
          {editTimelineIndex !== null && (
            <div style={{ marginTop: 8, padding: 12, borderRadius: 8, backgroundColor: "var(--bg-primary)", border: "1px solid var(--accent)44" }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text-heading)", marginBottom: 8 }}>Edit Timeline Event</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 8 }}>
                <div>
                  <div style={{ ...labelStyle, marginBottom: 4 }}>Type</div>
                  <select value={editTimelineForm.type} onChange={(e) => setEditTimelineForm((f) => ({ ...f, type: e.target.value }))} style={{ ...inputStyle, fontSize: 12 }}>
                    {TIMELINE_TYPES.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
                  </select>
                </div>
                <div style={{ display: "flex", gap: 6, alignItems: "flex-end" }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ ...labelStyle, marginBottom: 4 }}>Date & Time</div>
                    <input type="datetime-local" value={editTimelineForm.date} onChange={(e) => setEditTimelineForm((f) => ({ ...f, date: e.target.value }))} style={{ ...inputStyle, fontSize: 12 }} />
                  </div>
                  <button type="button" onClick={() => setEditTimelineForm((f) => ({ ...f, date: new Date().toISOString().slice(0, 16) }))}
                    style={{ fontSize: 11, padding: "6px 8px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-secondary)", cursor: "pointer", whiteSpace: "nowrap" }}>
                    Now
                  </button>
                </div>
                <div style={{ gridColumn: "1 / -1" }}>
                  <div style={{ ...labelStyle, marginBottom: 4 }}>Note</div>
                  <textarea rows={2} value={editTimelineForm.note} onChange={(e) => setEditTimelineForm((f) => ({ ...f, note: e.target.value }))} style={{ ...inputStyle, resize: "vertical", fontSize: 12 }} />
                </div>
              </div>
              <div className="flex gap-2 justify-end">
                <button type="button" onClick={() => setEditTimelineIndex(null)}
                  style={{ fontSize: 12, padding: "4px 12px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>Cancel</button>
                <button type="button" onClick={handleSaveTimelineEdit} disabled={savingTlEdit}
                  style={{ fontSize: 12, fontWeight: 600, padding: "4px 14px", borderRadius: 5, border: "none", backgroundColor: "var(--btn-primary)", color: "#fff", cursor: "pointer", opacity: savingTlEdit ? 0.6 : 1 }}>
                  {savingTlEdit ? "Saving..." : "Save"}
                </button>
              </div>
            </div>
          )}

          {canEdit && (
            <>
              {!showTimelineForm ? (
                <button type="button" onClick={() => setShowTimelineForm(true)}
                  style={{ fontSize: 12, padding: "4px 12px", borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-secondary)", cursor: "pointer", marginTop: 6 }}>
                  + Add Event
                </button>
              ) : (
                <div style={{ marginTop: 8, padding: 10, borderRadius: 8, backgroundColor: "var(--bg-primary)", border: "1px solid var(--border-primary)" }}>
                  {/* Row 1: Type + Date */}
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr auto", gap: 8, marginBottom: 8 }}>
                    <div>
                      <div style={{ ...labelStyle, marginBottom: 4 }}>Type</div>
                      <select value={timelineForm.type} onChange={(e) => setTimelineForm((f) => ({ ...f, type: e.target.value }))}
                        style={{ ...inputStyle, fontSize: 12 }}>
                        {TIMELINE_TYPES.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
                      </select>
                    </div>
                    <div>
                      <div style={{ ...labelStyle, marginBottom: 4 }}>Date & Time</div>
                      <input type="datetime-local" value={timelineForm.date}
                        onChange={(e) => setTimelineForm((f) => ({ ...f, date: e.target.value }))}
                        style={{ ...inputStyle, fontSize: 12 }}
                      />
                    </div>
                    <div style={{ display: "flex", alignItems: "flex-end" }}>
                      <button type="button" onClick={() => setTimelineForm((f) => ({ ...f, date: new Date().toISOString().slice(0, 16) }))}
                        style={{ fontSize: 11, padding: "6px 8px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-secondary)", cursor: "pointer", whiteSpace: "nowrap" }}>
                        Now
                      </button>
                    </div>
                  </div>
                  {/* Row 2: Note (resizable, 2 lines) + buttons */}
                  <div style={{ display: "flex", gap: 8, alignItems: "flex-end" }}>
                    <textarea
                      rows={2}
                      placeholder="Note (optional)..."
                      value={timelineForm.note}
                      onChange={(e) => setTimelineForm((f) => ({ ...f, note: e.target.value }))}
                      style={{ ...inputStyle, fontSize: 12, resize: "vertical", flex: 1 }}
                    />
                    <div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
                      <button type="button" onClick={handleAddTimeline} disabled={savingTl}
                        style={{ fontSize: 12, fontWeight: 600, padding: "6px 14px", borderRadius: 6, border: "none", backgroundColor: "var(--btn-primary)", color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", gap: 5, opacity: savingTl ? 0.6 : 1 }}>
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                        {savingTl ? "..." : "Add"}
                      </button>
                      <button type="button" onClick={() => { setShowTimelineForm(false); setTimelineForm({ type: "note", note: "", date: new Date().toISOString().slice(0, 16) }); }}
                        style={{ fontSize: 12, padding: "6px 12px", borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer", display: "flex", alignItems: "center", gap: 5 }}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                        Cancel
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      )}

      {deleteTlIndex !== null && (
        <DeleteConfirm
          message="Delete this timeline event? This cannot be undone."
          onConfirm={handleDeleteTimeline}
          onCancel={() => setDeleteTlIndex(null)}
          deleting={deletingTl}
        />
      )}
    </div>
  );
}

// ── New Order form ────────────────────────────────────────────────────────────
async function setCustomerActive(customerId) {
  try {
    await api.patch(`/crm/customers/${customerId}/relationship-status`, { status: "active" });
  } catch {
    // Non-critical — silently ignore
  }
}

function NewOrderForm({ customerId, user, onSaved, onCancel, suggestedOrderNumber }) {
  const [form, setForm] = useState({
    order_number: suggestedOrderNumber || "",
    title: "",
    status: "negotiating",
    notes: "",
    date: new Date().toISOString().slice(0, 16),
  });
  const [saving, setSaving] = useState(false);

  const handleSubmit = async () => {
    setSaving(true);
    try {
      await api.post(`/crm/customers/${customerId}/orders`, {
        customer_id: customerId,
        order_number: form.order_number || undefined,
        title: form.title || undefined,
        status: form.status,
        notes: form.notes || undefined,
        created_by: user?.name || "Staff",
        status_updated_date: new Date(form.date).toISOString(),
        status_updated_by: user?.name || "Staff",
      });
      await setCustomerActive(customerId);
      onSaved();
    } catch (err) {
      alert(err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="ui-section-card mb-3" style={{ border: "1px solid var(--accent)44" }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-heading)", marginBottom: 12 }}>New Order</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
        <div>
          <div style={{ ...labelStyle, marginBottom: 4 }}>Order Number</div>
          <input type="text" value={form.order_number} onChange={(e) => setForm((f) => ({ ...f, order_number: e.target.value }))} style={inputStyle} placeholder="Auto-generated if empty" />
        </div>
        <div>
          <div style={{ ...labelStyle, marginBottom: 4 }}>Title</div>
          <input type="text" value={form.title} onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))} style={inputStyle} placeholder="Order title..." />
        </div>
        <div>
          <div style={{ ...labelStyle, marginBottom: 4 }}>Starting Status</div>
          <select value={form.status} onChange={(e) => setForm((f) => ({ ...f, status: e.target.value }))} style={inputStyle}>
            {STATUSES.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
          </select>
        </div>
        <div>
          <div style={{ ...labelStyle, marginBottom: 4 }}>Date</div>
          <input type="datetime-local" value={form.date} onChange={(e) => setForm((f) => ({ ...f, date: e.target.value }))} style={inputStyle} />
        </div>
        <div style={{ gridColumn: "1 / -1" }}>
          <div style={{ ...labelStyle, marginBottom: 4 }}>Note</div>
          <textarea rows={2} value={form.notes} onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))} style={{ ...inputStyle, resize: "vertical" }} placeholder="Optional note..." />
        </div>
      </div>
      <div className="flex gap-2 justify-end">
        <button type="button" onClick={onCancel}
          style={{ fontSize: 12, padding: "4px 12px", borderRadius: 5, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>Cancel</button>
        <button type="button" onClick={handleSubmit} disabled={saving}
          style={{ fontSize: 12, fontWeight: 600, padding: "4px 14px", borderRadius: 5, border: "none", backgroundColor: "var(--btn-primary)", color: "#fff", cursor: "pointer", opacity: saving ? 0.6 : 1 }}>
          {saving ? "Creating..." : "Create Order"}
        </button>
      </div>
    </div>
  );
}

// ── Main export ───────────────────────────────────────────────────────────────
export default function OrdersTab({ customerId, orders, ordersLoading, canEdit, user, onReload, expandOrderId, onExpandOrderIdConsumed }) {
  const [expandedOrderId, setExpandedOrderId] = useState(null);
  const [showNewOrderForm, setShowNewOrderForm] = useState(false);
  const [deleteOrderId, setDeleteOrderId] = useState(null);
  const [deletingOrder, setDeletingOrder] = useState(false);
  // Suggested order number for the new-order form (fetched lazily)
  const [suggestedOrderNumber, setSuggestedOrderNumber] = useState("");

  useEffect(() => {
    if (expandOrderId) {
      setExpandedOrderId(expandOrderId);
      onExpandOrderIdConsumed?.();
    }
  }, [expandOrderId]);

  const handleToggle = (orderId) => {
    setExpandedOrderId((prev) => (prev === orderId ? null : orderId));
  };

  const handleDeleteOrder = async () => {
    setDeletingOrder(true);
    try {
      await api.delete(`/crm/customers/${customerId}/orders/${deleteOrderId}`);
      setDeleteOrderId(null);
      onReload();
    } catch (err) {
      alert(err.message);
    } finally {
      setDeletingOrder(false);
    }
  };

  const handleOpenNewOrder = async () => {
    try {
      const res = await api.get(`/crm/customers/${customerId}/orders/next-order-number`);
      setSuggestedOrderNumber(res.order_number || "");
    } catch {
      setSuggestedOrderNumber("");
    }
    setShowNewOrderForm(true);
  };

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
        <span style={{ fontSize: 13, color: "var(--text-muted)" }}>
          {orders.length} order{orders.length !== 1 ? "s" : ""}
        </span>
        {canEdit && (
          <button type="button" onClick={handleOpenNewOrder}
            style={{ fontSize: 12, fontWeight: 600, padding: "5px 14px", borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-secondary)", cursor: "pointer" }}>
            + New Order
          </button>
        )}
      </div>

      {showNewOrderForm && canEdit && (
        <NewOrderForm
          customerId={customerId}
          user={user}
          suggestedOrderNumber={suggestedOrderNumber}
          onSaved={() => { setShowNewOrderForm(false); onReload(); }}
          onCancel={() => setShowNewOrderForm(false)}
        />
      )}

      {ordersLoading ? (
        <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
      ) : orders.length === 0 ? (
        <div className="rounded-lg p-8 text-center text-sm border" style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}>
          No orders yet. Use "+ New Order" or the "Init Negotiations" button to create the first order.
        </div>
      ) : (
        [...orders].sort((a, b) => (b.created_at || "").localeCompare(a.created_at || "")).map((order) => (
          <OrderCard
            key={order.id}
            order={order}
            customerId={customerId}
            canEdit={canEdit}
            user={user}
            onReload={onReload}
            isOpen={expandedOrderId === order.id}
            onToggle={handleToggle}
            onDeleteOrder={(id) => setDeleteOrderId(id)}
          />
        ))
      )}

      {deleteOrderId && (
        <DeleteConfirm
          message="Delete this order and all its timeline events? This cannot be undone."
          onConfirm={handleDeleteOrder}
          onCancel={() => setDeleteOrderId(null)}
          deleting={deletingOrder}
        />
      )}
    </div>
  );
}
