/* Stratum Leads — Operations Console. Customers: searchable directory + a
   360 account view (Overview / Wallet & Billing / Lead Access / Tickets /
   Activity as separate tabs — never merged onto one screen). Also owns the
   shared Adjust Wallet drawer, since every wallet action ultimately touches
   a customer record. */

/* Design-system components — each Babel script has its own scope, so every
   ops-*.jsx file must destructure what it needs from the namespace. */
const { NavItem, IconButton, WalletPill, Tabs, LeadCard, Button, Field, Card, Metric, StatusChip, TierBadge, ContactQuality, ProgressBar, StrataAmount, Checkbox, Switch, Avatar, AvatarStack, SegmentedControl, GateCard, EmptyState, Toast } = window.StratumLeadsDesignSystem_6367ed;

const { I, fmtStrata, fmtSigned, getCustomer, TICKET_STATUS_TONE, PRIORITY_TONE, HEALTH_TONE, HEALTH_LABEL, VAULT_TONE, SideDrawer, IconCheckCircle } = window.OpsShared;

const PLAN_OPTIONS = ["Starter", "Professional", "Enterprise"];
const ADJUST_TYPES = [
{ value: "credit", label: "Support credit", sign: 1 },
{ value: "debit", label: "Debit / correction", sign: -1 },
{ value: "refund", label: "Refund", sign: 1 },
{ value: "chargeback", label: "Chargeback correction", sign: -1 }];

const REASON_CODES = [
"Payment authorized, balance not updated",
"Duplicate charge",
"Customer service goodwill",
"Chargeback resolution",
"Billing correction",
"Other (see note)"];


