/* DMS screens (part 2) — Record (4-block card), Search, Zones, Audit, Manage, EdgeCases. */
(function () {
  const DMS = window.DMS;
  const { Icon } = window;
  const {
    useTw, ConfidentialityBadge, StatusChip, LegalHoldChip, AccessIndicator,
    Card, SectionTitle, Button, EmptyState, DeniedState, Field, Block, DataTable,
  } = window;
  const useApp = (...a) => window.useApp(...a);
  const S = window.Screens;
  const { Breadcrumbs, formatField, moneyKeys, VERB_LABEL, VERB_ICON } = S;

  const {
    RECORDS, DEPARTMENTS, CONFIDENTIALITY, STATUS, RETENTION_CLASS, CATEGORIES,
    CATEGORY_BY_CODE, DEPARTMENT_BY_CODE,
    daysUntil, departmentOf, recordVisibility, recordById, versionsOf,
    relationshipsOf, categoryOf, caseById, personById, allowedVerbs, decideAccess,
    searchRecords, fieldsOf, runEdgeCases,
  } = DMS;

  /* ── Record — document card (4 blocks) ───────────────────── */
  function RecordScreen({ recordId }) {
    const { person, stepUp, confirmStepUp, logAccess } = useApp();
    const { recordLayout } = useTw();
    const [showStepUp, setShowStepUp] = React.useState(false);
    const r = recordById(recordId);
    const opts = { stepUpConfirmed: r ? stepUp.has(r.id) : false };
    const access = r ? recordVisibility(person, r, opts) : null;

    React.useEffect(() => {
      if (!r || !access) return;
      const res = access.readResult;
      logAccess(r, 'read', res.result, res.reason, res.step);
    }, [recordId, person.id, opts.stepUpConfirmed]);

    if (!r || !access) return <EmptyState title="Document not found" icon="file" />;

    const cat = categoryOf(r);
    const dep = departmentOf(r);
    const cs = caseById(r.caseId);
    const verbs = allowedVerbs(person, r, opts);
    const fields = fieldsOf(cat?.fieldSet ?? 'FS-00');
    const canSeeContent = access.visibility === 'read';

    const crumbs = [
      { label: 'Lobby', view: { name: 'lobby' } },
      { label: `${dep?.code} ${dep?.name}`, view: { name: 'department', dept: r.departmentCode } },
      { label: `${cat?.code} ${cat?.name}`, view: { name: 'category', cat: r.categoryCode } },
      ...(cs ? [{ label: cs.title, view: { name: 'case', caseId: cs.id } }] : []),
      { label: r.title },
    ];

    const editBlocked = blockedHint(person, r, 'edit', opts);

    const Identity = (
      <Block title="Identity" icon="file" className="lg:col-span-2">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div className="min-w-0">
            <h1 className="serif text-[22px] font-semibold leading-snug tracking-tight text-text text-balance">{r.title}</h1>
            <div className="mono mt-1.5 text-xs text-text-faint">{r.address}</div>
          </div>
          <div className="flex flex-wrap items-center justify-end gap-1.5">
            <ConfidentialityBadge level={r.confidentiality} />
            <StatusChip status={r.status} />
            {r.legalHold && <LegalHoldChip />}
          </div>
        </div>
        <div className="mt-3 grid grid-cols-1 gap-x-10 sm:grid-cols-2 lg:grid-cols-3">
          <Field label="Type" value={r.docType} />
          <Field label="Author/owner" value={personById(r.ownerId)?.name ?? r.ownerId} />
          <Field label="Doc date" value={r.documentDate} mono />
          <Field label="Department" value={`${dep?.code} ${dep?.name ?? ''}`} />
          <Field label="Version" value={`v${r.currentVersion}`} mono />
          <Field label="Source (record_kind)" value={r.recordKind === 'draft' ? 'Draft' : 'Record'} />
        </div>
      </Block>
    );

    const ActionBar = (
      <div className="flex flex-wrap items-center gap-2">
        {access.visibility === 'step_up' && <Button variant="danger" icon="lock" onClick={() => setShowStepUp(true)}>step-up and open</Button>}
        {verbs.map((v) => <Button key={v} variant={v === 'read' ? 'primary' : 'ghost'} icon={VERB_ICON[v]}>{VERB_LABEL[v] ?? v}</Button>)}
        {editBlocked && (
          <span className="inline-flex items-center gap-1.5 rounded-btn px-2 py-1 text-xs" style={{ background: 'color-mix(in srgb, rgb(var(--st-disposal)) 11%, white)', color: 'color-mix(in srgb, rgb(var(--st-disposal)) 85%, black)' }}>
            <Icon name="lock" size={12} /> edit blocked.: {editBlocked}
          </span>
        )}
      </div>
    );

    const ContentBlock = (
      <Block title="Content fields (field_set)" icon="layers">
        {!canSeeContent ? (
          <LockedContent stepUp={access.visibility === 'step_up'} onStepUp={() => setShowStepUp(true)} />
        ) : fields.length === 0 ? (
          <div className="text-sm text-text-muted">This type has no extra fields (FS-00).</div>
        ) : (
          fields.map((f) => <Field key={f.key} label={f.label} value={formatField(f, r.fields[f.key])} ai={r.aiSuggested?.includes(f.key)} mono={f.type === 'date' || moneyKeys.has(f.key)} />)
        )}
      </Block>
    );

    const LifecycleBlock = (
      <Block title="Lifecycle & access" icon="history">
        <Field label="Confidentiality" value={`${CONFIDENTIALITY[r.confidentiality].label} (${CONFIDENTIALITY[r.confidentiality].rank})`} />
        <Field label="Status" value={STATUS[r.status].label} />
        <Field label="Legal hold" value={r.legalHold ? 'Yes' : 'No'} />
        {r.sensitive && <Field label="Sensitive" value="Yes → automatically top secret (E3)" />}
        {r.retention && (
          <>
            <Field label="Retention class" value={RETENTION_CLASS[r.retention.retentionClass].label} />
            <Field label="Retention start" value={r.retention.trigger ?? '—'} />
            <Field label="Disposal date" value={r.retention.disposalDate ?? 'Retention not yet counting (E10)'} mono={!!r.retention.disposalDate} />
          </>
        )}
        {r.fields.expiry_date && <Field label="Expiry date" value={`${r.fields.expiry_date} (in ${daysUntil(r.fields.expiry_date)} days)`} mono />}
      </Block>
    );

    const RelationsBlock = (
      <Block title="Links & history" icon="link" className={recordLayout === 'blocks' ? 'lg:col-span-2' : ''}>
        <div className="grid grid-cols-1 gap-x-10 gap-y-4 md:grid-cols-2">
          <div>
            <div className="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-text-faint">Linked Doc</div>
            <Relations recordId={r.id} />
          </div>
          <div>
            <div className="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-text-faint">Version history</div>
            <Versions recordId={r.id} />
          </div>
        </div>
      </Block>
    );

    return (
      <div className="mx-auto max-w-[1180px]">
        <Breadcrumbs crumbs={crumbs} />
        <div className="space-y-4">
          {Identity}
          {ActionBar}
          {access.visibility === 'denied' ? (
            <DeniedState reason={access.readResult.reason} />
          ) : recordLayout === 'rail' ? (
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-[1fr_330px]">
              <div className="space-y-4">{ContentBlock}{RelationsBlock}</div>
              <div className="lg:sticky lg:top-4 lg:self-start">{LifecycleBlock}</div>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
              {ContentBlock}
              {LifecycleBlock}
              {RelationsBlock}
            </div>
          )}
        </div>

        {showStepUp && (
          <S.StepUpModal title={r.title} onCancel={() => setShowStepUp(false)}
            onConfirm={() => { confirmStepUp(r.id); logAccess(r, 'read', 'allow', 'step-up confirmed — access granted', 8); setShowStepUp(false); }} />
        )}
      </div>
    );
  }

  // metadata-only / step-up — clear "👁 you see it exists, content is locked" state (brief priority 2).
  function LockedContent({ stepUp, onStepUp }) {
    return (
      <div className="flex flex-col items-center gap-2.5 rounded-[8px] border border-dashed px-5 py-7 text-center"
        style={{ borderColor: 'color-mix(in srgb, rgb(var(--ax-meta)) 35%, transparent)', background: 'color-mix(in srgb, rgb(var(--ax-meta)) 6%, white)' }}>
        <div className="flex h-10 w-10 items-center justify-center rounded-full" style={{ background: 'color-mix(in srgb, rgb(var(--ax-meta)) 13%, white)', color: 'rgb(var(--ax-meta))' }}>
          <Icon name={stepUp ? 'lock' : 'eye'} size={20} strokeWidth={1.7} />
        </div>
        <div className="text-sm font-semibold" style={{ color: 'color-mix(in srgb, rgb(var(--ax-meta)) 85%, black)' }}>
          {stepUp ? 'Top secret — step-up required' : 'You have no content access'}
        </div>
        <div className="max-w-sm text-xs leading-relaxed text-text-muted text-balance">
          You see the document exists (metadata), but the content is locked — <span className="mono">see_metadata ≠ read</span>.
        </div>
        {stepUp && <Button variant="danger" icon="lock" onClick={onStepUp}>step-up Confirm</Button>}
      </div>
    );
  }

  function blockedHint(person, r, v, opts) {
    const res = decideAccess(person, r, v, opts);
    if (res.result === 'deny' && res.step === 6) return res.reason;
    return null;
  }

  function Relations({ recordId }) {
    const { person, go } = useApp();
    const rels = relationshipsOf(recordId);
    if (rels.length === 0) return <div className="text-sm text-text-faint">No links.</div>;
    return (
      <div className="space-y-1.5">
        {rels.map(({ rel, other, direction }) => {
          if (!other) return null;
          const denied = recordVisibility(person, other).visibility === 'denied';
          return (
            <div key={rel.id} className="flex items-center gap-2 text-sm">
              <span className="inline-flex items-center gap-1 rounded bg-surface-2 px-1.5 py-0.5 text-[11px] font-medium text-text-muted">
                <Icon name="arrowLeft" size={11} style={{ transform: direction === 'out' ? 'rotate(180deg)' : 'none' }} /> {rel.type}
              </span>
              {denied ? (
                <span className="inline-flex items-center gap-1 text-text-faint"><Icon name="ban" size={12} /> {other.title}</span>
              ) : (
                <button onClick={() => go({ name: 'record', recordId: other.id })} className="text-primary hover:underline">{other.title}</button>
              )}
            </div>
          );
        })}
      </div>
    );
  }

  function Versions({ recordId }) {
    const vers = versionsOf(recordId);
    if (vers.length === 0) return <div className="text-sm text-text-faint">one Version.</div>;
    return (
      <div className="space-y-2.5">
        {vers.map((v, i) => (
          <div key={v.id} className="flex gap-2.5 text-sm">
            <div className="flex flex-col items-center">
              <span className="mono flex h-5 items-center rounded bg-primary-tint px-1.5 text-[11px] font-semibold text-primary">v{v.no}</span>
              {i < vers.length - 1 && <span className="mt-0.5 w-px flex-1 bg-border" />}
            </div>
            <div className="pb-0.5">
              <div className="text-text">{v.note}</div>
              <div className="mono mt-0.5 text-[11px] text-text-faint">{v.createdAt.slice(0, 10)} · {personById(v.createdById)?.name}</div>
            </div>
          </div>
        ))}
      </div>
    );
  }

  /* ── Search ───────────────────────────────────────────────── */
  function SearchScreen() {
    const { person, go } = useApp();
    const [f, setF] = React.useState({});
    const results = searchRecords(person, f);
    const set = (patch) => setF((p) => ({ ...p, ...patch }));
    const active = Object.values(f).some(Boolean);
    return (
      <div className="mx-auto max-w-[1180px]">
        <S.PageTitle icon="search" title="Search" />
        <div className="grid grid-cols-1 gap-4 lg:grid-cols-[260px_1fr]">
          <Card className="dms-card h-fit space-y-3.5 lg:sticky lg:top-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-1.5 text-[13px] font-semibold text-text"><Icon name="filter" size={14} className="text-text-muted" /> Filter</div>
              {active && <button onClick={() => setF({})} className="text-xs text-primary hover:underline">Clear</button>}
            </div>
            <input value={f.query ?? ''} onChange={(e) => set({ query: e.target.value })} placeholder="Search term…"
              className="w-full rounded-btn border border-border bg-bg px-2.5 py-1.5 text-sm outline-none focus:border-primary focusring" />
            <Select label="Department" value={f.departmentCode ?? ''} onChange={(v) => set({ departmentCode: v || undefined })} options={DEPARTMENTS.map((d) => ({ value: d.code, label: `${d.code} ${d.name}` }))} />
            <Select label="Confidentiality" value={f.confidentiality ?? ''} onChange={(v) => set({ confidentiality: v || undefined })} options={Object.keys(CONFIDENTIALITY).map((k) => ({ value: k, label: CONFIDENTIALITY[k].label }))} />
            <Select label="Status" value={f.status ?? ''} onChange={(v) => set({ status: v || undefined })} options={Object.keys(STATUS).map((k) => ({ value: k, label: STATUS[k].label }))} />
            <div>
              <div className="mb-1 text-xs font-medium text-text-muted">Doc date (from)</div>
              <input type="date" value={f.documentDateFrom ?? ''} onChange={(e) => set({ documentDateFrom: e.target.value || undefined })}
                className="w-full rounded-btn border border-border bg-bg px-2.5 py-1.5 text-sm outline-none focus:border-primary focusring" />
              <div className="mt-1.5 text-[11px] leading-relaxed text-text-faint">Three dates are separate (document/created/registered) — sec. 2.</div>
            </div>
          </Card>

          <div>
            <div className="mb-2.5 flex items-center gap-1.5 text-[13px] text-text-muted">
              <span className="tnum font-semibold text-text">{results.length}</span> Result
              <span className="text-text-faint">· invisible isn’t shown (sec. 4)</span>
            </div>
            {results.length === 0 ? (
              <EmptyState title="Nothing found" hint="Change the filter or search term." icon="search" />
            ) : (
              <DataTable headers={[{ label: 'Document' }, { label: 'Type' }, { label: 'Dept.' }, { label: 'Date' }, { label: 'Confid.' }, { label: 'Access', style: { textAlign: 'right' } }]}>
                {results.map((r) => {
                  const vis = recordVisibility(person, r).visibility;
                  return (
                    <tr key={r.id} className="clickable" onClick={() => go({ name: 'record', recordId: r.id })}>
                      <td className="dms-td">
                        <span className="flex items-center gap-2"><Icon name="file" size={15} className="flex-none text-text-faint" /><span className="font-medium text-text">{r.title}</span></span>
                        <span className="mono ml-[23px] block text-[11px] text-text-faint">{r.address}</span>
                      </td>
                      <td className="dms-td text-text-muted">{r.docType}</td>
                      <td className="dms-td text-text-muted">{departmentOf(r)?.name}</td>
                      <td className="dms-td tnum text-text-muted">{r.documentDate}</td>
                      <td className="dms-td"><ConfidentialityBadge level={r.confidentiality} /></td>
                      <td className="dms-td text-right"><AccessIndicator visibility={vis} /></td>
                    </tr>
                  );
                })}
              </DataTable>
            )}
          </div>
        </div>
      </div>
    );
  }

  function Select({ label, value, onChange, options }) {
    return (
      <div>
        <div className="mb-1 text-xs font-medium text-text-muted">{label}</div>
        <select value={value} onChange={(e) => onChange(e.target.value)}
          className="w-full rounded-btn border border-border bg-surface px-2.5 py-1.5 text-sm outline-none focus:border-primary focusring">
          <option value="">All</option>
          {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      </div>
    );
  }

  /* ── Zones: Intake / Safe / Reading ───────────────────────── */
  function IntakeScreen() {
    const { person, go } = useApp();
    const drafts = RECORDS.filter((r) => r.tenantId === person.tenantId && r.recordKind === 'draft');
    return (
      <div className="mx-auto max-w-[1180px]">
        <S.PageTitle icon="inbox" title="Recipient" />
        <p className="-mt-2 mb-5 max-w-2xl text-sm text-text-muted">New. Incoming / Unclassified. On choosing a category, field_set and default confid. auto-fill.</p>
        <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
          <Block title="Incoming" icon="inbox">
            {drafts.length === 0 ? (
              <EmptyState title="No new docs" icon="inbox" />
            ) : (
              <div className="-mx-4 -my-3">
                {drafts.map((r, i) => (
                  <button key={r.id} onClick={() => go({ name: 'record', recordId: r.id })}
                    className={`dms-row flex w-full items-center justify-between gap-3 text-left text-sm transition-colors hover:bg-[rgb(var(--c-primary)/0.045)] ${i ? 'border-t border-border' : ''}`}>
                    <span className="flex items-center gap-2"><Icon name="file" size={15} className="text-text-faint" /><span className="font-medium text-text">{r.title}</span></span>
                    <span className="text-xs text-text-faint">{r.docType}</span>
                  </button>
                ))}
              </div>
            )}
          </Block>
          <Block title="Classification" icon="sparkles">
            <div className="flex flex-col items-center gap-2 rounded-[8px] border border-dashed border-border bg-surface-2/50 px-5 py-7 text-center">
              <span className="flex h-9 w-9 items-center justify-center rounded-full bg-primary-tint text-primary"><Icon name="sparkles" size={18} /></span>
              <div className="max-w-xs text-sm text-text-muted text-balance">Example hint: "this document seems to belong to case C-01" — illustration only, not active in this demo.</div>
            </div>
            <p className="mt-3 text-xs leading-relaxed text-text-faint">Registration cannot complete without required fields (sec. 2 §8). Actual file upload is not built.</p>
          </Block>
        </div>
      </div>
    );
  }

  function SafeScreen() {
    const { person, go } = useApp();
    if (person.clearance < 3) {
      return (
        <div className="mx-auto max-w-[1180px]">
          <S.PageTitle icon="vault" title="Safe" />
          <DeniedStatePanelClearance />
        </div>
      );
    }
    const secrets = RECORDS.filter((r) => r.tenantId === person.tenantId && r.confidentiality === 'secret');
    return (
      <div className="mx-auto max-w-[1180px]">
        <S.PageTitle icon="vault" title="Safe" />
        <p className="-mt-2 mb-5 text-sm text-text-muted">Top secret doc — opening requires step-up confirmation.</p>
        {secrets.length === 0 ? (
          <EmptyState title="No secret Doc is visible" icon="vault" />
        ) : (
          <DataTable headers={[{ label: 'Document' }, { label: 'Confid.' }, { label: 'Access', style: { textAlign: 'right' } }]}>
            {secrets.map((r) => {
              const vis = recordVisibility(person, r, { stepUpConfirmed: false }).visibility;
              return (
                <tr key={r.id} className="clickable" onClick={() => go({ name: 'record', recordId: r.id })}>
                  <td className="dms-td"><span className="flex items-center gap-2"><Icon name="lock" size={14} className="text-text-faint" /><span className="font-medium text-text">{r.title}</span></span></td>
                  <td className="dms-td"><ConfidentialityBadge level={r.confidentiality} /></td>
                  <td className="dms-td text-right"><AccessIndicator visibility={vis} /></td>
                </tr>
              );
            })}
          </DataTable>
        )}
      </div>
    );
  }

  function DeniedStatePanelClearance() {
    return (
      <div className="flex flex-col items-center justify-center gap-3 rounded-card border border-border bg-surface px-6 py-12 text-center">
        <div className="flex h-12 w-12 items-center justify-center rounded-full bg-surface-2 text-text-muted ring-1 ring-border"><Icon name="vault" size={22} strokeWidth={1.6} /></div>
        <div className="text-[15px] font-semibold text-text">This zone is closed</div>
        <div className="max-w-md text-sm text-text-muted">clearance insufficient — the safe opens only at clearance level 3.</div>
      </div>
    );
  }

  function ReadingRoomScreen() {
    return (
      <div className="mx-auto max-w-[1180px]">
        <S.PageTitle icon="book" title="Reading room" />
        <p className="-mt-2 mb-5 text-sm text-text-muted">External/temporary access (guest) — read only, no download, time-limited.</p>
        <EmptyState title="No Doc is currently shared" hint="guest-Docs shared for them appear here with an expiry." icon="book" />
      </div>
    );
  }

  /* ── Audit ────────────────────────────────────────────────── */
  function AuditScreen() {
    const { audit } = useApp();
    const RESULT = {
      allow: { label: 'Allow', color: 'var(--st-active)' },
      deny: { label: 'Deny', color: 'var(--st-hold)' },
      step_up: { label: 'step-up', color: 'var(--st-disposal)' },
    };
    return (
      <div className="mx-auto max-w-[1180px]">
        <S.PageTitle icon="history" title="Audit trail" />
        <p className="-mt-2 mb-5 text-sm text-text-muted">Immutable log — both allow and deny are recorded. Live entries are added when a doc is opened.</p>
        <DataTable headers={[{ label: 'Time' }, { label: 'Who' }, { label: 'Object' }, { label: 'verb' }, { label: 'Result' }, { label: 'Reason (step)' }]}>
          {audit.map((a) => {
            const rr = RESULT[a.result];
            return (
              <tr key={a.id}>
                <td className="dms-td mono whitespace-nowrap text-xs text-text-faint">{a.ts.slice(0, 19).replace('T', ' ')}</td>
                <td className="dms-td whitespace-nowrap text-text">{DMS.personById(a.subjectId)?.name ?? a.subjectId}</td>
                <td className="dms-td text-text-muted">{DMS.recordById(a.objectId)?.title ?? a.objectId}</td>
                <td className="dms-td mono text-xs text-text-muted">{a.verb}</td>
                <td className="dms-td">
                  <span className="chip" style={{ background: `color-mix(in srgb, rgb(${rr.color}) 13%, white)`, color: `color-mix(in srgb, rgb(${rr.color}) 80%, black)` }}>
                    <Icon name={a.result === 'allow' ? 'check' : a.result === 'deny' ? 'x' : 'lock'} size={11} strokeWidth={2} />{rr.label}
                  </span>
                </td>
                <td className="dms-td text-xs text-text-muted">{a.reason} <span className="mono text-text-faint">(step {a.step})</span></td>
              </tr>
            );
          })}
        </DataTable>
      </div>
    );
  }

  /* ── Manage (nomenclature) ────────────────────────────────── */
  function ManageScreen() {
    return (
      <div className="mx-auto max-w-[1180px]">
        <S.PageTitle icon="settings" title="Nomenclature management" />
        <p className="-mt-2 mb-5 max-w-2xl text-sm text-text-muted">Renumbering/renaming is forbidden (P1/P2). Closing ≠ deleting (P6). A change → version + log (P9).</p>
        <Card className="dms-card mb-4">
          <div className="mb-3 flex items-center gap-1.5 text-[13px] font-semibold text-text"><Icon name="clock" size={14} className="text-text-muted" /> Retention periods (config — years open)</div>
          <div className="flex flex-wrap gap-2.5">
            {Object.entries(RETENTION_CLASS).map(([k, v]) => (
              <div key={k} className="rounded-[8px] border border-border bg-surface-2/40 px-3 py-2 text-sm">
                <div className="font-semibold text-text">{v.label}</div>
                <div className="mt-0.5 text-xs text-text-faint">{v.years === null ? 'to fill (pending legal check)' : `${v.years} years`}</div>
              </div>
            ))}
          </div>
        </Card>
        <DataTable headers={[{ label: 'Code' }, { label: 'Category' }, { label: 'field_set' }, { label: 'Default confid.' }, { label: 'Status', style: { textAlign: 'right' } }]}>
          {CATEGORIES.map((c) => (
            <tr key={c.code} style={c.status === 'closed' ? { opacity: 0.55 } : undefined}>
              <td className="dms-td mono text-xs text-text-muted">{c.code}</td>
              <td className="dms-td font-medium text-text">{c.name}</td>
              <td className="dms-td mono text-xs text-text-faint">{c.fieldSet}</td>
              <td className="dms-td"><ConfidentialityBadge level={c.defaultConfidentiality} /></td>
              <td className="dms-td text-right">
                {c.status === 'closed'
                  ? <span className="inline-flex items-center gap-1 text-xs" style={{ color: 'rgb(var(--st-disposal))' }}><Icon name="lock" size={12} /> Closed</span>
                  : <span className="text-xs text-text-muted">Active</span>}
              </td>
            </tr>
          ))}
        </DataTable>
      </div>
    );
  }

  /* ── Edge cases ───────────────────────────────────────────── */
  function EdgeCasesScreen() {
    const cases = runEdgeCases();
    const passed = cases.filter((c) => c.pass).length;
    const allPass = passed === cases.length;
    return (
      <div className="mx-auto max-w-[1180px]">
        <div className="mb-5 flex flex-wrap items-center justify-between gap-3">
          <div className="flex items-center gap-3">
            <span className="flex h-9 w-9 items-center justify-center rounded-[9px] bg-primary-tint text-primary"><Icon name="checks" size={19} strokeWidth={1.7} /></span>
            <div>
              <h1 className="serif text-[24px] font-semibold tracking-tight text-text">E1–E12 — foundation test</h1>
              <p className="mt-0.5 text-sm text-text-muted">The access algorithm live on sample data. "View as"-switch the role — behavior changes.</p>
            </div>
          </div>
          <div className="chip tnum text-[15px]" style={{ padding: '6px 14px', background: `color-mix(in srgb, rgb(${allPass ? 'var(--st-active)' : 'var(--st-disposal)'}) 13%, white)`, color: `color-mix(in srgb, rgb(${allPass ? 'var(--st-active)' : 'var(--st-disposal)'}) 80%, black)` }}>
            <Icon name={allPass ? 'check' : 'alert'} size={15} strokeWidth={2} /> {passed}/{cases.length} passed
          </div>
        </div>
        <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
          {cases.map((c) => (
            <Card key={c.id} className="dms-card">
              <div className="mb-1 flex items-center gap-2">
                <span className="chip" style={{ background: `color-mix(in srgb, rgb(${c.pass ? 'var(--st-active)' : 'var(--st-hold)'}) 14%, white)`, color: `color-mix(in srgb, rgb(${c.pass ? 'var(--st-active)' : 'var(--st-hold)'}) 80%, black)` }}>
                  <Icon name={c.pass ? 'check' : 'x'} size={11} strokeWidth={2.2} /> {c.id}
                </span>
                <span className="font-semibold text-text">{c.title}</span>
              </div>
              <div className="mb-2.5 text-xs leading-relaxed text-text-faint">{c.rule}</div>
              <div className="space-y-1.5">
                {c.lines.map((l, i) => (
                  <div key={i} className="flex items-start gap-2 text-[13px]">
                    <Icon name={l.ok ? 'check' : 'x'} size={13} strokeWidth={2} className="mt-0.5 flex-none" style={{ color: `rgb(${l.ok ? 'var(--st-active)' : 'var(--st-hold)'})` }} />
                    <span className="text-text-muted"><span className="font-medium text-text">{l.label}</span> {l.detail}</span>
                  </div>
                ))}
              </div>
            </Card>
          ))}
        </div>
      </div>
    );
  }

  Object.assign(window.Screens, {
    RecordScreen, SearchScreen, IntakeScreen, SafeScreen, ReadingRoomScreen, AuditScreen, ManageScreen, EdgeCasesScreen, LockedContent,
  });
})();
