// csr-customers.jsx — CE console: customer directory, file view, booking history,
// lodge inquiry on behalf, edit file, add contacts & favourite addresses.
const { useState: useStateCu, useMemo: useMemoCu, useEffect: useEffectCu } = React;

const BK_STATUS = {
  "Booked":     { tone: "brand",   dot: "var(--brand)" },
  "In transit": { tone: "brand",   dot: "var(--brand)", pulse: true },
  "Delivered":  { tone: "success", dot: "#22b86e" },
  "Cancelled":  { tone: "danger",  dot: "var(--danger)" },
};

/* Lodge an inquiry on behalf of the customer (phone/email contact) */
function LodgeInquiryModal({ open, onClose, customer, bookings, onLodge }) {
  const [type, setType] = useStateCu(window.FX.INQUIRY_TYPES[0]);
  const [tracking, setTracking] = useStateCu("");
  const [message, setMessage] = useStateCu("");
  useEffectCu(() => { if (open) { setType(window.FX.INQUIRY_TYPES[0]); setTracking(""); setMessage(""); } }, [open]);
  const opts = bookings.map(b => ({ value: b.tracking, label: `${b.tracking} · ${b.pickup.suburb} → ${b.dropoff.suburb} · ${b.status}` }));
  return (
    <Modal open={open} onClose={onClose} title={"Lodge inquiry · " + (customer ? customer.name : "")} width={560}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", gap: 9, padding: "10px 13px", background: "var(--brand-soft)", borderRadius: "var(--r-sm)", alignItems: "flex-start" }}>
          <Icon name="headset" size={15} color="var(--brand)" style={{ flex: "none", marginTop: 1 }} />
          <span style={{ fontSize: 12.5, color: "var(--fg-body)", lineHeight: 1.45 }}>Lodged on the customer's behalf — it appears in their portal under <strong>My inquiries</strong> and they're emailed each response.</span>
        </div>
        <Field label="Query type"><Select value={type} onChange={setType} options={window.FX.INQUIRY_TYPES} /></Field>
        <Field label="Related booking (optional)"><Select value={tracking} onChange={setTracking} placeholder="General inquiry — no specific booking" options={opts} /></Field>
        <Field label="Details *">
          <textarea value={message} onChange={e => setMessage(e.target.value)} rows={4} placeholder="What did the caller report?" style={{ ...window.inputStyle, resize: "vertical", fontSize: 13.5, lineHeight: 1.5 }} />
        </Field>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" icon="message-square" disabled={!message.trim()} onClick={() => onLodge({ type, tracking, message: message.trim() })}>Lodge inquiry</Button>
        </div>
      </div>
    </Modal>
  );
}

/* Add a contact person to the customer file */
function AddContactModal({ open, onClose, onSave }) {
  const blank = { name: "", role: "", phone: "", email: "" };
  const [f, setF] = useStateCu(blank);
  useEffectCu(() => { if (open) setF(blank); }, [open]);
  const set = (k, v) => setF(prev => ({ ...prev, [k]: v }));
  return (
    <Modal open={open} onClose={onClose} title="Add contact" width={460}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 12 }}>
          <Field label="Name *"><TextInput value={f.name} onChange={v => set("name", v)} placeholder="Jane Smith" /></Field>
          <Field label="Role"><TextInput value={f.role} onChange={v => set("role", v)} placeholder="Dispatch" /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 12 }}>
          <Field label="Phone"><TextInput value={f.phone} onChange={v => set("phone", v)} placeholder="+61 4xx xxx xxx" mono /></Field>
          <Field label="Email"><TextInput value={f.email} onChange={v => set("email", v)} placeholder="email@company.com.au" /></Field>
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" icon="check" disabled={!f.name.trim()} onClick={() => onSave(f)}>Add contact</Button>
        </div>
      </div>
    </Modal>
  );
}

