/* Stratum Leads — Operations Console. Lead Enrichment: owner-contact resolution.
   Ported (UI/UX only) from the stale `stratum-lead-enrichment` v2 concept — 100%
   mock, shaped to the Phase-2 read models. Contact VALUES are always MASKED: we
   never fabricate a real phone/email for a real named owner. This surface shows
   the workflow — the ≥2-independent-sources verification rule, the evidence
   trail, compliance suppression, and "queen" source diagnostics — over the real
   DC owners. Enrichment is the step that turns a verified lead (Lead Review) into
   a deliverable contact; unresolved contacts are why Lead Review shows "pending". */

/* Design-system components — each Babel script has its own scope, so every
   ops-*.jsx file must destructure what it needs from the namespace. Use UNIQUE
   top-level names here: these text/babel scripts share one global scope and the
   last-loaded duplicate wins (see the fmtUSD trap). */
const { Button, Card, Metric, StatusChip, TierBadge, ProgressBar, Tabs, EmptyState, SegmentedControl } = window.StratumLeadsDesignSystem_6367ed;
const { I, Spinner } = window.OpsShared;

const ENRICH_BAND_TONE = { High: "success", Medium: "warning", Low: "danger" };
const ENRICH_STATUS_TONE = { verified: "success", unverified: "warning", suppressed: "danger" };
const CONTACT_ICON = { phone: "phone", email: "mail" };
const enrichUsd = (n) => "$" + (Number(n) || 0).toFixed(2);

function EnrichStat({ label, children }) {
  return (
    <div style={{ border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-sm)", padding: "10px 12px", background: "var(--surface-subtle)" }}>
      <span style={{ display: "block", fontSize: 11, color: "var(--text-muted)", marginBottom: 3 }}>{label}</span>
      <strong style={{ fontSize: 14 }}>{children}</strong>
    </div>);

}

/* ---------------- Queen source diagnostics ---------------- */
function QueenPanel({ sources }) {
  const maxCorr = Math.max(...sources.map((s) => s.corroborationRate), 1);
  return (
    <div style={{ display: "grid", gap: 10 }}>
      {sources.map((s) =>
      <div key={s.id} style={{ display: "grid", gridTemplateColumns: "180px 1fr auto", alignItems: "center", gap: 12 }}>
          <span style={{ display: "flex", alignItems: "center", gap: 7, minWidth: 0 }}>
            {s.queen && <span title="Queen — best corroborated yield" style={{ color: "var(--accent)" }}>{I("crown", { width: 15 })}</span>}
            <span style={{ minWidth: 0 }}>
              <strong style={{ display: "block", fontSize: 12.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.name}</strong>
              <span style={{ fontSize: 10.5, color: "var(--text-subtle)" }}>{s.kind} · {s.costPerHit === 0 ? "free" : enrichUsd(s.costPerHit) + "/hit"}</span>
            </span>
          </span>
          <div style={{ height: 9, borderRadius: "var(--radius-pill)", background: "var(--surface-sunken)", overflow: "hidden" }} title={`${s.corroborationRate}% corroborated`}>
            <div style={{ width: `${Math.round(s.corroborationRate / maxCorr * 100)}%`, height: "100%", borderRadius: "var(--radius-pill)", background: s.queen ? "var(--accent)" : "var(--text-subtle)" }} />
          </div>
          <span style={{ fontSize: 11.5, color: "var(--text-muted)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap", minWidth: 118, textAlign: "right" }}>
            hit {s.hitRate}% · corr {s.corroborationRate}%
          </span>
        </div>
      )}
    </div>);

}

/* ---------------- Recent runs ---------------- */
function EnrichRuns({ runs }) {
  return (
    <div style={{ display: "grid", gap: 2 }}>
      {runs.map((r, i) =>
      <div key={r.id} style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10, alignItems: "center", padding: "9px 4px", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)" }}>
          <span style={{ minWidth: 0 }}>
            <strong style={{ fontSize: 12.5 }}>{r.at}</strong>
            <span style={{ display: "block", fontSize: 11, color: "var(--text-muted)" }}>{r.targeted} owners · {r.resolved} resolved · {r.verified} verified · {r.suppressed} suppressed</span>
          </span>
          <span style={{ fontSize: 11.5, color: "var(--text-muted)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>{enrichUsd(r.costUsd)}</span>
        </div>
      )}
    </div>);

}

/* ---------------- Contact card (with evidence drill-down) ---------------- */
function EnrichContact({ c, onPromote }) {
  const [open, setOpen] = React.useState(false);
  React.useEffect(refresh, [open]);
  const suppressed = c.status === "suppressed";
  return (
    <div style={{ border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-sm)", background: "var(--surface)", overflow: "hidden" }}>
      <div style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", alignItems: "center", gap: 12, padding: "10px 12px" }}>
        <span style={{ width: 30, height: 30, display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent)" }}>{I(CONTACT_ICON[c.type], { width: 15 })}</span>
        <span style={{ minWidth: 0 }}>
          <strong style={{ fontSize: 13, fontFamily: "var(--font-mono)", textDecoration: suppressed ? "line-through" : "none", color: suppressed ? "var(--text-subtle)" : "var(--text)" }}>{c.masked}</strong>
          <span style={{ display: "block", fontSize: 11, color: "var(--text-muted)" }}>{c.ownerName}</span>
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {suppressed ?
          <StatusChip tone="danger" dot>Suppressed</StatusChip> :
          <React.Fragment>
              <StatusChip tone={ENRICH_BAND_TONE[c.band]}>{c.confidence}% · {c.band}</StatusChip>
              <button onClick={() => setOpen((o) => !o)} title="Evidence" style={{ display: "inline-flex", alignItems: "center", gap: 4, border: "1px solid var(--border)", borderRadius: "var(--radius-sm)", background: "var(--surface)", cursor: "pointer", padding: "4px 8px", fontSize: 11.5, color: "var(--text-muted)", fontFamily: "var(--font-sans)" }}>
                {c.corroboration} {c.corroboration === 1 ? "source" : "sources"} {I(open ? "chevron-up" : "chevron-down", { width: 13 })}
              </button>
            </React.Fragment>
          }
        </span>
      </div>
      {suppressed &&
      <div style={{ padding: "0 12px 10px 54px", fontSize: 11.5, color: "var(--danger)" }}>{I("shield-x", { width: 12 })} {c.suppressReason}</div>
      }
      {open && !suppressed &&
      <div style={{ borderTop: "1px solid var(--border-subtle)", background: "var(--surface-subtle)", padding: "10px 12px 12px 54px", display: "grid", gap: 8 }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: "var(--text-subtle)", textTransform: "uppercase", letterSpacing: "0.03em" }}>Evidence — {c.status === "verified" ? "corroborated by ≥2 independent sources" : "needs a second independent source"}</span>
          {c.sourceRefs.map((e, i) =>
        <div key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 10, alignItems: "center", fontSize: 12 }}>
              <StatusChip tone="neutral">{e.source}</StatusChip>
              <span style={{ fontFamily: "var(--font-mono)", color: "var(--text-muted)" }}>{e.returned}</span>
              <span style={{ fontSize: 11, color: "var(--text-subtle)", whiteSpace: "nowrap" }}>{e.at}</span>
            </div>
        )}
          {c.status === "verified" &&
        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 2 }}>
              <Button size="sm" variant="primary" icon={I("shield-check", { width: 14 })} onClick={() => onPromote(c)}>Promote to vault</Button>
            </div>
        }
        </div>
      }
    </div>);

}

