/* =========================================================================
   Veto · Money — the cross-file money-control center (a top-level space).
   One space, tabbed like Files:
     Overview · Funding In · Payoffs · Proceeds · Release Requests · Accounts · Matching
   The three review-line queues fold in as the first real tabs (operators
   still reach a specific queue mostly via Tasks). Release Requests, Accounts,
   Activity, and Matching render focused demo states.
   Also exports Records (the proof-artifact ledger, a secondary nav item).
   ========================================================================= */

const MONEY_TABS = [
  { key: "overview", label: "Overview", to: "/funds" },
  { key: "funding-in", label: "Funding In", to: "/funds/funding-in" },
  { key: "payoffs", label: "Payoffs", to: "/funds/payoffs" },
  { key: "proceeds", label: "Proceeds", to: "/funds/proceeds" },
  { key: "release-requests", label: "Release Requests", to: "/funds/release-requests" },
  { key: "changes", label: "Changes", to: "/funds/changes" },
  { key: "accounts", label: "Accounts", to: "/funds/accounts" },
  { key: "activity", label: "Activity", to: "/funds/activity" },
  { key: "matching", label: "Matching", to: "/funds/matching" },
];

/* Queue tabs map to the existing review-line data + new-review wizard. */
const MONEY_QUEUE = {
  "funding-in": { line: "buyer", label: "Funding In", newTo: "/buyer-funding/new", newLabel: "New funding review",
    blurb: "Money in. Review buyer and lender funding before the office relies on it. Every leg tied to source evidence and limits." },
  "payoffs": { line: "payoff", label: "Payoffs", newTo: "/payoff/new", newLabel: "New payoff review",
    blurb: "Obligations out. Pay off existing liens with a demand current through closing and a callback record." },
  "proceeds": { line: "seller", label: "Proceeds", newTo: "/seller-proceeds/new", newLabel: "New proceeds review",
    blurb: "Entitlements out. Reconcile the final statement, payee support, and destination before office sign-off." },
};

function MoneyTabbar({ active }) {
  return (
    <div className="border-b border-line">
      <nav className="flex items-center gap-6 overflow-x-auto">
        {MONEY_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>
  );
}

/* A review-line queue rendered inside the Money space (no own shell). */
function MoneyQueuePanel({ tabKey }) {
  const meta = MONEY_QUEUE[tabKey];
  const [sub, setSub] = useState("all");
  const rows = useMemo(() => lineQueueRows(meta.line), [meta.line]);
  const counts = useMemo(() => ({
    all: rows.length,
    open: rows.filter((r) => r.status === "In review").length,
    recorded: rows.filter((r) => r.status === "Recorded").length,
  }), [rows]);
  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-start justify-between gap-6">
        <p className="max-w-[480px] text-[13px] leading-relaxed text-ink-soft">{meta.blurb}</p>
        <Link to={meta.newTo} className="mt-0.5 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} />{meta.newLabel}
        </Link>
      </div>
      <div className="mt-6 border-b border-line pb-3"><QueueTabs tabs={subtabs} tab={sub} setTab={setSub} counts={counts} /></div>
      {visible.length === 0 ? (
        <div className="mt-14">
          <EmptyState icon={<Icon name="file-text" size={44} />}
            title={sub === "recorded" ? "Nothing recorded yet" : `Nothing in ${meta.label.toLowerCase()}`}
            note={sub === "recorded"
              ? `Recorded ${meta.label.toLowerCase()} reviews collect here with their signed receipts.`
              : `Open a ${meta.label.toLowerCase()} review and Veto sets its required sources and the callback.`}
            action={<Link to={meta.newTo} className="inline-flex h-9 items-center gap-1.5 rounded-lg bg-ink px-4 text-[13px] font-medium text-background transition hover:bg-ink/90"><Icon name="plus" size={14} /> {meta.newLabel}</Link>}
            secondaryAction={<LearnMore />} />
        </div>
      ) : (
        <ul className="mt-1 flex flex-col divide-y divide-line">
          {visible.map((r) => {
            const action = meta.line === "seller" && typeof getActionState === "function" ? getActionState(r.id, "seller-proceeds-release") : null;
            const status = action?.state || r.status;
            return (
              <FileRow key={r.id} id={r.id} street={r.street} city={r.city} party={r.party}
                status={status} meta={action ? "record stale" : shortClosing(r.when)} />
            );
          })}
        </ul>
      )}
    </div>
  );
}

