/* ============================================================================
   DIVONCI WORLD — CLIENTS + AGENCY PIPELINE  (screens_clients.jsx)
   ----------------------------------------------------------------------------
   The operational line, made literal:
   Lead → Discovery → Brief → Proposal → Contract → Project → Build → Launch → Retainer
   Every read here flows through useResource()/DW.get; every write through
   DW.mutate. Loading / Empty / Error states are rendered for each query.
   ========================================================================== */
const { useState: useStateCl, useEffect: useEffectCl } = React;

/* canonical operational line — the spine of the whole agency */
const LOOP_STAGES = [
  { key: "lead",      label: "Lead",      icon: "flag" },
  { key: "discovery", label: "Discovery", icon: "search" },
  { key: "brief",     label: "Brief",     icon: "doc" },
  { key: "proposal",  label: "Proposal",  icon: "evidence" },
  { key: "contract",  label: "Contract",  icon: "handshake" },
  { key: "project",   label: "Project",   icon: "project" },
  { key: "build",     label: "Build",     icon: "foundry" },
  { key: "launch",    label: "Launch",    icon: "rocket" },
  { key: "retainer",  label: "Retainer",  icon: "refresh" },
];
const STATE_RANK = { crisis: 5, caution: 4, active: 3, focus: 2, clear: 1, standby: 0 };
function worstState(states) {
  return states.reduce((w, s) => (STATE_RANK[s] > STATE_RANK[w] ? s : w), "standby");
}

/* ── the pipeline ribbon ─────────────────────────────────────────────────── */
function PipelineRibbon({ leads, clients, active, onPick }) {
  const counts = {};
  LOOP_STAGES.forEach((s) => (counts[s.key] = { n: 0, states: [] }));
  leads.forEach((l) => {
    const k = "lead";
    counts[k].n++; counts[k].states.push(l.state);
  });
  clients.forEach((c) => {
    const k = counts[c.stage] ? c.stage : "project";
    counts[k].n++; counts[k].states.push(c.state);
    // a retainer/launch client is also "live" support
    if (c.stage === "launch") { counts.retainer.n++; counts.retainer.states.push("clear"); }
  });
  return (
    <div className="pipeline" role="tablist" aria-label="Agency pipeline">
      {LOOP_STAGES.map((s) => {
        const c = counts[s.key];
        const st = c.states.length ? worstState(c.states) : "standby";
        return (
          <button key={s.key} role="tab" aria-selected={active === s.key}
            className={"pipe-step " + (active === s.key ? "on" : "")}
            onClick={() => onPick(active === s.key ? null : s.key)}>
            <div className="pk">{s.label}</div>
            <div className="pn">{c.n}</div>
            <div className="pc"><span className="led" style={{ background: DW.STATE_META[st].c, color: DW.STATE_META[st].c }} /> {c.n === 1 ? "entity" : "entities"}</div>
            <Icon name="arrow" className="arrow-n" />
          </button>
        );
      })}
    </div>
  );
}

