/* =========================================================================
   Veto · Receipt — the signed review record. Source-bound, printable.
   One component serves seller / buyer / payoff receipts.
   ========================================================================= */

const RECEIPT_LINE = { receipt: "seller", "buyer-receipt": "buyer", "payoff-receipt": "payoff" };

/* Sources that satisfied each checkpoint (for the provenance line). */
const RECEIPT_SOURCE = {
  payoff: ["Recorded DOT 2019-0442118", "Servicer payoff stmt · letterhead", "Reconciliation · per-diem $48.12/day", "Servicer of record · FNMA #5521", "Borrower authorization · wet-signed", "Wire instr · acct ••4471", "Callback · servicer desk 800-•••-2200"],
  seller: ["Signed seller instructions", "Final settlement statement", "Net proceeds reconciliation", "Vesting · grant deed of record", "Receiving acct ••8830 · titled", "Gov ID + notary journal", "Callback · seller line on file"],
  buyer: ["Closing disclosure · lender", "Cash-to-close worksheet", "Buyer ID + vesting instruction", "Clear-to-close · lender letterhead", "Incoming wire · funds posted", "Wire origin · buyer of record", "Recording package · title clear"],
};

function makeReceiptHash() {
  const h = "0123456789abcdef"; let s = "";
  for (let i = 0; i < 40; i++) s += h[Math.floor(Math.random() * 16)];
  return s;
}
function sentenceText(value) {
  const text = String(value || "").trim();
  return /[.!?]$/.test(text) ? text : `${text}.`;
}

function Receipt({ id, kind }) {
  const lineKey = RECEIPT_LINE[kind] || "seller";
  const cf = CASE_FILES[id];
  const defs = CHECKPOINTS[lineKey];
  const sources = RECEIPT_SOURCE[lineKey];
  const lineLabel = lineLabelOf(lineKey);
  const reviewer = cf?.reviewer || "Madeline Lane";
  const initials = cf?.reviewerInitials || "ML";
  const signedDate = cf?.closing || "May 19, 2026";
  const fullHash = useMemo(() => makeReceiptHash(), [id, kind]);

  return (
    <AppShell activeLine={lineKey} reviewer={{ name: "Madeline Lane", initials: "ML" }}>
      {/* Top bar */}
      <div className="no-print border-b border-line bg-background">
        <div className="mx-auto flex w-full max-w-[860px] items-center justify-between px-6 py-4 lg:px-10">
          <Link to="/file/$id" params={{ id }} className="inline-flex items-center gap-1 text-[12.5px] text-ink-soft transition hover:text-ink">
            <Icon name="arrow-left" size={13} /> File
          </Link>
          <div className="flex 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 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="download" size={14} /> Download</button>
          </div>
        </div>
      </div>

      {/* The sheet */}
      <div className="bg-surface/40 px-4 py-8 lg:py-12">
        <article className="print-page mx-auto w-full max-w-[760px] rounded-xl border border-line bg-background px-8 py-10 shadow-[0_2px_40px_-20px_rgba(0,0,0,0.25)] lg:px-14 lg:py-14">
          {/* header */}
          <div className="flex items-start justify-between border-b border-line pb-6">
            <div>
              <VetoLogo className="text-[17px]" />
              <div className="mt-3 text-[11px] uppercase tracking-[0.08em] text-muted-foreground">Review Record</div>
              <h1 className="mt-1.5 text-[21px] font-semibold tracking-[-0.015em] text-ink">{streetOf(cf?.property) || id}</h1>
              <div className="mt-0.5 text-[12.5px] text-ink-soft">{cityOf(cf?.property)}</div>
            </div>
            <div className="text-right text-[11px] leading-relaxed text-muted-foreground">
              <div>{id}</div>
              <div>{lineLabel}</div>
              <div className="mt-2 text-[var(--ok)]">SIGNED</div>
              <div>{signedDate}</div>
            </div>
          </div>

          {/* parties */}
          <div className="grid grid-cols-2 gap-6 border-b border-line py-5 text-[12.5px]">
            <div>
              <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Party</div>
              <div className="mt-1 text-ink">{cf?.party || "Not on file"}</div>
            </div>
            <div>
              <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Reviewer</div>
              <div className="mt-1 text-ink">{reviewer}</div>
            </div>
          </div>

          {/* recorded conditions */}
          <div className="py-6">
            <div className="text-[11px] uppercase tracking-[0.06em] text-muted-foreground">What the office recorded</div>
            <ul className="mt-3 divide-y divide-line">
              {defs.map((d, i) => (
                <li key={d.id} className="flex items-start gap-3 py-3">
                  <span className="mt-0.5 grid h-4 w-4 shrink-0 place-items-center rounded-full bg-[var(--ok-bg)] text-[var(--ok)]"><Icon name="check" size={10} strokeWidth={3} /></span>
                  <div className="min-w-0 flex-1">
                    <div className="text-[13px] text-ink">{d.name}</div>
                    <div className="mt-0.5 font-mono text-[11px] text-muted-foreground">{sources[i]}</div>
                  </div>
                  <span className="shrink-0 text-[11px] font-medium text-[var(--ok)]">Met</span>
                </li>
              ))}
            </ul>
          </div>

          {/* recording statement */}
          <div className="rounded-lg border border-line bg-surface/50 px-5 py-4">
            <p className="text-[13px] leading-relaxed text-ink">
              All conditions met. No open holds. <span className="font-medium">{lineLabel}</span> ready to record and signed by {reviewer} on {signedDate}.
            </p>
          </div>

          {/* signature + hash */}
          <div className="mt-7 flex items-end justify-between gap-6 border-t border-line pt-6">
            <div>
              <div style={{ fontFamily: "'IBM Plex Mono', monospace" }} className="text-[18px] text-ink">{reviewer}</div>
              <div className="mt-1 flex items-center gap-2 text-[11px] text-ink-soft">
                <span className="grid h-5 w-5 place-items-center rounded-full bg-surface-2 text-[9px] font-medium text-ink">{initials}</span>
                <span>Escrow officer · 805 Escrow</span>
              </div>
            </div>
            <div className="text-right">
              <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Receipt hash</div>
              <div className="mt-1 max-w-[220px] break-all font-mono text-[10px] leading-relaxed text-ink-soft">{fullHash}</div>
            </div>
          </div>

          <div className="mt-8 border-t border-line pt-5 text-center text-[11.5px] text-ink-soft">Veto records the review. The office decides.</div>
        </article>
      </div>
    </AppShell>
  );
}

