import * as DeckUi from '@overdeck/deck-ui'
import { createRef, useState, type ComponentType, type ReactNode } from 'react'
import { liveAgentIdentityFixture, agentTurnsFixture } from '../../../../../packages/deck-ui/src/fixtures/agent'
import { ATTENTION_ITEMS } from '../../../../../packages/deck-ui/src/fixtures/attention'
import { BOT_ROWS } from '../../../../../packages/deck-ui/src/fixtures/bots'
import { CAPACITY_ACCOUNTS, LIMITED_CODEX } from '../../../../../packages/deck-ui/src/fixtures/capacity'
import {
  CI_AMPLIFICATION_GATES,
  CI_AMPLIFICATION_RESTART,
  CI_REPO_GAP_SUMMARY,
  CI_REPO_DEFERRED_SUMMARY,
  CI_REPO_SUMMARIES,
  CI_REPO_SUMMARY,
  CI_PR_QUEUE,
  CI_PR_QUEUE_REPOS,
  CI_RUNNERS,
  CI_RUNNERS_ALL_BUSY,
  CI_RUNNERS_ALL_OFFLINE,
  CI_TRAIN,
  CI_TRAIN_REPO_COMPLETENESS,
} from '../../../../../packages/deck-ui/src/fixtures/ci-trains'
import { RUN_TASK_CELLS, RUN_TASK_CELLS_ALARMED } from '../../../../../packages/deck-ui/src/fixtures/distance-to-done'
import {
  OPT_DATA_INTEGRITY_ATTRIBUTION,
  OPT_DATA_INTEGRITY_RUNS,
  OPT_DATA_INTEGRITY_SEGMENTS,
  OPT_DATA_INTEGRITY_TILES,
} from '../../../../../packages/deck-ui/src/fixtures/forensics'
import { INBOX_FIXTURES } from '../../../../../packages/deck-ui/src/fixtures/inbox'
import { KV_CI_RUNNERS } from '../../../../../packages/deck-ui/src/fixtures/kv'
import { LIMIT_ACCOUNTS } from '../../../../../packages/deck-ui/src/fixtures/limits'
import {
  CLUSTER_QUEUE_FIXTURE,
  FLEET_CONFIG_DRIFTED,
  FLEET_CONFIG_UNREACHABLE,
  FLEET_PROBE_FAILING,
  FLEET_DEBIAN1,
  FLEET_DEBIAN2_JOINING,
  OFFLOAD_CONTROL_FIXTURE,
  REMOTE_JOBS_FIXTURE,
} from '../../../../../packages/deck-ui/src/fixtures/offload'
import {
  abandonedPlanFixture,
  planRunListRowFixture,
  planTableItemsFixture,
  planTableItemStalledFixture,
  projectGroupFixture,
} from '../../../../../packages/deck-ui/src/fixtures/plans'
import { SCORE_MULTIDEAL } from '../../../../../packages/deck-ui/src/fixtures/scoreboard'
import { RUN_SETTINGS } from '../../../../../packages/deck-ui/src/fixtures/settings'
import { TERMINAL_SCREEN_FIXTURE } from '../../../../../packages/deck-ui/src/fixtures/terminal'
import { STALE_HARNESS_STATUS } from '../../../../../packages/deck-ui/src/fixtures/stale'
import {
  REAL_TRACE_BANDS,
  REAL_TRACE_LANES,
  GALLERY_TRACE_MULTI_DAY_LANES,
  GALLERY_TRACE_NO_TEMPORAL_LANES,
  GALLERY_TRACE_RUNNING_NOW_MS,
  GALLERY_TRACE_SHORT_SPAN_LANES,
  GALLERY_TRACE_SHORT_SPAN_START_MS,
  TRACE_START_MS,
} from '../../../../../packages/deck-ui/src/fixtures/swimlane-trace'
import { AttemptDetailDrawer } from '../plans/AttemptDetailDrawer'
import { AttemptTimeline } from '../plans/AttemptTimeline'
import { AutopsyStrip } from '../plans/AutopsyStrip'
import { BurnPanel } from '../plans/BurnPanel'
import type { AttemptRecord } from '../plans/attempt-record'

export type GalleryDomain = 'tables' | 'chips' | 'forensics' | 'agent' | 'offload' | 'overlays' | 'inputs' | 'layout'

export interface GalleryEntry {
  name: string
  domain: GalleryDomain
  component: ComponentType<any>
  render(): ReactNode
}

const noop = () => undefined

const SELECT_FIXTURE_OPTIONS: DeckUi.SelectOption[] = [
  { value: 'claude', label: 'claude' },
  { value: 'codex', label: 'codex' },
  { value: 'cursor', label: 'cursor · not incident-capable', disabled: true },
]
const asyncNoop = async () => undefined
const toastHandle: DeckUi.UndoToastHandle = { toast: noop, toastUndo: noop }
const undoRef = createRef<DeckUi.UndoToastHandle>()
const icon = (
  <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
    <path d="M5 12h14" />
  </svg>
)
const mapNode: DeckUi.MapNodeModel = {
  id: 'fixture-host',
  title: 'Fixture host',
  subtitle: 'Static gallery data',
  pulse: 'busy',
  chips: [{ label: '2 jobs' }],
  x: 8,
  y: 12,
  inspectorKvs: [{ label: 'Source', value: 'fixture' }],
  actions: [],
}

const GALLERY_NOW_MS = Date.parse('2026-08-04T03:00:00.000Z')