/* ── client detail drawer (pulls the whole loop for one client) ─────────── */
function ClientDrawer({ client, onClose, nav }) {
  const auth = useAuth();
  const discovery = useResource("discovery_sessions", { eq: { clientId: client.id } });
  const briefs = useResource("briefs", { eq: { clientId: client.id } });
  const proposals = useResource("proposals", { eq: { clientId: client.id } });
  const contracts = useResource("contracts", { eq: { clientId: client.id } });
  const invoices = useResource("invoices", { eq: { clientId: client.id } });
  const packets = useResource("foundry_packets", { eq: { clientId: client.id } });

  const loading = [discovery, briefs, proposals, contracts, invoices, packets].some((r) => r.loading);

  function advance() {
    const idx = LOOP_STAGES.findIndex((s) => s.key === client.stage);
    const next = LOOP_STAGES[Math.min(idx + 1, LOOP_STAGES.length - 1)].key;
    DW.mutate("client.advanceStage", { id: client.id, stage: next });
    onClose();
  }

  const proj = client.projectId ? DW.PROJECTS.find((p) => p.id === client.projectId) : null;

  // build the loop steps from real fetched rows
  const steps = [];
  const push = (key, title, desc, state) => steps.push({ key, title, desc, state });
  (discovery.data || []).forEach((d) => push("discovery", d.title, d.findings.length + " findings · " + d.duration + " · " + d.nextStep, d.state));
  (briefs.data || []).forEach((b) => push("brief", b.title, (b.approved ? "Approved — " : "Draft — ") + b.outcome, b.state));
  (proposals.data || []).forEach((p) => push("proposal", p.title, "$" + (p.value / 1000) + "k · " + p.status, p.state));
  (contracts.data || []).forEach((c) => push("contract", c.title, "$" + (c.value / 1000) + "k · " + c.status + (c.depositPaid ? " · deposit paid" : " · deposit pending"), c.state));
  if (proj) push("project", proj.name, proj.stage + " · health " + proj.health + " · owner " + DW.agent(proj.owner).name, proj.state);
  (packets.data || []).forEach((p) => push("build", p.name, p.stage + " · readiness " + p.readiness + " · " + p.openDecisions + " open decision(s)", p.state));
  (invoices.data || []).forEach((i) => push("retainer", "Invoice " + i.number, "$" + (i.amount / 1000) + "k · " + i.status + (i.due ? " · due " + i.due : ""), i.state));

  return (
    <>
      <div className="dw-drawer-scrim" onClick={onClose} />
      <aside className="dw-drawer" role="dialog" aria-label={client.name + " detail"}>
        <div className="dw-drawer-head">
          <div className="client-logo" style={{ background: client.logoTone }}>{client.name[0]}</div>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18 }}>{client.name}</div>
            <div className="client-sub">{client.tier} · client since {client.since} · owner {DW.agent(client.owner).name}</div>
          </div>
          <button className="dw-drawer-x" onClick={onClose} aria-label="Close"><Icon name="close" style={{ width: 16, height: 16 }} /></button>
        </div>
        <div className="dw-drawer-body">
          {/* contact + money strip */}
          <div className="cols c-3" style={{ marginBottom: "var(--s-7)" }}>
            <Panel style={{ padding: "12px 14px" }}><div className="mtile"><div className="k">ARR</div><div className="v">${(client.arr / 1000) || 0}k</div></div></Panel>
            <Panel style={{ padding: "12px 14px" }}><div className="mtile"><div className="k"><Led state={client.state} size={7} /> Health</div><div className="v" style={{ color: DW.STATE_META[client.state].c }}>{client.health}</div></div></Panel>
            <Panel style={{ padding: "12px 14px" }}><div className="mtile"><div className="k">Stage</div><div className="v" style={{ fontSize: 16, paddingTop: 6 }}>{(LOOP_STAGES.find((s) => s.key === client.stage) || {}).label || client.stage}</div></div></Panel>
          </div>

          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--violet-ink)", marginBottom: 12 }}>The loop · {client.name}</div>

          {loading ? <LoadingState lines={4} label="Tracing the loop" /> : steps.length === 0 ? (
            <EmptyState icon="handshake" title="No loop activity yet" hint="This client has no discovery, brief, proposal or contract on record. Start the loop from the lead." />
          ) : (
            <div className="loop">
              {steps.map((s, i) => {
                const cls = s.state === "crisis" ? "crisis" : (s.state === "clear" ? "done" : "active");
                return (
                  <div className="loop-step" key={i}>
                    <div className={"loop-dot " + cls} style={{ color: DW.STATE_META[s.state].c }}><i /></div>
                    <div>
                      <div className="loop-k">{(LOOP_STAGES.find((x) => x.key === s.key) || {}).label || s.key}</div>
                      <div className="loop-t">{s.title}</div>
                      <div className="loop-d">{s.desc}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          <div style={{ display: "flex", gap: 10, marginTop: "var(--s-8)", flexWrap: "wrap" }}>
            <button className="btn primary" disabled={!auth.can("clients")} title={auth.can("clients") ? "" : "Your role cannot write to clients"}
              onClick={advance}><Icon name="arrow" className="glyph" style={{ width: 14, height: 14 }} /> Advance stage</button>
            {proj && <button className="btn" onClick={() => { onClose(); nav("project:" + proj.id); }}><Icon name="project" className="glyph" style={{ width: 14, height: 14 }} /> Open project</button>}
            <button className="btn" onClick={() => { onClose(); nav("foundry"); }}><Icon name="foundry" className="glyph" style={{ width: 14, height: 14 }} /> Foundry packet</button>
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-4)", marginTop: 14, lineHeight: 1.5 }}>
            ⇄ every row above is fetched via DW.get(resource, &#123;eq:&#123;clientId&#125;&#125;). “Advance stage” writes through DW.mutate → audit event → realtime.
          </div>
        </div>
      </aside>
    </>
  );
}

/* ── the Clients screen ──────────────────────────────────────────────────── */
function ClientsScreen({ nav }) {
  const auth = useAuth();
  const leadsQ = useResource("leads", {});
  const clientsQ = useResource("clients", {});
  const [stageFilter, setStageFilter] = useStateCl(null);
  const [open, setOpen] = useStateCl(null); // client row open in drawer
  const [q, setQ] = useStateCl("");

  const leads = leadsQ.data || [];
  const clients = clientsQ.data || [];

  let shown = clients;
  if (stageFilter) shown = stageFilter === "lead" ? [] : clients.filter((c) => c.stage === stageFilter || (stageFilter === "retainer" && c.stage === "launch"));
  if (q.trim()) shown = shown.filter((c) => (c.name + c.contact).toLowerCase().includes(q.toLowerCase()));

  const totalArr = clients.reduce((s, c) => s + (c.arr || 0), 0);

  return (
    <div className="screen">
      <div className="screen-head">
        <div>
          <div className="title"><span className="sub">Agency · Pipeline</span>Clients</div>
          <div className="meta">Every client on the operational line, from first signal to retainer. The pipeline is the agency — nothing here is decoration.</div>
        </div>
        <div className="screen-actions">
          <div className="role-pill" onClick={() => { const order = ["sovereign", "commander", "operator", "viewer"]; const i = order.indexOf(auth.user.role); auth.signInAs(order[(i + 1) % order.length]); }} title="Cycle role to see permission boundaries">
            <Led state={auth.user.role === "viewer" ? "standby" : "active"} size={7} /> {auth.user.role}
          </div>
          <button className="btn primary pkt-cta" disabled={!auth.can("clients")}
            title={auth.can("clients") ? "Create a new lead" : "Your role is read-only here"}
            onClick={() => { DW.mutate("create", { resource: "leads", row: { name: "New Lead", contact: "—", source: "Manual", stage: "lead", value: 0, owner: "claws", state: "focus", created: "2026-06-15", note: "Created from Clients." } }); }}>
            <Icon name="plus" className="glyph" /> New Lead
          </button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="cols c-4" style={{ marginBottom: "var(--s-6)" }}>
        <Panel style={{ padding: "13px 16px" }}><div className="mtile"><div className="k"><Icon name="users" style={{ width: 13, height: 13 }} /> Active clients</div><div className="v">{clientsQ.loading ? "—" : clients.length}</div></div></Panel>
        <Panel style={{ padding: "13px 16px" }}><div className="mtile"><div className="k"><Icon name="flag" style={{ width: 13, height: 13 }} /> Open leads</div><div className="v">{leadsQ.loading ? "—" : leads.length}</div></div></Panel>
        <Panel style={{ padding: "13px 16px" }}><div className="mtile"><div className="k"><Icon name="finance" style={{ width: 13, height: 13 }} /> Portfolio ARR</div><div className="v">${Math.round(totalArr / 1000)}k</div></div></Panel>
        <Panel style={{ padding: "13px 16px" }}><div className="mtile"><div className="k"><Led state="crisis" size={7} /> At risk</div><div className="v" style={{ color: "var(--state-crisis)" }}>{clients.filter((c) => c.state === "crisis").length}</div></div></Panel>
      </div>

      {/* the operational line */}
      <Panel style={{ padding: 14, marginBottom: "var(--s-6)" }}>
        {clientsQ.loading || leadsQ.loading ? <LoadingState lines={1} label="Building the pipeline" /> : (
          <PipelineRibbon leads={leads} clients={clients} active={stageFilter} onPick={setStageFilter} />
        )}
      </Panel>

      {/* clients table */}
      <Panel className="tight">
        <PHead icon="users" eyebrow={stageFilter ? "Clients · " + (LOOP_STAGES.find((s) => s.key === stageFilter) || {}).label : "All clients"}
          right={<input className="dw-inline-search" placeholder="Filter clients…" value={q} onChange={(e) => setQ(e.target.value)}
            style={{ background: "var(--graphite)", border: "1px solid var(--hairline-2)", borderRadius: "var(--r-sm)", color: "var(--ink)", padding: "6px 10px", fontSize: 12, fontFamily: "var(--font-ui)", width: 160 }} />} />
        {clientsQ.loading ? <div style={{ padding: 20 }}><LoadingState lines={4} /></div>
          : clientsQ.error ? <ErrorState error={clientsQ.error} onRetry={clientsQ.refetch} />
          : shown.length === 0 ? (
            <EmptyState icon={stageFilter === "lead" ? "flag" : "users"}
              title={stageFilter === "lead" ? "Leads live in the rail" : "No clients at this stage"}
              hint={stageFilter === "lead" ? "Leads haven't converted to clients yet — see the Leads list on the right." : "Nothing is sitting at this stage of the line right now."}
              action={stageFilter ? <button className="btn" onClick={() => setStageFilter(null)}>Clear filter</button> : null} />
          ) : (
            shown.map((c) => {
              const a = DW.agent(c.owner);
              const stage = LOOP_STAGES.find((s) => s.key === c.stage) || { label: c.stage };
              return (
                <div className="client-row" key={c.id} onClick={() => setOpen(c)}>
                  <div className="client-logo" style={{ background: c.logoTone }}>{c.name[0]}</div>
                  <div>
                    <div className="client-name">{c.name}</div>
                    <div className="client-sub">{c.contact} · {c.email}</div>
                  </div>
                  <div>
                    <span className={"tierchip " + (c.tier === "Sovereign" ? "sovereign" : "")}>{c.tier}</span>
                    <div className="client-mono" style={{ marginTop: 7 }}>stage · {stage.label}</div>
                  </div>
                  <div>
                    <div className="healthbar"><i style={{ width: Math.max(6, c.health) + "%", background: DW.STATE_META[c.state].c }} /></div>
                    <div className="client-mono" style={{ marginTop: 6 }}>health {c.health}</div>
                  </div>
                  <div className="client-mono">${Math.round((c.arr || 0) / 1000)}k ARR<div style={{ marginTop: 6 }}>owner · {a.name}</div></div>
                  <div style={{ textAlign: "right" }}><span className="sbadge" style={{ color: DW.STATE_META[c.state].c }}><span className="led" />{DW.STATE_META[c.state].label}</span></div>
                </div>
              );
            })
          )}
      </Panel>

      {/* leads rail */}
      <div style={{ marginTop: "var(--s-7)" }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--violet-ink)", marginBottom: 12 }}>Inbound · leads</div>
        {leadsQ.loading ? <LoadingState lines={2} /> : leads.length === 0 ? (
          <EmptyState icon="flag" title="No open leads" hint="New signals from referrals, outbound and the Studio demo land here." />
        ) : (
          <div className="cols c-3">
            {leads.map((l) => (
              <Panel key={l.id} style={{ padding: "14px 16px", cursor: "default" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                  <span className="sbadge" style={{ color: DW.STATE_META[l.state].c }}><span className="led" />{l.stage}</span>
                  <span className="client-mono">${Math.round(l.value / 1000)}k</span>
                </div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 15 }}>{l.name}</div>
                <div className="client-sub" style={{ marginBottom: 8 }}>{l.source} · {l.contact}</div>
                <div style={{ fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.5 }}>{l.note}</div>
                <div style={{ marginTop: 12, display: "flex", gap: 8 }}>
                  <button className="btn" style={{ padding: "6px 12px", fontSize: 12 }} disabled={!auth.can("clients")}
                    onClick={() => DW.mutate("create", { resource: "clients", row: { name: l.name, tier: "Standard", since: "2026-06", health: 60, state: "focus", owner: l.owner, contact: l.contact, email: "—", arr: 0, stage: "discovery", logoTone: "#F5B544", note: "Converted from lead." } }).then(() => DW.mutate("remove", { resource: "leads", id: l.id })) }>
                    Convert → Client
                  </button>
                </div>
              </Panel>
            ))}
          </div>
        )}
      </div>

      {open && <ClientDrawer client={open} onClose={() => setOpen(null)} nav={nav} />}
    </div>
  );
}

Object.assign(window, { ClientsScreen, PipelineRibbon, LOOP_STAGES });