Object.assign(window, { Receipt });

function ChangeImpactRecord({ id }) {
  const cf = CASE_FILES[id];
  const change = typeof getChangeEvents === "function" ? getChangeEvents(id)[0] : null;
  const actionKey = change?.actionKey || "seller-proceeds-release";
  const policy = change && typeof getPolicyControl === "function" ? getPolicyControl(change.policyId) : null;
  const sources = typeof getSourceRows === "function" ? getSourceRows(id, actionKey) : [];
  const records = typeof getRecordsForAction === "function" ? getRecordsForAction(id, actionKey) : [];
  const prior = records.find((r) => r.id === change?.staledRecordId) || records[0];
  const draft = records.find((r) => r.status === "Draft");

  return (
    <AppShell activeLine="records" reviewer={{ name: "Madeline Lane", initials: "ML" }}>
      <div className="no-print border-b border-line bg-background">
        <div className="mx-auto flex w-full max-w-[860px] items-center justify-between px-6 py-4 lg:px-10">
          <Link to="/file/$id" params={{ id }} className="inline-flex items-center gap-1 text-[12.5px] text-ink-soft transition hover:text-ink">
            <Icon name="arrow-left" size={13} /> File
          </Link>
          <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>
        </div>
      </div>

      <div className="bg-surface/40 px-4 py-8 lg:py-12">
        <article className="print-page mx-auto w-full max-w-[1040px] rounded-xl border border-line bg-background px-6 py-8 shadow-[0_2px_40px_-20px_rgba(0,0,0,0.25)] lg:px-10 lg:py-10">
          <div className="flex flex-col gap-5 border-b border-line pb-6 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <VetoLogo className="text-[17px]" />
              <div className="mt-3 text-[11px] uppercase tracking-[0.08em] text-muted-foreground">Material Change Impact Record</div>
              <h1 className="mt-1.5 text-[26px] font-semibold tracking-[-0.015em] text-ink">{streetOf(cf?.property) || id}</h1>
              <div className="mt-0.5 text-[12.5px] text-ink-soft">{cityOf(cf?.property)} · {id}</div>
            </div>
            <div className="grid min-w-[260px] grid-cols-2 gap-3 text-[11.5px] leading-relaxed text-muted-foreground">
              <div className="rounded-lg border border-line bg-surface/40 px-3 py-2">
                <div className="uppercase tracking-[0.06em]">Record</div>
                <div className="mt-1 font-mono text-ink">{change?.id || "CHG"}</div>
              </div>
              <div className="rounded-lg border border-[var(--warn)]/25 bg-[var(--warn-bg)] px-3 py-2">
                <div className="uppercase tracking-[0.06em]">Status</div>
                <div className="mt-1 font-medium text-[var(--warn)]">Blocked</div>
              </div>
              <div className="col-span-2 rounded-lg border border-line bg-surface/40 px-3 py-2">
                <div className="uppercase tracking-[0.06em]">Detected</div>
                <div className="mt-1 font-mono text-ink">{change?.detectedAt}</div>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 gap-4 border-b border-line py-5 text-[12.5px] lg:grid-cols-2">
            <div>
              <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Action</div>
              <div className="mt-1 text-ink">{change?.action}</div>
            </div>
            <div>
              <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Policy applied</div>
              <div className="mt-1 text-ink">{policy?.name}</div>
              <div className="mt-0.5 font-mono text-[11px] text-muted-foreground">{policy?.version}</div>
            </div>
          </div>

          <div className="grid grid-cols-1 gap-3 border-b border-line py-6 lg:grid-cols-2">
            <div className="rounded-lg border border-line bg-surface/50 px-4 py-3">
              <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Prior accepted state</div>
              <div className="mt-1 font-mono text-[12px] text-ink-soft">{change?.from}</div>
              <div className="mt-2 text-[11.5px] text-[var(--warn)]">{prior?.type} {prior?.version} · superseded</div>
            </div>
            <div className="rounded-lg border border-ink/20 bg-background px-4 py-3">
              <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Changed state</div>
              <div className="mt-1 font-mono text-[12px] text-ink">{change?.to}</div>
              <div className="mt-2 text-[11.5px] text-ink">{draft?.type} {draft?.version} · draft</div>
            </div>
          </div>

          <div className="py-6">
            <div className="text-[11px] uppercase tracking-[0.06em] text-muted-foreground">Sources and limitations</div>
            <ul className="mt-3 grid gap-3">
              {sources.map((s) => (
                <li key={s.id} className="rounded-lg border border-line bg-background px-4 py-3">
                  <div className="flex items-start justify-between gap-4">
                    <div>
                      <div className="text-[13.5px] font-medium text-ink">{s.label}</div>
                      <div className="mt-0.5 font-mono text-[11px] text-muted-foreground">{s.type} · {s.status}</div>
                    </div>
                    <span className="font-mono text-[10.5px] text-muted-foreground">{s.id}</span>
                  </div>
                  <div className="mt-3 grid gap-2 text-[12.5px] leading-relaxed text-ink-soft lg:grid-cols-2">
                    <div className="rounded-md bg-surface/50 px-3 py-2"><span className="font-medium text-ink">Supports</span><br />{sentenceText(s.shows)}</div>
                    <div className="rounded-md bg-surface/50 px-3 py-2"><span className="font-medium text-ink">Does not support</span><br />{sentenceText(s.doesNotShow)}</div>
                  </div>
                </li>
              ))}
            </ul>
          </div>

          <div className="rounded-lg border border-line bg-surface/50 px-5 py-4">
            <p className="text-[13px] leading-relaxed text-ink">
              This record marks {prior?.type} {prior?.version} as stale for release to the prior destination. It supports creating {draft?.type} {draft?.version} or requesting a manager exception. It does not authorize money movement.
            </p>
          </div>

          <div className="mt-7 grid grid-cols-1 gap-5 border-t border-line pt-6 text-[12px] lg:grid-cols-2">
            <div>
              <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Open blockers</div>
              <div className="mt-1 text-ink">Independent callback and source limitation review</div>
            </div>
            <div>
              <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Exception status</div>
              <div className="mt-1 text-ink">Available by Escrow Manager, expires same day</div>
            </div>
          </div>

          <div className="mt-8 border-t border-line pt-5 text-center text-[11.5px] text-ink-soft">
            Veto records the evidence state and office review. The office decides and acts under its escrow instructions and policies.
          </div>
        </article>
      </div>
    </AppShell>
  );
}

Object.assign(window, { ChangeImpactRecord });
