/* =========================================================================
   Veto · File overview — the escrow control record (one transaction).
   Plain reading order: what this file is, the one thing to do next, the
   money moving through it, and the proof. A movement is the unit of work:
   you review it, then it's recorded. The file closes when every movement
   is recorded and the ledger balances.
   ========================================================================= */

const MV_STATUS = {
  "Recorded":    { chip: "bg-[var(--ok-bg)] text-[var(--ok)]", bar: "bg-[var(--ok)]" },
  "Blocked":     { chip: "bg-[var(--warn-bg)] text-[var(--warn)]", bar: "bg-[var(--warn)]" },
  "In review":   { chip: "bg-[var(--warn-bg)] text-[var(--warn)]", bar: "bg-[var(--warn)]" },
  "Not started": { chip: "bg-surface-2 text-ink-soft", bar: "bg-line" },
};

/* One row in the ledger. A movement with a review line is clickable. */
function MovementRow({ id, m, dir }) {
  const reviewable = !!m.line;
  const recorded = m.status === "Recorded";
  const action = m.line === "seller" && typeof getActionState === "function" ? getActionState(id, "seller-proceeds-release") : null;
  const displayStatus = action?.state || m.status;
  const s = MV_STATUS[displayStatus] || MV_STATUS[m.status];

  const inner = (
    <div className="flex items-center gap-3.5 px-4 py-3.5">
      <span className={cn("grid h-9 w-9 shrink-0 place-items-center rounded-lg", dir === "in" ? "bg-[var(--ok-bg)] text-[var(--ok)]" : "bg-surface-2 text-ink-soft")}>
        <Icon name={dir === "in" ? "arrow-down-left" : "arrow-up-right"} size={16} />
      </span>
      <div className="min-w-0 flex-1">
        <div className="truncate text-[13.5px] font-medium text-ink">{m.label}</div>
        <div className="truncate text-[12px] text-ink-soft">{m.party}</div>
      </div>
      <div className="w-28 shrink-0 text-right font-mono text-[13px] tabular-nums text-ink">{fmtUSD(m.amount)}</div>
      <span className={cn("hidden w-[88px] shrink-0 justify-center whitespace-nowrap rounded-full px-2 py-0.5 text-center text-[11px] sm:inline-flex", s.chip)}>{displayStatus}</span>
      {reviewable ? (
        <span className="hidden w-[74px] shrink-0 items-center justify-end gap-0.5 text-[12px] font-medium text-ink-soft transition group-hover:text-ink sm:flex">
          {recorded ? "View" : "Review"}<Icon name="chevron-right" size={14} />
        </span>
      ) : (
        <span className="hidden w-[74px] shrink-0 justify-end text-[11px] text-muted-foreground sm:flex">Ledger entry</span>
      )}
      <Icon name="chevron-right" size={15} className={cn("shrink-0 text-ink-soft sm:hidden", !reviewable && "opacity-0")} />
    </div>
  );

  if (reviewable) {
    return (
      <li>
        <Link to="/file/$id/review/$line" params={{ id, line: m.line }} className="group block transition hover:bg-surface/50">{inner}</Link>
      </li>
    );
  }
  return <li className="bg-surface/20">{inner}</li>;
}

function LedgerGroup({ id, title, total, items, dir }) {
  return (
    <div>
      <div className="flex items-baseline justify-between px-1 pb-2">
        <h3 className="whitespace-nowrap text-[11.5px] font-medium uppercase tracking-[0.06em] text-muted-foreground">{title}</h3>
        <span className="font-mono text-[12.5px] tabular-nums text-ink-soft">{fmtUSD(total)}</span>
      </div>
      <ul className="divide-y divide-line overflow-hidden rounded-xl border border-line bg-background">
        {items.map((m) => <MovementRow key={m.id} id={id} m={m} dir={dir} />)}
      </ul>
    </div>
  );
}