/* ---------------- Shared Adjust Wallet drawer ---------------- */
function AdjustWalletDrawer({ ctx, customers, onClose, onApply }) {
  const customer = customers.find((c) => c.id === ctx.customerId);
  const [type, setType] = React.useState("credit");
  const [amount, setAmount] = React.useState("");
  const [reason, setReason] = React.useState("");
  const [note, setNote] = React.useState("");
  if (!customer) return null;

  const num = parseFloat(amount) || 0;
  const meta = ADJUST_TYPES.find((t) => t.value === type);
  const delta = meta.sign * num;
  const newBalance = customer.wallet.available + delta;
  const valid = num > 0 && reason !== "";

  return (
    <SideDrawer title="Adjust Wallet" subtitle={customer.name} icon={I("wallet-cards")} onClose={onClose} footer={
    <React.Fragment>
        <Button variant="secondary" onClick={onClose}>Cancel</Button>
        <Button variant="primary" icon={I("check", { width: 15 })} disabled={!valid} onClick={() => onApply({ customerId: customer.id, ticketId: ctx.ticketId, type, amount: num, reasonLabel: reason, note: note.trim() })}>Apply Adjustment</Button>
      </React.Fragment>
    }>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Metric icon={I("coins")} value={fmtStrata(customer.wallet.available)} label="Available Strata" accent="violet" />
        <Metric icon={I("lock")} value={fmtStrata(customer.wallet.escrowed)} label="Escrowed" accent="cyan" />
      </div>
      <Field label="Adjustment type" as="select" value={type} onChange={(e) => setType(e.target.value)}>
        {ADJUST_TYPES.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
      </Field>
      <Field label="Amount (Strata)" type="number" min="0" step="0.25" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="0.00" />
      <Field label="Reason code" as="select" value={reason} onChange={(e) => setReason(e.target.value)}>
        <option value="">Select a reason</option>
        {REASON_CODES.map((r) => <option key={r} value={r}>{r}</option>)}
      </Field>
      <Field label="Note (optional)" as="textarea" rows={2} value={note} onChange={(e) => setNote(e.target.value)} placeholder="Context for the audit trail" />
      {num > 0 &&
      <Card padding={true} style={{ boxShadow: "none", background: "var(--surface-subtle)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
            <span style={{ color: "var(--text-muted)" }}>New balance will be</span>
            <StrataAmount amount={Math.max(0, newBalance)} />
          </div>
        </Card>
      }
    </SideDrawer>);

}

/* ---------------- Directory ---------------- */
function CustomerRow({ c, ticketCount, onClick }) {
  return (
    <button onClick={onClick} style={{ display: "grid", gridTemplateColumns: "auto 1.6fr 1fr 1fr 1fr auto", alignItems: "center", gap: 14, width: "100%", textAlign: "left", padding: "13px 16px", border: "none", borderBottom: "1px solid var(--border-subtle)", background: "var(--surface)", cursor: "pointer" }}>
      <Avatar name={c.name} initials={c.initials} size={34} style={{ fontWeight: 800, fontSize: 12 }} />
      <span style={{ minWidth: 0 }}>
        <strong style={{ display: "block", fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</strong>
        <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{c.id} · {c.location}</span>
      </span>
      <span style={{ fontSize: 13 }}>{c.plan.name}</span>
      <StrataAmount amount={c.wallet.available} size="sm" />
      <StatusChip tone={HEALTH_TONE[c.health]}>{HEALTH_LABEL[c.health]}</StatusChip>
      <span style={{ fontSize: 12, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{ticketCount} ticket{ticketCount === 1 ? "" : "s"}</span>
    </button>);

}

/* ---------------- Detail tabs ---------------- */
function OverviewTab({ customer, onUpdateOwner, onResetPassword }) {
  const [editing, setEditing] = React.useState(false);
  const [name, setName] = React.useState(customer.owner.name);
  const [email, setEmail] = React.useState(customer.owner.email);
  const [phone, setPhone] = React.useState(customer.owner.phone);
  const [location, setLocation] = React.useState(customer.location);
  React.useEffect(() => {setName(customer.owner.name);setEmail(customer.owner.email);setPhone(customer.owner.phone);setLocation(customer.location);setEditing(false);}, [customer.id]);
  React.useEffect(refresh, [editing]);

  const save = () => {
    onUpdateOwner(customer.id, { name: name.trim(), email: email.trim(), phone: phone.trim(), location: location.trim() });
    setEditing(false);
  };
  const cancel = () => {
    setName(customer.owner.name);setEmail(customer.owner.email);setPhone(customer.owner.phone);setLocation(customer.location);
    setEditing(false);
  };

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
      <Card title="Account owner" note={editing ? "Editing — changes are logged to Activity" : undefined} actions={
      !editing && <IconButton label="Edit account owner" variant="ghost" onClick={() => setEditing(true)}>{I("pencil", { width: 15 })}</IconButton>
      }>
        {editing ?
        <div style={{ display: "grid", gap: 10 }}>
            <Field label="Name" value={name} onChange={(e) => setName(e.target.value)} />
            <Field label="Email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
            <Field label="Phone" value={phone} onChange={(e) => setPhone(e.target.value)} />
            <Field label="Location" value={location} onChange={(e) => setLocation(e.target.value)} />
            <DetailRow k="Customer since" v={customer.createdAt} />
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 4 }}>
              <Button size="sm" variant="secondary" onClick={cancel}>Cancel</Button>
              <Button size="sm" variant="primary" disabled={!name.trim() || !email.trim()} icon={I("check", { width: 14 })} onClick={save}>Save</Button>
            </div>
          </div> :

        <React.Fragment>
            <DetailRow k="Name" v={customer.owner.name} />
            <DetailRow k="Email" v={customer.owner.email} />
            <DetailRow k="Phone" v={customer.owner.phone} />
            <DetailRow k="Location" v={customer.location} />
            <DetailRow k="Customer since" v={customer.createdAt} />
          </React.Fragment>
        }
      </Card>
      <Card title="Users" note={`${customer.users.length} on this account`}>
        <div style={{ display: "grid", gap: 10 }}>
          {customer.users.map((u, i) =>
          <div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, paddingBottom: i < customer.users.length - 1 ? 10 : 0, borderBottom: i < customer.users.length - 1 ? "1px solid var(--border-subtle)" : "none" }}>
              <span style={{ minWidth: 0 }}>
                <strong style={{ display: "block", fontSize: 13 }}>{u.name} <span style={{ fontWeight: 500, color: "var(--text-muted)" }}>· {u.role}</span></strong>
                <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{u.email} · last login {u.lastLogin}</span>
              </span>
              <span style={{ display: "flex", alignItems: "center", gap: 8, flexShrink: 0 }}>
                <StatusChip tone={u.verified ? "success" : "warning"}>{u.verified ? "Verified" : "Unverified"}</StatusChip>
                <IconButton label={`Send password reset to ${u.email}`} variant="ghost" onClick={() => onResetPassword(customer.id, u.email)}>{I("mail", { width: 14 })}</IconButton>
              </span>
            </div>
          )}
        </div>
      </Card>
    </div>);

}
function DetailRow({ k, v }) {
  return <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "7px 0", borderBottom: "1px solid var(--border-subtle)", fontSize: 13 }}><span style={{ color: "var(--text-muted)" }}>{k}</span><span style={{ fontWeight: 600, textAlign: "right" }}>{v}</span></div>;
}