const galleryAttemptFixtures: AttemptRecord[] = [
  {
    attemptId: 'gallery-attempt-done',
    task: 't1',
    phase: 'coder',
    seat: 'coder',
    model: 'gpt-test',
    wrapper: '/tmp/agent.sh',
    timeoutSecs: 120,
    promptSha: 'a'.repeat(64),
    causalInput: 't1:initial',
    valid: true,
    failureClass: 'gate-failed',
    replyPath: '/run/attempts/gallery-attempt-done.reply.json',
    usage: { inputTokens: 11, outputTokens: 7, model: 'gpt-test' },
    liveness: null,
    activity: {
      toolCalls: 6,
      filesTouched: ['src/app.js'],
      repeatedCommands: [['bash', 'npm test']],
      failureFingerprint: 'coder:coder:gpt-test',
    },
  },
  {
    attemptId: 'gallery-attempt-stalled',
    task: 't1',
    phase: 'coder',
    seat: 'coder',
    model: 'gpt-alt',
    wrapper: '/tmp/agent.sh',
    timeoutSecs: 60,
    causalInput: 'gate-error:retry',
    usage: { unknown: true, model: 'gpt-alt' },
    liveness: {
      elapsedSecs: 200,
      lastActivity: 'tool_call:bash',
      lastSignalAt: '2026-08-04T02:50:00.000Z',
    },
    activity: null,
  },
  {
    attemptId: 'gallery-attempt-repeat-a',
    task: 't1',
    phase: 'coder',
    seat: 'coder',
    model: 'gpt-review',
    wrapper: '/tmp/agent.sh',
    timeoutSecs: 120,
    valid: false,
    verdict: 'FAIL',
    causalInput: 'same-base:retry',
    failureClass: 'gate-failed',
    usage: { unknown: true, model: 'gpt-review' },
    liveness: null,
    activity: { failureFingerprint: 'gate:compile:model-x' },
  },
  {
    attemptId: 'gallery-attempt-repeat-b',
    task: 't1',
    phase: 'coder',
    seat: 'coder',
    model: 'gpt-review',
    wrapper: '/tmp/agent.sh',
    timeoutSecs: 120,
    valid: false,
    verdict: 'FAIL',
    causalInput: 'review-findings:retry',
    usage: { inputTokens: 4, outputTokens: 2, model: 'gpt-review' },
    liveness: null,
    activity: { failureFingerprint: 'gate:compile:model-x' },
  },
]

function entry(
  name: string,
  domain: GalleryDomain,
  component: ComponentType<any>,
  render: () => ReactNode,
): GalleryEntry {
  return { name, domain, component, render }
}

function SectionCardGallery() {
  const [collapsedOpen, setCollapsedOpen] = useState(false)
  const [expandedOpen, setExpandedOpen] = useState(true)
  return (
    <div className="space-y-4">
      <DeckUi.SectionCard title="Fixture section">Static fixture content; missing timestamp —.</DeckUi.SectionCard>
      <DeckUi.SectionCard
        title="Fixture section (starts collapsed)"
        collapsible={{ expanded: collapsedOpen, onToggle: () => setCollapsedOpen(!collapsedOpen) }}
      >
        <p className="text-fg-subtle">Body revealed by the disclosure; hidden while collapsed.</p>
      </DeckUi.SectionCard>
      <DeckUi.SectionCard
        title="Fixture section (starts expanded, with a deliberately long title that must truncate)"
        titleBadge={<DeckUi.StatusChip status="unknown" />}
        collapsible={{ expanded: expandedOpen, onToggle: () => setExpandedOpen(!expandedOpen) }}
      >
        <p className="text-fg-subtle">Body revealed by the disclosure; hidden while collapsed.</p>
      </DeckUi.SectionCard>
    </div>
  )
}

