// csr-customer.jsx — customer search, active-customer card, add-customer modal
const { useState: useStateCust, useRef: useRefCust, useEffect: useEffCust } = React;

/* Big command-style search: by name OR reference number */
function CustomerSearch({ customers, onSelect, onAddNew, autoFocus }) {
  const [q, setQ] = useStateCust("");
  const [open, setOpen] = useStateCust(false);
  const ref = useRefCust(null);
  useEffCust(() => { if (autoFocus && ref.current) ref.current.focus(); }, [autoFocus]);
  const ql = q.trim().toLowerCase();
  const results = ql ? customers.filter(c =>
    c.name.toLowerCase().includes(ql) || c.ref.toLowerCase().includes(ql) ||
    c.account.toLowerCase().includes(ql) || (c.phone || "").includes(ql)
  ).slice(0, 6) : [];
  return (
    <div style={{ position: "relative" }}>
      <div style={{ position: "relative" }}>
        <span style={{ position: "absolute", left: 16, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="search" size={20} /></span>
        <input ref={ref} value={q} placeholder="Search customer by name or reference number…"
          onChange={e => { setQ(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)}
          onBlur={() => setTimeout(() => setOpen(false), 180)}
          style={{ width: "100%", padding: "16px 16px 16px 48px", fontSize: 16, fontWeight: 500, color: "var(--fg-strong)",
            background: "var(--surface)", border: "1.5px solid var(--border-strong)", borderRadius: "var(--r-lg)", outline: "none" }} />
        <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-faint)", background: "var(--bg-mist)", padding: "3px 8px", borderRadius: 6 }}>⏎ to select</span>
      </div>
      {open && (ql ? (
        <div className="fade-in" style={{ position: "absolute", top: "calc(100% + 8px)", left: 0, right: 0, background: "var(--surface)", borderRadius: "var(--r-lg)", boxShadow: "var(--shadow-pop)", border: "1px solid var(--border)", padding: 6, zIndex: 60, maxHeight: 360, overflowY: "auto" }}>
          {results.map(c => (
            <button key={c.id} onMouseDown={() => { onSelect(c); setQ(""); setOpen(false); }} style={{
              display: "flex", alignItems: "center", gap: 13, width: "100%", textAlign: "left", padding: "12px 12px", borderRadius: "var(--r-sm)", border: "none", background: "transparent" }}
              onMouseEnter={e => e.currentTarget.style.background = "var(--bg-mist)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
              <span style={{ width: 40, height: 40, borderRadius: 10, background: "var(--brand-soft)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none", fontWeight: 700, fontSize: 14 }}>{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: 8 }}>
                  <span style={{ fontWeight: 600, fontSize: 14.5, color: "var(--fg-strong)" }}>{c.name}</span>
                  {c.priority && <Badge tone="accent">Priority</Badge>}
                  {c.broker && <Badge tone="brand">Broker</Badge>}
                  {c.status && c.status !== "active" && <Badge tone="danger">{c.status === "stop-trade" ? "Stop-trade" : "Inactive"}</Badge>}
                </span>
                <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-mute)", marginTop: 2 }}>{c.ref} · {c.account} · {c.suburb}</span>
              </span>
              <Icon name="arrow-right" size={16} color="var(--fg-faint)" />
            </button>
          ))}
          {results.length === 0 && (
            <div style={{ padding: "14px 12px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
              <span style={{ fontSize: 13.5, color: "var(--fg-mute)" }}>No customer matches “{q}”.</span>
              <Button size="sm" variant="primary" icon="plus" onMouseDown={() => { onAddNew(q); setOpen(false); }}>Add new</Button>
            </div>
          )}
        </div>
      ) : null)}
    </div>
  );
}

function AccountStatusPill({ status }) {
  const m = { active: { t: "Active", tone: "success", dot: "#22b86e" }, "stop-trade": { t: "Stop-trade", tone: "danger", dot: "var(--danger)" }, inactive: { t: "Inactive", tone: "neutral", dot: "var(--fg-faint)" } }[status] || { t: status || "Active", tone: "neutral", dot: "var(--fg-faint)" };
  return <Badge tone={m.tone}><StatusDot color={m.dot} pulse={status === "active"} /> {m.t}</Badge>;
}

/* Account validation gate: blocks stop-trade/inactive accounts, or requires the operator to
   verify the caller against the account access phrase before quoting (items 24–25). */
function AccountGate({ customer, onVerified }) {
  const blocked = customer.status === "stop-trade" || customer.status === "inactive";
  const [checked, setChecked] = useStateCust(false);
  if (blocked) {
    return (
      <Card pad={28} style={{ borderColor: "var(--danger)", background: "color-mix(in srgb, var(--danger), white 94%)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 13, marginBottom: 14 }}>
          <span style={{ width: 46, height: 46, borderRadius: 12, flex: "none", background: "var(--danger)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="alert-triangle" size={23} /></span>
          <div>
            <div style={{ fontSize: 18, fontWeight: 700, color: "var(--fg-strong)" }}>Booking blocked · {customer.status === "stop-trade" ? "Account on stop-trade" : "Account inactive"}</div>
            <div style={{ fontSize: 14, color: "var(--fg-body)" }}>Quoting is disabled for this account.</div>
          </div>
        </div>
        <div style={{ fontSize: 14, color: "var(--fg-body)", lineHeight: 1.5, padding: "13px 15px", background: "var(--surface)", borderRadius: "var(--r-md)", border: "1px solid var(--border)" }}>{customer.stopReason || "This account cannot be quoted at the moment. Refer to your team lead."}</div>
      </Card>
    );
  }
  return (
    <Card pad={28}>
      <div style={{ display: "flex", alignItems: "center", gap: 13, marginBottom: 16 }}>
        <span style={{ width: 46, height: 46, borderRadius: 12, flex: "none", background: "var(--brand-soft)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="shield" size={23} /></span>
        <div>
          <div style={{ fontSize: 18, fontWeight: 700, color: "var(--fg-strong)" }}>Verify the caller</div>
          <div style={{ fontSize: 14, color: "var(--fg-mute)" }}>{customer.broker ? "Broker account" : "Phone booking"} — confirm the caller with the account access phrase before booking.</div>
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "15px 17px", background: "var(--brand-soft)", borderRadius: "var(--r-md)", marginBottom: 16 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--brand)" }}>Account access phrase</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 22, fontWeight: 800, color: "var(--fg-strong)", letterSpacing: "1px" }}>{customer.accessPhrase || "—"}</div>
        </div>
        <span style={{ fontSize: 12, color: "var(--fg-mute)", maxWidth: 168, textAlign: "right", lineHeight: 1.4 }}>Ask the caller to confirm this. Don't read it out to them.</span>
      </div>
      <button onClick={() => setChecked(!checked)} style={{ display: "flex", gap: 12, alignItems: "flex-start", width: "100%", textAlign: "left", background: checked ? "var(--brand-soft)" : "var(--surface)", border: "1.5px solid " + (checked ? "var(--brand)" : "var(--border)"), borderRadius: "var(--r-md)", padding: "14px 15px", cursor: "pointer" }}>
        <span style={{ width: 22, height: 22, borderRadius: 6, flex: "none", marginTop: 1, border: "1.5px solid " + (checked ? "var(--brand)" : "var(--border-strong)"), background: checked ? "var(--brand)" : "transparent", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>{checked && <Icon name="check" size={14} color="#fff" />}</span>
        <span style={{ fontSize: 14, color: "var(--fg-body)", lineHeight: 1.5 }}>Caller verified — they correctly confirmed the account access phrase.</span>
      </button>
      <div style={{ display: "flex", gap: 10, marginTop: 16, flexWrap: "wrap" }}>
        <Button variant="primary" size="lg" iconRight="arrow-right" disabled={!checked} onClick={onVerified}>Continue — caller verified</Button>
      </div>
      <div style={{ fontSize: 11.5, color: "var(--fg-faint)", marginTop: 10 }}>Security note: this is an <strong>access phrase</strong>, not a password. Accounts without a phrase on file skip this step.</div>
    </Card>
  );
}

function CustomerCard({ customer, onClear, onAddAddress }) {
  const [addOpen, setAddOpen] = useStateCust(false);
  if (!customer) return null;
  const c = customer;
  const addresses = c.addresses || [];
  return (
    <Card pad={0} style={{ overflow: "hidden" }}>
      <div style={{ background: "var(--brand)", color: "#fff", padding: "16px 18px", display: "flex", alignItems: "center", gap: 13 }}>
        <span style={{ width: 44, height: 44, borderRadius: 11, background: "rgba(255,255,255,0.16)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none", fontWeight: 800, fontSize: 16 }}>{c.name.split(/\s+/).map(w => w[0]).slice(0,2).join("")}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontWeight: 700, fontSize: 16, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</span>
            {c.priority && <Badge style={{ background: "var(--accent)", color: "#fff" }}>Priority</Badge>}
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, opacity: 0.8, marginTop: 2 }}>{c.ref} · {c.account}</div>
        </div>
        <button onClick={onClear} title="Change customer" style={{ background: "rgba(255,255,255,0.14)", border: "none", borderRadius: 8, width: 32, height: 32, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "#fff", flex: "none" }}><Icon name="x" size={16} /></button>
      </div>
      <div style={{ padding: "14px 18px" }}>
        {/* CE account panel: type, status, broker, access phrase, third-party auth */}
        <div style={{ marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap", marginBottom: 10 }}>
            <AccountStatusPill status={c.status} />
            <span style={{ fontSize: 11.5, fontWeight: 600, background: "var(--bg-mist)", color: "var(--fg-body)", borderRadius: 999, padding: "3px 9px" }}>{c.type || "Account"}</span>
            {c.broker && <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 700, background: "var(--accent-soft)", color: "var(--accent-700)", borderRadius: 999, padding: "3px 9px" }}><Icon name="shield" size={11} /> Broker</span>}
          </div>
          {c.broker && c.brokerName && <div style={{ fontSize: 12, color: "var(--fg-mute)", marginBottom: 10 }}>Broker: <strong style={{ color: "var(--fg-strong)" }}>{c.brokerName}</strong></div>}
          {c.accessPhrase && (
            <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", background: "var(--brand-soft)", borderRadius: "var(--r-sm)", marginBottom: (c.thirdPartyAuth && c.thirdPartyAuth.length) ? 10 : 0 }}>
              <Icon name="shield" size={15} color="var(--brand)" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.6px", textTransform: "uppercase", color: "var(--brand)" }}>Account access phrase</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 14, fontWeight: 700, color: "var(--fg-strong)", letterSpacing: "0.5px" }}>{c.accessPhrase}</div>
              </div>
              <span style={{ fontSize: 10, color: "var(--fg-mute)", textAlign: "right", maxWidth: 88, lineHeight: 1.35 }}>Verify caller before booking</span>
            </div>
          )}
          {c.thirdPartyAuth && c.thirdPartyAuth.length > 0 && (
            <div style={{ padding: "8px 11px", background: "var(--bg-mist)", borderRadius: "var(--r-sm)" }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.6px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Authorised to book on this account</span>
              {c.thirdPartyAuth.map((tp, i) => (<div key={i} style={{ fontSize: 12.5, color: "var(--fg-strong)", marginTop: 4 }}>{tp.name} <span style={{ color: "var(--fg-mute)", fontFamily: "var(--font-mono)", fontSize: 11 }}>· {tp.account}</span></div>))}
            </div>
          )}
        </div>
        {c.notes && (
          <div style={{ display: "flex", gap: 9, padding: "10px 12px", background: "var(--warn-soft)", borderRadius: "var(--r-sm)", marginBottom: 12, alignItems: "flex-start" }}>
            <Icon name="info" size={14} color="#a36a00" style={{ flex: "none", marginTop: 2 }} />
            <span style={{ fontSize: 12.5, color: "#8a5a00", lineHeight: 1.45 }}>{c.notes}</span>
          </div>
        )}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
          <Meta icon="wallet" label="Terms" value={c.terms} />
          <Meta icon="map-pin" label="Base" value={c.suburb} />
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 12 }}>
          <Meta icon="phone" label="Phone" value={c.phone} mono wrap />
          <Meta icon="mail" label="Email" value={c.email} wrap />
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)", marginBottom: 8 }}>Contacts ({c.contacts.length})</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
          {c.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} <span style={{ color: "var(--fg-mute)", fontWeight: 400 }}>· {p.role}</span></div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-mute)" }}>{p.phone}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Address book history */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "16px 0 8px" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Address book ({addresses.length})</span>
          <button onClick={() => setAddOpen(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 }}><Icon name="plus" size={13} /> Add</button>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
          {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>
          ))}
          {addresses.length === 0 && <div style={{ fontSize: 12.5, color: "var(--fg-faint)", fontStyle: "italic", padding: "4px 2px" }}>No saved addresses yet.</div>}
        </div>
      </div>
      <AddAddressModal open={addOpen} onClose={() => setAddOpen(false)} onSave={a => { onAddAddress && onAddAddress(c.id, a); setAddOpen(false); }} />
    </Card>
  );
}

function AddAddressModal({ open, onClose, onSave }) {
  const blank = { label: "", line: "", unit: "", suburb: "", postcode: "", contact: "", phone: "" };
  const [f, setF] = useStateCust(blank);
  useEffCust(() => { if (open) setF(blank); }, [open]);
  const set = (k, v) => setF(prev => ({ ...prev, [k]: v }));
  const valid = f.label && f.line && f.suburb;
  return (
    <Modal open={open} onClose={onClose} title="Add address to customer" width={520}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label="Label *" hint="How this address appears in the customer's book"><TextInput value={f.label} onChange={v => set("label", v)} placeholder="e.g. Warehouse 2" /></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 12 }}>
          <Field label="Unit / level"><TextInput value={f.unit} onChange={v => set("unit", v)} placeholder="Unit 4" /></Field>
          <Field label="Street address *"><TextInput value={f.line} onChange={v => set("line", v)} placeholder="123 George St" /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
          <Field label="Suburb *"><Select value={f.suburb} onChange={v => set("suburb", v)} options={window.FX.suburbNames()} placeholder="Select suburb" /></Field>
          <Field label="Postcode"><TextInput value={f.postcode} onChange={v => set("postcode", v)} placeholder="2000" mono /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Contact"><TextInput value={f.contact} onChange={v => set("contact", v)} placeholder="Jane Smith" /></Field>
          <Field label="Phone"><TextInput value={f.phone} onChange={v => set("phone", v)} placeholder="+61 4xx xxx xxx" mono /></Field>
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" full icon="check" onClick={() => valid && onSave(f)} disabled={!valid}>Save to address book</Button>
        </div>
      </div>
    </Modal>
  );
}
function Meta({ icon, label, value, mono, small, wrap }) {
  return (
    <div style={{ display: "flex", alignItems: wrap ? "flex-start" : "center", gap: 8, minWidth: 0 }}>
      <Icon name={icon} size={15} color="var(--fg-faint)" style={{ flex: "none", marginTop: wrap ? 2 : 0 }} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 10.5, color: "var(--fg-mute)", fontFamily: "var(--font-mono)", letterSpacing: "0.5px", textTransform: "uppercase" }}>{label}</div>
        <div style={{ fontSize: small ? 11.5 : 13, fontWeight: 500, color: "var(--fg-strong)", marginTop: 1, whiteSpace: wrap ? "normal" : "nowrap", overflow: wrap ? "visible" : "hidden", textOverflow: wrap ? "clip" : "ellipsis", wordBreak: wrap ? "break-word" : "normal", fontFamily: mono ? "var(--font-mono)" : "var(--font-sans)" }}>{value}</div>
      </div>
    </div>
  );
}

