/* Stratum Leads — Operations Console. Publishing Queue: verified leads → live
   marketplace, gated by the crawl_publish_gate. A lead only publishes when every
   gate check passes — crucially, "owner contact verified", which is why the flow
   is Lead Review (verify) → Lead Enrichment (resolve contact) → Publishing. 100%
   mock; reads LEAD_QUEUE (verified) + ENRICHMENT (for the contact gate).
   UNIQUE top-level names only (shared global scope — see the fmtUSD trap). */

const { Button, Card, Metric, StatusChip, TierBadge, EmptyState, Tabs } = window.StratumLeadsDesignSystem_6367ed;
const { I, Spinner } = window.OpsShared;

const pubUsdK = (n) => n == null ? "—" : "$" + Math.round(n / 1000).toLocaleString() + "k";

function pubGate(lead, enrichMap) {
  const e = enrichMap[lead.leadId] || enrichMap[lead.id];
  return [
    { key: "score", label: "Canonical score ≥ 60", ok: lead.score >= 60 },
    { key: "dedupe", label: "Deduplicated against marketplace", ok: true },
    { key: "price", label: "Opening bid priced", ok: lead.startingBid > 0 },
    { key: "contact", label: "Owner contact verified (≥2 sources)", ok: !!(e && e.verifiedCount > 0), hint: e ? (e.verifiedCount > 0 ? null : "Contacts resolved but unverified") : "Not yet enriched" },
    { key: "compliance", label: "Compliance / suppression clear", ok: true }];
}
const pubReady = (lead, enrichMap) => pubGate(lead, enrichMap).every((g) => g.ok);

function PubLeadRow({ l, ready, active, onClick }) {
  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)" }}>{l.cityZip}</span>
      </span>
      <span style={{ display: "grid", justifyItems: "end", gap: 4 }}>
        {l.status === "published" ?
        <StatusChip tone="violet" dot>Published</StatusChip> :
        <StatusChip tone={ready ? "success" : "warning"} dot>{ready ? "Ready" : "Blocked"}</StatusChip>}
        <span style={{ fontSize: 11, color: "var(--text-subtle)" }}>{l.startingBid} Strata</span>
      </span>
    </button>);

}

function PubGateItem({ g, onFix }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 0", borderTop: "1px solid var(--border-subtle)" }}>
      <span style={{ width: 22, height: 22, flexShrink: 0, display: "grid", placeItems: "center", borderRadius: "50%", background: g.ok ? "var(--success-soft, var(--accent-soft))" : "var(--danger-soft)", color: g.ok ? "var(--success)" : "var(--danger)" }}>
        {I(g.ok ? "check" : "x", { width: 13 })}
      </span>
      <span style={{ flex: 1, fontSize: 13, color: g.ok ? "var(--text)" : "var(--text-muted)" }}>{g.label}</span>
      {!g.ok && g.hint && <span style={{ fontSize: 11.5, color: "var(--danger)" }}>{g.hint}</span>}
      {!g.ok && g.key === "contact" && <Button size="sm" variant="secondary" onClick={onFix}>Enrich</Button>}
    </div>);

}

function PubDetail({ lead, enrichMap, publishing, onPublish, onNavigate }) {
  React.useEffect(refresh, [lead?.leadId || lead?.id, publishing]);
  if (!lead) return <Card style={{ height: "100%" }}><EmptyState icon="upload-cloud" title="Select a lead" message="Choose a verified lead to review its publish-gate checks." /></Card>;
  const checks = pubGate(lead, enrichMap);
  const ready = checks.every((c) => c.ok);
  const published = lead.status === "published";

  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.county}</span>
          </div>
        </div>
        <StatusChip tone={published ? "violet" : ready ? "success" : "warning"} dot>{published ? "Published" : ready ? "Ready to publish" : "Blocked at gate"}</StatusChip>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10 }}>
        <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)" }}>Score</span><strong style={{ fontSize: 14 }}>{lead.score} / 100</strong></div>
        <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)" }}>Est. value</span><strong style={{ fontSize: 14 }}>{pubUsdK(lead.estValue)}</strong></div>
        <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)" }}>Opening bid</span><strong style={{ fontSize: 14 }}>{lead.startingBid} Strata</strong></div>
      </div>

      <Card title="Publish gate" note="crawl_publish_gate — all checks must pass" style={{ boxShadow: "none" }}>
        <div>
          {checks.map((g) => <PubGateItem key={g.key} g={g} onFix={() => onNavigate("enrich")} />)}
        </div>
      </Card>

      {published ?
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--accent)" }}>{I("check-circle-2", { width: 16 })} Live in the marketplace.</div> :
      <Button variant="primary" fullWidth disabled={!ready || publishing} icon={publishing ? <Spinner size={14} /> : I("upload-cloud", { width: 16 })} onClick={() => onPublish(lead)}>
          {publishing ? "Publishing…" : ready ? "Publish to Marketplace" : "Blocked — resolve gate checks"}
        </Button>}
    </div>);

}