export const GALLERY_REGISTRY: GalleryEntry[] = [
  entry('AbandonedPlansTable', 'tables', DeckUi.AbandonedPlansTable, () => <div className="space-y-4"><DeckUi.AbandonedPlansTable items={[abandonedPlanFixture]} onRestore={noop} /><DeckUi.AbandonedPlansTable items={[]} onRestore={noop} /></div>),
  entry('TimeSeriesChart', 'forensics', DeckUi.TimeSeriesChart, () => <div className="space-y-4"><DeckUi.TimeSeriesChart label="Active agents" status="available" coverageFrom="2026-08-13T00:00:00.000Z" points={[{ ts: '2026-08-13T00:00:00.000Z', value: 1 }, { ts: '2026-08-13T00:15:00.000Z', value: 3 }, { ts: '2026-08-13T00:30:00.000Z', value: 2 }]} gaps={[{ reason: 'Fixture source gap' }]} valueLabel="agents" /><DeckUi.TimeSeriesChart label="Builds" status="available" points={[]} valueLabel="builds" /><DeckUi.TimeSeriesChart label="Commits" status="unavailable" points={[]} reason="Fixture source has no authoritative commit capability" /></div>),
  entry('AmplificationSpark', 'forensics', DeckUi.AmplificationSpark, () => <div className="space-y-4"><DeckUi.AmplificationSpark repo="alexcodeplace/multideal" gates={CI_AMPLIFICATION_GATES} historyComplete warmedAt="2026-07-19T12:00:00.000Z" /><DeckUi.AmplificationSpark repo="alexcodeplace/overdeck" gates={[]} historyComplete warmedAt="2026-07-19T12:00:00.000Z" /><DeckUi.AmplificationSpark {...CI_AMPLIFICATION_RESTART} /></div>),
  entry('ActionsMenu', 'overlays', DeckUi.ActionsMenu, () => <DeckUi.ActionsMenu items={[{ label: 'Inspect fixture', onSelect: noop }]} />),
  entry('AgentComposer', 'inputs', DeckUi.AgentComposer, () => <DeckUi.AgentComposer onSend={asyncNoop} />),
  entry('AgentFeed', 'agent', DeckUi.AgentFeed, () => <DeckUi.AgentFeed turns={agentTurnsFixture} live rawLogAvailable={false} />),
  entry('AgentMetaSidebar', 'agent', DeckUi.AgentMetaSidebar, () => (
    <div className="grid gap-4">
      <DeckUi.AgentMetaSidebar seat="coder" model="fixture-model" attempt={1} branch="fixture/gallery" taskId="t1" taskHref="#" account="zync" />
      <DeckUi.AgentMetaSidebar seat="coder" model="fixture-model" attempt={1} branch="fixture/gallery" taskId="t1" taskHref="#" account={null} />
    </div>
  )),
  entry('AgentModeToggle', 'inputs', DeckUi.AgentModeToggle, () => <DeckUi.AgentModeToggle mode="live" liveAvailable onModeChange={noop} />),
  entry('AgentStatusBar', 'agent', DeckUi.AgentStatusBar, () => <DeckUi.AgentStatusBar agent={liveAgentIdentityFixture} onRestart={noop} toastHandle={toastHandle} killPauseAvailable={false} />),
  entry('AttentionPanel', 'agent', DeckUi.AttentionPanel, () => <div className="space-y-4"><DeckUi.AttentionPanel items={ATTENTION_ITEMS} /><DeckUi.AttentionPanel items={[]} /></div>),
  entry('AttentionRow', 'agent', DeckUi.AttentionRow, () => <div role="list"><DeckUi.AttentionRow item={ATTENTION_ITEMS[0]!} /></div>),
  entry('AttemptDetailDrawer', 'overlays', AttemptDetailDrawer, () => (
    <AttemptDetailDrawer
      attempt={galleryAttemptFixtures[0]}
      open={false}
      onClose={noop}
      promptHref="/plans/gallery/attempts/gallery-attempt-done/prompt"
      replyHref="/plans/gallery/attempts/gallery-attempt-done/reply"
    />
  )),
  entry('AttemptTimeline', 'forensics', AttemptTimeline, () => (
    <AttemptTimeline attempts={galleryAttemptFixtures} nowMs={GALLERY_NOW_MS} selectedAttemptId="gallery-attempt-stalled" />
  )),
  entry('AutopsyStrip', 'forensics', AutopsyStrip, () => <AutopsyStrip attempts={galleryAttemptFixtures} runStatus="failed" nowMs={GALLERY_NOW_MS} />),
  entry('BurnPanel', 'forensics', BurnPanel, () => <BurnPanel attempts={galleryAttemptFixtures} budget={4} />),
  entry('Button', 'inputs', DeckUi.Button, () => (
    <div className="flex flex-wrap gap-3">
      <DeckUi.Button>Solid accent</DeckUi.Button>
      <DeckUi.Button tone="danger">Solid danger</DeckUi.Button>
      <DeckUi.Button tone="neutral">Solid neutral</DeckUi.Button>
      <DeckUi.Button variant="outline">Outline accent</DeckUi.Button>
      <DeckUi.Button variant="outline" tone="danger">Outline danger</DeckUi.Button>
      <DeckUi.Button variant="outline" tone="neutral">Outline neutral</DeckUi.Button>
      <DeckUi.Button variant="ghost">Ghost accent</DeckUi.Button>
      <DeckUi.Button variant="ghost" tone="danger">Ghost danger</DeckUi.Button>
      <DeckUi.Button variant="ghost" tone="neutral">Ghost neutral</DeckUi.Button>
      <DeckUi.Button size="sm">Small</DeckUi.Button>
      <DeckUi.Button disabled>Disabled</DeckUi.Button>
    </div>
  )),
  entry('BotTable', 'tables', DeckUi.BotTable, () => (
    <div className="space-y-4">
      <DeckUi.BotTable bots={BOT_ROWS} />
      <DeckUi.BotTable bots={BOT_ROWS.map((bot) => ({ ...bot, messagesTotal: 1200 }))} density="full" />
      <DeckUi.BotTable bots={[]} />
    </div>
  )),
  entry('ClusterQueue', 'offload', DeckUi.ClusterQueue, () => <div className="space-y-4"><DeckUi.ClusterQueue queue={CLUSTER_QUEUE_FIXTURE} /><DeckUi.ClusterQueue queue={{ ...CLUSTER_QUEUE_FIXTURE, depth: 0, oldestAgeSeconds: 0, p95AgeSeconds: 0, tickets: [] }} /></div>),
  entry('Checkbox', 'inputs', DeckUi.Checkbox, () => (
    <div className="space-y-3">
      <DeckUi.Checkbox label="Unsafe" checked={false} onCheckedChange={noop} hint="Fixture: unchecked default; the CLI runs in its registered safe mode." />
      <DeckUi.Checkbox label="Unsafe" checked onCheckedChange={noop} hint="Fixture: checked authorises the CLI's registered bypass mode for this attempt." />
      <DeckUi.Checkbox label="Unsafe" checked={false} onCheckedChange={noop} error="Fixture: this CLI declares no safe mode." />
      <DeckUi.Checkbox label="Unsafe (disabled fixture)" checked={false} onCheckedChange={noop} disabled />
    </div>
  )),
  entry('CriterionRow', 'chips', DeckUi.CriterionRow,() => <DeckUi.CriterionRow id="AC-00" text="Fixture criterion with a deliberately long title for wrapping coverage" verdict="unverified" evidence={null} reachedAt={null} />),
  entry('DataCoveragePanel', 'overlays', DeckUi.DataCoveragePanel, () => <div className="flex flex-wrap gap-3"><DeckUi.DataCoveragePanel gaps={[{ id: 'A10', label: 'Fixture watchdog gap', specRef: '#coverage' }]} /><DeckUi.DataCoveragePanel gaps={[]} /></div>),
  entry('DecisionDialog', 'overlays', DeckUi.DecisionDialog, () => <DeckUi.DecisionDialog detail={null} open={false} onClose={noop} onDecide={noop} toastHandle={toastHandle} />),
  entry('DetailDrawer', 'overlays', DeckUi.DetailDrawer, () => (
    <>
      <DeckUi.DetailDrawer eyebrow="Fixture detail" title="t1 · attempt-a" titleId="gallery-detail-drawer-title" onClose={noop}>
        <p className="mt-5 text-sm text-fg-muted">Fixture drawer body slot.</p>
      </DeckUi.DetailDrawer>
      {/* translate-x-0 makes this box the containing block, so the movable variant previews
          inside the gallery cell instead of covering the modal variant beside it. */}
      <div className="relative h-72 w-full translate-x-0 overflow-hidden rounded-md border border-border">
        <DeckUi.DetailDrawer draggable modal={false} size="wide" eyebrow="Fixture terminal" title="fixture session" titleId="gallery-draggable-detail-drawer-title" onClose={noop}>
          <p className="mt-5 text-sm text-fg-muted">Fixture draggable drawer body slot.</p>
        </DeckUi.DetailDrawer>
      </div>
    </>
  )),
  entry('DecisionRow', 'inputs', DeckUi.DecisionRow, () => <DeckUi.DecisionRow itemId="fixture-decision" projectName="fixture" projectColor="var(--mod-color-accent)" title="Choose fixture behavior?" meta="static gallery data" waitingAgeLabel="waiting —" options={[{ label: 'Proceed', choice: 'proceed', recommended: true }]} />),
  entry('DeckTooltipLayer', 'overlays', DeckUi.DeckTooltipLayer, () => <><DeckUi.IconButton icon={icon} label="Tooltip fixture" onClick={noop} tooltip="Fixture tooltip" /><DeckUi.DeckTooltipLayer /></>),
  entry('DistanceToDone', 'forensics', DeckUi.DistanceToDone, () => (
    <div className="space-y-4">
      <DeckUi.DistanceToDone landed={2} total={RUN_TASK_CELLS.length} cells={RUN_TASK_CELLS} etaMs={null} fixLoop={null} truthNote="Fixture trajectory; missing measurements remain explicit." />
      <DeckUi.DistanceToDone landed={1} total={RUN_TASK_CELLS_ALARMED.length} cells={RUN_TASK_CELLS_ALARMED} etaMs={null} fixLoop={null} truthNote="Fixture with a stalled active task cell." />
    </div>
  )),
  entry('FilterInput', 'inputs', DeckUi.FilterInput, () => <div className="space-y-3"><DeckUi.FilterInput label="Populated filter" value="press" onChange={noop} /><DeckUi.FilterInput label="Empty filter" value="" onChange={noop} placeholder="Title, slug, project, or topic" /></div>),
  entry('IconButton', 'inputs', DeckUi.IconButton, () => <div className="flex items-center gap-2"><DeckUi.IconButton icon={icon} label="Fixture icon action" onClick={noop} /><DeckUi.IconButton icon={icon} label="Fixture danger action" tone="danger" onClick={noop} /><DeckUi.IconButton icon={icon} label="Fixture drag handle" tooltip="Drag, or move with the arrow keys" dragHandle={{}} /></div>),
  entry('IdleTimer', 'agent', DeckUi.IdleTimer, () => <DeckUi.IdleTimer idle={null} />),
  entry('InboxItem', 'layout', DeckUi.InboxItem, () => <DeckUi.InboxItem {...INBOX_FIXTURES[0]!} />),
  entry('KpiTile', 'forensics', DeckUi.KpiTile, () => <div className="grid grid-cols-2 gap-3"><DeckUi.KpiTile tile={OPT_DATA_INTEGRITY_TILES[0]!} /><DeckUi.KpiTile tile={{ key: 'fixtureZero', label: 'fixture zero', value: 0 }} /></div>),
  entry('KvPanel', 'layout', DeckUi.KvPanel, () => <DeckUi.KvPanel rows={KV_CI_RUNNERS} />),
  entry('LayerLadderEditor', 'inputs', DeckUi.LayerLadderEditor, () => <DeckUi.LayerLadderEditor item={RUN_SETTINGS[0]!} onSave={noop} />),
  entry('LinkButton', 'inputs', DeckUi.LinkButton, () => (
    <div className="flex flex-wrap gap-3">
      <DeckUi.LinkButton href="#">Fixture link</DeckUi.LinkButton>
      <DeckUi.LinkButton onClick={noop}>Fixture button</DeckUi.LinkButton>
      <DeckUi.LinkButton onClick={noop} disabled>
        Disabled fixture
      </DeckUi.LinkButton>
    </div>
  )),
  entry('LaneBar', 'forensics', DeckUi.LaneBar, () => <DeckUi.LaneBar jobs={CI_TRAIN.gateRun!.jobs} jobsComplete />),
  entry('LaneSegment', 'forensics', DeckUi.LaneSegment, () => <DeckUi.LaneSegment job={CI_TRAIN.gateRun!.jobs[0]!} jobsComplete />),
  entry('LimitMeter', 'chips', DeckUi.LimitMeter, () => <div>{LIMIT_ACCOUNTS.map((account) => <DeckUi.LimitMeter key={account.slug} account={account} />)}</div>),
  entry('LiveDuration', 'forensics', DeckUi.LiveDuration, () => (
    <div className="flex flex-col gap-1 tabular-nums text-fg">
      <DeckUi.LiveDuration startAtMs={null} />
      <DeckUi.LiveDuration startAtMs={Date.now() - 45_000} />
      <DeckUi.LiveDuration startAtMs={Date.now() - 5_400_000} tooltipLabel="Session started" />
      <DeckUi.LiveDuration startAtMs={null} missingNote="No lastActiveAt recorded for this session" refreshMs={1_000} />
    </div>
  )),
  entry('MachineCard', 'offload', DeckUi.MachineCard, () => (
    <div className="grid gap-3 lg:grid-cols-2">
      <DeckUi.MachineCard machine={FLEET_DEBIAN1} actions={[]} statusPill="fixture" />
      <DeckUi.MachineCard machine={FLEET_DEBIAN2_JOINING} actions={[]} statusPill="joining" />
      <DeckUi.MachineCard machine={FLEET_CONFIG_DRIFTED} actions={[]} statusPill="config drift" statusPillIntent="warn" warn />
      <DeckUi.MachineCard machine={FLEET_CONFIG_UNREACHABLE} actions={[]} statusPill="fixture" />
      <DeckUi.MachineCard machine={FLEET_PROBE_FAILING} actions={[]} statusPill="probe failing" statusPillIntent="warn" />
      <DeckUi.MachineCard
        machine={{ ...FLEET_DEBIAN1, remoteWork: null }}
        actions={[]}
        statusPill="work count unobserved"
      />
      <DeckUi.MachineCard
        machine={{ ...FLEET_DEBIAN1, sessions: null, builds24h: null }}
        actions={[]}
        statusPill="partial sources"
      />
      <DeckUi.MachineCard
        machine={{
          ...FLEET_DEBIAN1,
          sessions: 0,
          builds24h: 0,
          remoteWork: { agentSeats: 0, remoteBuildJobs: 0, offloadShells: 0 },
        }}
        actions={[]}
        statusPill="measured zero"
      />
    </div>
  )),
  entry('HostLogsModal', 'overlays', DeckUi.HostLogsModal, () => (
    <div className="space-y-4">
      <DeckUi.HostLogsModal
        open
        host="debian1"
        lines={['2026-07-21T10:00:00Z builder ready', '2026-07-21T10:01:00Z dispatch ok']}
        loading={false}
        error={null}
        onClose={noop}
        onRefresh={noop}
      />
      <DeckUi.HostLogsModal
        open
        host="debian1"
        lines={[]}
        loading
        error={null}
        onClose={noop}
        onRefresh={noop}
      />
      <DeckUi.HostLogsModal
        open
        host="debian1"
        lines={[]}
        loading={false}
        error="collector unreachable"
        onClose={noop}
        onRefresh={noop}
      />
      <DeckUi.HostLogsModal
        open
        host="debian1"
        lines={[]}
        loading={false}
        error={null}
        onClose={noop}
        onRefresh={noop}
      />
    </div>
  )),
  entry('MachineDetailModal', 'overlays', DeckUi.MachineDetailModal, () => (
    <div className="space-y-4">
      <DeckUi.MachineDetailModal
        machine={FLEET_DEBIAN1}
        open
        actions={[
          { label: 'Drain', verb: 'box-drain', danger: true },
          { label: 'Reconcile dispatch', verb: 'admission-reconcile', primary: true },
        ]}
        onClose={noop}
        onAction={noop}
        pendingVerb={null}
        actionError={null}
      />
      <DeckUi.MachineDetailModal
        machine={FLEET_DEBIAN1}
        open
        actions={[{ label: 'Drain', verb: 'box-drain', danger: true }]}
        onClose={noop}
        onAction={noop}
        pendingVerb="box-drain"
        actionError={null}
      />
      <DeckUi.MachineDetailModal
        machine={FLEET_DEBIAN1}
        open
        actions={[{ label: 'Drain', verb: 'box-drain', danger: true }]}
        onClose={noop}
        onAction={noop}
        pendingVerb={null}
        actionError={{ verb: 'box-drain', message: '409 stale revision' }}
      />
    </div>
  )),
  entry('MachineSummaryPopover', 'overlays', DeckUi.MachineSummaryPopover, () => <DeckUi.MachineSummaryPopover machine={FLEET_DEBIAN1} x={0} y={0} visible={false} />),
  entry('MapCanvas', 'offload', DeckUi.MapCanvas, () => <DeckUi.MapCanvas nodes={[mapNode]} edges={[]} selectedNodeId={mapNode.id} onSelectNode={noop} />),
  entry('MapNode', 'offload', DeckUi.MapNode, () => <div className="relative h-48"><DeckUi.MapNode node={mapNode} selected onSelect={noop} /></div>),
  entry('OffloadControl', 'offload', DeckUi.OffloadControl, () => (
    <div className="space-y-4">
      <DeckUi.OffloadControl
        control={OFFLOAD_CONTROL_FIXTURE}
        selectedHost={FLEET_DEBIAN1}
        onAction={noop}
        pendingVerb={null}
        actionError={null}
      />
      <DeckUi.OffloadControl
        control={OFFLOAD_CONTROL_FIXTURE}
        selectedHost={null}
        onAction={noop}
        pendingVerb={null}
        actionError={null}
      />
      <DeckUi.OffloadControl
        control={OFFLOAD_CONTROL_FIXTURE}
        selectedHost={FLEET_DEBIAN1}
        onAction={noop}
        pendingVerb="box-drain"
        actionError={null}
      />
      <DeckUi.OffloadControl
        control={OFFLOAD_CONTROL_FIXTURE}
        selectedHost={FLEET_DEBIAN1}
        onAction={noop}
        pendingVerb={null}
        actionError={{ verb: 'host-quarantine', message: 'controller refused' }}
      />
    </div>
  )),
  entry('PhaseBars', 'forensics', DeckUi.PhaseBars, () => <DeckUi.PhaseBars attribution={OPT_DATA_INTEGRITY_ATTRIBUTION} />),
  entry('PlanRunListRow', 'tables', DeckUi.PlanRunListRow, () => <DeckUi.PlanRunListRow {...planRunListRowFixture} selected={false} onSelect={noop} />),
  entry('PlanTable', 'tables', DeckUi.PlanTable, () => <div className="space-y-4"><DeckUi.PlanTable items={planTableItemsFixture} selectedRunId={null} onOpen={noop} onAbandon={noop} onResolve={noop} /><DeckUi.PlanTable items={[]} selectedRunId={null} onOpen={noop} onAbandon={noop} onResolve={noop} /></div>),
  entry('PlanTableRow', 'tables', DeckUi.PlanTableRow, () => (
    <div className="space-y-4">
      <DeckUi.PlanTableRow item={planTableItemsFixture[0]!} selected={false} onOpen={noop} onAbandon={noop} onResolve={noop} />
      <DeckUi.PlanTableRow item={planTableItemStalledFixture} selected={false} onOpen={noop} onAbandon={noop} onResolve={noop} />
    </div>
  )),
  entry('PrQueueTable', 'tables', DeckUi.PrQueueTable, () => <div className="space-y-4"><DeckUi.PrQueueTable prs={CI_PR_QUEUE} repos={CI_PR_QUEUE_REPOS} allScope /><DeckUi.PrQueueTable prs={[]} repos={CI_PR_QUEUE_REPOS} allScope /></div>),
  entry('ProjectGroupRow', 'tables', DeckUi.ProjectGroupRow, () => <DeckUi.ProjectGroupRow group={projectGroupFixture} expanded={false} onToggle={noop} />),
  entry('RateLimitDialog', 'overlays', DeckUi.RateLimitDialog, () => <DeckUi.RateLimitDialog limit={LIMITED_CODEX} wrapper="codex" accounts={CAPACITY_ACCOUNTS} open={false} onClose={noop} onResolve={noop} />),
  entry('RemoteJobsTable', 'offload', DeckUi.RemoteJobsTable, () => <div className="space-y-4"><DeckUi.RemoteJobsTable jobs={REMOTE_JOBS_FIXTURE} hostLabel="fixture-host" /><DeckUi.RemoteJobsTable jobs={[]} hostLabel="fixture-empty" /></div>),
  entry('RepoCiStrip', 'layout', DeckUi.RepoCiStrip, () => <div className="space-y-4"><DeckUi.RepoCiStrip repos={CI_REPO_SUMMARIES} selectedRepo={null} onScope={noop} /><DeckUi.RepoCiStrip repos={[]} selectedRepo={null} onScope={noop} /></div>),
  entry('CiCoverageBanner', 'overlays', DeckUi.CiCoverageBanner, () => (
    <DeckUi.CiCoverageBanner
      gaps={DeckUi.resolveCiRepoGaps(CI_REPO_DEFERRED_SUMMARY)}
      repoPrefix="platform-modules/mod"
    />
  )),
  entry('RepoCiTile', 'layout', DeckUi.RepoCiTile, () => <div className="flex flex-wrap gap-3"><DeckUi.RepoCiTile summary={CI_REPO_SUMMARY} selected onScope={noop} /><DeckUi.RepoCiTile summary={CI_REPO_GAP_SUMMARY} selected={false} onScope={noop} /><DeckUi.RepoCiTile summary={CI_REPO_DEFERRED_SUMMARY} selected={false} onScope={noop} /></div>),
  entry('RunCommandBar', 'agent', DeckUi.RunCommandBar, () => <DeckUi.RunCommandBar title="Fixture run" status="running" state="executing" updatedAt={null} capacity={<DeckUi.StatusChip status="healthy" />} coverage={<DeckUi.DataCoveragePanel gaps={[]} />} />),
  entry('RunLanes', 'forensics', DeckUi.RunLanes, () => <div className="space-y-4"><DeckUi.RunLanes runs={OPT_DATA_INTEGRITY_RUNS} segments={OPT_DATA_INTEGRITY_SEGMENTS} /><DeckUi.RunLanes runs={[]} segments={[]} /></div>),
  entry('RunTable', 'tables', DeckUi.RunTable, () => <DeckUi.RunTable runs={OPT_DATA_INTEGRITY_RUNS} />),
  entry('RunnerFleetStrip', 'layout', DeckUi.RunnerFleetStrip, () => <div className="space-y-4"><DeckUi.RunnerFleetStrip runners={CI_RUNNERS} runnersComplete oldestQueuedAgeH={0.1} /><DeckUi.RunnerFleetStrip runners={CI_RUNNERS_ALL_BUSY} runnersComplete oldestQueuedAgeH={0.5} /><DeckUi.RunnerFleetStrip runners={CI_RUNNERS_ALL_OFFLINE} runnersComplete oldestQueuedAgeH={2} /><DeckUi.RunnerFleetStrip runners={CI_RUNNERS} runnersComplete={false} oldestQueuedAgeH={1} /><DeckUi.RunnerFleetStrip runners={[]} runnersComplete oldestQueuedAgeH={null} /></div>),
  entry('ScoreCard', 'layout', DeckUi.ScoreCard, () => <DeckUi.ScoreCard {...SCORE_MULTIDEAL} />),
  entry('Select', 'inputs', DeckUi.Select, () => (
    <div className="space-y-3">
      <DeckUi.Select label="CLI" value="claude" options={SELECT_FIXTURE_OPTIONS} onValueChange={noop} />
      <DeckUi.Select label="CLI (nothing chosen)" value="" options={SELECT_FIXTURE_OPTIONS} onValueChange={noop} placeholder="Select a CLI" hint="Fixture: options come from the deployed capability manifest." />
      <DeckUi.Select label="CLI (invalid)" value="" options={SELECT_FIXTURE_OPTIONS} onValueChange={noop} placeholder="Select a CLI" error="Fixture: choose a CLI." />
      <DeckUi.Select label="CLI (inline label)" labelMode="inline" value="claude" options={SELECT_FIXTURE_OPTIONS} onValueChange={noop} />
      <DeckUi.Select label="CLI (no options registered)" value="" options={[]} onValueChange={noop} placeholder="No incident-capable CLI is registered" disabled />
    </div>
  )),
  entry('SectionCard', 'layout', DeckUi.SectionCard,() => <SectionCardGallery />),
  entry('SectionHeading', 'layout', DeckUi.SectionHeading, () => <DeckUi.SectionHeading title="Fixture heading with a deliberately long title" subtitle="· static data" titleBadge={<DeckUi.StatusChip status="unknown" />} />),
  entry('SegmentDetailDrawer', 'overlays', DeckUi.SegmentDetailDrawer, () => <DeckUi.SegmentDetailDrawer lane={REAL_TRACE_LANES[0]!} segmentIndex={0} open={false} onClose={noop} />),
  entry('SettingRow', 'tables', DeckUi.SettingRow, () => <DeckUi.SettingsTable items={[RUN_SETTINGS[0]!]} onSave={noop} />),
  entry('SettingsTable', 'tables', DeckUi.SettingsTable, () => <div className="space-y-4"><DeckUi.SettingsTable items={RUN_SETTINGS} onSave={noop} /><DeckUi.SettingsTable items={null} onSave={noop} /></div>),
  entry('StaleBadge', 'chips', DeckUi.StaleBadge, () => <DeckUi.StaleBadge status={STALE_HARNESS_STATUS} now={STALE_HARNESS_STATUS.lastSuccess! + 120_000} />),
  entry('StatusChip', 'chips', DeckUi.StatusChip, () => <div className="flex flex-wrap gap-2">{['healthy', 'success', 'pass', 'stale', 'error', 'fail', 'running', 'queued', 'degraded', 'incomplete', 'killed', 'unknown', 'ok', 'absent', 'warn', 'notice', 'info', 'debug'].map((status) => <DeckUi.StatusChip key={status} status={status} />)}</div>),
  entry('SwimlaneTrace', 'forensics', DeckUi.SwimlaneTrace, () => (
    <div className="space-y-6">
      <div>
        <p className="mb-2 text-xs font-semibold text-fg-subtle">Fixture: short span (~45s)</p>
        <DeckUi.SwimlaneTrace
          lanes={GALLERY_TRACE_SHORT_SPAN_LANES}
          nowMs={GALLERY_TRACE_SHORT_SPAN_START_MS + 22_500}
          bands={[]}
          zoom="fit"
          onZoom={noop}
          onSegmentClick={noop}
        />
      </div>
      <div>
        <p className="mb-2 text-xs font-semibold text-fg-subtle">Fixture: medium span (run trace)</p>
        <DeckUi.SwimlaneTrace
          lanes={REAL_TRACE_LANES}
          nowMs={TRACE_START_MS + 60_000}
          bands={REAL_TRACE_BANDS}
          zoom="fit"
          onZoom={noop}
          onSegmentClick={noop}
        />
      </div>
      <div>
        <p className="mb-2 text-xs font-semibold text-fg-subtle">Fixture: multi-day span</p>
        <DeckUi.SwimlaneTrace
          lanes={GALLERY_TRACE_MULTI_DAY_LANES}
          nowMs={null}
          bands={[]}
          zoom="fit"
          onZoom={noop}
          onSegmentClick={noop}
        />
      </div>
      <div>
        <p className="mb-2 text-xs font-semibold text-fg-subtle">Fixture: last hour (running)</p>
        <DeckUi.SwimlaneTrace
          lanes={REAL_TRACE_LANES}
          nowMs={GALLERY_TRACE_RUNNING_NOW_MS}
          bands={[]}
          zoom="hour"
          onZoom={noop}
          onSegmentClick={noop}
        />
      </div>
      <div>
        <p className="mb-2 text-xs font-semibold text-fg-subtle">Fixture: follow live (running)</p>
        <DeckUi.SwimlaneTrace
          lanes={REAL_TRACE_LANES}
          nowMs={GALLERY_TRACE_RUNNING_NOW_MS}
          bands={[]}
          zoom="live"
          onZoom={noop}
          onSegmentClick={noop}
        />
      </div>
      <div>
        <p className="mb-2 text-xs font-semibold text-fg-subtle">Fixture: no temporal data</p>
        <DeckUi.SwimlaneTrace
          lanes={GALLERY_TRACE_NO_TEMPORAL_LANES}
          nowMs={null}
          bands={[]}
          zoom="fit"
          onZoom={noop}
          onSegmentClick={noop}
        />
      </div>
    </div>
  )),
  entry('TextArea', 'inputs', DeckUi.TextArea, () => (
    <div className="space-y-3">
      <DeckUi.TextArea label="Description" value="" onValueChange={noop} placeholder="What happened, and what should the agent do?" hint="Fixture: 1–20,000 characters." />
      <DeckUi.TextArea label="Description" value={'Collector stopped emitting the incidents panel after the 03:14 restart.\nLast good snapshot is 40 minutes old.'} onValueChange={noop} />
      <DeckUi.TextArea label="Description (invalid)" value="" onValueChange={noop} error="Fixture: description is required." />
      <DeckUi.TextArea label="Message to agent (hidden label fixture)" labelMode="hidden" value="" onValueChange={noop} placeholder="Add a useful correction or priority…" />
      <DeckUi.TextArea label="Description (disabled fixture)" value="Submitted; input is held while filing." onValueChange={noop} disabled />
    </div>
  )),
  entry('TextField', 'inputs', DeckUi.TextField, () => (
    <div className="space-y-3">
      <DeckUi.TextField label="Title" value="" onValueChange={noop} placeholder="One line naming the failure" hint="Fixture: 1–160 characters." />
      <DeckUi.TextField label="Title" value="Collector incidents panel stopped updating after restart" onValueChange={noop} />
      <DeckUi.TextField label="Title (invalid)" value="" onValueChange={noop} error="Fixture: title is required." />
      <DeckUi.TextField label="Inline label fixture" labelMode="inline" value="press" onValueChange={noop} />
      <DeckUi.TextField label="Hidden label fixture" labelMode="hidden" value="" onValueChange={noop} placeholder="Label is screen-reader only" />
      <DeckUi.TextField label="Title (disabled fixture)" value="Held while filing" onValueChange={noop} disabled />
    </div>
  )),
  entry('TerminalView', 'agent', DeckUi.TerminalView, () => (
    <div className="space-y-4">
      <DeckUi.TerminalView screen={TERMINAL_SCREEN_FIXTURE} state="attached" label="fixture session" onSend={noop} capturedNote="captured 2s ago" rows={9} />
      <DeckUi.TerminalView screen={TERMINAL_SCREEN_FIXTURE} state="attached" label="fixture busy session" onSend={noop} busy rows={5} />
      <DeckUi.TerminalView screen={null} state="connecting" label="fixture connecting session" rows={4} />
      <DeckUi.TerminalView screen={null} state="unavailable" reason="tmux is not installed on this host" label="fixture unavailable session" rows={4} />
      <DeckUi.TerminalView screen={TERMINAL_SCREEN_FIXTURE} state="ended" reason="Session ended." label="fixture ended session" rows={5} />
    </div>
  )),
  entry('TraceSegment', 'forensics', DeckUi.TraceSegment, () => <div className="relative h-10"><DeckUi.TraceSegment laneId={REAL_TRACE_LANES[0]!.taskId} segmentIndex={0} segment={REAL_TRACE_LANES[0]!.segments[0]!} leftPercent={5} widthPercent={40} startOffsetMs={0} onClick={noop} /></div>),
  entry('TrainCard', 'layout', DeckUi.TrainCard, () => <DeckUi.TrainCard train={CI_TRAIN} onAction={noop} onOpen={noop} />),
  entry('TrainRail', 'layout', DeckUi.TrainRail, () => <div className="space-y-4"><DeckUi.TrainRail trains={[CI_TRAIN]} repos={CI_TRAIN_REPO_COMPLETENESS} onAction={noop} onOpen={noop} /><DeckUi.TrainRail trains={[]} repos={CI_TRAIN_REPO_COMPLETENESS} onAction={noop} onOpen={noop} /></div>),
  entry('TurnCard', 'agent', DeckUi.TurnCard, () => <DeckUi.TurnCard turn={agentTurnsFixture[0]!} />),
  entry('UndoToast', 'overlays', DeckUi.UndoToast, () => <DeckUi.UndoToast handleRef={undoRef} />),
  entry('VerdictBadge', 'chips', DeckUi.VerdictBadge, () => <div className="flex flex-wrap gap-2">{(['works', 'broken', 'missing', 'unverified'] as const).map((verdict) => <DeckUi.VerdictBadge key={verdict} verdict={verdict} />)}</div>),
  entry('WrapperCapacity', 'forensics', DeckUi.WrapperCapacity, () => <DeckUi.WrapperCapacity wrappers={['cursor', 'codex']} ratelimits={[LIMITED_CODEX]} dataAvailable onOpen={noop} />),
]