/* Add-customer modal: ref + account + details + contact people */
function AddCustomerModal({ open, onClose, onSave, prefillName, seed }) {
  const blank = { ref: "", name: prefillName || "", account: "", terms: "Account · Net 30", phone: "", email: "", suburb: "", priority: false,
    type: "Corporate account", status: "active", accessPhrase: "", broker: false, brokerName: "", notes: "",
    contacts: [{ name: "", role: "", phone: "", email: "" }] };
  const [f, setF] = useStateCust(blank);
  useEffCust(() => {
    if (!open) return;
    if (seed) setF({ ...blank, ...seed, contacts: (seed.contacts && seed.contacts.length) ? seed.contacts : blank.contacts });
    else setF({ ...blank, name: prefillName || "" });
  }, [open, seed]);
  const set = (k, v) => setF(prev => ({ ...prev, [k]: v }));
  const setContact = (i, k, v) => setF(prev => ({ ...prev, contacts: prev.contacts.map((c, idx) => idx === i ? { ...c, [k]: v } : c) }));
  const addContact = () => setF(prev => ({ ...prev, contacts: [...prev.contacts, { name: "", role: "", phone: "", email: "" }] }));
  const rmContact = (i) => setF(prev => ({ ...prev, contacts: prev.contacts.filter((_, idx) => idx !== i) }));
  const valid = f.name && f.ref && f.account;
  function save() {
    if (!valid) return;
    onSave({ ...(seed || {}), ...f, id: seed ? seed.id : "c" + Date.now(), contacts: f.contacts.filter(c => c.name) });
  }
  return (
    <Modal open={open} onClose={onClose} title={seed ? "Edit customer" : "Add new customer"} width={620}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Customer reference *"><TextInput value={f.ref} onChange={v => set("ref", v)} placeholder="CUST-00000" mono /></Field>
          <Field label="Account number *"><TextInput value={f.account} onChange={v => set("account", v)} placeholder="FX-AU-000000" mono /></Field>
        </div>
        <Field label="Business name *"><TextInput value={f.name} onChange={v => set("name", v)} placeholder="Acme Pty Ltd" /></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 12 }}>
          <Field label="Billing terms"><Select value={f.terms} onChange={v => set("terms", v)} options={["Account · Net 30", "Account · Net 14", "Account · Net 7", "Prepaid · Card", "COD"]} /></Field>
          <Field label="Base suburb"><Select value={f.suburb} onChange={v => set("suburb", v)} options={window.FX.suburbNames()} placeholder="Suburb" /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: 12 }}>
          <Field label="Main phone"><TextInput value={f.phone} onChange={v => set("phone", v)} placeholder="+61 2 0000 0000" mono /></Field>
          <Field label="Account email"><TextInput value={f.email} onChange={v => set("email", v)} placeholder="accounts@company.com.au" /></Field>
        </div>
        <button onClick={() => set("priority", !f.priority)} style={{ display: "flex", alignItems: "center", gap: 10, background: "transparent", border: "none", padding: 0, textAlign: "left" }}>
          <span style={{ width: 38, height: 22, borderRadius: 999, flex: "none", background: f.priority ? "var(--accent)" : "var(--bg-mist-2)", position: "relative", transition: "all 160ms ease" }}>
            <span style={{ position: "absolute", top: 2, left: f.priority ? 18 : 2, width: 18, height: 18, borderRadius: "50%", background: "#fff", transition: "all 160ms ease" }} />
          </span>
          <span style={{ fontSize: 14, color: "var(--fg-strong)", fontWeight: 500 }}>Flag as priority customer</span>
        </button>

        <div style={{ borderTop: "1px solid var(--border)", paddingTop: 14, display: "flex", flexDirection: "column", gap: 14 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-strong)" }}>Account &amp; security</span>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Field label="Customer type"><Select value={f.type} onChange={v => set("type", v)} options={["Corporate account", "Government / Health", "Retail account", "Clinical / Research", "Small business"]} /></Field>
            <Field label="Account status"><Select value={f.status} onChange={v => set("status", v)} options={[{ value: "active", label: "Active" }, { value: "stop-trade", label: "Stop-trade — block bookings" }, { value: "inactive", label: "Inactive" }]} /></Field>
          </div>
          <Field label="Account access phrase" hint="The caller must confirm this before an operator can quote. Not a password."><TextInput value={f.accessPhrase} onChange={v => set("accessPhrase", v.toUpperCase())} placeholder="e.g. MERIDIAN-4417" mono /></Field>
          <button onClick={() => set("broker", !f.broker)} style={{ display: "flex", alignItems: "center", gap: 10, background: "transparent", border: "none", padding: 0, textAlign: "left", cursor: "pointer" }}>
            <span style={{ width: 38, height: 22, borderRadius: 999, flex: "none", background: f.broker ? "var(--brand)" : "var(--bg-mist-2)", position: "relative", transition: "all 160ms ease" }}>
              <span style={{ position: "absolute", top: 2, left: f.broker ? 18 : 2, width: 18, height: 18, borderRadius: "50%", background: "#fff", transition: "all 160ms ease" }} />
            </span>
            <span style={{ fontSize: 14, color: "var(--fg-strong)", fontWeight: 500 }}>Broker account — caller verification required</span>
          </button>
          {f.broker && <Field label="Broker name"><TextInput value={f.brokerName} onChange={v => set("brokerName", v)} placeholder="e.g. Acme Global Forwarding" /></Field>}
          <Field label="Customer notes" hint="Shown to every operator who opens this customer.">
            <textarea value={f.notes} onChange={e => set("notes", 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 }} />
          </Field>
        </div>

        <div style={{ borderTop: "1px solid var(--border)", paddingTop: 14 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-strong)" }}>Contact people</span>
            <Button size="sm" variant="ghost" icon="plus" onClick={addContact}>Add contact</Button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {f.contacts.map((c, i) => (
              <div key={i} style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", padding: 12 }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 30px", gap: 10, alignItems: "end" }}>
                  <Field label={i === 0 ? "Name" : ""}><TextInput value={c.name} onChange={v => setContact(i, "name", v)} placeholder="Jane Smith" /></Field>
                  <Field label={i === 0 ? "Role" : ""}><TextInput value={c.role} onChange={v => setContact(i, "role", v)} placeholder="Dispatch" /></Field>
                  {f.contacts.length > 1 ? <button onClick={() => rmContact(i)} style={{ background: "var(--bg-mist)", border: "none", borderRadius: 8, width: 30, height: 38, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--fg-mute)" }}><Icon name="x" size={14} /></button> : <span />}
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 10 }}>
                  <TextInput value={c.phone} onChange={v => setContact(i, "phone", v)} placeholder="+61 4xx xxx xxx" mono />
                  <TextInput value={c.email} onChange={v => setContact(i, "email", v)} placeholder="email@company.com.au" />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" full icon="check" onClick={save} disabled={!valid}>{seed ? "Save changes" : "Save customer & continue"}</Button>
        </div>
      </div>
    </Modal>
  );
}

/* Customer overview shown when an operator selects a customer in take-a-booking:
   their booking history + quotes, with new / open / duplicate / convert actions. */
function CustomerOverview({ customer, bookings, quotes, currency, onNewBooking, onOpen, onDuplicate, onConvertQuote, onEditBooking }) {
  const money = (n) => window.FX.money(n, currency);
  const bTone = (s) => s === "Delivered" ? "success" : s === "Cancelled" ? "danger" : s === "In transit" ? "brand" : "neutral";
  const bDot = (s) => s === "Delivered" ? "#22b86e" : s === "Cancelled" ? "var(--danger)" : s === "In transit" ? "var(--brand)" : "var(--fg-mute)";
  const recent = [...bookings].sort((a, b) => new Date(b.placedAt || 0) - new Date(a.placedAt || 0));
  const openQuotes = [...quotes].sort((a, b) => new Date(b.createdAt || 0) - new Date(a.createdAt || 0));
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <div>
          <div style={{ fontSize: 16.5, fontWeight: 700, color: "var(--fg-strong)" }}>Customer overview</div>
          <div style={{ fontSize: 13, color: "var(--fg-mute)", marginTop: 2 }}>{recent.length} booking{recent.length === 1 ? "" : "s"} · {openQuotes.length} quote{openQuotes.length === 1 ? "" : "s"} on file</div>
        </div>
        <Button variant="primary" icon="plus" onClick={onNewBooking}>New booking</Button>
      </div>

      {/* Booking history */}
      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "13px 18px 11px" }}>
          <Icon name="history" size={15} color="var(--brand)" />
          <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)" }}>Booking history</span>
        </div>
        {recent.length === 0 && <div style={{ padding: "0 18px 18px", fontSize: 13, color: "var(--fg-mute)" }}>No bookings yet for this customer.</div>}
        {recent.map((b, i) => (
          <div key={b.tracking} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 18px", borderTop: "1px solid var(--border)" }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 700, color: "var(--brand)", width: 108, flex: "none" }}>{b.tracking}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{b.pickup ? b.pickup.suburb : "?"} → {b.dropoff ? b.dropoff.suburb : "?"}</div>
              <div style={{ fontSize: 11.5, color: "var(--fg-mute)" }}>{b.date ? window.FX.fmtDate(b.date) : ""}{b.total ? " · " + money(b.total) : ""}</div>
            </div>
            <Badge tone={bTone(b.status)}><StatusDot color={bDot(b.status)} pulse={b.status === "In transit"} /> {b.status}</Badge>
            <button onClick={() => onOpen(b)} title="Open booking" style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8, padding: "6px 11px", fontSize: 12.5, fontWeight: 600, color: "var(--fg-body)", cursor: "pointer" }}>Open</button>
            <button onClick={() => onDuplicate(b)} title="Duplicate as a new booking" style={{ display: "inline-flex", alignItems: "center", gap: 5, background: "var(--brand-soft)", border: "none", borderRadius: 8, padding: "6px 11px", fontSize: 12.5, fontWeight: 600, color: "var(--brand)", cursor: "pointer" }}><Icon name="plus" size={13} /> Duplicate</button>
          </div>
        ))}
      </Card>

      {/* Quotes */}
      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "13px 18px 11px" }}>
          <Icon name="calculator" size={15} color="var(--brand)" />
          <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)" }}>Quotes</span>
        </div>
        {openQuotes.length === 0 && <div style={{ padding: "0 18px 18px", fontSize: 13, color: "var(--fg-mute)" }}>No quotes on file for this customer.</div>}
        {openQuotes.map((qt) => (
          <div key={qt.no} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 18px", borderTop: "1px solid var(--border)" }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 700, color: "var(--brand)", width: 108, flex: "none" }}>{qt.no}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{qt.from} → {qt.to}</div>
              <div style={{ fontSize: 11.5, color: "var(--fg-mute)" }}>{money(qt.total)}{qt.source === "agent" ? " · " + (qt.agentName || "agent") : " · customer"}</div>
            </div>
            {window.QuoteStatusPill ? <QuoteStatusPill q={qt} /> : null}
            {qt.status === "booked"
              ? <span style={{ fontSize: 11.5, color: "var(--fg-mute)", fontFamily: "var(--font-mono)" }}>{qt.convertedBookingTracking || ""}</span>
              : <button onClick={() => onConvertQuote(qt)} style={{ display: "inline-flex", alignItems: "center", gap: 5, background: "var(--brand)", border: "none", borderRadius: 8, padding: "6px 12px", fontSize: 12.5, fontWeight: 600, color: "#fff", cursor: "pointer" }}>Convert <Icon name="arrow-right" size={13} /></button>}
          </div>
        ))}
      </Card>
    </div>
  );
}

Object.assign(window, { CustomerSearch, CustomerCard, AddCustomerModal, AddAddressModal, AccountGate, AccountStatusPill, CustomerOverview });