function PublishingQueuePage({ leadQueue, enrichment, onPublish, onNavigate }) {
  const [tab, setTab] = React.useState("ready");
  const [selId, setSelId] = React.useState(null);
  const [publishing, setPublishing] = React.useState(false);
  const enrichMap = React.useMemo(() => {
    const m = {};(enrichment.leads || []).forEach((l) => m[l.leadId] = l);return m;
  }, [enrichment]);
  React.useEffect(refresh, [tab, selId, publishing]);

  const verified = leadQueue.filter((l) => l.status === "verified");
  const published = leadQueue.filter((l) => l.status === "published");
  const ready = verified.filter((l) => pubReady(l, enrichMap));
  const blocked = verified.filter((l) => !pubReady(l, enrichMap));
  const rows = tab === "ready" ? ready : tab === "blocked" ? blocked : published;
  const selected = leadQueue.find((l) => (l.id || l.leadId) === selId) || rows[0] || null;

  const doPublish = (lead) => {
    if (publishing) return;
    setPublishing(true);
    setTimeout(() => {setPublishing(false);onPublish(lead);setSelId(null);}, 850);
  };
  const publishAll = () => {
    if (ready.length === 0) return;
    onPublish(ready);
  };

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)", height: "calc(100vh - 4px)", display: "flex", flexDirection: "column" }}>
      <PageHeader eyebrow="Lead Operations" title="Publishing Queue" description="Verified leads pass the crawl_publish_gate and go live on the marketplace. Contact must be enriched before a lead can publish."
        actions={ready.length > 0 ? <Button variant="primary" icon={I("upload-cloud", { width: 15 })} onClick={publishAll}>Publish all ready ({ready.length})</Button> : null} />

      <Reveal style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(170px,1fr))", gap: 14, marginBottom: 18 }}>
        <Metric icon={I("upload-cloud")} value={ready.length} label="Ready to publish" accent="green" />
        <Metric icon={I("shield-alert")} value={blocked.length} label="Blocked at gate" accent="amber" />
        <Metric icon={I("check-circle-2")} value={published.length} label="Published" accent="violet" />
        <Metric icon={I("gavel")} value={verified.length + published.length} label="Total this cycle" accent="cyan" />
      </Reveal>

      <div style={{ marginBottom: 14 }}>
        <Tabs value={tab} onChange={(v) => {setTab(v);setSelId(null);}} tabs={[{ value: "ready", label: "Ready", count: ready.length }, { value: "blocked", label: "Blocked", count: blocked.length }, { value: "published", label: "Published", count: published.length }]} />
      </div>

      <div style={{ flex: 1, minHeight: 0, display: "grid", gridTemplateColumns: "400px 1fr", gap: 18 }}>
        <div style={{ overflowY: "auto", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)" }}>
          {rows.length === 0 ?
          <EmptyState icon="upload-cloud" title="Nothing here" message={tab === "ready" ? "No leads currently pass the gate." : tab === "blocked" ? "No blocked leads." : "Nothing published yet."} /> :
          rows.map((l) => <PubLeadRow key={l.id || l.leadId} l={l} ready={tab === "ready"} active={(selected?.id || selected?.leadId) === (l.id || l.leadId)} onClick={() => setSelId(l.id || l.leadId)} />)}
        </div>
        <PubDetail lead={selected} enrichMap={enrichMap} publishing={publishing} onPublish={doPublish} onNavigate={onNavigate} />
      </div>
    </div>);

}

Object.assign(window, { OpsPublishing: { PublishingQueuePage } });
