/* =========================================================================
   Veto · Files + Line queues + New-review wizard
   - /files            all escrows, recent activity desc (memory surface)
   - /seller-proceeds  queue of seller-proceeds reviews + New review
   - /buyer-funding    queue of buyer-funding reviews + New review
   - /payoff           queue of payoff-demand reviews + New review
   - /<line>/new       the wizard
   ========================================================================= */

function StatusDot({ status }) {
  const cls = status === "Recorded" ? "bg-[var(--ok)]"
    : status === "Blocked" ? "bg-[var(--destructive)]"
    : status === "In review" ? "bg-[var(--warn)]"
    : "bg-[var(--ink-soft)]/40";
  return <span className={cn("inline-block h-1.5 w-1.5 rounded-full", cls)} aria-hidden />;
}
function StatusText({ status }) {
  const cls = status === "Recorded" ? "text-[var(--ok)]"
    : status === "Blocked" ? "text-[var(--destructive)]"
    : status === "In review" ? "text-[var(--warn)]" : "text-ink-soft";
  return (
    <span className={cn("inline-flex items-center gap-1.5 text-[12px]", cls)}>
      <StatusDot status={status} />{status}
    </span>
  );
}

/* Address-first file row, shared by Files + line queues. Pin on hover. */
function FileRow({ id, street, city, party, status, meta, lineLabel }) {
  const cf = CASE_FILES[id];
  const { has, toggle } = useLocalList("veto.bookmarks");
  const pinned = has(id);
  return (
    <li className="group/row relative">
      <Link to="/file/$id" params={{ id }} className="group flex items-center gap-4 py-3.5 pl-1 pr-10 transition hover:bg-surface/40">
        <span className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-surface-2 text-[11px] font-medium text-ink" aria-hidden>
          {cf?.reviewerInitials || "ML"}
        </span>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <span className="truncate text-[13.5px] text-ink">{street}</span>
            <span className="shrink-0 text-[11px] text-muted-foreground">{id}</span>
          </div>
          <div className="mt-0.5 truncate text-[12px] text-ink-soft">
            {lineLabel ? <span>{lineLabel} · </span> : null}{party}{city ? ` · ${city}` : ""}
          </div>
        </div>
        <div className="hidden shrink-0 sm:block"><StatusText status={status} /></div>
        <span className="w-16 shrink-0 text-right font-mono text-[11.5px] tabular-nums text-ink-soft">{meta}</span>
      </Link>
      <button type="button" onClick={(e) => { e.preventDefault(); e.stopPropagation(); toggle({ id, name: street }); }}
        aria-label={pinned ? "Unpin file" : "Pin file"} title={pinned ? "Unpin from sidebar" : "Pin to sidebar"}
        className={cn("absolute right-1 top-1/2 z-10 grid h-7 w-7 -translate-y-1/2 place-items-center rounded-md transition",
          pinned ? "text-ink opacity-100" : "text-ink-soft opacity-0 hover:bg-surface group-hover/row:opacity-100 focus:opacity-100")}>
        <svg width="14" height="14" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" fill={pinned ? "currentColor" : "none"} aria-hidden="true">
          <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
        </svg>
      </button>
    </li>
  );
}

function QueueTabs({ tabs, tab, setTab, counts }) {
  return (
    <nav className="flex items-center gap-6">
      {tabs.map((t) => (
        <button key={t.key} type="button" onClick={() => setTab(t.key)}
          className={cn("-mb-[13px] flex items-center gap-1.5 border-b py-3 text-[13.5px] transition",
            tab === t.key ? "border-ink text-ink" : "border-transparent text-ink-soft hover:text-ink")}>
          <span>{t.label}</span>
          <span className={cn("font-mono text-[11px] tabular-nums", tab === t.key ? "text-ink-soft" : "text-ink-soft/70")}>{counts[t.key]}</span>
        </button>
      ))}
    </nav>
  );
}