/* Focused state panel for secondary money tabs. */
function MoneyScaffold({ icon, phase, title, note, action }) {
  return (
    <div className="mt-2">
      {phase && (
        <div className="mb-6 inline-flex items-center gap-2 rounded-full border border-line bg-surface px-2.5 py-1 text-[11px] text-ink-soft">
          <span className="inline-block h-1.5 w-1.5 rounded-full bg-ink-soft/50" />{phase}
        </div>
      )}
      <div className="mt-2"><EmptyState icon={<Icon name={icon} size={22} />} title={title} note={note} action={action} /></div>
    </div>
  );
}

function ChangeLedgerPanel() {
  const rows = Object.keys(CASE_FILES).flatMap((id) => typeof getChangeEvents === "function" ? getChangeEvents(id) : []);
  return (
    <div>
      <p className="max-w-[560px] text-[13px] leading-relaxed text-ink-soft">
        Every material value that changed after the office relied on a prior state. Veto stales the affected record and opens the required task before release.
      </p>
      <div className="mt-6 overflow-hidden rounded-xl border border-line bg-background">
        {rows.map((c, i) => {
          const cf = CASE_FILES[c.fileId];
          const policy = typeof getPolicyControl === "function" ? getPolicyControl(c.policyId) : null;
          return (
            <div key={c.id} className={cn("px-4 py-4", i > 0 && "border-t border-line")}>
              <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                <div className="min-w-0">
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="inline-flex items-center gap-1.5 rounded-full bg-[var(--warn-bg)] px-2 py-0.5 text-[11px] font-medium text-[var(--warn)]">
                      <span className="h-1.5 w-1.5 rounded-full bg-[var(--warn)]" />{c.status}
                    </span>
                    <span className="font-mono text-[11px] text-muted-foreground">{c.fileId}</span>
                  </div>
                  <div className="mt-2 text-[13.5px] font-medium text-ink">{streetOf(cf?.property)} · {c.action}</div>
                  <p className="mt-1 text-[12.5px] text-ink-soft">{c.field} changed after reliance. {c.staledRecordLabel} is no longer current.</p>
                </div>
                <div className="shrink-0 text-left sm:text-right">
                  <div className="font-mono text-[11px] text-muted-foreground">{c.detectedAt}</div>
                  <div className="mt-1 text-[11.5px] text-[var(--warn)]">{c.age} old</div>
                </div>
              </div>
              <div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-3">
                <div className="rounded-lg border border-line bg-surface/40 px-3 py-2.5">
                  <div className="text-[10px] uppercase tracking-[0.06em] text-muted-foreground">Prior</div>
                  <div className="mt-1 font-mono text-[12px] text-ink-soft">{c.from}</div>
                </div>
                <div className="rounded-lg border border-ink/20 bg-background px-3 py-2.5">
                  <div className="text-[10px] uppercase tracking-[0.06em] text-muted-foreground">Changed to</div>
                  <div className="mt-1 font-mono text-[12px] text-ink">{c.to}</div>
                </div>
                <div className="rounded-lg border border-line bg-surface/40 px-3 py-2.5">
                  <div className="text-[10px] uppercase tracking-[0.06em] text-muted-foreground">Policy effect</div>
                  <div className="mt-1 text-[12px] text-ink">{policy?.effect || "Require v2 record"}</div>
                </div>
              </div>
              <div className="mt-4 flex flex-wrap items-center gap-2">
                <Link to="/tasks" className="inline-flex items-center gap-1.5 rounded-md bg-ink px-3 py-1.5 text-[12px] font-medium text-background transition hover:bg-ink/90">Create v2 record</Link>
                <Link to="/file/$id" params={{ id: c.fileId }} className="inline-flex items-center gap-1.5 rounded-md border border-line px-3 py-1.5 text-[12px] font-medium text-ink transition hover:bg-surface">Open file</Link>
                <Link to="/file/$id/change-impact" params={{ id: c.fileId }} className="inline-flex items-center gap-1.5 rounded-md border border-line px-3 py-1.5 text-[12px] font-medium text-ink transition hover:bg-surface">Impact record</Link>
                <Link to="/settings/policy" className="inline-flex items-center gap-1.5 rounded-md border border-line px-3 py-1.5 text-[12px] font-medium text-ink transition hover:bg-surface">Policy</Link>
                <span className="ml-auto text-[11.5px] text-ink-soft">{c.requiredNextStep}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* Cross-file money overview — the lifecycle, in order, as the landing tab. */
function MoneyOverview() {
  const openCount = (line) => lineQueueRows(line).filter((r) => r.status === "In review").length;
  const cards = [
    { to: "/funds/funding-in", icon: "arrow-down-left", label: "Funding In", sub: "Money in", count: openCount("buyer") },
    { to: "/funds/payoffs", icon: "landmark", label: "Payoffs", sub: "Obligations out", count: openCount("payoff") },
    { to: "/funds/proceeds", icon: "arrow-up-right", label: "Proceeds", sub: "Entitlements out", count: openCount("seller") },
    { to: "/funds/release-requests", icon: "arrow-right", label: "Release Requests", sub: "The no-bypass gate" },
    { to: "/funds/accounts", icon: "building", label: "Accounts", sub: "Destinations & sources" },
    { to: "/funds/matching", icon: "check-circle", label: "Matching", sub: "Did money match the record?" },
  ];
  return (
    <div>
      <p className="max-w-[560px] text-[13px] leading-relaxed text-ink-soft">
        The lifecycle of every dollar across open files: in, out, requested, and matched. Each step opens its own working queue.
      </p>
      <div className="mt-6 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {cards.map((c) => (
          <Link key={c.to} to={c.to}
            className="group flex 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={c.icon} size={17} />
              </span>
              {typeof c.count === "number"
                ? <span className="font-mono text-[12px] tabular-nums text-ink-soft">{c.count} open</span>
                : null}
            </div>
            <div className="mt-3 text-[14px] font-medium tracking-[-0.01em] text-ink">{c.label}</div>
            <div className="mt-0.5 text-[12px] text-ink-soft">{c.sub}</div>
          </Link>
        ))}
      </div>
      <footer className="mt-10 border-t border-line pt-5">
        <p className="text-[12px] text-ink-soft">Veto records support. The office decides and acts.</p>
      </footer>
    </div>
  );
}

/* Accounts + Activity tabs are hubs into their real control surfaces. */
const ACCOUNT_CARDS = [
  { key: "money-trust", icon: "landmark", label: "Trust Accounts", sub: "Office trust, watched against the record" },
  { key: "money-destinations", icon: "building", label: "Destination Accounts", sub: "Where outgoing money may go" },
  { key: "money-sources", icon: "arrow-down-left", label: "Funding Source Accounts", sub: "Where incoming money came from" },
  { key: "money-payees", icon: "users", label: "Payee Directory", sub: "Cross-file payee memory" },
  { key: "money-checks", icon: "shield", label: "Account Checks", sub: "What a check does and does not prove" },
  { key: "money-restricted", icon: "lock", label: "Restricted Details", sub: "Sensitive values behind permission" },
];
const ACTIVITY_CARDS = [
  { key: "act-incoming", icon: "arrow-down-left", label: "Incoming", sub: "Buyer and lender money arriving" },
  { key: "act-outgoing", icon: "arrow-up-right", label: "Outgoing", sub: "Money that left or is scheduled" },
  { key: "act-pending", icon: "clock", label: "Pending Release", sub: "Requests not yet consumed or matched" },
  { key: "act-matched", icon: "check-circle", label: "Matched", sub: "Wires reconciled to the record" },
  { key: "act-unmatched", icon: "alert-circle", label: "Unmatched", sub: "The page that should stay empty" },
  { key: "act-exceptions", icon: "shield", label: "Exceptions", sub: "Movement that needs review" },
];
function MoneyHubGrid({ cards }) {
  return (
    <div className="mt-2 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
      {cards.map((c) => (
        <Link key={c.key} to="/scaffold/$key" params={{ key: c.key }}
          className="group flex flex-col rounded-xl border border-line bg-background p-4 outline-none transition hover:border-ink/20 hover:bg-surface/40 focus-visible:ring-2 focus-visible:ring-ink/40">
          <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={c.icon} size={17} /></span>
          <div className="mt-3 text-[13.5px] font-medium tracking-[-0.01em] text-ink">{c.label}</div>
          <div className="mt-0.5 text-[12px] text-ink-soft">{c.sub}</div>
        </Link>
      ))}
    </div>
  );
}
function AccountsHub() { return <MoneyHubGrid cards={ACCOUNT_CARDS} />; }
function ActivityHub() { return <MoneyHubGrid cards={ACTIVITY_CARDS} />; }

const MONEY_LABEL = { "funding-in": "Funding In", "payoffs": "Payoffs", "proceeds": "Proceeds", "release-requests": "Release Requests", "changes": "Changes After Reliance", "accounts": "Accounts", "activity": "Activity", "matching": "Matching" };
function MoneyCenter({ tab = "overview" }) {
  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">
        {tab === "overview" ? (
          <header className="mb-6">
            <h1 className="text-[20px] font-semibold tracking-[-0.01em] text-ink">Funds</h1>
            <p className="mt-1 text-[13px] text-ink-soft">The office's money-control center, across every open file rather than buried in one.</p>
          </header>
        ) : (
          <header className="mb-6">
            <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">{MONEY_LABEL[tab] || "Funds"}</h1>
          </header>
        )}
        <div>
          {tab === "overview" && <MoneyOverview />}
          {MONEY_QUEUE[tab] && <MoneyQueuePanel tabKey={tab} />}
          {tab === "release-requests" && <ControlSurfaceBody spec={SURFACE_CONTENT["money-release"]} headless />}
          {tab === "accounts" && <AccountsHub />}
          {tab === "matching" && <ControlSurfaceBody spec={SURFACE_CONTENT["act-matched"]} headless />}
          {tab === "changes" && <ChangeLedgerPanel />}
          {tab === "activity" && <ActivityHub />}
        </div>
      </div>
    </AppShell>
  );
}

/* ------------------------------------------------------------- Records */
const RECORD_CARDS = [
  { to: "rec-all", icon: "file-text", label: "All Records", sub: "Every signed and draft artifact" },
  { to: "rec-release", icon: "arrow-right", label: "Release Request Records", sub: "The pre-money-action artifact" },
  { to: "rec-change", icon: "alert-circle", label: "Change Impact Records", sub: "What changed and what it staled" },
  { to: "rec-payoff", icon: "landmark", label: "Payoff Records", sub: "Obligation support" },
  { to: "rec-proceeds", icon: "arrow-up-right", label: "Proceeds Records", sub: "Entitlement support" },
  { to: "rec-funding", icon: "arrow-down-left", label: "Funding Records", sub: "Money-in support" },
  { to: "rec-exception", icon: "shield", label: "Exception Records", sub: "Manager-reviewed gaps" },
  { to: "rec-holdlock", icon: "lock", label: "Hold / Lock Records", sub: "Stop-action states" },
  { to: "rec-audit", icon: "file-text", label: "Audit Packets", sub: "Exportable file-review package" },
];
function RecordsScreen() {
  return (
    <AppShell activeLine="records" reviewer={{ name: "Madeline Lane", initials: "ML" }}>
      <div className="mx-auto w-full max-w-[920px] px-6 py-10 lg:px-10 lg:py-12">
        <header className="mb-2">
          <div className="text-[11.5px] uppercase tracking-[0.06em] text-muted-foreground">Proof artifacts</div>
          <h1 className="mt-2 text-[26px] font-semibold leading-[1.15] tracking-[-0.02em] text-ink">Records</h1>
          <p className="mt-2 max-w-[560px] text-[13.5px] leading-relaxed text-ink-soft text-pretty">
            The immutable record behind every consequential action: review records, change-impact records, release requests, exceptions, and holds. The office's answer to what state allowed money to move.
          </p>
        </header>
        <div className="mt-8 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {RECORD_CARDS.map((c) => (
            <Link key={c.to} to="/scaffold/$key" params={{ key: c.to }}
              className="group flex 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={c.icon} 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">{c.label}</div>
              <div className="mt-0.5 text-[12px] text-ink-soft">{c.sub}</div>
            </Link>
          ))}
        </div>
        <footer className="mt-10 border-t border-line pt-5">
          <p className="text-[12px] text-ink-soft">Records are produced by completed tasks, never written by hand.</p>
        </footer>
      </div>
    </AppShell>
  );
}

Object.assign(window, { MoneyCenter, RecordsScreen });
