/* =========================================================================
   Veto · Review Register (/overview) — owner surface across the office.
   ========================================================================= */


function sanitizeRegisterText(s) {
  if (!s) return s;
  return String(s)
    .replace(/Beach Pacific Escrow/g, "805 Escrow")
    .replace(/Pacific Coast Escrow/g, "805 Escrow")
    .replace(/Newport Beach/g, "Westlake Village")
    .replace(/Sebastian John Heyneman Wells/g, "James Whitfield")
    .replace(/Sebastian Heyneman Wells/g, "James Whitfield")
    .replace(/Sebastian Wells/g, "James Whitfield")
    .replace(/Heyneman Holdings/g, "Whitfield Coast Holdings LLC")
    .replace(/\bJavier Reyes\b/g, "Madeline Lane");
}

function registerOfficerLabel(cf) {
  if (!cf) return "M. Lane";
  if (cf.reviewerInitials === "ML" || cf.reviewer === "Madeline Lane") return "M. Lane";
  return cf.reviewer || cf.reviewerInitials || "M. Lane";
}

function registerRows() {
  const rows = [];
  const hero = {
    id: "SP-0214",
    property: "4125 Lakeview Canyon Rd",
    closing: "May 22, 2026",
    officer: "M. Lane",
    officerInitials: "ML",
    state: "Blocked/held",
    stateTone: "warn",
    signal: "Payout destination linked to the acting officer — held for owner review",
    payee: "Whitfield Coast Holdings LLC",
    ownerHeld: true,
  };
  rows.push(hero);
  const seen = new Set(["SP-0214"]);
  for (const cf of Object.values(CASE_FILES || {})) {
    if (seen.has(cf.id)) continue;
    seen.add(cf.id);
    const anyReview = Object.values(cf.lines || {}).some((l) => l.status === "In review");
    if (!anyReview) continue;
    const r = getReadiness(cf.id) || buildReadinessFrom(cf.id, cf.reviewer, cf.reviewerInitials, cf.closing);
    const hold = r.holds.find((h) => h.state !== "Cleared");
    const blocker = hold ? hold.cure : (r.lines.find((l) => l.blocker)?.blocker || r.recording.summary);
    rows.push({
      id: cf.id,
      property: sanitizeRegisterText(streetOf(cf.property)),
      closing: cf.closing,
      officer: registerOfficerLabel(cf),
      officerInitials: cf.reviewerInitials,
      state: hold ? "Held" : "In review",
      stateTone: hold ? "warn" : "neutral",
      signal: sanitizeRegisterText(blocker),
      ownerHeld: false,
    });
  }
  return rows;
}

function RegisterStatePill({ state, tone }) {
  const cls = tone === "warn"
    ? "border-[var(--warn)]/30 bg-[var(--warn-bg)] text-[var(--warn)]"
    : "border-line bg-surface text-ink-soft";
  return (
    <span className={cn("inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11px] font-medium", cls)}>
      {tone === "warn" && <span className="h-1.5 w-1.5 rounded-full bg-[var(--warn)]" />}
      {state}
    </span>
  );
}

function ReviewRegisterGate() {
  return (
    <AppShell activeLine="overview">
      <div className="mx-auto w-full max-w-[640px] px-6 py-16 lg:px-12">
        <div className="rounded-xl border border-line bg-surface/30 px-6 py-10 text-center">
          <Icon name="lock" size={20} className="mx-auto text-ink-soft" />
          <p className="mt-4 text-[15px] font-medium text-ink">Review Register is available to the Owner / Principal seat.</p>
          <p className="mt-2 text-[13px] text-ink-soft">Switch to the owner role in the top bar, or ask your principal to open this surface.</p>
          <p className="mt-6 text-[11.5px] text-muted-foreground">The office decides. Veto records the review.</p>
        </div>
      </div>
    </AppShell>
  );
}

function Dashboard() {
  const demoRole = typeof useDemoRoleRead === "function" ? useDemoRoleRead() : (window.VETO_DEMO_ROLE || readDemoRole());
  const rows = useMemo(() => registerRows(), []);
  if (demoRole !== "owner") return <ReviewRegisterGate />;

  return (
    <AppShell activeLine="overview">
      <div className="mx-auto w-full max-w-[1000px] px-6 py-10 lg:px-12 lg:py-12">
        <div className="flex items-start justify-between gap-6">
          <div>
            <p className="text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground">Owner surface</p>
            <h1 className="mt-1 text-[26px] font-semibold tracking-[-0.02em] text-ink">Review Register</h1>
            <p className="mt-1 max-w-[560px] text-[13px] text-ink-soft">805 Escrow · Westlake Village · covered files and their review state across all officers.</p>
          </div>
        </div>

        <div className="mt-8 overflow-hidden rounded-xl border border-line">
          <div className="grid grid-cols-[minmax(0,1.4fr)_100px_120px_minmax(0,1.6fr)_140px] gap-3 border-b border-line bg-surface/40 px-4 py-2.5 text-[10.5px] font-medium uppercase tracking-[0.06em] text-muted-foreground">
            <span>File</span>
            <span>Officer</span>
            <span>Closing</span>
            <span>Review state</span>
            <span className="text-right">Action</span>
          </div>
          <ul className="divide-y divide-line">
            {rows.map((row) => (
              <li key={row.id} className={cn("grid grid-cols-[minmax(0,1.4fr)_100px_120px_minmax(0,1.6fr)_140px] gap-3 px-4 py-4", row.ownerHeld && "bg-[var(--warn-bg)]/40")}>
                <div className="min-w-0">
                  <Link to="/file/$id" params={{ id: row.id }} className="group block">
                    <span className="block truncate text-[13.5px] font-medium text-ink group-hover:underline">{row.property}</span>
                    <span className="mt-0.5 block font-mono text-[11px] text-muted-foreground">{row.id}</span>
                    {row.payee && <span className="mt-0.5 block text-[11px] text-ink-soft">Payee · {row.payee}</span>}
                  </Link>
                </div>
                <div className="flex items-start pt-0.5">
                  <span className="font-mono text-[12px] text-ink-soft">{row.officer}</span>
                </div>
                <div className="flex items-start pt-0.5">
                  <span className="font-mono text-[11.5px] tabular-nums text-ink-soft">{shortClosing(row.closing)}</span>
                </div>
                <div className="min-w-0 space-y-1.5">
                  <RegisterStatePill state={row.state} tone={row.stateTone} />
                  <p className="text-[12px] leading-relaxed text-ink-soft">{row.signal}</p>
                </div>
                <div className="flex items-start justify-end pt-0.5">
                  {row.ownerHeld ? (
                    <button type="button"
                      className="inline-flex h-8 items-center rounded-lg border border-line bg-background px-3 text-[12px] font-medium text-ink transition hover:bg-surface">
                      Record owner exception
                    </button>
                  ) : (
                    <span className="text-[11.5px] text-muted-foreground">—</span>
                  )}
                </div>
              </li>
            ))}
          </ul>
        </div>

        <p className="mt-8 text-[11.5px] text-muted-foreground">The office decides. Veto records the review.</p>
      </div>
    </AppShell>
  );
}

Object.assign(window, { Dashboard });