function WalletTab({ customer, ledger, onOpenAdjustWallet, onChangePlan, onResendInvoice, onSendCardUpdateLink }) {
  const [plan, setPlan] = React.useState(customer.plan.name);
  const [openInvoice, setOpenInvoice] = React.useState(null);
  const rows = ledger.filter((l) => l.customerId === customer.id);
  return (
    <div style={{ display: "grid", gap: 16 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr auto", gap: 12, alignItems: "center" }}>
        <Metric icon={I("coins")} value={fmtStrata(customer.wallet.available)} label="Available Strata" accent="violet" />
        <Metric icon={I("lock")} value={fmtStrata(customer.wallet.escrowed)} label="Escrowed in active bids" accent="cyan" />
        <Button variant="primary" icon={I("wallet-cards", { width: 15 })} onClick={() => onOpenAdjustWallet({ customerId: customer.id })}>Adjust Wallet</Button>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <Card title="Subscription">
          <DetailRow k="Plan" v={
          <span style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <Field as="select" value={plan} onChange={(e) => setPlan(e.target.value)} style={{ minWidth: 140 }}>
                  {PLAN_OPTIONS.map((p) => <option key={p} value={p}>{p}</option>)}
                </Field>
                {plan !== customer.plan.name && <Button size="sm" variant="primary" onClick={() => onChangePlan(customer.id, plan)}>Apply</Button>}
              </span>
          } />
          <DetailRow k="Status" v={<StatusChip tone={customer.plan.status === "active" ? "success" : customer.plan.status === "past_due" ? "danger" : "info"}>{customer.plan.status.replace("_", " ")}</StatusChip>} />
          <DetailRow k="Renews" v={customer.plan.renews} />
          <DetailRow k="Payment method" v={
          <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                {customer.payment.brand ? `${customer.payment.brand} \u2022\u2022\u2022\u2022 ${customer.payment.last4}` : "None on file"}
                <Button size="sm" variant="ghost" icon={I("send", { width: 12 })} onClick={() => onSendCardUpdateLink(customer.id)}>Send Update Link</Button>
              </span>
          } />
        </Card>
        <Card title="Invoices" note={`${customer.invoices.length} total`}>
          {customer.invoices.length === 0 ?
          <EmptyState icon="receipt" title="No invoices yet" /> :

          customer.invoices.map((inv, i) =>
          <button key={inv.id} onClick={() => setOpenInvoice(inv)} style={{ display: "flex", width: "100%", justifyContent: "space-between", padding: "8px 0", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)", border: "none", borderTopWidth: i === 0 ? 0 : 1, borderTopStyle: "solid", borderTopColor: "var(--border-subtle)", background: "transparent", cursor: "pointer", fontSize: 13, textAlign: "left", font: "inherit", color: "inherit" }}>
                <span>{inv.id} <span style={{ color: "var(--text-muted)" }}>· {inv.date}</span></span>
                <span style={{ display: "flex", gap: 8, alignItems: "center" }}><StrataAmount amount={inv.amount} size="sm" /><StatusChip tone={inv.status === "paid" ? "success" : "danger"}>{inv.status}</StatusChip></span>
              </button>
          )
          }
        </Card>
      </div>
      <Card title="Wallet ledger" note={`${rows.length} transactions`}>
        {rows.length === 0 ?
        <EmptyState icon="list" title="No transactions yet" /> :

        <div style={{ display: "grid" }}>
            {rows.map((r, i) =>
          <div key={r.id} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", gap: 12, alignItems: "center", padding: "9px 0", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)", fontSize: 13 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-muted)" }}>{r.createdAt}</span>
                <span style={{ color: "var(--text-muted)" }}>{r.note}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: r.amount < 0 ? "var(--danger)" : "var(--success)" }}>{fmtSigned(r.amount)}</span>
                <StatusChip tone={r.status === "succeeded" ? "success" : r.status === "failed" ? "danger" : "warning"}>{r.status}</StatusChip>
              </div>
          )}
          </div>
        }
      </Card>
      {openInvoice &&
      <SideDrawer title={openInvoice.id} subtitle={customer.name} icon={I("receipt")} onClose={() => setOpenInvoice(null)} footer={
      <Button variant="primary" icon={I("send", { width: 15 })} onClick={() => onResendInvoice(customer.id, openInvoice.id)}>Resend Invoice</Button>
      }>
          <DetailRow k="Invoice" v={openInvoice.id} />
          <DetailRow k="Date" v={openInvoice.date} />
          <DetailRow k="Amount" v={<StrataAmount amount={openInvoice.amount} size="sm" />} />
          <DetailRow k="Status" v={<StatusChip tone={openInvoice.status === "paid" ? "success" : "danger"}>{openInvoice.status}</StatusChip>} />
        </SideDrawer>
      }
    </div>);

}

