/* Stratum Leads — Operations Console. Lead Review (intake): the marketplace
   lead verification queue. Reads the REAL held-out DC pool (ops-leads-data.js),
   scored by the canonical model (score 0–100, quality 1–5, tier from equity,
   starting bid). No customer/ticket data here — this page's single job is
   deciding what enters the Preview Feed / Live Marketplace.

   Owner *contact* enrichment (phone/email) is intentionally pending here — that
   is the Lead Enrichment surface's job — so this page verifies the lead itself. */

/* 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, Tabs, LeadCard, Button, Field, Card, Metric, StatusChip, TierBadge, ContactQuality, ProgressBar, StrataAmount, SegmentedControl, EmptyState } = window.StratumLeadsDesignSystem_6367ed;

const { I, LEADQ_TONE, Spinner, IconCheckCircle } = window.OpsShared;

const LQ_TABS = ["pending", "verified", "rejected", "all"];
const LQ_TAB_LABEL = { pending: "Pending Review", verified: "Verified", rejected: "Rejected", all: "All" };
const TIER_OPTIONS = ["AA", "A", "BBB", "BB"];
const REJECT_REASONS = ["Owner mailing address matches property — not absentee", "Equity estimate unverifiable against assessment", "Duplicate of an existing marketplace lead", "Property already sold — listing closed", "Other"];

const usdK = (n) => n == null ? "—" : "$" + Math.round(n / 1000).toLocaleString() + "k";
const scoreColor = (s) => s >= 80 ? "green" : s >= 60 ? "amber" : "red";

/* 1–5 canonical quality, rendered as filled pips. */
function QualityPips({ value }) {
  return (
    <span style={{ display: "inline-flex", gap: 3, alignItems: "center" }}>
      {[1, 2, 3, 4, 5].map((n) =>
      <span key={n} style={{ width: 8, height: 8, borderRadius: "50%", background: n <= value ? "var(--accent)" : "var(--surface-sunken)", border: n <= value ? "none" : "1px solid var(--border)" }} />
      )}
      <span style={{ fontSize: 11.5, color: "var(--text-muted)", marginLeft: 4, fontWeight: 600 }}>{value}/5</span>
    </span>);

}

function StatCard({ 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>);

}