function FileOverview({ id }) {
  const cf = CASE_FILES[id];
  const mv = useMemo(() => fileMovements(id), [id]);
  const all = [...mv.deposits, ...mv.disbursements];
  const recorded = all.filter((m) => m.status === "Recorded").length;
  const reviewable = all.filter((m) => m.line);
  const openReviews = reviewable.filter((m) => m.status !== "Recorded");
  const next = openReviews.find((m) => m.status === "In review") || openReviews[0];
  const balanced = Math.abs(mv.net) < 1;
  const allRecorded = all.every((m) => m.status === "Recorded");
  const recordedLines = all.filter((m) => m.line && m.status === "Recorded");
  const [shared, setShared] = useState(false);
  const sellerAction = typeof getActionState === "function" ? getActionState(id, "seller-proceeds-release") : null;
  const sellerChange = typeof getChangeEvents === "function" ? getChangeEvents(id).find((c) => c.actionKey === "seller-proceeds-release") : null;
  const sellerRecords = typeof getRecordsForAction === "function" ? getRecordsForAction(id, "seller-proceeds-release") : [];
  const staleSellerRecord = sellerRecords.find((r) => r.id === sellerAction?.priorRecordId);
  const releaseGate = typeof getReleaseGateStatus === "function" ? getReleaseGateStatus(id, "seller-proceeds-release") : null;

  const activity = [
    { who: "Madeline", what: "recorded the buyer closing funds", at: "May 18" },
    { who: "Javier", what: "opened the payoff review", at: "May 20" },
    { who: "Madeline", what: "opened the file", at: "May 17" },
  ];

  return (
    <AppShell activeFileId={id} reviewer={{ name: "Madeline Lane", initials: "ML" }}>
      {/* ---------------------------------------------------------- Header */}
      <div className="border-b border-line bg-background">
        <div className="mx-auto w-full max-w-[1040px] px-6 py-6 lg:px-10">
          <Link to="/files" className="mb-3 inline-flex items-center gap-1.5 text-[12px] text-ink-soft transition hover:text-ink">
            <Icon name="arrow-left" size={13} /> Files
          </Link>
          <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.5">
                <h1 className="text-[24px] font-semibold leading-tight tracking-[-0.02em] text-ink">{streetOf(cf?.property) || id}</h1>
                <span className={cn("shrink-0 whitespace-nowrap rounded-full px-2.5 py-0.5 text-[11.5px] font-medium", allRecorded ? "bg-[var(--ok-bg)] text-[var(--ok)]" : "bg-[var(--warn-bg)] text-[var(--warn)]")}>{allRecorded ? "Cleared to close" : "In review"}</span>
              </div>
              <div className="mt-1.5 text-[13px] text-ink-soft">
                {cityOf(cf?.property)} · {cf?.party} · Closing {shortClosing(cf?.closing)} · <span className="text-[12px] text-muted-foreground">{id}</span>
              </div>
            </div>
            <div className="no-print flex shrink-0 items-center gap-1">
              <button onClick={() => window.print()} className="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-[12.5px] text-ink-soft transition hover:bg-surface hover:text-ink"><Icon name="printer" size={14} /> Print</button>
              <button onClick={async () => { const ok = await copyText(shareUrlFor("/file/$id", { id })); setShared(ok ? "Copied" : "Copy failed"); setTimeout(() => setShared(false), 1500); }} className="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-[12.5px] text-ink-soft transition hover:bg-surface hover:text-ink"><Icon name={shared === "Copied" ? "check" : "link"} size={14} /> {shared || "Share"}</button>
            </div>
          </div>
        </div>
      </div>

      <div className="mx-auto w-full max-w-[1040px] px-6 py-8 lg:px-10">
        <div className="print-flow grid grid-cols-1 gap-10 lg:grid-cols-[minmax(0,1fr)_280px]">
          <div className="min-w-0">

            {/* ------------------------------------------ Status + next step */}
            <section className="rounded-2xl border border-line bg-surface/40 p-5 sm:p-6">
              {allRecorded ? (
                <div className="flex items-start gap-3">
                  <span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-[var(--ok-bg)] text-[var(--ok)]"><Icon name="check" size={18} strokeWidth={2.5} /></span>
                  <div className="min-w-0">
                    <div className="text-[15px] font-semibold text-ink">Cleared to close</div>
                    <p className="mt-1 text-[13px] leading-relaxed text-ink-soft">Every movement is recorded and the ledger balances. The receipts are in the proof rail.</p>
                  </div>
                </div>
              ) : (
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                  <div className="min-w-0">
                    <div className="text-[15px] font-semibold text-ink">
                      {openReviews.length} {openReviews.length === 1 ? "review" : "reviews"} left before this file can close
                    </div>
                    <p className="mt-1 text-[13px] leading-relaxed text-ink-soft">
                      Veto records the review path for each money movement. {recorded} of {all.length} movements recorded.
                    </p>
                  </div>
                  {next && (
                    <Link to="/file/$id/review/$line" params={{ id, line: next.line }} className="inline-flex shrink-0 items-center gap-2 rounded-lg bg-ink px-4 py-2.5 text-[13px] font-medium text-background transition hover:bg-ink/90">
                      <span>Continue review</span>
                      <span className="hidden font-normal text-background/60 sm:inline">{next.label}</span>
                      <Icon name="arrow-right" size={14} />
                    </Link>
                  )}
                </div>
              )}
              <div className="mt-5 flex items-center gap-1.5" aria-hidden>
                {all.map((m, i) => <span key={i} className={cn("h-1.5 flex-1 rounded-full", MV_STATUS[m.status].bar)} />)}
              </div>
            </section>

            {/* ----------------------------------------------------- Ledger */}
            <div className="mt-9">
              <div className="mb-4 flex items-baseline justify-between">
                <h2 className="text-[15px] font-semibold tracking-[-0.01em] text-ink">Ledger</h2>
                <p className="text-[12px] text-ink-soft">Open a movement to review it</p>
              </div>
              <div className="space-y-6">
                <LedgerGroup id={id} title="Money in · deposits" total={mv.totalIn} items={mv.deposits} dir="in" />
                <LedgerGroup id={id} title="Money out · disbursements" total={mv.totalOut} items={mv.disbursements} dir="out" />
              </div>

              {/* Balance line */}
              <div className={cn("mt-6 flex flex-col gap-2 rounded-xl border px-5 py-4 sm:flex-row sm:items-center sm:justify-between",
                balanced ? "border-[var(--ok)]/25 bg-[var(--ok-bg)]" : "border-[var(--warn)]/30 bg-[var(--warn-bg)]")}>
                <div className="flex items-center gap-2.5">
                  <Icon name={balanced ? "check-circle" : "alert-circle"} size={18} className={balanced ? "text-[var(--ok)]" : "text-[var(--warn)]"} />
                  <div>
                    <div className={cn("text-[13.5px] font-medium", balanced ? "text-[var(--ok)]" : "text-[var(--warn)]")}>
                      {balanced ? "The ledger balances" : `Out of balance by ${fmtUSD(Math.abs(mv.net))}`}
                    </div>
                    <div className="text-[12px] text-ink-soft">Money in has to equal money out before a file can close.</div>
                  </div>
                </div>
                <div className="pl-8 font-mono text-[12px] tabular-nums text-ink-soft sm:pl-0">{fmtUSD(mv.totalIn)} in &nbsp;=&nbsp; {fmtUSD(mv.totalOut)} out</div>
              </div>
            </div>
          </div>

          {/* ------------------------------------------------------ Right rail */}
          <aside className="lg:sticky lg:top-20 lg:self-start">
            {sellerAction && (
              <section className="mb-6 border-b border-line pb-6">
                <div className="mb-3 text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground">Release gate</div>
                <div className="rounded-xl border border-[var(--warn)]/25 bg-[var(--warn-bg)] px-3.5 py-3">
                  <div className="flex items-center gap-2 text-[12.5px] font-medium text-[var(--warn)]">
                    <Icon name="alert-circle" size={14} /> {releaseGate?.status || sellerAction.state}
                  </div>
                  <p className="mt-1.5 text-[12px] leading-relaxed text-ink-soft">{sellerAction.reason}</p>
                  <div className="mt-3 space-y-2 border-t border-[var(--warn)]/20 pt-3">
                    <div className="flex items-start justify-between gap-3 text-[11.5px]">
                      <span className="text-ink-soft">Current record</span>
                      <span className="text-right font-mono text-[11px] text-[var(--warn)]">{staleSellerRecord?.version || "v1"} · stale</span>
                    </div>
                    <div className="flex items-start justify-between gap-3 text-[11.5px]">
                      <span className="text-ink-soft">Destination</span>
                      <span className="text-right font-mono text-[11px] text-ink">{sellerChange ? `${sellerChange.from} → ${sellerChange.to}` : "changed"}</span>
                    </div>
                    <div className="flex items-start justify-between gap-3 text-[11.5px]">
                      <span className="text-ink-soft">Required</span>
                      <span className="text-right text-ink">v2 record or exception</span>
                    </div>
                  </div>
                  <Link to="/file/$id/review/seller" params={{ id }} className="mt-3 inline-flex w-full items-center justify-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/change-impact" params={{ id }} className="mt-2 inline-flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--warn)]/25 bg-background/60 px-3 py-1.5 text-[12px] font-medium text-ink transition hover:bg-background">
                    View impact record
                  </Link>
                </div>
              </section>
            )}
            <section className="mb-6 border-b border-line pb-6">
              <div className="mb-3 text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground">Activity</div>
              <ul className="space-y-2.5">
                {activity.map((a, i) => (
                  <li key={i} className="flex gap-2 text-[12px] leading-snug">
                    <span className="mt-[5px] inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-ink-soft/40" />
                    <span className="text-ink-soft"><span className="text-ink">{a.who}</span> {a.what}<span className="font-mono text-[11px] text-muted-foreground"> · {a.at}</span></span>
                  </li>
                ))}
              </ul>
            </section>
            <section>
              <div className="mb-3 text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground">Proof</div>
              {recordedLines.length ? (
                <div className="space-y-2">
                  {recordedLines.map((m) => (
                    <Link key={m.id} to={MOVEMENT_RECEIPT[m.line]} params={{ id }} className="group flex items-center gap-2.5 rounded-lg border border-line bg-background px-3 py-2.5 transition hover:border-ink/25 hover:bg-surface/50">
                      <span className="grid h-8 w-8 shrink-0 place-items-center rounded-md bg-surface-2 text-ink-soft"><Icon name="file-text" size={15} /></span>
                      <span className="min-w-0 flex-1"><span className="block truncate text-[12.5px] font-medium text-ink">{m.label}</span><span className="block font-mono text-[11px] text-muted-foreground">receipt · signed</span></span>
                      <Icon name="arrow-right" size={14} className="text-ink-soft transition group-hover:translate-x-0.5" />
                    </Link>
                  ))}
                </div>
              ) : (
                <p className="text-[12px] leading-relaxed text-ink-soft">Receipts appear here as each movement is recorded.</p>
              )}
              <Link to="/file/$id/manifest" params={{ id }} className="mt-4 inline-flex items-center gap-1.5 text-[12px] text-ink-soft underline decoration-line underline-offset-4 transition hover:text-ink">
                <Icon name="paperclip" size={12} /> Evidence manifest
              </Link>
            </section>
          </aside>
        </div>
      </div>
    </AppShell>
  );
}

Object.assign(window, { FileOverview });