function CustHistoryRow({ b, currency }) {
  const st = BK_STATUS[b.status] || BK_STATUS.Booked;
  const t = window.FX.BOOKING_TYPES.find(x => x.id === b.typeId);
  return (
    <a href={"Fedex Booking.html#t=" + encodeURIComponent(b.tracking)} target="_blank" rel="noopener" style={{ display: "grid", gridTemplateColumns: "1fr 0.75fr 1.5fr 0.6fr 0.75fr", gap: 10, padding: "11px 16px", borderTop: "1px solid var(--border)", alignItems: "center", textDecoration: "none", cursor: "pointer" }}
      onMouseEnter={e => e.currentTarget.style.background = "var(--bg-mist)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
      <span style={{ minWidth: 0 }}>
        <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, color: "var(--brand)" }}>{b.tracking}</span>
        <span style={{ display: "block", fontSize: 11, color: "var(--fg-mute)" }}>{window.FX.fmtDate(b.date)}{b.time ? " · " + b.time : ""}</span>
      </span>
      <span><Badge tone={t ? t.tone : "neutral"}>{t ? t.short : b.typeId}</Badge></span>
      <span style={{ display: "flex", alignItems: "center", gap: 7, minWidth: 0, fontSize: 12.5, color: "var(--fg-body)" }}>
        <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{b.pickup.suburb}</span>
        <Icon name="arrow-right" size={11} color="var(--fg-faint)" style={{ flex: "none" }} />
        <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{b.dropoff.suburb}</span>
      </span>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, color: "var(--fg-strong)", textAlign: "right" }}>{window.FX.money(b.total, currency)}</span>
      <span style={{ textAlign: "right" }}><Badge tone={st.tone}><StatusDot color={st.dot} pulse={st.pulse} /> {b.status}</Badge></span>
    </a>
  );
}

/* Edit booking requirements: pop-up alert + reference-field rules */
function BookingReqModal({ open, onClose, seed, onSave }) {
  const [alertTxt, setAlertTxt] = useStateCu("");
  const [r1, setR1] = useStateCu({ label: "", required: false, prefix: "" });
  const [r2, setR2] = useStateCu({ label: "", required: false, prefix: "" });
  useEffectCu(() => {
    if (open && seed) {
      setAlertTxt(seed.bookingAlert || "");
      setR1({ label: "", required: false, prefix: "", ...((seed.refConfig || {}).ref1 || {}) });
      setR2({ label: "", required: false, prefix: "", ...((seed.refConfig || {}).ref2 || {}) });
    }
  }, [open, seed && seed.id]);
  const refEditor = (title, val, setVal) => (
    <div style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", padding: 13 }}>
      <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--fg-strong)", marginBottom: 10 }}>{title}</div>
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 10, marginBottom: 10 }}>
        <Field label="Field label"><TextInput value={val.label} onChange={v => setVal({ ...val, label: v })} placeholder="e.g. PO number" /></Field>
        <Field label="Must start with"><TextInput value={val.prefix} onChange={v => setVal({ ...val, prefix: v })} placeholder="e.g. 45" mono /></Field>
      </div>
      <button onClick={() => setVal({ ...val, required: !val.required })} style={{ display: "inline-flex", alignItems: "center", gap: 9, background: "transparent", border: "none", padding: 0, cursor: "pointer" }}>
        <span style={{ width: 34, height: 20, borderRadius: 999, flex: "none", background: val.required ? "var(--accent)" : "var(--bg-mist-2)", position: "relative", transition: "all 160ms ease" }}>
          <span style={{ position: "absolute", top: 2, left: val.required ? 16 : 2, width: 16, height: 16, borderRadius: "50%", background: "#fff", transition: "all 160ms ease" }} />
        </span>
        <span style={{ fontSize: 13, color: "var(--fg-strong)", fontWeight: 500 }}>Mandatory at booking</span>
      </button>
    </div>
  );
  return (
    <Modal open={open} onClose={onClose} title="Booking requirements" width={540}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label="Pop-up alert at booking" hint="Shown to the operator (and must be acknowledged) every time a booking is started for this customer. Leave blank for none.">
          <textarea value={alertTxt} onChange={e => setAlertTxt(e.target.value)} rows={3} placeholder="e.g. Always confirm the dock is staffed before booking a pickup." style={{ ...window.inputStyle, resize: "vertical", fontSize: 13.5, lineHeight: 1.5 }} />
        </Field>
        {refEditor("Reference 1", r1, setR1)}
        {refEditor("Reference 2", r2, setR2)}
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" icon="check" onClick={() => onSave({ bookingAlert: alertTxt.trim(), refConfig: { ref1: r1, ref2: r2 } })}>Save requirements</Button>
        </div>
      </div>
    </Modal>
  );
}

