// kova/library.jsx — design library page · Wave B deliverable
// Lives at route 'library'. Documents every atom, molecule, organism preview,
// state, and overlay primitive. The atomic-design contract made visible.

const {
  Icon, Btn, IconBtn, Input, Textarea, Checkbox, Switch, Chip, StatusDot, Kbd, Avatar, Spinner, Skeleton,
  Field, Tabs, Seg, Search, Crumb, KPITile, ConfidenceMeter, NotificationRow,
  ApprovalStep, ApprovalChain, RunBadge, StatusBadge, VerificationStamp, PageHead, Card,
  EmptyState, RestrictedState, ErrorState, LoadingBlock,
  DecisionCard, DECISION_FIXTURES,
  RunObject, EvidencePanel, WorkflowTimeline, ExceptionCard, ApprovalSurface, ActivityStream,
} = window.K;

/* small helper — section heading with number + sub */
const LibSection = ({ num, title, sub, children }) => (
  <section style={{ marginTop: 56 }}>
    <header style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 24, paddingBottom: 16, borderBottom: '1px solid var(--line)' }}>
      <span className="t-mono" style={{ fontSize: 12, color: 'var(--mute-2)' }}>{num}</span>
      <h2 className="t-h1" style={{ margin: 0 }}>{title}</h2>
      {sub && <p style={{ fontSize: 13, color: 'var(--mute)', marginLeft: 'auto', maxWidth: 380, lineHeight: 1.5 }}>{sub}</p>}
    </header>
    {children}
  </section>
);

/* small helper — labelled demo block */
const Demo = ({ label, sub, children }) => (
  <div className="k-card">
    {label && <div className="t-eyebrow" style={{ marginBottom: sub ? 4 : 10 }}>{label}</div>}
    {sub && <div className="t-meta" style={{ marginBottom: 10, color: 'var(--mute)' }}>{sub}</div>}
    {children}
  </div>
);

const Row = ({ children, style }) => (
  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'center', ...style }}>
    {children}
  </div>
);

const Grid = ({ cols = 2, children, gap = 16 }) => (
  <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gap }}>{children}</div>
);


/* ============================================================
   LIBRARY PAGE
   ============================================================ */