/* ----------------------------------------------------------------- Files */
function FilesPage() {
  const [tab, setTab] = useState("all");
  const rows = useMemo(() => allFilesRows(), []);
  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 tabs = [{ key: "all", label: "All" }, { key: "open", label: "In review" }, { key: "recorded", label: "Recorded" }];
  const visible = tab === "all" ? rows : rows.filter((r) => (tab === "open" ? r.status === "In review" : r.status === "Recorded"));

  return (
    <AppShell activeLine="files" 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-1">
          <h1 className="text-[20px] font-semibold tracking-[-0.01em] text-ink">Files</h1>
          <p className="mt-1 text-[13px] text-ink-soft">Every escrow you've touched, most recent first. Open and recorded.</p>
        </header>
        <div className="mt-6 flex items-center justify-between gap-4 border-b border-line pb-3">
          <QueueTabs tabs={tabs} tab={tab} setTab={setTab} counts={counts} />
          <Link to="/files/new" className="rounded-md bg-ink px-3 py-1.5 text-[12.5px] font-medium text-background transition hover:bg-ink/90">New file</Link>
        </div>
        {visible.length === 0 ? (
          <div className="mt-14">
            <EmptyState icon={<Icon name="file-text" size={44} />}
              title={tab === "recorded" ? "No recorded files yet" : tab === "open" ? "Nothing in review" : "No files yet"}
              note={tab === "recorded"
                ? "Files land here once every movement is recorded and the receipt is signed."
                : tab === "open"
                  ? "When you open a file it stays here until it closes. Nothing is mid-review right now."
                  : "Open your first file to start a review and walk it to a signed receipt."}
              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 transition hover:bg-ink/90"><Icon name="plus" size={14} /> New file</Link>}
              secondaryAction={<LearnMore />} />
          </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} lineLabel={r.lineLabel} meta={shortClosing(r.closing)} />
            ))}
          </ul>
        )}
        <footer className="mt-12 border-t border-line pt-5">
          <p className="text-[12px] text-ink-soft">Veto records the review. The office decides.</p>
        </footer>
      </div>
    </AppShell>
  );
}

/* ------------------------------------------------------------ Line queue */
const LINE_META = {
  seller: { label: "Proceeds", to: "/funds/proceeds", newLabel: "New proceeds review", blurb: "Reviews seller proceeds before office sign-off. Reconcile the final statement and destination evidence." },
  buyer: { label: "Funding In", to: "/funds/funding-in", newLabel: "New funding review", blurb: "Reviews buyer funding source, amount, and limits. Every leg of the wire tied to source evidence." },
  payoff: { label: "Payoffs", to: "/funds/payoffs", newLabel: "New payoff review", blurb: "Reviews existing-lien payoff support. Demand current through closing, callback recorded." },
};

