/* =========================================================================
   Veto · New-file composer (/files/new) + Evidence manifest (/file/$id/manifest)
   ========================================================================= */

const LINE_OPTIONS = [
  { key: "buyer", label: "Buyer Funding", icon: "arrow-down-left", note: "Review the buyer funding source, amount, and limits." },
  { key: "seller", label: "Seller Proceeds", icon: "arrow-up-right", note: "Reconcile proceeds and destination before office sign-off." },
  { key: "payoff", label: "Payoff Demand", icon: "scale", note: "Review payoff evidence current through closing." },
];

function NewFileComposer() {
  const [address, setAddress] = useState("");
  const [buyer, setBuyer] = useState("");
  const [seller, setSeller] = useState("");
  const [closing, setClosing] = useState("");
  const [lines, setLines] = useState({ buyer: true, seller: true, payoff: false });
  const toggle = (k) => setLines((l) => ({ ...l, [k]: !l[k] }));
  const anyLine = Object.values(lines).some(Boolean);
  const ready = address.trim() && anyLine;

  return (
    <AppShell reviewer={{ name: "Madeline Lane", initials: "ML" }}>
      <div className="mx-auto w-full max-w-[640px] px-6 py-12 lg:py-16">
        <Link to="/files" className="inline-flex items-center gap-1.5 rounded-md px-2 py-1.5 -ml-2 text-[13px] text-ink-soft transition hover:bg-surface hover:text-ink">
          <Icon name="arrow-left" size={15} /> Files
        </Link>
        <h1 className="mt-4 text-[24px] font-semibold tracking-[-0.02em] text-ink">Open a file.</h1>
        <p className="mt-1.5 text-[13.5px] leading-relaxed text-ink-soft">Intake the transaction. Veto opens the review lines you choose and sets their checkpoints.</p>

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

          <div className="grid grid-cols-2 gap-3">
            <Field label="Buyer"><input value={buyer} onChange={(e) => setBuyer(e.target.value)} placeholder="Buyer name"
              className="h-11 w-full rounded-lg border border-line bg-background px-3.5 text-[13.5px] text-ink outline-none transition placeholder:text-muted-foreground focus:border-ink/40 focus:ring-1 focus:ring-ink/15" /></Field>
            <Field label="Seller"><input value={seller} onChange={(e) => setSeller(e.target.value)} placeholder="Seller name"
              className="h-11 w-full rounded-lg border border-line bg-background px-3.5 text-[13.5px] text-ink outline-none transition placeholder:text-muted-foreground focus:border-ink/40 focus:ring-1 focus:ring-ink/15" /></Field>
          </div>

          <Field label="Closing date">
            <DateField value={closing} onChange={setClosing} />
          </Field>

          <div>
            <div className="mb-2 text-[12.5px] font-medium text-ink">Open these review lines</div>
            <div className="space-y-2">
              {LINE_OPTIONS.map((o) => (
                <button key={o.key} type="button" onClick={() => toggle(o.key)}
                  className={cn("flex w-full items-center gap-3 rounded-xl border px-4 py-3 text-left transition", lines[o.key] ? "border-ink/40 bg-surface/60" : "border-line bg-background hover:border-ink/20 hover:bg-surface/40")}>
                  <span className={cn("grid h-8 w-8 shrink-0 place-items-center rounded-lg", lines[o.key] ? "bg-ink text-background" : "bg-surface-2 text-ink-soft")}><Icon name={o.icon} size={15} /></span>
                  <span className="min-w-0 flex-1">
                    <span className="block text-[13.5px] font-medium text-ink">{o.label}</span>
                    <span className="block text-[12px] text-ink-soft">{o.note}</span>
                  </span>
                  <span className={cn("grid h-5 w-5 shrink-0 place-items-center rounded-md border transition", lines[o.key] ? "border-ink bg-ink text-background" : "border-line")}>
                    {lines[o.key] && <Icon name="check" size={11} strokeWidth={3} />}
                  </span>
                </button>
              ))}
            </div>
          </div>

          <div className="flex items-center gap-3 pt-1">
            <button type="button" disabled={!ready} onClick={() => navigate("/file/$id", { id: "SP-0211" })}
              className={cn("inline-flex h-11 items-center rounded-lg px-5 text-[13.5px] font-medium transition", ready ? "bg-ink text-background hover:bg-ink/90" : "cursor-not-allowed bg-surface-2 text-muted-foreground")}>Open file</button>
            <Link to="/files" className="text-[12.5px] text-ink-soft underline decoration-line underline-offset-4 hover:text-ink">Cancel</Link>
          </div>
        </div>
      </div>
    </AppShell>
  );
}