const LibraryPage = ({ openDrawer, openModal, openCmdK, pushToast }) => {
  const [checkA, setCheckA] = React.useState(true);
  const [checkB, setCheckB] = React.useState(false);
  const [switchA, setSwitchA] = React.useState(true);
  const [switchB, setSwitchB] = React.useState(false);
  const [tab, setTab] = React.useState('pending');
  const [seg, setSeg] = React.useState('comfortable');

  return (
    <div className="k-page-enter">
      <PageHead
        crumb={['SYSTEM', 'Design library']}
        title="Design library"
        subtitle="Wave B · every atom, molecule, and primitive in the production system. Click any organism preview to open it live."
        actions={
          <>
            <Btn size="sm" onClick={openCmdK} kbd="⌘K">Command palette</Btn>
            <Btn size="sm" variant="primary" onClick={openDrawer}>Open evidence drawer</Btn>
          </>
        }
      />

      {/* ============ ATOMS ============ */}
      <LibSection num="01" title="Atoms"
        sub="Indivisible primitives. Buttons, inputs, chips, status. Every state mapped.">
        <Grid cols={2}>
          <Demo label="Buttons · variants">
            <Row>
              <Btn variant="primary" kbd="⌘⏎">Approve &amp; sign</Btn>
              <Btn>Open ORBIT</Btn>
              <Btn variant="ghost">Cancel</Btn>
            </Row>
            <Row style={{ marginTop: 12 }}>
              <Btn variant="accent">Generate brief</Btn>
              <Btn variant="approve" icon="check">Approve</Btn>
              <Btn variant="reject" icon="cross">Reject</Btn>
            </Row>
            <div className="t-eyebrow" style={{ margin: '20px 0 10px' }}>States · primary</div>
            <Row>
              <Btn variant="primary">Default</Btn>
              <Btn variant="primary" style={{ background: 'var(--ink-2)', borderColor: 'var(--ink-2)' }}>Hover</Btn>
              <Btn variant="primary" style={{ background: '#000' }}>Active</Btn>
              <Btn variant="primary" style={{ boxShadow: 'var(--focus-ring)' }}>Focus</Btn>
              <Btn variant="primary" disabled>Disabled</Btn>
              <Btn variant="primary" loading>Working…</Btn>
            </Row>
            <div className="t-eyebrow" style={{ margin: '20px 0 10px' }}>Sizes</div>
            <Row>
              <Btn size="sm">Small · 26 px</Btn>
              <Btn>Default · 32 px</Btn>
              <Btn size="lg">Large · 40 px</Btn>
            </Row>
          </Demo>

          <Demo label="Inputs · states">
            <Grid cols={2}>
              <Field label="SKU" help="Paste a list with ⌘V">
                <Input defaultValue="SKU-00883-RG" />
              </Field>
              <Field label="Reserve price">
                <Input defaultValue="142,800" prefix="₹" />
              </Field>
              <Field label="Discount cap" error="Exceeds CEO ceiling of 20 %">
                <Input defaultValue="42" suffix="%" error />
              </Field>
              <Field label="Vendor" help="Vendor changes require CONNECT approval">
                <Input defaultValue="Mehta Castings · locked" disabled />
              </Field>
            </Grid>
            <Field label="Designer brief" help="Markdown supported">
              <Textarea defaultValue="Solitaire bands · Delhi clientele · ages 28–38. Lean editorial. Avoid baroque motifs — wiki note rcp-44ab." />
            </Field>
          </Demo>

          <Demo label="Chips · semantic">
            <Row>
              <Chip variant="success" dot>Verified</Chip>
              <Chip variant="warn" dot>Awaiting CEO</Chip>
              <Chip variant="danger" dot>Rejected</Chip>
              <Chip variant="info" dot>Generating</Chip>
              <Chip variant="accent" dot>Pending review</Chip>
              <Chip variant="mute">Draft</Chip>
              <Chip variant="solid">Sign · ⌘⏎</Chip>
            </Row>
            <div className="t-eyebrow" style={{ margin: '20px 0 10px' }}>Status dots</div>
            <Row>
              <StatusDot kind="success" /> Verified
              <StatusDot kind="warn" /> Attention
              <StatusDot kind="danger" /> Failed
              <StatusDot kind="info" /> Info
              <StatusDot /> Drift
            </Row>
            <div className="t-eyebrow" style={{ margin: '20px 0 10px' }}>Keyboard hints</div>
            <Row>
              <Kbd>⌘K</Kbd><Kbd>⌘⏎</Kbd><Kbd>⌘⇧⏎</Kbd><Kbd>esc</Kbd><Kbd>g</Kbd><Kbd>o</Kbd>
            </Row>
          </Demo>

          <Demo label="Checkbox · Switch · Avatar · Spinner · Skeleton">
            <Grid cols={2} gap={12}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                <Checkbox checked={checkA} onChange={setCheckA} label="Approve also queues notification" />
                <Checkbox checked={checkB} onChange={setCheckB} label="Notify logistics on approval" />
                <Checkbox checked={false} disabled label="Auto-promote (admin only)" />
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-start' }}>
                <Row><Switch on={switchA} onChange={setSwitchA} /> <span className="t-body-sm">Verified outputs only</span></Row>
                <Row><Switch on={switchB} onChange={setSwitchB} /> <span className="t-body-sm">Reduced motion</span></Row>
                <Row><Switch on={false} disabled /> <span className="t-body-sm" style={{ color: 'var(--mute-2)' }}>Cross-tenant memory (locked)</span></Row>
              </div>
              <Row>
                <Avatar initials="RP" /> <Avatar initials="PV" size={32} /> <Avatar initials="AK" size={36} />
              </Row>
              <Row>
                <Spinner /> <Skeleton width={120} /> <Skeleton width={80} height={22} />
              </Row>
            </Grid>
          </Demo>
        </Grid>
      </LibSection>

      {/* ============ MOLECULES ============ */}
      <LibSection num="02" title="Molecules" sub="2–3 atoms composed into one functional unit.">
        <Grid cols={3}>
          <KPITile mod="home" label="Approvals waiting" value="4" trend={{ dir: 'up', label: '+2' }} foot="since 9 am" />
          <KPITile mod="vault" label="Unlock identified" value="₹14.2 L" foot="38 SKUs · VAULT" />
          <KPITile mod="price" label="Margin Δ · 7 d" value="+ 6.4 %" foot="vs. previous 7 days" valueColor="var(--success)" />
        </Grid>

        <Grid cols={2} gap={16} style={{ marginTop: 16 }}>
          <Demo label="Tabs · with counts">
            <Tabs value={tab} onChange={setTab} mod="approvals" items={[
              { id: 'pending',  label: 'Pending',  count: 4 },
              { id: 'approved', label: 'Approved', count: 128 },
              { id: 'rejected', label: 'Rejected', count: 12 },
              { id: 'all',      label: 'All' },
            ]} />
            <div style={{ marginTop: 14 }} className="t-meta">Active: {tab}</div>
          </Demo>

          <Demo label="Segmented control">
            <Seg value={seg} onChange={setSeg} items={[
              { id: 'compact',     label: 'Compact' },
              { id: 'comfortable', label: 'Comfortable' },
              { id: 'spacious',    label: 'Spacious' },
            ]} />
            <div style={{ marginTop: 14 }} className="t-meta">Active: {seg}</div>
          </Demo>

          <Demo label="Confidence meter · 4 levels">
            <Row>
              <ConfidenceMeter level={1} label="Low" />
              <ConfidenceMeter level={2} label="Medium" />
              <ConfidenceMeter level={3} label="High" mod="orbit" />
              <ConfidenceMeter level={4} label="Verified" mod="approvals" />
            </Row>
          </Demo>

          <Demo label="Status badges">
            <Row>
              <StatusBadge kind="verified">Verified</StatusBadge>
              <StatusBadge kind="pending">Pending CEO sign</StatusBadge>
              <StatusBadge kind="failed">Verifier rejected</StatusBadge>
              <StatusBadge kind="drift">Drift · stale 6 h</StatusBadge>
            </Row>
          </Demo>

          <Demo label="Run badge · always points to MONITOR">
            <Row>
              <RunBadge id="rcp-44c9" version="v3" when="2 min ago" />
            </Row>
            <Row style={{ marginTop: 10 }}>
              <RunBadge id="orbit.daily_brief" version="v17" when="9:04" />
              <RunBadge id="vault.deadstock_scan" version="v2" when="Wed 7:00" />
            </Row>
          </Demo>

          <Demo label="Approval chain · timeline">
            <ApprovalChain mod="orbit" steps={[
              { who: 'Priya · Merch lead',  meta: 'Drafted recommendation · 9:02', state: 'done' },
              { who: 'Auto · evidence sweep', meta: '3 of 3 claims sourced · 9:04', state: 'done' },
              { who: 'You · CEO',           meta: 'Awaiting sign · ⌘⏎ to approve', state: 'now' },
              { who: 'Logistics · execution', meta: 'Will queue transfer manifest', state: 'pending' },
            ]} />
          </Demo>

          <Demo label="Notification row · feed">
            <NotificationRow mod="orbit"
              title={<><b>Orbit</b> · new daily brief · 3 recommendations</>}
              meta="2 min ago" />
            <NotificationRow mod="approvals"
              title={<><b>Vault</b> · awaiting your approval on rcp-44c9</>}
              meta="9 min ago" />
            <NotificationRow read
              title="Connect · Tally sync completed"
              meta="1 h ago" />
            <NotificationRow read
              title="Kraft · CAD-117 ready for review"
              meta="Yesterday" />
          </Demo>

          <Demo label="Verification stamp · provenance">
            <Row>
              <VerificationStamp>Verified · Orbit daily brief</VerificationStamp>
            </Row>
            <Row style={{ marginTop: 8 }}>
              <VerificationStamp>Verified · Price recommendation</VerificationStamp>
            </Row>
          </Demo>
        </Grid>
      </LibSection>

      {/* ============ ORGANISMS — Wave C ============ */}
      <LibSection num="03" title="Organisms · Wave C"
        sub="The 10 named UI objects. Each composes lower primitives only. Direction restyles atoms; organisms are invariant.">

        {/* 3.1 — DecisionCard 4 module variants */}
        <div style={{ marginBottom: 16 }}>
          <div className="t-eyebrow" style={{ marginBottom: 10 }}>1 · Decision Card · 4 module variants</div>
          <Grid cols={2} gap={20}>
            <DecisionCard {...DECISION_FIXTURES.orbit}
              onEvidence={openDrawer} onRunHistory={() => {}}
              onReject={openModal} onRevise={() => {}}
              onApprove={() => pushToast({ kind: 'success', title: 'Approved · rcp-44c9', body: 'Transfer queued for CONNECT.' })} />
            <DecisionCard {...DECISION_FIXTURES.vault}
              onEvidence={openDrawer} onRunHistory={() => {}}
              onReject={openModal} onRevise={() => {}}
              onApprove={() => pushToast({ kind: 'success', title: 'Approved · rcp-44ca', body: 'Reprice queued for PRICE.' })} />
            <DecisionCard {...DECISION_FIXTURES.price}
              onEvidence={openDrawer} onRunHistory={() => {}}
              onReject={openModal} onRevise={() => {}}
              onApprove={() => pushToast({ kind: 'success', title: 'Approved · rcp-44cb', body: 'Rate update applied to 412 SKUs.' })} />
            <DecisionCard {...DECISION_FIXTURES.kraft}
              onEvidence={openDrawer} onRunHistory={() => {}}
              onReject={openModal} onRevise={() => {}}
              onApprove={() => pushToast({ kind: 'success', title: 'Signed off · CAD-117', body: 'Launch pack moved to manufacturing.' })} />
          </Grid>
        </div>

        {/* 3.2 — RunObject */}
        <div style={{ marginBottom: 16 }}>
          <div className="t-eyebrow" style={{ marginBottom: 10 }}>2 · Run Object · header card</div>
          <RunObject
            mod="orbit"
            runId="rcp-44c9"
            status="verified"
            title="orbit.daily_brief · v3 · 09:42 IST"
            agent="orbit_brief_agent · v2.1"
            skillVersion="acme.orbit.skills @ 2026.05.18-3"
            memoryVersion="acme.memory @ 2026.05.20"
            startedAt="09:42:01 IST"
            cost="$0.018"
            latency="8.4 s"
            onOpenTrace={() => {}}
          />
        </div>

        {/* 3.3 — EvidencePanel */}
        <div style={{ marginBottom: 16 }}>
          <div className="t-eyebrow" style={{ marginBottom: 10 }}>3 · Evidence Panel · tabbed claims / receipts / math</div>
          <EvidencePanel
            runId="rcp-44c9"
            claims={[
              { text: 'Delhi demand outperforming for solitaire bands.',           source: 'sales.read',             receipt: 'rcp-44c9 / claim 1' },
              { text: 'Median age 214 d exceeds 180-day deadstock floor.',         source: 'inventory.read',         receipt: 'rcp-44c9 / claim 2' },
              { text: 'Delhi sell-price within 4 % of catalogue — no reprice.',    source: 'price.read · deterministic', receipt: 'rcp-44c9 / claim 3' },
            ]}
            receipts={[
              { tool: 'sql.query',         scope: 'sales.read',     id: 'tool-receipt-882' },
              { tool: 'sql.query',         scope: 'inventory.read', id: 'tool-receipt-883' },
              { tool: 'price.calculate',   scope: 'deterministic',  id: 'tool-receipt-884' },
              { tool: 'wiki.lookup',       scope: 'wiki.read',      id: 'tool-receipt-885' },
            ]}
            math={[
              { expr: 'delhi_velocity_14d - forecast_14d',  value: '+22.3 %' },
              { expr: 'mumbai_velocity_14d - forecast_14d', value: '−22.1 %' },
              { expr: 'unlock = Σ(sku_value × age_weight)', value: '₹14,21,800' },
              { expr: 'margin_delta = transfer − reprice',  value: '+ 6.4 %' },
            ]}
          />
        </div>

        {/* 3.4 — WorkflowTimeline */}
        <Grid cols={2} gap={20}>
          <div>
            <div className="t-eyebrow" style={{ marginBottom: 10 }}>4 · Workflow Timeline · pending approval</div>
            <WorkflowTimeline
              title="orbit.daily_brief · rcp-44c9"
              actions={<Btn size="sm" variant="ghost">Open in MONITOR ›</Btn>}
              steps={[
                { label: 'Queued',          meta: 'workflow.start',         time: '09:42:01', state: 'done' },
                { label: 'Context built',   meta: '128 KB · 4 sources',     time: '09:42:02', state: 'done' },
                { label: 'Agent ran',       meta: 'orbit_brief_agent v2.1', time: '09:42:09', state: 'done' },
                { label: 'Verified',        meta: '3 / 3 claims sourced',   time: '09:42:11', state: 'done' },
                { label: 'Awaiting approval', meta: 'CEO · ⌘⏎ to sign',     time: 'now',      state: 'now' },
                { label: 'Execute · CONNECT', meta: 'transfer.manifest',    time: '—',        state: 'pending' },
                { label: 'Outcome tracked',  meta: 'curator records',        time: '—',        state: 'pending' },
              ]}
            />
          </div>

          <div>
            <div className="t-eyebrow" style={{ marginBottom: 10 }}>5 · Exception Card · connector failure</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <ExceptionCard
                kind="failed"
                icon="!"
                title="Tally connector lost session token"
                source="connect.tally"
                errorCode="err.connect.401"
                when="11:38:22 IST"
                detail="The sync token expired and the IdP returned 401 on refresh. Your data is unchanged. Tenant admin can reauthorize the connector in CONNECT."
                onRetry={() => pushToast({ kind: 'info', title: 'Retry queued', body: 'connect.tally · attempt 2 of 3' })}
                onOpen={() => {}}
              />
              <ExceptionCard
                kind="warn"
                icon="!"
                title="Verifier rejected 1 of 4 claims · rcp-44cd"
                source="output.controller"
                errorCode="verifier.evidence.missing"
                when="11:24:08 IST"
                detail="Claim 3 (margin projection) lacked a receipt from price.read. Agent will re-run with stricter source binding."
                onRetry={() => pushToast({ kind: 'info', title: 'Re-running rcp-44cd' })}
                onOpen={() => {}}
              />
            </div>
          </div>
        </Grid>

        {/* 3.5 — ApprovalSurface */}
        <div style={{ marginTop: 20, marginBottom: 16 }}>
          <div className="t-eyebrow" style={{ marginBottom: 10 }}>6 · Approval Surface · standalone</div>
          <ApprovalSurface
            mod="orbit"
            runId="rcp-44c9"
            title="Transfer Mumbai → Delhi · 38 SKUs"
            chain={[
              { who: 'Priya · Merch lead',     meta: 'Drafted recommendation · 9:02',  state: 'done' },
              { who: 'Auto · evidence sweep',  meta: '3 of 3 claims sourced · 9:04',   state: 'done' },
              { who: 'You · CEO',              meta: 'Awaiting sign · ⌘⏎ to approve',  state: 'now' },
              { who: 'Logistics · execution',  meta: 'Will queue transfer manifest',   state: 'pending' },
            ]}
            onReject={openModal}
            onRevise={() => {}}
            onApprove={() => pushToast({ kind: 'success', title: 'Approved · rcp-44c9', body: 'Transfer queued for CONNECT.' })}
          />
        </div>

        {/* 3.6 — ActivityStream */}
        <Grid cols={2} gap={20}>
          <div>
            <div className="t-eyebrow" style={{ marginBottom: 10 }}>7 · Activity Stream · chronological feed</div>
            <ActivityStream
              title="Today’s activity"
              onSeeAll={() => {}}
              items={[
                { mod: 'orbit',     icon: 'O', title: 'orbit.daily_brief verified · 3 recommendations', meta: 'orbit_brief_agent', runId: 'rcp-44c9', time: '2 min' },
                { mod: 'approvals', icon: 'A', title: 'Awaiting your sign on Mumbai → Delhi transfer',  meta: 'co-sign · Priya',  runId: 'rcp-44c9', time: '9 min' },
                { mod: 'vault',     icon: 'V', title: 'vault.deadstock_scan completed · 38 candidates', meta: 'vault_action_agent', runId: 'rcp-44ca', time: '11 min' },
                { mod: 'connect',   icon: 'C', title: 'Tally sync completed · 412 SKUs reconciled',      meta: 'connector', time: '32 min' },
                { mod: 'kraft',     icon: 'K', title: 'CAD-117 packet ready for CEO review',             meta: 'designer · Vikram', runId: 'rcp-44cc', time: '1 h' },
              ]}
            />
          </div>

          <div>
            <div className="t-eyebrow" style={{ marginBottom: 10 }}>8–10 · Already in system · live demos</div>
            <Card>
              <p className="t-body-sm" style={{ marginTop: 0 }}>
                <b>VerificationLayer</b>, <b>StatusBadge</b>, and <b>ConfidenceIndicator</b> were
                built as molecules in Wave B and are used by every organism above. They live in
                the molecules section (02).
              </p>
              <p className="t-body-sm">
                The drawer · modal · command palette · toast organisms are interactive. Try them:
              </p>
              <Row style={{ marginTop: 12 }}>
                <Btn size="sm" onClick={openDrawer}>Open drawer</Btn>
                <Btn size="sm" onClick={openModal}>Open modal</Btn>
                <Btn size="sm" onClick={openCmdK} kbd="⌘K">Command palette</Btn>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <Btn size="sm" variant="ghost" onClick={() => pushToast({ kind: 'success', title: 'Approved · rcp-44c9', body: 'Transfer queued for CONNECT.' })}>Success toast</Btn>
                <Btn size="sm" variant="ghost" onClick={() => pushToast({ kind: 'warn',    title: 'Tally sync failed · 12 rows', body: 'Mapping mismatch on metal_rate_24k.' })}>Warn toast</Btn>
                <Btn size="sm" variant="ghost" onClick={() => pushToast({ kind: 'error',   title: 'Connector lost token', body: 'Open CONNECT to reauthorize.' })}>Error toast</Btn>
              </Row>
            </Card>
          </div>
        </Grid>
      </LibSection>

      {/* ============ STATES ============ */}
      <LibSection num="04" title="Mandatory states"
        sub="No screen ships without all four. Each has a primary CTA so the user is never stranded.">
        <Grid cols={4}>
          <Card>
            <div className="t-eyebrow" style={{ marginBottom: 8 }}>Empty</div>
            <EmptyState
              title="No decisions today."
              body="Orbit hasn’t found anything that needs you. It scans every 6 hours."
              cta={<Btn size="sm">Run brief now</Btn>}
            />
          </Card>
          <Card>
            <div className="t-eyebrow" style={{ marginBottom: 8 }}>Loading</div>
            <LoadingBlock rows={6} />
            <div className="t-meta" style={{ marginTop: 12 }}>Skeleton min-show 400 ms before swap.</div>
          </Card>
          <Card style={{ background: 'transparent', boxShadow: 'none', borderColor: 'transparent' }}>
            <div className="t-eyebrow" style={{ marginBottom: 8, color: 'var(--danger)' }}>Error</div>
            <ErrorState
              code="err.connect.401 · 11:38:22"
              title="Could not reach Tally"
              body="CONNECT lost the sync token. Your data is unchanged."
              retry={<><Btn size="sm" variant="primary">Retry sync</Btn><Btn size="sm">Open CONNECT</Btn></>}
            />
          </Card>
          <Card>
            <div className="t-eyebrow" style={{ marginBottom: 8 }}>Restricted</div>
            <RestrictedState
              badge="ADMIN ONLY"
              title="Pricing ceiling controls"
              body="You have read access. Edits are reserved for Pricing Lead and CEO."
              cta={<><Btn size="sm">Request access</Btn> <Btn size="sm" variant="ghost">Open WIKI · policy</Btn></>}
            />
          </Card>
        </Grid>
      </LibSection>

      {/* ============ KEYBOARD ============ */}
      <LibSection num="05" title="Keyboard map"
        sub="Linear-style. Every primary action reachable by keyboard.">
        <Grid cols={3}>
          <Card eyebrow="Global">
            {[
              ['⌘ K', 'Command palette'],
              ['⌘ E', 'Open evidence drawer'],
              ['⌘ \\', 'Collapse rail'],
              ['?', 'Show shortcuts overlay'],
              ['esc', 'Close any overlay'],
            ].map(([k, v]) => (
              <div key={k} className="t-body-sm" style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line-2)' }}>
                <span>{v}</span>
                <span style={{ display: 'flex', gap: 4 }}>{k.split(' ').map((p, i) => <Kbd key={i}>{p}</Kbd>)}</span>
              </div>
            ))}
          </Card>
          <Card eyebrow="Decision">
            {[
              ['⌘ ⏎',   'Approve & sign'],
              ['⌘ ⇧ ⏎', 'Reject with reason'],
              ['⌘ R',   'Request revision'],
              ['⌘ V',   'Open evidence'],
              ['⌘ H',   'Open run history'],
            ].map(([k, v]) => (
              <div key={k} className="t-body-sm" style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line-2)' }}>
                <span>{v}</span>
                <span style={{ display: 'flex', gap: 4 }}>{k.split(' ').map((p, i) => <Kbd key={i}>{p}</Kbd>)}</span>
              </div>
            ))}
          </Card>
          <Card eyebrow="Navigate">
            {[
              ['g h', 'Go to Home'],
              ['g o', 'Go to Orbit'],
              ['g v', 'Go to Vault'],
              ['g p', 'Go to Price'],
              ['g k', 'Go to Kraft'],
              ['g a', 'Go to Approvals'],
              ['g m', 'Go to Monitor'],
            ].map(([k, v]) => (
              <div key={k} className="t-body-sm" style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line-2)' }}>
                <span>{v}</span>
                <span style={{ display: 'flex', gap: 4 }}>{k.split(' ').map((p, i) => <Kbd key={i}>{p}</Kbd>)}</span>
              </div>
            ))}
          </Card>
        </Grid>
      </LibSection>
    </div>
  );
};

window.LibraryPage = LibraryPage;
