/* =========================================================================
   Veto · Today (ported from routes/index.tsx)
   ========================================================================= */
const REVIEWER_TODAY = { name: "Madeline Lane", initials: "ML" };
const DAY_MS = 24 * 60 * 60 * 1000;

function todayCollectRows() {
  const out = [];
  const seen = new Set();
  for (const cf of Object.values(CASE_FILES)) {
    if (seen.has(cf.id)) continue;
    seen.add(cf.id);
    const allSigned = Object.values(cf.lines).every((l) => l.status !== "In review");
    if (allSigned) continue;
    const readiness = getReadiness(cf.id) ?? buildReadinessFrom(cf.id, cf.reviewer, cf.reviewerInitials, cf.closing);
    out.push({ fileNo: cf.id, party: cf.party, property: cf.property, closingMs: parseClosingMs(cf.closing), summary: todayRowSummary(readiness), readiness });
  }
  return out;
}
function anchorToday(rows) { return rows.length ? Math.min(...rows.map((r) => r.closingMs)) : Date.now(); }
function todayPriority(r) { const s = r.readiness.recording.state; return s === "Clear to record" ? 0 : s === "Holds open" ? 1 : 2; }
function todayRowSummary(r) {
  if (r.recording.state === "Clear to record") return "Review complete. Sign to record.";
  const openHolds = r.holds.filter((h) => h.state !== "Cleared");
  if (openHolds.length) return openHolds[0].cure;
  const fb = r.lines.find((l) => l.blocker)?.blocker;
  return fb || r.recording.summary;
}
function sentenceToday(ready, holds, total) {
  const parts = [];
  if (ready > 0) parts.push(`${ready} ready to record`);
  if (holds > 0) parts.push(`${holds} with holds open`);
  const rest = total - ready - holds;
  if (rest > 0) parts.push(`${rest} waiting on evidence`);
  const head = `${total} ${total === 1 ? "file closes" : "files close"} today`;
  return parts.length ? `${head}, ${parts.join(", ")}.` : `${head}.`;
}
function greetingToday() { const h = new Date().getHours(); return h < 12 ? "Good morning" : h < 18 ? "Good afternoon" : "Good evening"; }
function relativeLabel(ms, todayMs) {
  const days = Math.round((ms - todayMs) / DAY_MS);
  if (days === 1) return "Tomorrow";
  if (days < 7) return `In ${days} days`;
  return shortClosingMs(ms);
}
function sameDay(a, b) { return Math.abs(a - b) < DAY_MS / 2; }
function parseClosingMs(s) { const t = Date.parse(s); return Number.isFinite(t) ? t : Number.MAX_SAFE_INTEGER; }
function shortClosing(s) { const parts = s.split(","); return (parts[0] ?? s).trim(); }
function shortClosingMs(ms) { return new Date(ms).toLocaleDateString("en-US", { month: "short", day: "numeric" }); }

function TodaySectionHead({ label, count }) {
  return (
    <div className="flex items-baseline justify-between">
      <h2 className="text-[14px] font-medium text-ink">{label}</h2>
      <span className="font-mono text-[11.5px] tabular-nums text-muted-foreground">{count}</span>
    </div>
  );
}
function TodayStatePill({ state }) {
  const map = {
    "Clear to record": { label: "Ready to record", cls: "bg-[var(--ok-bg)] text-[var(--ok)]" },
    "Holds open": { label: "Holds open", cls: "bg-[var(--warn-bg)] text-[var(--warn)]" },
    "Evidence open": { label: "Evidence open", cls: "bg-surface-2 text-ink-soft" },
  };
  const { label, cls } = map[state];
  return <span className={cn("inline-flex whitespace-nowrap rounded-full px-2.5 py-0.5 text-[11px]", cls)}>{label}</span>;
}
function TodayRow({ row, relative }) {
  const state = row.readiness.recording.state;
  return (
    <li>
      <Link to="/file/$id" params={{ id: row.fileNo }} className="group flex items-center gap-5 px-5 py-4 hover:bg-surface/60">
        <div className="flex w-24 shrink-0 flex-col">
          <span className="text-[12px] text-ink">{row.fileNo}</span>
          <span className="mt-0.5 text-[11px] text-muted-foreground">{relative}</span>
        </div>
        <div className="min-w-0 flex-1">
          <div className="truncate text-[13.5px] text-ink">{row.party}</div>
          <div className="mt-0.5 truncate text-[12px] text-ink-soft">{row.summary}</div>
        </div>
        <div className="hidden shrink-0 sm:block"><TodayStatePill state={state} /></div>
      </Link>
    </li>
  );
}
function CalendarGlyph() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="18" height="18" rx="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" />
    </svg>
  );
}