function CsrCustomers({ customers, bookings, currency, onSaveCustomer, onAddCustomer, onAddAddress, onAddContact, onLodgeInquiry, onBook }) {
  const [selId, setSelId] = useStateCu(customers[0] ? customers[0].id : null);
  const [q, setQ] = useStateCu("");
  const [editOpen, setEditOpen] = useStateCu(false);
  const [newOpen, setNewOpen] = useStateCu(false);
  const [inqOpen, setInqOpen] = useStateCu(false);
  const [contactOpen, setContactOpen] = useStateCu(false);
  const [addrOpen, setAddrOpen] = useStateCu(false);
  const [reqOpen, setReqOpen] = useStateCu(false);
  const [histFilter, setHistFilter] = useStateCu("all");
  const [notesEdit, setNotesEdit] = useStateCu(false);
  const [notesDraft, setNotesDraft] = useStateCu("");
  const [phraseEdit, setPhraseEdit] = useStateCu(false);
  const [phraseDraft, setPhraseDraft] = useStateCu("");
  useEffectCu(() => { setNotesEdit(false); setPhraseEdit(false); }, [selId]);

  const ql = q.trim().toLowerCase();
  const list = ql ? customers.filter(c => c.name.toLowerCase().includes(ql) || c.ref.toLowerCase().includes(ql) || (c.account || "").toLowerCase().includes(ql)) : customers;
  const sel = customers.find(c => c.id === selId) || list[0] || null;
  const hist = useMemoCu(() => bookings
    .filter(b => sel && b.customerId === sel.id)
    .sort((a, b) => (b.placedAt || "").localeCompare(a.placedAt || "")), [bookings, sel && sel.id]);
  const histShown = histFilter === "all" ? hist : hist.filter(b => histFilter === "active" ? (b.status === "Booked" || b.status === "In transit") : b.status === histFilter);
  const spend = hist.filter(b => b.status !== "Cancelled").reduce((s, b) => s + (b.total || 0), 0);

  return (
    <div className="fade-up">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, marginBottom: 18, flexWrap: "wrap" }}>
        <div>
          <Eyebrow>Customer service</Eyebrow>
          <h1 style={{ margin: "9px 0 0", fontSize: 25, fontWeight: 700, letterSpacing: "-0.6px", color: "var(--fg-strong)" }}>Customers</h1>
          <p style={{ margin: "7px 0 0", fontSize: 14.5, color: "var(--fg-mute)" }}>Every account, their booking history, and the tools to update a file or lodge an inquiry on a caller's behalf.</p>
        </div>
        <Button variant="primary" icon="user-plus" onClick={() => setNewOpen(true)}>Add customer</Button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "300px minmax(0,1fr)", gap: 20, alignItems: "start" }}>
        {/* Directory */}
        <div style={{ position: "sticky", top: 16 }}>
          <div style={{ position: "relative", marginBottom: 10 }}>
            <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)", zIndex: 1 }}><Icon name="search" size={15} /></span>
            <TextInput value={q} onChange={setQ} placeholder="Filter customers…" style={{ paddingLeft: 36 }} />
          </div>
          <Card pad={0} style={{ overflow: "hidden" }}>
            {list.map((c, i) => {
              const on = sel && c.id === sel.id;
              const n = bookings.filter(b => b.customerId === c.id).length;
              return (
                <button key={c.id} onClick={() => setSelId(c.id)} style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", textAlign: "left", padding: "12px 14px", border: "none", borderTop: i ? "1px solid var(--border)" : "none", background: on ? "var(--brand-soft)" : "transparent", cursor: "pointer", borderLeft: "3px solid " + (on ? "var(--brand)" : "transparent") }}>
                  <span style={{ width: 36, height: 36, borderRadius: 10, flex: "none", background: on ? "var(--brand)" : "var(--bg-mist)", color: on ? "#fff" : "var(--fg-mute)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 12.5 }}>{c.name.split(/\s+/).map(w => w[0]).slice(0, 2).join("")}</span>
                  <span style={{ flex: 1, minWidth: 0 }}>
                    <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
                      <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</span>
                      {c.status && c.status !== "active" && <StatusDot color="var(--danger)" />}
                    </span>
                    <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-mute)", marginTop: 1 }}>{c.ref} · {n} booking{n === 1 ? "" : "s"}</span>
                  </span>
                </button>
              );
            })}
            {list.length === 0 && <div style={{ padding: 24, fontSize: 13, color: "var(--fg-mute)", textAlign: "center" }}>No customers match “{q}”.</div>}
          </Card>
        </div>

        {/* File */}
        {sel ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Card pad={0} style={{ overflow: "hidden" }}>
              <div style={{ background: "var(--brand)", color: "#fff", padding: "18px 22px", display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
                <span style={{ width: 48, height: 48, borderRadius: 12, background: "rgba(255,255,255,0.16)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none", fontWeight: 800, fontSize: 17 }}>{sel.name.split(/\s+/).map(w => w[0]).slice(0, 2).join("")}</span>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                    <span style={{ fontWeight: 800, fontSize: 18 }}>{sel.name}</span>
                    {sel.priority && <Badge style={{ background: "var(--accent)", color: "#fff" }}>Priority</Badge>}
                    {sel.broker && <Badge style={{ background: "rgba(255,255,255,0.2)", color: "#fff" }}>Broker</Badge>}
                    {sel.status && sel.status !== "active" && <Badge style={{ background: "#fff", color: "var(--danger)" }}>{sel.status === "stop-trade" ? "Stop-trade" : "Inactive"}</Badge>}
                  </div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, opacity: 0.85, marginTop: 3 }}>{sel.ref} · {sel.account} · {sel.terms}{sel.accessPhrase ? <span> · <Icon name="shield" size={11} style={{ verticalAlign: "-1px" }} /> {sel.accessPhrase}</span> : null}</div>
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  <Button variant="secondary" size="sm" icon="pencil" onClick={() => setEditOpen(true)}>Edit file</Button>
                  <Button variant="secondary" size="sm" icon="message-square" onClick={() => setInqOpen(true)}>Lodge inquiry</Button>
                  <Button size="sm" icon="plus" style={{ background: "#fff", color: "var(--brand)" }} onClick={() => onBook(sel)}>New booking</Button>
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 0, borderBottom: "1px solid var(--border)" }}>
                {[["Bookings", hist.length], ["Active", hist.filter(b => b.status === "Booked" || b.status === "In transit").length], ["Total spend", window.FX.money(spend, currency)], ["Status", null]].map(([l, v], i) => (
                  <div key={l} style={{ padding: "13px 18px", borderLeft: i ? "1px solid var(--border)" : "none" }}>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.7px", textTransform: "uppercase", color: "var(--fg-mute)" }}>{l}</div>
                    <div style={{ fontSize: 16, fontWeight: 700, color: "var(--fg-strong)", marginTop: 3 }}>{v === null ? <AccountStatusPill status={sel.status} /> : v}</div>
                  </div>
                ))}
              </div>

              {/* Account access phrase */}
              <div style={{ padding: "14px 22px 0" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Account access phrase</span>
                  {!phraseEdit && <button onClick={() => { setPhraseDraft(sel.accessPhrase || ""); setPhraseEdit(true); }} style={{ display: "inline-flex", alignItems: "center", gap: 4, background: "var(--brand-soft)", border: "none", borderRadius: "var(--r-pill)", padding: "4px 10px", color: "var(--brand)", fontSize: 12, fontWeight: 500, cursor: "pointer" }}><Icon name="pencil" size={12} /> {sel.accessPhrase ? "Edit" : "Add phrase"}</button>}
                </div>
                {phraseEdit ? (
                  <div>
                    <div style={{ display: "flex", gap: 8 }}>
                      <div style={{ flex: 1, minWidth: 0 }}><TextInput value={phraseDraft} onChange={v => setPhraseDraft(v.toUpperCase())} placeholder="e.g. ACME-1234" mono /></div>
                      <Button variant="ghost" size="sm" onClick={() => setPhraseEdit(false)}>Cancel</Button>
                      <Button variant="primary" size="sm" icon="check" onClick={() => { onSaveCustomer({ ...sel, accessPhrase: phraseDraft.trim() }); setPhraseEdit(false); }}>Save phrase</Button>
                    </div>
                    <div style={{ fontSize: 11.5, color: "var(--fg-faint)", marginTop: 7 }}>This is an access phrase the caller confirms before an operator can quote — not a password. Leave blank to remove it.</div>
                  </div>
                ) : sel.accessPhrase ? (
                  <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 13px", background: "var(--brand-soft)", borderRadius: "var(--r-sm)" }}>
                    <Icon name="shield" size={15} color="var(--brand)" />
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 14.5, fontWeight: 700, color: "var(--fg-strong)", letterSpacing: "0.5px", flex: 1 }}>{sel.accessPhrase}</span>
                    <span style={{ fontSize: 11, color: "var(--fg-mute)", textAlign: "right", maxWidth: 210, lineHeight: 1.35 }}>Caller must confirm this before every phone booking</span>
                  </div>
                ) : (
                  <div style={{ fontSize: 12.5, color: "var(--fg-faint)", fontStyle: "italic" }}>No access phrase — phone bookings on this account skip caller verification.</div>
                )}
              </div>

              {/* Customer notes */}
              <div style={{ padding: "14px 22px 0" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Customer notes</span>
                  {!notesEdit && <button onClick={() => { setNotesDraft(sel.notes || ""); setNotesEdit(true); }} style={{ display: "inline-flex", alignItems: "center", gap: 4, background: "var(--brand-soft)", border: "none", borderRadius: "var(--r-pill)", padding: "4px 10px", color: "var(--brand)", fontSize: 12, fontWeight: 500, cursor: "pointer" }}><Icon name="pencil" size={12} /> {sel.notes ? "Edit" : "Add note"}</button>}
                </div>
                {notesEdit ? (
                  <div>
                    <textarea autoFocus value={notesDraft} onChange={e => setNotesDraft(e.target.value)} rows={3} placeholder="e.g. Always call the dock before pickup · invoices go to head office" style={{ ...window.inputStyle, resize: "vertical", fontSize: 13.5, lineHeight: 1.5 }} />
                    <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 8 }}>
                      <Button variant="ghost" size="sm" onClick={() => setNotesEdit(false)}>Cancel</Button>
                      <Button variant="primary" size="sm" icon="check" onClick={() => { onSaveCustomer({ ...sel, notes: notesDraft.trim() }); setNotesEdit(false); }}>Save note</Button>
                    </div>
                  </div>
                ) : sel.notes ? (
                  <div style={{ display: "flex", gap: 9, padding: "11px 13px", background: "var(--warn-soft)", borderRadius: "var(--r-sm)", alignItems: "flex-start" }}>
                    <Icon name="info" size={15} color="#a36a00" style={{ flex: "none", marginTop: 2 }} />
                    <span style={{ fontSize: 13, color: "#8a5a00", lineHeight: 1.5 }}>{sel.notes}</span>
                  </div>
                ) : (
                  <div style={{ fontSize: 12.5, color: "var(--fg-faint)", fontStyle: "italic" }}>No notes on this customer.</div>
                )}
              </div>

              {/* Booking requirements: pop-up alert + reference rules */}
              <div style={{ padding: "14px 22px 0" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Booking requirements</span>
                  <button onClick={() => setReqOpen(true)} style={{ display: "inline-flex", alignItems: "center", gap: 4, background: "var(--brand-soft)", border: "none", borderRadius: "var(--r-pill)", padding: "4px 10px", color: "var(--brand)", fontSize: 12, fontWeight: 500, cursor: "pointer" }}><Icon name="pencil" size={12} /> Edit</button>
                </div>
                {sel.bookingAlert ? (
                  <div style={{ display: "flex", gap: 9, padding: "11px 13px", background: "color-mix(in srgb, var(--danger), white 93%)", border: "1px solid var(--danger)", borderRadius: "var(--r-sm)", alignItems: "flex-start", marginBottom: 8 }}>
                    <Icon name="megaphone" size={15} color="var(--danger)" style={{ flex: "none", marginTop: 2 }} />
                    <span style={{ fontSize: 13, color: "var(--fg-strong)", lineHeight: 1.5 }}><strong>Pops up at booking:</strong> {sel.bookingAlert}</span>
                  </div>
                ) : <div style={{ fontSize: 12.5, color: "var(--fg-faint)", fontStyle: "italic", marginBottom: 8 }}>No booking pop-up set for this customer.</div>}
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {[["Reference 1", (sel.refConfig && sel.refConfig.ref1) || null], ["Reference 2", (sel.refConfig && sel.refConfig.ref2) || null]].map(([fb, cfg]) => (
                    <span key={fb} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, background: "var(--bg-mist)", borderRadius: 999, padding: "5px 12px", color: "var(--fg-body)" }}>
                      <Icon name="check" size={12} color={cfg && cfg.required ? "var(--danger)" : "var(--fg-faint)"} />
                      <strong style={{ color: "var(--fg-strong)" }}>{(cfg && cfg.label) || fb}</strong>
                      <span>{cfg && cfg.required ? "· mandatory" : "· optional"}{cfg && cfg.prefix ? ` · starts with “${cfg.prefix}”` : ""}</span>
                    </span>
                  ))}
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, padding: "16px 22px" }}>
                {/* Contacts */}
                <div>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 9 }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Contacts ({(sel.contacts || []).length})</span>
                    <button onClick={() => setContactOpen(true)} style={{ display: "inline-flex", alignItems: "center", gap: 4, background: "var(--brand-soft)", border: "none", borderRadius: "var(--r-pill)", padding: "4px 10px", color: "var(--brand)", fontSize: 12, fontWeight: 500, cursor: "pointer" }}><Icon name="plus" size={13} /> Add</button>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                    {(sel.contacts || []).map((p, i) => (
                      <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", background: "var(--bg-mist)", borderRadius: "var(--r-sm)" }}>
                        <span style={{ width: 28, height: 28, borderRadius: "50%", background: "var(--surface)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none", fontWeight: 700, fontSize: 11 }}>{p.name.split(/\s+/).map(w => w[0]).slice(0, 2).join("")}</span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-strong)" }}>{p.name}{p.role ? <span style={{ color: "var(--fg-mute)", fontWeight: 400 }}> · {p.role}</span> : null}</div>
                          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-mute)" }}>{[p.phone, p.email].filter(Boolean).join(" · ") || "—"}</div>
                        </div>
                      </div>
                    ))}
                    {(sel.contacts || []).length === 0 && <div style={{ fontSize: 12.5, color: "var(--fg-faint)", fontStyle: "italic" }}>No contacts on file.</div>}
                  </div>
                </div>
                {/* Favourite addresses */}
                <div>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 9 }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Favourite addresses ({(sel.addresses || []).length})</span>
                    <button onClick={() => setAddrOpen(true)} style={{ display: "inline-flex", alignItems: "center", gap: 4, background: "var(--brand-soft)", border: "none", borderRadius: "var(--r-pill)", padding: "4px 10px", color: "var(--brand)", fontSize: 12, fontWeight: 500, cursor: "pointer" }}><Icon name="plus" size={13} /> Add</button>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                    {(sel.addresses || []).map((a, i) => (
                      <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "8px 10px", background: "var(--bg-mist)", borderRadius: "var(--r-sm)" }}>
                        <span style={{ width: 28, height: 28, borderRadius: 8, background: "var(--surface)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="map-pin" size={14} /></span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-strong)" }}>{a.label}</div>
                          <div style={{ fontSize: 12, color: "var(--fg-mute)" }}>{a.unit ? a.unit + ", " : ""}{a.line}, {a.suburb}{a.postcode ? " " + a.postcode : ""}</div>
                        </div>
                      </div>
                    ))}
                    {(sel.addresses || []).length === 0 && <div style={{ fontSize: 12.5, color: "var(--fg-faint)", fontStyle: "italic" }}>No favourite addresses yet.</div>}
                  </div>
                </div>
              </div>
            </Card>

            {/* Booking history */}
            <Card pad={0} style={{ overflow: "hidden" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 16px", borderBottom: "1px solid var(--border)", flexWrap: "wrap" }}>
                <Icon name="history" size={16} color="var(--brand)" />
                <span style={{ fontSize: 14.5, fontWeight: 700, color: "var(--fg-strong)", flex: 1 }}>Booking history</span>
                <div style={{ display: "inline-flex", gap: 4, background: "var(--bg-mist)", padding: 3, borderRadius: "var(--r-pill)" }}>
                  {[["all", "All"], ["active", "Active"], ["Delivered", "Delivered"], ["Cancelled", "Cancelled"]].map(([k, l]) => (
                    <button key={k} onClick={() => setHistFilter(k)} style={{ padding: "5px 11px", borderRadius: "var(--r-pill)", border: "none", fontSize: 12, fontWeight: 600, background: histFilter === k ? "var(--surface)" : "transparent", color: histFilter === k ? "var(--brand)" : "var(--fg-mute)", cursor: "pointer" }}>{l}</button>
                  ))}
                </div>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 0.75fr 1.5fr 0.6fr 0.75fr", gap: 10, padding: "9px 16px", background: "var(--bg-mist)", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.7px", textTransform: "uppercase", color: "var(--fg-mute)" }}>
                <span>Booking</span><span>Type</span><span>Route</span><span style={{ textAlign: "right" }}>Total</span><span style={{ textAlign: "right" }}>Status</span>
              </div>
              {histShown.map(b => <CustHistoryRow key={b.tracking} b={b} currency={currency} />)}
              {histShown.length === 0 && <div style={{ padding: 32, textAlign: "center", fontSize: 13.5, color: "var(--fg-mute)" }}>{hist.length === 0 ? "No bookings yet for this customer." : "No bookings match this filter."}</div>}
            </Card>
          </div>
        ) : (
          <Card pad={48} style={{ textAlign: "center", borderStyle: "dashed", background: "var(--bg-mist)" }}>
            <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--fg-strong)" }}>Select a customer</div>
          </Card>
        )}
      </div>

      <AddCustomerModal open={newOpen} onClose={() => setNewOpen(false)} onSave={c => { onAddCustomer(c); setSelId(c.id); setNewOpen(false); }} />
      {sel && (
        <React.Fragment>
          <AddCustomerModal open={editOpen} onClose={() => setEditOpen(false)} seed={sel} onSave={c => { onSaveCustomer(c); setEditOpen(false); }} />
          <LodgeInquiryModal open={inqOpen} onClose={() => setInqOpen(false)} customer={sel} bookings={hist} onLodge={p => { onLodgeInquiry(sel, p); setInqOpen(false); }} />
          <AddContactModal open={contactOpen} onClose={() => setContactOpen(false)} onSave={p => { onAddContact(sel.id, p); setContactOpen(false); }} />
          <AddAddressModal open={addrOpen} onClose={() => setAddrOpen(false)} onSave={a => { onAddAddress(sel.id, a); setAddrOpen(false); }} />
          <BookingReqModal open={reqOpen} onClose={() => setReqOpen(false)} seed={sel} onSave={patch => { onSaveCustomer({ ...sel, ...patch }); setReqOpen(false); }} />
        </React.Fragment>
      )}
    </div>
  );
}

Object.assign(window, { CsrCustomers });