/* ---------------- Lead list row ---------------- */
function EnrichLeadRow({ l, active, onClick }) {
  const tone = l.verifiedCount > 0 ? "success" : l.resolvedCount > 0 ? "warning" : "neutral";
  return (
    <button onClick={onClick} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", alignItems: "center", gap: 12, width: "100%", textAlign: "left", padding: "12px 14px", border: "none", borderBottom: "1px solid var(--border-subtle)", borderLeft: active ? "3px solid var(--accent)" : "3px solid transparent", background: active ? "var(--accent-soft)" : "var(--surface)", cursor: "pointer" }}>
      <TierBadge tier={l.tier} />
      <span style={{ minWidth: 0 }}>
        <strong style={{ display: "block", fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.address}</strong>
        <span style={{ fontSize: 11.5, color: "var(--text-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", display: "block" }}>{l.owners[0]}{l.owners.length > 1 ? ` +${l.owners.length - 1}` : ""}</span>
      </span>
      <span style={{ display: "grid", justifyItems: "end", gap: 4 }}>
        <StatusChip tone={tone} dot>{l.verifiedCount} ✓</StatusChip>
        <span style={{ fontSize: 11, color: "var(--text-subtle)" }}>{l.bestConfidence}%</span>
      </span>
    </button>);

}

/* ---------------- Detail ---------------- */
function EnrichDetail({ lead, onPromote }) {
  React.useEffect(refresh, [lead?.leadId]);
  if (!lead) return <Card style={{ height: "100%" }}><EmptyState icon="user-search" title="Select a lead" message="Choose a lead to review its resolved owner contacts, confidence, and evidence." /></Card>;

  const verified = lead.contacts.filter((c) => c.status === "verified");
  const unverified = lead.contacts.filter((c) => c.status === "unverified");
  const suppressed = lead.contacts.filter((c) => c.status === "suppressed");
  const Section = ({ title, tone, items }) => items.length === 0 ? null :
  <div style={{ display: "grid", gap: 8 }}>
      <span style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, fontWeight: 700 }}>
        <StatusChip tone={tone}>{items.length}</StatusChip>{title}
      </span>
      {items.map((c) => <EnrichContact key={c.id} c={c} onPromote={(ct) => onPromote(lead, ct)} />)}
    </div>;


  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)", padding: 20, display: "grid", gap: 16, height: "100%", overflowY: "auto", alignContent: "start" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <TierBadge tier={lead.tier} />
          <div>
            <strong style={{ fontSize: 17, fontWeight: 800, display: "block" }}>{lead.address}</strong>
            <span style={{ fontSize: 12.5, color: "var(--text-muted)" }}>{lead.cityZip} · {lead.owners.join(", ")}</span>
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10 }}>
        <EnrichStat label="Resolved">{lead.resolvedCount}</EnrichStat>
        <EnrichStat label="Verified (≥2 src)">{lead.verifiedCount}</EnrichStat>
        <EnrichStat label="Best confidence">{lead.bestConfidence}%</EnrichStat>
      </div>

      <Section title="Verified — deliverable" tone="success" items={verified} />
      <Section title="Needs corroboration" tone="warning" items={unverified} />
      <Section title="Suppressed — held back" tone="danger" items={suppressed} />
    </div>);

}