function Today() {
  const rows = useMemo(() => todayCollectRows(), []);
  const todayMs = useMemo(() => anchorToday(rows), [rows]);
  const today = rows.filter((r) => sameDay(r.closingMs, todayMs));
  const upcoming = rows.filter((r) => r.closingMs > todayMs && r.closingMs <= todayMs + 7 * DAY_MS).sort((a, b) => a.closingMs - b.closingMs);
  today.sort((a, b) => todayPriority(a) - todayPriority(b));
  const ready = today.filter((r) => r.readiness.recording.state === "Clear to record").length;
  const holds = today.filter((r) => r.readiness.recording.state === "Holds open").length;

  return (
    <AppShell activeLine={null} reviewer={REVIEWER_TODAY}>
      <div className="mx-auto w-full max-w-[820px] px-6 py-10 lg:px-10 lg:py-14">
        <header>
          <div className="text-[11.5px] uppercase tracking-[0.06em] text-muted-foreground">Today</div>
          <h1 className="mt-3 text-[26px] font-semibold leading-[1.15] tracking-[-0.015em] text-ink">{greetingToday()}, {REVIEWER_TODAY.name.split(" ")[0]}.</h1>
          <p className="mt-2 text-[13.5px] text-ink-soft">{today.length === 0 ? "Nothing closes today." : sentenceToday(ready, holds, today.length)}</p>
        </header>

        {today.length === 0 && upcoming.length === 0 && (
          <div className="mt-8 rounded-xl border border-line bg-background">
            <EmptyState icon={<CalendarGlyph />} title="Nothing on the calendar" note="No files closing today or in the next seven days."
              action={<Link to="/files/new" className="inline-flex h-9 items-center gap-1.5 rounded-lg bg-ink px-4 text-[13px] font-medium text-background hover:bg-ink/90"><span aria-hidden className="text-[14px] leading-none">＋</span>Open a file</Link>} />
          </div>
        )}

        {today.length > 0 && (
          <section className="mt-10">
            <TodaySectionHead label="Money moves today" count={today.length} />
            <ul className="mt-3 flex flex-col divide-y divide-line rounded-xl border border-line bg-background">
              {today.map((r) => <TodayRow key={r.fileNo} row={r} relative="today" />)}
            </ul>
          </section>
        )}

        {upcoming.length > 0 && (
          <section className="mt-10">
            <TodaySectionHead label="Coming up" count={upcoming.length} />
            <ul className="mt-3 flex flex-col divide-y divide-line rounded-xl border border-line bg-background">
              {upcoming.map((r) => <TodayRow key={r.fileNo} row={r} relative={relativeLabel(r.closingMs, todayMs)} />)}
            </ul>
          </section>
        )}

        <footer className="mt-12 border-t border-line pt-5 text-[11.5px]">
          <p className="text-[12px] text-ink">Veto records the review. The office decides.</p>
          <p className="mt-1 text-[11.5px] text-muted-foreground"><Link to="/files" className="hover:text-ink">All files →</Link></p>
        </footer>
      </div>
    </AppShell>
  );
}

Object.assign(window, { Today });