/* ----------------------------------------------------------- Manifest */
const MANIFEST_ROWS = [
  { doc: "Recorded deed of trust", cat: "Identity", src: "County recorder · 2019-0442118", when: "May 18", status: "Reviewed" },
  { doc: "Payoff statement", cat: "Instruction", src: "Servicer letterhead · FNMA #5521", when: "May 20", status: "Reviewed" },
  { doc: "Beneficiary wire instructions", cat: "Destination", src: "Servicer · acct ••4471", when: "May 20", status: "Callback pending" },
  { doc: "Borrower authorization", cat: "Authority", src: "Wet-signed · notarized", when: "May 19", status: "Reviewed" },
  { doc: "Government ID, borrower", cat: "Identity", src: "DL · liveness matched", when: "May 17", status: "Reviewed" },
  { doc: "Reconciliation worksheet", cat: "Math", src: "Per-diem $48.12/day", when: "May 21", status: "Reviewed" },
  { doc: "Preliminary title report", cat: "Entitlement", src: "Title unit · order 88231", when: "May 16", status: "Reviewed" },
  { doc: "Closing disclosure", cat: "Instruction", src: "Lender · letterhead", when: "May 18", status: "Superseded" },
];
function ManifestStatus({ status }) {
  const map = { "Reviewed": "text-[var(--ok)]", "Callback pending": "text-[var(--warn)]", "Superseded": "text-muted-foreground" };
  return <span className={cn("inline-flex items-center gap-1.5 text-[12px]", map[status])}><span className={cn("h-1.5 w-1.5 rounded-full", status === "Reviewed" ? "bg-[var(--ok)]" : status === "Callback pending" ? "bg-[var(--warn)]" : "bg-muted-foreground/50")} />{status}</span>;
}
function Manifest({ id }) {
  const cf = CASE_FILES[id];
  return (
    <AppShell activeFileId={id} reviewer={{ name: "Madeline Lane", initials: "ML" }}>
      <div className="border-b border-line">
        <div className="mx-auto w-full max-w-[920px] px-6 py-6 lg:px-10">
          <Link to="/file/$id" params={{ id }} className="inline-flex items-center gap-1.5 text-[12.5px] text-ink-soft transition hover:text-ink"><Icon name="arrow-left" size={13} /> File</Link>
          <h1 className="mt-3 text-[22px] font-semibold tracking-[-0.015em] text-ink">Evidence manifest</h1>
          <div className="mt-1 text-[12px] text-muted-foreground">{id} · {streetOf(cf?.property) || ""}</div>
        </div>
      </div>
      <div className="mx-auto w-full max-w-[920px] px-6 py-8 lg:px-10">
        <p className="mb-5 text-[13px] text-ink-soft">Every source gathered for this file, with its category and provenance. Each row binds to a checkpoint on the receipt.</p>
        <div className="overflow-hidden rounded-xl border border-line">
          <table className="w-full text-left">
            <thead>
              <tr className="border-b border-line bg-surface/50 text-[11px] uppercase tracking-[0.05em] text-muted-foreground">
                <th className="px-4 py-2.5 font-medium">Document</th>
                <th className="px-4 py-2.5 font-medium">Category</th>
                <th className="hidden px-4 py-2.5 font-medium sm:table-cell">Source</th>
                <th className="hidden px-4 py-2.5 font-medium sm:table-cell">Received</th>
                <th className="px-4 py-2.5 font-medium">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-line">
              {MANIFEST_ROWS.map((r) => (
                <tr key={r.doc} className="transition hover:bg-surface/40">
                  <td className="px-4 py-3 text-[13px] text-ink">{r.doc}</td>
                  <td className="px-4 py-3"><span className="rounded border border-line px-1.5 py-0.5 text-[11px] text-ink-soft">{r.cat}</span></td>
                  <td className="hidden px-4 py-3 font-mono text-[11.5px] text-ink-soft sm:table-cell">{r.src}</td>
                  <td className="hidden px-4 py-3 font-mono text-[11.5px] text-ink-soft sm:table-cell">{r.when}</td>
                  <td className="px-4 py-3"><ManifestStatus status={r.status} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </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, { NewFileComposer, Manifest });