function LineQueue({ lineKey }) {
  const meta = LINE_META[lineKey];
  const [tab, setTab] = useState("all");
  const rows = useMemo(() => lineQueueRows(lineKey), [lineKey]);
  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 tabs = [{ key: "all", label: "All" }, { key: "open", label: "In review" }, { key: "recorded", label: "Recorded" }];
  const visible = tab === "all" ? rows : rows.filter((r) => (tab === "open" ? r.status === "In review" : r.status === "Recorded"));

  return (
    <AppShell activeLine={lineKey} 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="flex items-start justify-between gap-6">
          <div className="max-w-[460px]">
            <h1 className="text-[20px] font-semibold tracking-[-0.01em] text-ink">{meta.label}</h1>
            <p className="mt-1 text-[13px] leading-relaxed text-ink-soft">{meta.blurb}</p>
          </div>
          <Link to={meta.to + "/new"} 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>
        </header>
        <div className="mt-7 border-b border-line pb-3"><QueueTabs tabs={tabs} tab={tab} setTab={setTab} counts={counts} /></div>
        {visible.length === 0 ? (
          <div className="mt-14">
            <EmptyState icon={<Icon name="file-text" size={44} />}
              title={tab === "recorded" ? "Nothing recorded yet" : `No ${meta.label.toLowerCase()} here`}
              note={tab === "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.to + "/new"} 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) => (
              <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>
    </AppShell>
  );
}

/* ------------------------------------------------------- New review wizard */
function NewReview({ lineKey }) {
  const meta = LINE_META[lineKey];
  const kinds = REVIEW_KINDS[lineKey];
  const [kindId, setKindId] = useState(kinds[0].id);
  const [address, setAddress] = useState("");
  const kind = kinds.find((k) => k.id === kindId);

  return (
    <AppShell activeLine={lineKey} reviewer={{ name: "Madeline Lane", initials: "ML" }}>
      <div className="mx-auto w-full max-w-[640px] px-6 py-12 lg:py-16">
        <div className="mb-7">
          <Link to={meta.to} className="inline-flex items-center gap-1 text-[12px] text-ink-soft transition hover:text-ink">
            <Icon name="arrow-left" size={13} /> {meta.label}
          </Link>
          <h1 className="mt-4 text-[22px] font-semibold tracking-[-0.015em] text-ink">{meta.newLabel}</h1>
          <p className="mt-1.5 text-[13px] text-ink-soft">Open a review line. Veto sets the required sources and the callback for this kind.</p>
        </div>

        <div className="space-y-7">
          <Field label="Property">
            <Autocomplete value={address} onChange={setAddress} placeholder="Start typing an address" options={ADDRESS_SUGGESTIONS} places />
          </Field>

          <Field label="Kind">
            <div className="grid gap-2 sm:grid-cols-2">
              {kinds.map((k) => (
                <button key={k.id} type="button" onClick={() => setKindId(k.id)}
                  className={cn("rounded-lg border px-3.5 py-3 text-left transition",
                    kindId === k.id ? "border-ink/50 bg-surface ring-1 ring-ink/10" : "border-line bg-background hover:border-ink/25 hover:bg-surface/50")}>
                  <div className="flex items-start justify-between gap-2">
                    <span className="text-[13px] font-medium leading-tight text-ink">{k.label}</span>
                    <span className={cn("mt-0.5 grid h-4 w-4 shrink-0 place-items-center rounded-full border transition",
                      kindId === k.id ? "border-ink bg-ink text-background" : "border-line")}>
                      {kindId === k.id && <Icon name="check" size={10} strokeWidth={3} />}
                    </span>
                  </div>
                  <p className="mt-1 text-[11.5px] leading-snug text-ink-soft">{k.blurb}</p>
                </button>
              ))}
            </div>
          </Field>

          <div className="rounded-lg border border-line bg-surface/40 p-4">
            <div className="text-[11px] uppercase tracking-[0.05em] text-muted-foreground">Required sources</div>
            <ul className="mt-2.5 space-y-1.5">
              {kind.requiredDocs.map((d) => (
                <li key={d} className="flex items-start gap-2 text-[12.5px] text-ink">
                  <span className="mt-[5px] inline-block h-1 w-1 shrink-0 rounded-full bg-ink-soft" />{d}
                </li>
              ))}
            </ul>
            <div className="mt-4 flex items-start gap-2 border-t border-line pt-3">
              <Icon name="phone" size={13} className="mt-0.5 shrink-0 text-ink-soft" />
              <div>
                <div className="text-[11px] uppercase tracking-[0.05em] text-muted-foreground">Independent callback</div>
                <p className="mt-0.5 text-[12.5px] text-ink">{kind.callback}</p>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-3 pt-1">
            <button type="button" onClick={() => navigate("/file/$id", { id: "SP-0211" })}
              className="inline-flex h-10 items-center rounded-md bg-ink px-5 text-[13px] font-medium text-background transition hover:bg-ink/90">
              Open review
            </button>
            <Link to={meta.to} className="text-[12.5px] text-ink-soft underline decoration-line underline-offset-4 hover:text-ink">Cancel</Link>
          </div>
        </div>
      </div>
    </AppShell>
  );
}

function Field({ label, children }) {
  return (
    <div>
      <label className="mb-1.5 block text-[12.5px] font-medium text-ink">{label}</label>
      {children}
    </div>
  );
}

Object.assign(window, { FilesPage, LineQueue, NewReview, FileRow, StatusText, StatusDot, QueueTabs });