function LeadQueueRow({ l, 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.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.address}</strong>
        <span style={{ display: "block", fontSize: 11.5, color: "var(--text-muted)", margin: "2px 0 6px" }}>{l.cityZip}</span>
        <span style={{ display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center" }}>
          <StatusChip tone="neutral">{l.trigger}</StatusChip>
          <span style={{ fontSize: 11, color: "var(--text-subtle)" }}>{l.submittedAt}</span>
        </span>
      </span>
      <span style={{ display: "grid", justifyItems: "end", gap: 4 }}>
        <StatusChip tone={LEADQ_TONE[l.status]}>{LQ_TAB_LABEL[l.status] || l.status}</StatusChip>
        <span style={{ fontSize: 11.5, color: "var(--text-subtle)", fontVariantNumeric: "tabular-nums" }}>Score {l.score}</span>
      </span>
    </button>);

}

function LeadQueueDetail({ lead, onVerify, onReject }) {
  const [tier, setTier] = React.useState(lead?.tier);
  const [rejecting, setRejecting] = React.useState(false);
  const [reason, setReason] = React.useState(REJECT_REASONS[0]);
  const [publishing, setPublishing] = React.useState(false);
  React.useEffect(() => {setTier(lead?.tier);setRejecting(false);setPublishing(false);}, [lead?.id]);
  React.useEffect(refresh, [lead?.id, rejecting, publishing]);

  const publish = () => {
    setPublishing(true);
    setTimeout(() => onVerify(lead.id, { tier }), 900);
  };

  if (!lead) return <Card style={{ height: "100%" }}><EmptyState icon="radar" title="Select a lead" message="Choose a lead from the queue to review its score and verify or reject it." /></Card>;

  const owners = (lead.owners || []).join(", ") || "Property Owner";
  const signals = [
  lead.absentee && { icon: "map-pin-off", label: `Absentee — mails to ${lead.mailingCity || "elsewhere"}`, tone: "violet" },
  lead.vacant && { icon: "door-closed", label: "Vacant", tone: "warning" },
  lead.ownerType === "COMPANY" && { icon: "building", label: "Entity-owned", tone: "neutral" },
  lead.ownershipMonths != null && { icon: "calendar-clock", label: `Owned ${Math.floor(lead.ownershipMonths / 12)}y ${lead.ownershipMonths % 12}m`, tone: "neutral" }].
  filter(Boolean);

  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>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
            <TierBadge tier={lead.tier} />
            <strong style={{ fontSize: 18, fontWeight: 800 }}>{lead.address}</strong>
          </div>
          <span style={{ fontSize: 13, color: "var(--text-muted)" }}>{lead.cityZip} · {lead.county}</span>
        </div>
        <StatusChip tone={LEADQ_TONE[lead.status]}>{LQ_TAB_LABEL[lead.status] || lead.status}</StatusChip>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10 }}>
        <StatCard label="Trigger">{lead.trigger}</StatCard>
        <StatCard label="Source">{lead.source || "DC Property & Ownership Export"}</StatCard>
        <StatCard label="Submitted">{lead.submittedAt}</StatCard>
        <StatCard label="Owner(s)"><span style={{ fontSize: 12.5, fontWeight: 700 }}>{owners}</span></StatCard>
      </div>

      <Card title="Lead score" note={lead.model || "canonical model v2"} actions={<QualityPips value={lead.quality} />}>
        <div style={{ display: "grid", gap: 14 }}>
          <ProgressBar value={lead.score} max={100} color={scoreColor(lead.score)} label="Score" valueText={`${lead.score} / 100`} />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10 }}>
            <StatCard label="Est. value">{usdK(lead.estValue)}</StatCard>
            <StatCard label="Equity">{lead.equityPct == null ? "—" : lead.equityPct + "%"}</StatCard>
            <StatCard label="Starting bid">{lead.startingBid} <span style={{ fontSize: 11, color: "var(--text-muted)" }}>Strata</span></StatCard>
            <StatCard label="Tier">{lead.tier}</StatCard>
          </div>
          {signals.length > 0 &&
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {signals.map((s, i) => <StatusChip key={i} tone={s.tone}>{I(s.icon, { width: 12 })} {s.label}</StatusChip>)}
            </div>
          }
        </div>
      </Card>

      <Card title="Owner contact" style={{ boxShadow: "none", background: "var(--surface-subtle)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12.5, color: "var(--text-muted)" }}>
          {I("hourglass", { width: 15, color: "var(--warning)" })}
          <span>Phone / email enrichment <strong style={{ color: "var(--text)" }}>pending</strong> — resolved on the Lead Enrichment surface before delivery.</span>
        </div>
      </Card>

      {lead.status === "rejected" && lead.rejectReason &&
      <Card title="Rejection reason" style={{ boxShadow: "none", background: "var(--danger-soft)" }}>
          <p style={{ margin: 0, fontSize: 13 }}>{lead.rejectReason}</p>
        </Card>
      }

      {lead.status === "pending" &&
      <div style={{ display: "grid", gap: 12 }}>
          <Field label="Publish tier" as="select" value={tier} onChange={(e) => setTier(e.target.value)}>
            {TIER_OPTIONS.map((t) => <option key={t} value={t}>{t}</option>)}
          </Field>
          {!rejecting ?
        <div style={{ display: "flex", gap: 10 }}>
              <Button variant="danger" disabled={publishing} icon={I("x-circle", { width: 15 })} onClick={() => setRejecting(true)}>Reject</Button>
              <Button variant="primary" disabled={publishing} icon={publishing ? <Spinner size={14} /> : <IconCheckCircle size={15} />} onClick={publish} fullWidth>{publishing ? "Publishing…" : "Verify & Publish to Preview Feed"}</Button>
            </div> :

        <Card title="Reject lead" style={{ boxShadow: "none" }}>
              <div style={{ display: "grid", gap: 10 }}>
                <Field as="select" value={reason} onChange={(e) => setReason(e.target.value)}>
                  {REJECT_REASONS.map((r) => <option key={r} value={r}>{r}</option>)}
                </Field>
                <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
                  <Button variant="secondary" onClick={() => setRejecting(false)}>Cancel</Button>
                  <Button variant="danger" onClick={() => onReject(lead.id, { reason })}>Confirm Reject</Button>
                </div>
              </div>
            </Card>
        }
        </div>
      }
    </div>);

}

function LeadOpsPage({ leadQueue, onVerify, onReject, selectedLeadId, onSelectLead }) {
  const [tab, setTab] = React.useState("pending");
  const rows = tab === "all" ? leadQueue : leadQueue.filter((l) => l.status === tab);
  const paged = usePaged(rows, { k: "leadq", dep: tab }, 25);
  React.useEffect(refresh, [tab, selectedLeadId, paged.page]);

  const selected = leadQueue.find((l) => l.id === selectedLeadId) || rows[0] || null;

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)", height: "calc(100vh - 4px)", display: "flex", flexDirection: "column" }}>
      <PageHeader eyebrow="Lead Operations" title="Marketplace Lead Review" description="Verify inbound DC trigger leads before they enter the Preview Feed or Live Marketplace." />

      <div style={{ marginBottom: 14 }}>
        <Tabs value={tab} onChange={(v) => {setTab(v);onSelectLead(null);}} tabs={LQ_TABS.map((t) => ({ value: t, label: LQ_TAB_LABEL[t], count: t === "all" ? leadQueue.length : leadQueue.filter((l) => l.status === t).length }))} />
      </div>

      <div style={{ flex: 1, minHeight: 0, display: "grid", gridTemplateColumns: "400px 1fr", gap: 18 }}>
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0, border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)", overflow: "hidden" }}>
          <div style={{ flex: 1, overflowY: "auto" }}>
            {rows.length === 0 ?
            <EmptyState icon="radar" title="Nothing here" message="No leads in this state." /> :

            paged.slice.map((l) => <LeadQueueRow key={l.id} l={l} active={selected?.id === l.id} onClick={() => onSelectLead(l.id)} />)
            }
          </div>
          {rows.length > 0 &&
          <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="leads" options={[25, 50, 100]} />
            </div>
          }
        </div>
        <LeadQueueDetail lead={selected} onVerify={onVerify} onReject={onReject} />
      </div>
    </div>);

}

Object.assign(window, { OpsLeadOps: { LeadOpsPage } });