function AssignLeadModal({ leadQueue, customer, onClose, onAssign }) {
  const [query, setQuery] = React.useState("");
  const [selectedId, setSelectedId] = React.useState(null);
  React.useEffect(refresh, [selectedId]);
  const q = query.trim().toLowerCase();
  const pool = leadQueue.filter((l) => l.status === "verified");
  const rows = (q === "" ? pool : pool.filter((l) => l.address.toLowerCase().includes(q) || l.trigger.toLowerCase().includes(q) || l.cityZip.toLowerCase().includes(q))).slice(0, 20);
  const selected = pool.find((l) => l.id === selectedId) || null;

  return (
    <SideDrawer title="Assign a Lead" subtitle={`To ${customer.name}`} icon={I("key-round")} onClose={onClose} footer={
    <React.Fragment>
        <Button variant="secondary" onClick={onClose}>Cancel</Button>
        <Button variant="primary" icon={I("check", { width: 15 })} disabled={!selected} onClick={() => onAssign(selected)}>Assign to Vault</Button>
      </React.Fragment>
    }>
      <Field icon={I("search")} placeholder="Search verified leads by address, trigger, or city..." value={query} onChange={(e) => setQuery(e.target.value)} />
      <div style={{ display: "grid", gap: 2, maxHeight: 440, overflowY: "auto" }}>
        {rows.length === 0 ?
        <EmptyState icon="radar" title="No matching leads" message="Try a different search term." /> :

        rows.map((l) =>
        <button key={l.id} onClick={() => setSelectedId(l.id)} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 10, alignItems: "center", width: "100%", textAlign: "left", padding: "10px 8px", border: "none", borderRadius: "var(--radius-sm)", borderLeft: selectedId === l.id ? "3px solid var(--accent)" : "3px solid transparent", background: selectedId === l.id ? "var(--accent-soft)" : "transparent", cursor: "pointer" }}>
              <TierBadge tier={l.tier} />
              <span style={{ minWidth: 0 }}>
                <strong style={{ display: "block", fontSize: 13 }}>{l.address}</strong>
                <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{l.cityZip} · {l.trigger}</span>
              </span>
              {selectedId === l.id ? <IconCheckCircle size={16} style={{ color: "var(--accent)" }} /> : <span style={{ width: 16 }} />}
            </button>
        )}
      </div>
    </SideDrawer>);

}