/* ---------------- Page ---------------- */
function LeadEnrichPage({ enrichment, onNotify, onPromote }) {
  const [selId, setSelId] = React.useState(enrichment.leads[0]?.leadId || null);
  const [running, setRunning] = React.useState(false);
  const paged = usePaged(enrichment.leads, { k: "enrich" }, 25);
  const timers = React.useRef([]);
  React.useEffect(refresh, [selId, running, paged.page]);
  React.useEffect(() => () => timers.current.forEach(clearTimeout), []);

  const selected = enrichment.leads.find((l) => l.leadId === selId) || enrichment.leads[0] || null;
  const lr = enrichment.lastRun;

  const runBatch = () => {
    if (running) return;
    setRunning(true);
    timers.current.push(setTimeout(() => {
      setRunning(false);
      onNotify && onNotify("success", "Enrichment batch complete", `${lr.resolved} contacts resolved · ${lr.verified} verified · ${lr.suppressed} suppressed`);
    }, 1600));
  };
  const promote = (lead, contact) => {
    onPromote && onPromote(lead, contact);
  };

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)" }}>
      <PageHeader
        eyebrow="Lead Operations"
        title="Lead Enrichment"
        description="Resolve owner phone & email to deliverable confidence — verified only when ≥2 independent sources agree."
        actions={
        <Button variant="primary" disabled={running} icon={running ? <Spinner size={14} /> : I("contact", { width: 15 })} onClick={runBatch}>
            {running ? "Enriching…" : "Run Enrichment Batch"}
          </Button>
        } />

      <Reveal style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(170px,1fr))", gap: 14, marginBottom: 22 }}>
        <Metric icon={I("users-round")} value={lr.targeted} label="Owners targeted" accent="violet" />
        <Metric icon={I("contact")} value={lr.resolved} label="Contacts resolved" accent="cyan" />
        <Metric icon={I("shield-check")} value={lr.verified} label="Verified (≥2 src)" accent="green" />
        <Metric icon={I("shield-x")} value={lr.suppressed} label="Suppressed" accent="amber" />
        <Metric icon={I("crown")} value={enrichment.sources.find((s) => s.queen)?.name || "—"} label="Queen source" accent="violet" />
      </Reveal>

      <Reveal delay={60} style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 20, alignItems: "start", marginBottom: 20 }}>
        <Card title="Source diagnostics" note={enrichment.model}>
          <QueenPanel sources={enrichment.sources} />
        </Card>
        <Card title="Recent enrichment runs" note="Batched owner-contact resolution">
          <EnrichRuns runs={enrichment.runs} />
        </Card>
      </Reveal>

      <Reveal delay={100} style={{ display: "grid", gridTemplateColumns: "380px 1fr", gap: 18, height: 620 }}>
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0, border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)", overflow: "hidden" }}>
          <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--border)", fontSize: 12.5, fontWeight: 700, color: "var(--text-muted)" }}>Owners in enrichment</div>
          <div style={{ flex: 1, overflowY: "auto" }}>
            {paged.slice.map((l) => <EnrichLeadRow key={l.leadId} l={l} active={selected?.leadId === l.leadId} onClick={() => setSelId(l.leadId)} />)}
          </div>
          <div style={{ padding: "6px 12px", borderTop: "1px solid var(--border-subtle)" }}>
            <Pager page={paged.page} setPage={paged.setPage} perPage={paged.perPage} setPerPage={paged.setPerPage} pageCount={paged.pageCount} total={paged.total} start={paged.start} isAll={paged.isAll} noun="owners" options={[25, 50]} />
          </div>
        </div>
        <EnrichDetail lead={selected} onPromote={promote} />
      </Reveal>
    </div>);

}

Object.assign(window, { OpsEnrich: { LeadEnrichPage } });
