/* ============================================================
   F2 UI — Data display stories
   ============================================================ */
(function () {
  const F2 = window.F2;
  const { Icon, Avatar, AvatarGroup, List, Timeline, Stat, Progress, Skeleton, EmptyState, CodeBlock, Accordion, DataTable, Badge, Button, StatusDot, IconButton } = F2;
  const G = 'Data display';

  const PEOPLE = [
    { name: 'Ana Ribeiro' }, { name: 'Bruno Costa' }, { name: 'Carla Dias' }, { name: 'Diego Melo' }, { name: 'Elena Souza' }, { name: 'Felipe Ramos' },
  ];

  /* ---------------- Avatar ---------------- */
  window.story({
    id: 'avatar', group: G, name: 'Avatar', status: 'new',
    tagline: 'A person or entity marker — image or initials fallback, optional status dot, with an overlapping AvatarGroup.',
    importLine: "const { Avatar, AvatarGroup } = F2;",
    keywords: ['avatar', 'user', 'initials', 'presence'],
    props: [
      { name: 'name', type: 'string', default: 'Ana Ribeiro', control: 'text', description: 'Used for initials fallback + alt text.' },
      { name: 'src', type: 'string', description: 'Image URL; falls back to initials if absent.' },
      { name: 'size', type: 'number', default: 44, control: 'number', min: 24, max: 72, step: 4, description: 'Diameter in px.' },
      { name: 'shape', type: "'circle' | 'rounded'", default: 'circle', control: 'select', options: ['circle', 'rounded'], description: 'Avatar shape.' },
      { name: 'status', type: "'active' | 'success' | 'warning' | 'error' | 'neutral'", default: 'success', control: 'select', options: ['none', 'active', 'success', 'warning', 'error'], description: 'Presence dot.' },
    ],
    render: (v) => <Avatar name={v.name} size={v.size} shape={v.shape} status={v.status === 'none' ? undefined : v.status} />,
    code: (v) => `<Avatar\n  name="${v.name}"\n  size={${v.size}}\n  shape="${v.shape}"${v.status !== 'none' ? `\n  status="${v.status}"` : ''}\n/>`,
    examples: [
      { name: 'initials', render: () => <Avatar name="Ana Ribeiro" size={44} /> },
      { name: 'rounded', render: () => <Avatar name="F2" shape="rounded" size={44} /> },
      { name: 'with status', render: () => <Avatar name="Bruno Costa" size={44} status="success" /> },
      { name: 'AvatarGroup', render: () => <AvatarGroup people={PEOPLE} size={38} max={4} /> },
    ],
    a11y: [
      'Image avatars carry <code>alt</code> from the name; initials fall back gracefully when no image is set.',
      'A status dot alone is not labelled — surface presence in adjacent text where it matters.',
    ],
  });

  /* ---------------- List ---------------- */
  window.story({
    id: 'list', group: G, name: 'List', status: 'new',
    tagline: 'A divided row list for settings, members, or resources — leading media, title/subtitle, meta and a trailing action.',
    importLine: "const { List } = F2;",
    keywords: ['list', 'rows', 'members', 'settings'],
    props: [
      { name: 'items', type: 'Array<{title,subtitle?,icon?,leading?,meta?,action?}>', description: 'Row definitions.' },
      { name: 'divided', type: 'boolean', default: true, control: 'boolean', description: 'Hairline dividers between rows.' },
    ],
    render: (v) => <List divided={v.divided} style={{ width: 460, maxWidth: '100%' }} items={[
      { leading: <Avatar name="Ana Ribeiro" size={36} status="success" />, title: 'Ana Ribeiro', subtitle: 'Owner · ana@f2.tech', action: <Badge tone="active">Admin</Badge> },
      { leading: <Avatar name="Bruno Costa" size={36} />, title: 'Bruno Costa', subtitle: 'bruno@f2.tech', meta: '2d ago' },
      { icon: 'KeyRound', title: 'API key', subtitle: 'sk_live_••••  4f9a', action: <IconButton variant="ghost" size="sm" aria-label="Copy"><Icon name="Copy" size={16} /></IconButton> },
    ]} />,
    code: () => `<List items={[\n  { leading: <Avatar name="Ana Ribeiro" status="success" />,\n    title: 'Ana Ribeiro', subtitle: 'Owner · ana@f2.tech',\n    action: <Badge tone="active">Admin</Badge> },\n  { icon: 'KeyRound', title: 'API key', subtitle: 'sk_live_•••• 4f9a',\n    action: <IconButton aria-label="Copy"><Icon name="Copy" /></IconButton> },\n]} />`,
    a11y: [
      'Renders a semantic <code>&lt;ul&gt;</code>/<code>&lt;li&gt;</code>; keep one primary action per row reachable by keyboard.',
      'When the whole row is clickable, make the title a link or button rather than a click handler on the <code>&lt;li&gt;</code>.',
    ],
  });

  /* ---------------- Timeline ---------------- */
  window.story({
    id: 'timeline', group: G, name: 'Timeline', status: 'new',
    tagline: 'A vertical activity feed — nodes light by tone (amber = the active/live event), with time and detail.',
    importLine: "const { Timeline } = F2;",
    keywords: ['timeline', 'activity', 'feed', 'history'],
    props: [
      { name: 'items', type: 'Array<{title,time?,description?,tone?,icon?}>', description: 'Events, newest first by convention.' },
    ],
    render: () => <Timeline style={{ width: 420, maxWidth: '100%' }} items={[
      { title: 'Agent deployed', time: 'now', tone: 'active', icon: 'Rocket', description: 'invoice-ocr v4 is live in production.' },
      { title: 'Dry run passed', time: '4m ago', tone: 'success', icon: 'Check', description: '142 records, 0 exceptions.' },
      { title: 'Prompt updated', time: '12m ago', icon: 'PenLine' },
      { title: 'Workflow created', time: '1h ago', icon: 'Plus' },
    ]} />,
    code: () => `<Timeline items={[\n  { title: 'Agent deployed', time: 'now', tone: 'active', icon: 'Rocket',\n    description: 'invoice-ocr v4 is live in production.' },\n  { title: 'Dry run passed', time: '4m ago', tone: 'success', icon: 'Check' },\n  { title: 'Prompt updated', time: '12m ago', icon: 'PenLine' },\n]} />`,
    a11y: [
      'Rendered as an ordered list so the sequence is conveyed to assistive tech.',
      'Tone nodes pair an icon with the title text — meaning never rests on color alone.',
    ],
  });

  /* ---------------- Stat ---------------- */
  window.story({
    id: 'stat', group: G, name: 'Stat', status: 'new',
    tagline: 'A single KPI — mono label, oversized display value, and a directional delta that colors itself.',
    importLine: "const { Stat } = F2;",
    keywords: ['stat', 'kpi', 'metric', 'number'],
    props: [
      { name: 'label', type: 'string', default: 'Processed today', control: 'text', description: 'Mono caption above the value.' },
      { name: 'value', type: 'ReactNode', default: '1,284', control: 'text', description: 'The headline figure.' },
      { name: 'delta', type: 'string', default: '+12.4%', control: 'text', description: 'Change indicator; leading "-" colors it down.' },
      { name: 'deltaTone', type: "'auto' | 'up' | 'down' | 'flat'", default: 'auto', control: 'select', options: ['auto', 'up', 'down', 'flat'], description: 'Override the delta direction/color.' },
      { name: 'icon', type: 'string', default: 'FileText', control: 'text', description: 'Optional Lucide icon by the label.' },
      { name: 'hint', type: 'string', description: 'Small note under the value.' },
    ],
    render: (v) => <Stat label={v.label} value={v.value} delta={v.delta} deltaTone={v.deltaTone} icon={v.icon} hint="vs. last 24h" />,
    code: (v) => `<Stat\n  label="${v.label}"\n  value="${v.value}"\n  delta="${v.delta}"\n  icon="${v.icon}"\n  hint="vs. last 24h"\n/>`,
    examples: [
      { name: 'up', render: () => <Stat label="Processed" value="1,284" delta="+12.4%" icon="FileText" /> },
      { name: 'down', render: () => <Stat label="Avg. latency" value="19s" delta="-31%" icon="Timer" /> },
      { name: 'flat', render: () => <Stat label="Active agents" value="7" delta="0" deltaTone="flat" icon="Bot" /> },
    ],
    a11y: [
      'The mono label names the metric; pair value + label in the DOM so screen readers read them together.',
      'Delta direction is shown with an arrow icon as well as color.',
    ],
  });

  /* ---------------- Progress ---------------- */
  function ProgDemo(v) {
    return <Progress value={v.value} tone={v.tone} size={v.size} showValue={v.showValue} indeterminate={v.indeterminate} style={{ width: 360 }} />;
  }
  window.story({
    id: 'progress', group: G, name: 'Progress', status: 'new',
    tagline: 'A linear progress bar with an amber fill, semantic tones, three sizes and an indeterminate mode.',
    importLine: "const { Progress } = F2;",
    keywords: ['progress', 'bar', 'loading', 'percentage'],
    props: [
      { name: 'value', type: 'number', default: 64, control: 'number', min: 0, max: 100, step: 1, description: 'Current value (0–max).' },
      { name: 'max', type: 'number', default: 100, description: 'Maximum value.' },
      { name: 'tone', type: "'accent' | 'success' | 'warning' | 'error'", default: 'accent', control: 'select', options: ['accent', 'success', 'warning', 'error'], description: 'Fill color.' },
      { name: 'size', type: "'sm' | 'md' | 'lg'", default: 'md', control: 'select', options: ['sm', 'md', 'lg'], description: 'Bar thickness.' },
      { name: 'showValue', type: 'boolean', default: true, control: 'boolean', description: 'Show a % readout.' },
      { name: 'indeterminate', type: 'boolean', default: false, control: 'boolean', description: 'Looping bar for unknown duration.' },
    ],
    render: (v) => <ProgDemo {...v} />,
    code: (v) => `<Progress\n  value={${v.value}}\n  tone="${v.tone}"\n  size="${v.size}"${v.showValue ? '\n  showValue' : ''}${v.indeterminate ? '\n  indeterminate' : ''}\n/>`,
    examples: [
      { name: 'accent', render: () => <Progress value={64} showValue style={{ width: 220 }} /> },
      { name: 'success', render: () => <Progress value={100} tone="success" showValue style={{ width: 220 }} /> },
      { name: 'warning', render: () => <Progress value={88} tone="warning" showValue style={{ width: 220 }} /> },
      { name: 'indeterminate', render: () => <Progress indeterminate style={{ width: 220 }} /> },
    ],
    a11y: [
      'Uses <code>role="progressbar"</code> with <code>aria-valuenow/min/max</code> (omitted while indeterminate).',
      'The looping animation is disabled under <code>prefers-reduced-motion</code>.',
    ],
  });

  /* ---------------- Skeleton ---------------- */
  window.story({
    id: 'skeleton', group: G, name: 'Skeleton', status: 'new',
    tagline: 'Loading placeholders that mirror the shape of incoming content — text lines, circles and blocks.',
    importLine: "const { Skeleton } = F2;",
    keywords: ['skeleton', 'loading', 'placeholder', 'shimmer'],
    props: [
      { name: 'variant', type: "'text' | 'circle' | 'rect'", default: 'text', control: 'select', options: ['text', 'circle', 'rect'], description: 'Shape preset.' },
      { name: 'width', type: 'number | string', default: 220, description: 'CSS width (ignored for circle).' },
      { name: 'height', type: 'number', description: 'CSS height; sensible default per variant.' },
      { name: 'radius', type: 'number | string', description: 'Override border radius.' },
    ],
    render: (v) => (
      <div style={{ display: 'flex', gap: 14, alignItems: 'center', width: 320 }}>
        <Skeleton variant="circle" height={48} />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Skeleton variant="text" width="70%" />
          <Skeleton variant="text" width="45%" />
        </div>
      </div>
    ),
    code: () => `<div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>\n  <Skeleton variant="circle" height={48} />\n  <div style={{ flex: 1 }}>\n    <Skeleton variant="text" width="70%" />\n    <Skeleton variant="text" width="45%" />\n  </div>\n</div>`,
    examples: [
      { name: 'card', render: () => <div style={{ width: 200, display: 'flex', flexDirection: 'column', gap: 10 }}><Skeleton variant="rect" height={90} /><Skeleton variant="text" width="80%" /><Skeleton variant="text" width="55%" /></div> },
    ],
    a11y: [
      'Skeletons are decorative — mark the loading container <code>aria-busy="true"</code> and announce completion via a live region.',
      'The pulse stops under <code>prefers-reduced-motion</code>.',
    ],
  });

  /* ---------------- EmptyState ---------------- */
  window.story({
    id: 'empty-state', group: G, name: 'EmptyState', status: 'new',
    tagline: 'A calm placeholder for empty lists, zero results, or first-run — icon, message, and a single clear action.',
    importLine: "const { EmptyState } = F2;",
    keywords: ['empty', 'zero', 'placeholder', 'first-run'],
    props: [
      { name: 'icon', type: 'string', default: 'Inbox', control: 'text', description: 'Lucide icon name.' },
      { name: 'title', type: 'string', default: 'No automations yet', control: 'text', description: 'Headline.' },
      { name: 'description', type: 'string', description: 'Supporting copy.' },
      { name: 'action', type: 'ReactNode', description: 'Primary call to action.' },
    ],
    render: (v) => <EmptyState icon={v.icon} title={v.title} description="Create your first agent to start automating a workflow." action={<Button iconLeft={<Icon name="Plus" size={16} />}>New automation</Button>} style={{ width: 420 }} />,
    code: (v) => `<EmptyState\n  icon="${v.icon}"\n  title="${v.title}"\n  description="Create your first agent to start automating a workflow."\n  action={<Button iconLeft={<Icon name="Plus" />}>New automation</Button>}\n/>`,
    a11y: [
      'Keep one primary action; secondary links can sit in the description.',
      'The icon is decorative — the title carries the meaning.',
    ],
  });

  /* ---------------- CodeBlock ---------------- */
  window.story({
    id: 'code-block', group: G, name: 'CodeBlock', status: 'new',
    tagline: 'A read-only code surface with a title bar and copy button — the same restrained highlighting used across the docs.',
    importLine: "const { CodeBlock } = F2;",
    keywords: ['code', 'snippet', 'pre', 'copy'],
    props: [
      { name: 'code', type: 'string', description: 'Source to display.' },
      { name: 'title', type: 'string', default: 'deploy.ts', control: 'text', description: 'Title-bar label (often a filename).' },
      { name: 'showCopy', type: 'boolean', default: true, control: 'boolean', description: 'Show the copy button.' },
    ],
    render: (v) => <CodeBlock title={v.title} showCopy={v.showCopy} style={{ width: 480, maxWidth: '100%' }}
      code={`import { deployAgent } from '@f2/sdk';\n\nconst run = await deployAgent({\n  workflow: 'invoice-ocr',\n  threshold: 0.82,\n});`} />,
    code: (v) => `<CodeBlock\n  title="${v.title}"${v.showCopy ? '' : '\n  showCopy={false}'}\n  code={source}\n/>`,
    a11y: [
      'Content sits in a <code>&lt;pre&gt;&lt;code&gt;</code> block; the copy button is labelled "Copy code".',
      'Highlighting is purely visual — the raw text is what gets copied and read.',
    ],
  });

  /* ---------------- Accordion ---------------- */
  window.story({
    id: 'accordion', group: G, name: 'Accordion', status: 'new',
    tagline: 'Collapsible sections with a smooth height transition. Single-open by default, or allow multiple.',
    importLine: "const { Accordion } = F2;",
    keywords: ['accordion', 'collapse', 'faq', 'disclosure'],
    props: [
      { name: 'items', type: 'Array<{title, content}>', description: 'Section definitions.' },
      { name: 'allowMultiple', type: 'boolean', default: false, control: 'boolean', description: 'Allow several panels open at once.' },
      { name: 'defaultOpen', type: 'number[]', default: '[0]', description: 'Indexes open initially.' },
    ],
    render: (v) => <Accordion allowMultiple={v.allowMultiple} defaultOpen={[0]} style={{ width: 480, maxWidth: '100%' }} items={[
      { title: 'How does F2 price automations?', content: 'Each automation is scoped and quoted up front; usage-based runs are billed monthly with no per-seat fees.' },
      { title: 'Can it run on our own infrastructure?', content: 'Yes — agents deploy to your cloud or ours, with the same observability either way.' },
      { title: 'What about data residency?', content: 'Data stays in your region. We process in-region and never train on your data.' },
    ]} />,
    code: (v) => `<Accordion${v.allowMultiple ? '\n  allowMultiple' : ''}\n  defaultOpen={[0]}\n  items={[\n    { title: 'How does F2 price automations?', content: '…' },\n    { title: 'Can it run on our own infrastructure?', content: '…' },\n  ]}\n/>`,
    a11y: [
      'Each header is a <code>&lt;button&gt;</code> with <code>aria-expanded</code>; the chevron rotates as a secondary cue.',
      'Height animates via a grid-rows transition that collapses cleanly under reduced motion.',
    ],
  });

  /* ---------------- DataTable ---------------- */
  function TableDemo(v) {
    const rows = [
      { id: 'r1', name: 'Invoice OCR → ERP', status: 'Running', runs: 1284, latency: 19, owner: 'Ana Ribeiro' },
      { id: 'r2', name: 'Lead routing agent', status: 'Running', runs: 932, latency: 8, owner: 'Bruno Costa' },
      { id: 'r3', name: 'Support triage', status: 'Paused', runs: 410, latency: 24, owner: 'Carla Dias' },
      { id: 'r4', name: 'Bank reconciliation', status: 'Failed', runs: 76, latency: 51, owner: 'Diego Melo' },
    ];
    const toneFor = { Running: 'success', Paused: 'neutral', Failed: 'error' };
    const columns = [
      { key: 'name', header: 'Automation', sortable: true, render: (r) => <span style={{ fontWeight: 500, color: 'var(--f2-text)' }}>{r.name}</span> },
      { key: 'status', header: 'Status', sortable: true, render: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><StatusDot tone={toneFor[r.status]} live={r.status === 'Running'} size={7} />{r.status}</span> },
      { key: 'runs', header: 'Runs', align: 'right', sortable: true, nowrap: true, render: (r) => <span style={{ fontFamily: 'var(--f2-font-mono)' }}>{r.runs.toLocaleString()}</span> },
      { key: 'latency', header: 'Avg. latency', align: 'right', sortable: true, nowrap: true, render: (r) => <span style={{ fontFamily: 'var(--f2-font-mono)' }}>{r.latency}s</span> },
      { key: 'owner', header: 'Owner', render: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><Avatar name={r.owner} size={24} />{r.owner}</span> },
    ];
    return <DataTable columns={columns} rows={rows} selectable={v.selectable} dense={v.dense} getRowId={(r) => r.id} style={{ width: 720, maxWidth: '100%' }} />;
  }
  window.story({
    id: 'data-table', group: G, name: 'DataTable', status: 'new',
    tagline: 'A sortable, selectable table with custom cell renderers, hover rows and a dense mode — the workhorse of any panel.',
    importLine: "const { DataTable } = F2;",
    keywords: ['table', 'grid', 'data', 'sortable', 'rows'],
    props: [
      { name: 'columns', type: 'Array<{key,header,render?,align?,width?,sortable?,sortValue?,nowrap?}>', description: 'Column definitions; render(row) for custom cells.' },
      { name: 'rows', type: 'object[]', description: 'Row data.' },
      { name: 'getRowId', type: '(row, i) => string', description: 'Stable id per row (for selection).' },
      { name: 'selectable', type: 'boolean', default: true, control: 'boolean', description: 'Show selection checkboxes + select-all.' },
      { name: 'dense', type: 'boolean', default: false, control: 'boolean', description: 'Tighter row padding.' },
      { name: 'onRowClick', type: '(row) => void', description: 'Row click handler.' },
    ],
    render: (v) => <TableDemo {...v} />,
    code: () => `const columns = [\n  { key: 'name', header: 'Automation', sortable: true,\n    render: (r) => <strong>{r.name}</strong> },\n  { key: 'status', header: 'Status', sortable: true,\n    render: (r) => <><StatusDot tone={toneFor[r.status]} /> {r.status}</> },\n  { key: 'runs', header: 'Runs', align: 'right', sortable: true },\n];\n\n<DataTable\n  columns={columns}\n  rows={rows}\n  getRowId={(r) => r.id}\n  selectable\n/>`,
    examples: [
      { name: 'dense', render: () => <TableDemo dense selectable={false} /> },
    ],
    a11y: [
      'Renders a real <code>&lt;table&gt;</code> with <code>&lt;th&gt;</code> headers; sorted columns expose <code>aria-sort</code>.',
      'Status uses a dot + text label; sortable headers are buttons-in-cells reachable by keyboard.',
      'Row-selection checkboxes stop click propagation so selecting never triggers a row navigation.',
    ],
  });
})();