function LeadAccessTab({ customer, leadQueue, onResendVault, onAssignLead }) {
  const [assigning, setAssigning] = React.useState(false);
  return (
    <React.Fragment>
    <Card title="Won leads" note={`${customer.wonLeads.length} won`} actions={
    <IconButton label="Assign a lead" onClick={() => setAssigning(true)}>{I("plus", { width: 16 })}</IconButton>
    }>
      {customer.wonLeads.length === 0 ?
      <EmptyState icon="key-round" title="No won leads yet" /> :

      customer.wonLeads.map((l, i) =>
      <div key={l.id} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto auto", gap: 14, alignItems: "center", padding: "12px 0", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)" }}>
            <TierBadge tier={l.tier} />
            <span style={{ minWidth: 0 }}>
              <strong style={{ display: "block", fontSize: 13.5 }}>{l.address}</strong>
              <span style={{ fontSize: 12, color: "var(--text-muted)" }}>{l.cityZip} · {l.trigger} · {l.contact}</span>
            </span>
            <StrataAmount amount={l.amount} size="sm" />
            <StatusChip tone={VAULT_TONE[l.vaultStatus]}>{l.vaultStatus === "delivered" ? "Vault delivered" : "Vault pending"}</StatusChip>
            {l.vaultStatus === "pending" ?
        <Button size="sm" variant="secondary" icon={I("unlock", { width: 14 })} onClick={() => onResendVault(customer.id, l.id)}>Release Vault</Button> :

        <span style={{ width: 1 }} />
        }
          </div>
      )
      }
    </Card>
    {assigning && <AssignLeadModal leadQueue={leadQueue} customer={customer} onClose={() => setAssigning(false)} onAssign={(lead) => {onAssignLead(customer.id, lead);setAssigning(false);}} />}
    </React.Fragment>);

}

