/* =========================================================================
   Veto · Payoffs — the first money line promoted from a Money tab into a real
   sub-product page with its own tabs. This is the missing tier-2/tier-3 layer:
     Money (rail) → Money overview (directory) → Payoffs (sub-product) → tabs.
   It also doubles as the shell for the seller/payoff vertical slice.
   ========================================================================= */

const PAYOFF_TABS = [
  { key: "overview", label: "Overview", to: "/funds/payoffs" },
  { key: "queue", label: "Queue", to: "/funds/payoffs/queue" },
  { key: "holds", label: "Holds", to: "/funds/payoffs/holds" },
  { key: "records", label: "Records", to: "/funds/payoffs/records" },
  { key: "policy", label: "Policy", to: "/funds/payoffs/policy" },
];

const PAYOFF_HOLDS = [
  { id: "HOLD-014", file: "SP-0211", street: "2208 Westcliff Dr", raised: "May 21 · 4:12 pm", owner: "Javier Reyes", state: "Open",
    cure: "Confirm beneficiary phone against the office contact file before any release." },
  { id: "HOLD-031", file: "PD-1027", street: "412 Marigold Ave", raised: "May 22 · 9:05 am", owner: "Madeline Lane", state: "In cure",
    cure: "Updated demand required; good-through date falls short of closing." },
];

const PAYOFF_POLICIES = [
  { name: "Updated payoff demand stales prior record", effect: "Stale prior record · create v2", status: "Active" },
  { name: "Expired good-through date blocks release", effect: "Block release request", status: "Active" },
  { name: "Private payoff requires manager review", effect: "Require manager exception", status: "Active" },
  { name: "Payoff destination change requires callback", effect: "Require source · trusted callback", status: "Active" },
];

function PayoffTabbar({ active }) {
  return (
    <div className="border-b border-line">
      <nav className="flex items-center gap-6 overflow-x-auto">
        {PAYOFF_TABS.map((t) => (
          <Link key={t.key} to={t.to}
            className={cn("-mb-px shrink-0 whitespace-nowrap border-b py-3 text-[13.5px] transition",
              active === t.key ? "border-ink font-medium text-ink" : "border-transparent text-ink-soft hover:text-ink")}>
            {t.label}
          </Link>
        ))}
      </nav>
    </div>
  );
}

function PayoffOverview({ rows }) {
  const open = rows.filter((r) => r.status === "In review").length;
  const steps = [
    { icon: "file-text", label: "Demand", note: "Captured, amount and good-through extracted." },
    { icon: "phone", label: "Review", note: "Current through closing, callback recorded." },
    { icon: "shield", label: "Payoff Record", note: "Source-bound, limitations visible." },
    { icon: "arrow-right", label: "Release", note: "Requested only against the current record." },
  ];
  const stats = [
    { label: "In review", value: open },
    { label: "Open holds", value: PAYOFF_HOLDS.filter((h) => h.state === "Open").length },
    { label: "Closing this week", value: rows.length },
  ];
  return (
    <div>
      <p className="max-w-[560px] text-[13px] leading-relaxed text-ink-soft">
        Obligations out. Pay off existing liens with a demand current through closing and a callback record. No release request proceeds without a current Payoff Record.
      </p>
      <div className="mt-6 grid grid-cols-3 gap-3">
        {stats.map((s) => (
          <div key={s.label} className="rounded-xl border border-line bg-background p-4">
            <div className="font-mono text-[24px] tabular-nums tracking-[-0.02em] text-ink">{s.value}</div>
            <div className="mt-0.5 text-[12px] text-ink-soft">{s.label}</div>
          </div>
        ))}
      </div>
      <div className="mt-7 text-[11px] uppercase tracking-[0.06em] text-muted-foreground">The payoff line</div>
      <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
        {steps.map((s, i) => (
          <div key={s.label} className="rounded-xl border border-line bg-background p-4">
            <div className="flex items-center gap-2">
              <span className="grid h-7 w-7 place-items-center rounded-lg border border-line bg-surface/60 text-ink-soft"><Icon name={s.icon} size={14} /></span>
              <span className="font-mono text-[11px] text-muted-foreground">{String(i + 1).padStart(2, "0")}</span>
            </div>
            <div className="mt-3 text-[13.5px] font-medium tracking-[-0.01em] text-ink">{s.label}</div>
            <div className="mt-1 text-[12px] leading-snug text-ink-soft text-pretty">{s.note}</div>
          </div>
        ))}
      </div>
      <footer className="mt-9 border-t border-line pt-5">
        <p className="text-[12px] text-ink-soft">Veto records support. The office decides and acts.</p>
      </footer>
    </div>
  );
}

function PayoffQueue({ rows }) {
  const [sub, setSub] = useState("all");
  const counts = { all: rows.length, open: rows.filter((r) => r.status === "In review").length, recorded: rows.filter((r) => r.status === "Recorded").length };
  const subtabs = [{ key: "all", label: "All" }, { key: "open", label: "In review" }, { key: "recorded", label: "Recorded" }];
  const visible = sub === "all" ? rows : rows.filter((r) => (sub === "open" ? r.status === "In review" : r.status === "Recorded"));
  return (
    <div>
      <div className="flex items-center justify-between gap-6">
        <p className="text-[13px] text-ink-soft">Every open and recorded payoff review.</p>
        <Link to="/payoff/new" className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-ink px-3.5 py-2 text-[12.5px] font-medium text-background transition hover:bg-ink/90">
          <Icon name="plus" size={14} strokeWidth={2} />New payoff review
        </Link>
      </div>
      <div className="mt-5 border-b border-line pb-3"><QueueTabs tabs={subtabs} tab={sub} setTab={setSub} counts={counts} /></div>
      {visible.length === 0 ? (
        <div className="mt-12"><EmptyState icon={<Icon name="file-text" size={40} />} title="Nothing here" note="Open a payoff review and Veto sets its required sources and the callback." /></div>
      ) : (
        <ul className="mt-1 flex flex-col divide-y divide-line">
          {visible.map((r) => <FileRow key={r.id} id={r.id} street={r.street} city={r.city} party={r.party} status={r.status} meta={shortClosing(r.when)} />)}
        </ul>
      )}
    </div>
  );
}