function TicketsTab({ customer, tickets, onOpenTicket }) {
  const rows = tickets.filter((t) => t.customerId === customer.id);
  return (
    <Card title="Tickets" note={`${rows.length} total`}>
      {rows.length === 0 ?
      <EmptyState icon="inbox" title="No tickets" /> :

      rows.map((t, i) =>
      <button key={t.id} onClick={() => onOpenTicket(t.id)} style={{ display: "grid", gridTemplateColumns: "1fr auto auto", gap: 12, alignItems: "center", width: "100%", textAlign: "left", padding: "11px 0", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)", border: "none", borderTopWidth: i === 0 ? 0 : 1, borderTopStyle: "solid", borderTopColor: "var(--border-subtle)", background: "transparent", cursor: "pointer" }}>
            <span style={{ minWidth: 0 }}>
              <strong style={{ display: "block", fontSize: 13.5 }}>{t.subject}</strong>
              <span style={{ fontSize: 12, color: "var(--text-muted)" }}>{t.id} · {t.updatedAt}</span>
            </span>
            <StatusChip tone={PRIORITY_TONE[t.priority]}>{t.priority}</StatusChip>
            <StatusChip tone={TICKET_STATUS_TONE[t.status]}>{t.status}</StatusChip>
          </button>
      )
      }
    </Card>);

}

function ActivityTab({ customer, auditLog }) {
  const rows = auditLog.filter((a) => a.targetId === customer.id);
  return (
    <Card title="Activity" note={`${rows.length} logged actions`}>
      {rows.length === 0 ?
      <EmptyState icon="history" title="No activity yet" /> :

      rows.map((a, i) =>
      <div key={a.id} style={{ display: "flex", gap: 10, padding: "10px 0", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)" }}>
            <span style={{ fontSize: 12, color: "var(--text-muted)", width: 90, flexShrink: 0 }}>{a.time}</span>
            <span style={{ fontSize: 13 }}>{a.action} <span style={{ color: "var(--text-muted)" }}>— {a.actor}</span></span>
          </div>
      )
      }
    </Card>);

}

function CustomerDetail({ customer, tickets, ledger, auditLog, leadQueue, onBack, onOpenAdjustWallet, onResetPassword, onChangePlan, onResendVault, onOpenTicket, onUpdateOwner, onAssignLead, onResendInvoice, onSendCardUpdateLink }) {
  const [tab, setTab] = React.useState("overview");
  React.useEffect(refresh, [tab]);
  return (
    <div>
      <button onClick={onBack} style={{ display: "flex", alignItems: "center", gap: 6, border: "none", background: "transparent", color: "var(--text-muted)", fontSize: 13, fontWeight: 600, cursor: "pointer", padding: "0 0 14px" }}>{I("chevron-left", { width: 15 })}Back to directory</button>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap", marginBottom: 18 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <Avatar name={customer.name} initials={customer.initials} size={48} style={{ fontWeight: 800, fontSize: 16 }} />
          <div>
            <h1 style={{ margin: 0, fontSize: 22, fontWeight: 800 }}>{customer.name}</h1>
            <div style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 4 }}>
              <span style={{ fontSize: 12.5, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>{customer.id}</span>
              <StatusChip tone={HEALTH_TONE[customer.health]}>{HEALTH_LABEL[customer.health]}</StatusChip>
              <StatusChip tone="neutral">{customer.plan.name}</StatusChip>
            </div>
          </div>
        </div>
      </div>
      <div style={{ marginBottom: 16 }}>
        <Tabs value={tab} onChange={setTab} tabs={[
        { value: "overview", label: "Overview" },
        { value: "wallet", label: "Wallet & Billing" },
        { value: "leads", label: "Lead Access", count: customer.wonLeads.length },
        { value: "tickets", label: "Tickets", count: tickets.filter((t) => t.customerId === customer.id).length },
        { value: "activity", label: "Activity" }]
        } />
      </div>
      {tab === "overview" && <OverviewTab customer={customer} onUpdateOwner={onUpdateOwner} onResetPassword={onResetPassword} />}
      {tab === "wallet" && <WalletTab customer={customer} ledger={ledger} onOpenAdjustWallet={onOpenAdjustWallet} onChangePlan={onChangePlan} onResendInvoice={onResendInvoice} onSendCardUpdateLink={onSendCardUpdateLink} />}
      {tab === "leads" && <LeadAccessTab customer={customer} leadQueue={leadQueue} onResendVault={onResendVault} onAssignLead={onAssignLead} />}
      {tab === "tickets" && <TicketsTab customer={customer} tickets={tickets} onOpenTicket={onOpenTicket} />}
      {tab === "activity" && <ActivityTab customer={customer} auditLog={auditLog} />}
    </div>);

}

function CustomersPage({ customers, tickets, ledger, auditLog, leadQueue, selectedCustomerId, onSelectCustomer, onOpenAdjustWallet, onResetPassword, onChangePlan, onResendVault, onOpenTicket, onUpdateOwner, onAssignLead, onResendInvoice, onSendCardUpdateLink }) {
  const [query, setQuery] = React.useState("");
  React.useEffect(refresh, [selectedCustomerId]);
  const selected = customers.find((c) => c.id === selectedCustomerId) || null;

  if (selected) {
    return (
      <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)" }}>
        <CustomerDetail customer={selected} tickets={tickets} ledger={ledger} auditLog={auditLog} leadQueue={leadQueue} onBack={() => onSelectCustomer(null)} onOpenAdjustWallet={onOpenAdjustWallet} onResetPassword={onResetPassword} onChangePlan={onChangePlan} onResendVault={onResendVault} onOpenTicket={onOpenTicket} onUpdateOwner={onUpdateOwner} onAssignLead={onAssignLead} onResendInvoice={onResendInvoice} onSendCardUpdateLink={onSendCardUpdateLink} />
      </div>);

  }

  const q = query.trim().toLowerCase();
  const rows = customers.filter((c) => q === "" || c.name.toLowerCase().includes(q) || c.id.toLowerCase().includes(q) || c.owner.email.toLowerCase().includes(q));

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)" }}>
      <PageHeader eyebrow="Customer Operations" title="Customers" description="Search an account to view identity, wallet & billing, lead access, tickets, and activity." actions={
      <div style={{ width: 280 }}><Field icon={I("search")} placeholder="Name, account ID, or email..." value={query} onChange={(e) => setQuery(e.target.value)} /></div>
      } />
      <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)", overflow: "hidden" }}>
        {rows.length === 0 ?
        <EmptyState icon="users-round" title="No matching accounts" /> :

        rows.map((c) => <CustomerRow key={c.id} c={c} ticketCount={tickets.filter((t) => t.customerId === c.id).length} onClick={() => onSelectCustomer(c.id)} />)
        }
      </div>
    </div>);

}

Object.assign(window, { OpsCustomers: { CustomersPage, AdjustWalletDrawer } });