function PayoffHolds() {
  return (
    <div>
      <p className="text-[13px] text-ink-soft">Open and curing holds on the payoff line. A hold blocks the release until its cure is recorded.</p>
      <ul className="mt-5 flex flex-col divide-y divide-line">
        {PAYOFF_HOLDS.map((h) => (
          <li key={h.id} className="py-4">
            <div className="flex items-center gap-3">
              <span className={cn("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-medium",
                h.state === "Open" ? "bg-[var(--warn-bg)] text-[var(--warn)]" : "bg-surface-2 text-ink-soft")}>
                <span className={cn("h-1.5 w-1.5 rounded-full", h.state === "Open" ? "bg-[var(--warn)]" : "bg-ink-soft/50")} />{h.state}
              </span>
              <span className="text-[13.5px] text-ink">{h.street}</span>
              <span className="font-mono text-[11px] text-muted-foreground">{h.id} · {h.file}</span>
            </div>
            <p className="mt-1.5 max-w-[620px] text-[12.5px] leading-relaxed text-ink-soft">{h.cure}</p>
            <div className="mt-1.5 font-mono text-[11px] text-muted-foreground">Raised {h.raised} · {h.owner}</div>
          </li>
        ))}
      </ul>
    </div>
  );
}

function PayoffRecords() {
  return (
    <div>
      <p className="max-w-[560px] text-[13px] leading-relaxed text-ink-soft">
        The proof artifacts this line produces. Each Payoff Record carries the demand source, good-through date, per diem, destination, and callback record.
      </p>
      <div className="mt-6">
        <Link to="/scaffold/$key" params={{ key: "rec-payoff" }}
          className="group flex max-w-[420px] flex-col rounded-xl border border-line bg-background p-4 transition hover:border-ink/20 hover:bg-surface/40">
          <div className="flex items-center justify-between">
            <span className="grid h-9 w-9 place-items-center rounded-lg border border-line bg-surface/60 text-ink-soft transition group-hover:text-ink"><Icon name="landmark" size={17} /></span>
            <span className="rounded-full border border-line px-2 py-0.5 text-[10.5px] text-muted-foreground">Open</span>
          </div>
          <div className="mt-3 text-[13.5px] font-medium tracking-[-0.01em] text-ink">Payoff Records</div>
          <div className="mt-0.5 text-[12px] text-ink-soft">Obligation support, demand-bound</div>
        </Link>
      </div>
    </div>
  );
}

function PayoffPolicy() {
  return (
    <div>
      <p className="max-w-[560px] text-[13px] leading-relaxed text-ink-soft">
        The office policy that governs this line. These controls produce the tasks, stale the records, and block the releases you see elsewhere. Authoring lives in Settings.
      </p>
      <div className="mt-6 overflow-hidden rounded-xl border border-line">
        {PAYOFF_POLICIES.map((p, i) => (
          <div key={p.name} className={cn("flex items-center gap-3 px-4 py-3.5", i > 0 && "border-t border-line")}>
            <Icon name="shield" size={15} className="shrink-0 text-[var(--ok)]" />
            <div className="min-w-0 flex-1">
              <div className="text-[13px] text-ink">{p.name}</div>
              <div className="mt-0.5 font-mono text-[11px] text-muted-foreground">{p.effect}</div>
            </div>
            <span className="inline-flex items-center gap-1.5 rounded-full bg-[var(--ok-bg)] px-2 py-0.5 text-[11px] font-medium text-[var(--ok)]">
              <span className="h-1.5 w-1.5 rounded-full bg-[var(--ok)]" />{p.status}
            </span>
          </div>
        ))}
      </div>
      <p className="mt-4 text-[12px] text-ink-soft">Veto records the evidence state and office review. The office decides and acts under its instructions and policies.</p>
    </div>
  );
}

function PayoffsProduct({ tab = "overview" }) {
  const rows = useMemo(() => lineQueueRows("payoff"), []);
  return (
    <AppShell activeLine="money" reviewer={{ name: "Madeline Lane", initials: "ML" }}>
      <div className="mx-auto w-full max-w-[960px] px-6 py-10 lg:px-10 lg:py-12">
        <header className="mb-5">
          <Link to="/funds" className="inline-flex items-center gap-1 text-[12px] text-ink-soft transition hover:text-ink">
            <Icon name="chevron-left" size={13} /> Funds
          </Link>
          <h1 className="mt-3 text-[20px] font-semibold tracking-[-0.01em] text-ink">Payoffs &amp; Obligations</h1>
        </header>
        <PayoffTabbar active={tab} />
        <div className="mt-7">
          {tab === "overview" && <PayoffOverview rows={rows} />}
          {tab === "queue" && <PayoffQueue rows={rows} />}
          {tab === "holds" && <PayoffHolds />}
          {tab === "records" && <PayoffRecords />}
          {tab === "policy" && <PayoffPolicy />}
        </div>
      </div>
    </AppShell>
  );
}

Object.assign(window, { PayoffsProduct });
