/* ============================================================
   F2 UI — Navigation stories
   ============================================================ */
(function () {
  const F2 = window.F2;
  const { Icon, Button, Tabs, Breadcrumb, Pagination, DropdownMenu, CommandPalette, Stepper, IconButton } = F2;
  const G = 'Navigation';

  function Stage({ children, h = 320 }) {
    return <div style={{ position: 'relative', width: '100%', height: h, border: '1px solid var(--f2-border)', borderRadius: 'var(--f2-radius-md)', overflow: 'hidden', background: 'var(--f2-surface)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{children}</div>;
  }

  /* ---------------- Tabs ---------------- */
  function TabsDemo(v) {
    const [tab, setTab] = React.useState('runs');
    return <Tabs variant={v.variant} value={tab} onChange={setTab} style={{ width: v.variant === 'line' ? 460 : undefined }}
      tabs={[{ value: 'overview', label: 'Overview', icon: 'LayoutDashboard' }, { value: 'runs', label: 'Runs', icon: 'Play', badge: 24 }, { value: 'logs', label: 'Logs', icon: 'ScrollText' }, { value: 'settings', label: 'Settings', icon: 'Settings2' }]} />;
  }
  window.story({
    id: 'tabs', group: G, name: 'Tabs', status: 'new',
    tagline: 'Switch between views — an underline (line) or a segmented (pill) variant. Arrow-key navigable.',
    importLine: "const { Tabs } = F2;",
    keywords: ['tabs', 'segmented', 'views', 'switch'],
    props: [
      { name: 'tabs', type: 'Array<{value,label,icon?,badge?}>', description: 'Tab definitions.' },
      { name: 'value', type: 'string', description: 'Active tab value (controlled).' },
      { name: 'onChange', type: '(value) => void', description: 'Fired with the next tab value.' },
      { name: 'variant', type: "'line' | 'pill'", default: 'line', control: 'select', options: ['line', 'pill'], description: 'Underline tabs or a segmented control.' },
    ],
    render: (v) => <TabsDemo {...v} />,
    code: (v) => `const [tab, setTab] = useState('runs');\n<Tabs\n  variant="${v.variant}"\n  value={tab}\n  onChange={setTab}\n  tabs={[\n    { value: 'overview', label: 'Overview', icon: 'LayoutDashboard' },\n    { value: 'runs', label: 'Runs', icon: 'Play', badge: 24 },\n    { value: 'logs', label: 'Logs', icon: 'ScrollText' },\n  ]}\n/>`,
    examples: [
      { name: 'line', render: () => <TabsDemo variant="line" /> },
      { name: 'pill', render: () => <TabsDemo variant="pill" /> },
    ],
    a11y: [
      'Buttons use <code>role="tab"</code> with <code>aria-selected</code>; the active tab is the only one in the tab order (roving <code>tabindex</code>).',
      '<kbd>←</kbd>/<kbd>→</kbd> move between tabs.',
      'Pair with a <code>role="tabpanel"</code> region that is labelled by the active tab.',
    ],
  });

  /* ---------------- Breadcrumb ---------------- */
  window.story({
    id: 'breadcrumb', group: G, name: 'Breadcrumb', status: 'new',
    tagline: 'Shows the path to the current page; the last item is the current location.',
    importLine: "const { Breadcrumb } = F2;",
    keywords: ['breadcrumb', 'path', 'navigation', 'hierarchy'],
    props: [
      { name: 'items', type: 'Array<{label,href?,icon?}>', description: 'Trail items, root first. The last is the current page.' },
    ],
    render: () => <Breadcrumb items={[{ label: 'Workspace', href: '#', icon: 'House' }, { label: 'Automations', href: '#' }, { label: 'Invoice OCR', href: '#' }, { label: 'Run 8c21' }]} />,
    code: () => `<Breadcrumb items={[\n  { label: 'Workspace', href: '/', icon: 'House' },\n  { label: 'Automations', href: '/automations' },\n  { label: 'Invoice OCR', href: '/automations/invoice' },\n  { label: 'Run 8c21' },\n]} />`,
    examples: [
      { name: 'short', render: () => <Breadcrumb items={[{ label: 'Docs', href: '#' }, { label: 'Components' }]} /> },
      { name: 'with icon root', render: () => <Breadcrumb items={[{ label: 'Home', href: '#', icon: 'House' }, { label: 'Billing', href: '#' }, { label: 'Invoices' }]} /> },
    ],
    a11y: [
      'Wrapped in <code>&lt;nav aria-label="Breadcrumb"&gt;</code> with an ordered list.',
      'The current page is a non-link with <code>aria-current="page"</code>.',
    ],
  });

  /* ---------------- Pagination ---------------- */
  function PageDemo(v) {
    const [page, setPage] = React.useState(3);
    return <Pagination page={page} count={v.count || 12} onChange={setPage} />;
  }
  window.story({
    id: 'pagination', group: G, name: 'Pagination', status: 'new',
    tagline: 'Page through long lists with first/last anchors and truncated middle pages.',
    importLine: "const { Pagination } = F2;",
    keywords: ['pagination', 'pages', 'list', 'navigation'],
    props: [
      { name: 'page', type: 'number', default: 1, description: 'Current page (1-based, controlled).' },
      { name: 'count', type: 'number', default: 12, control: 'number', min: 3, max: 40, step: 1, description: 'Total number of pages.' },
      { name: 'onChange', type: '(page) => void', description: 'Fired with the next page.' },
    ],
    render: (v) => <PageDemo {...v} />,
    code: () => `const [page, setPage] = useState(1);\n<Pagination page={page} count={12} onChange={setPage} />`,
    examples: [
      { name: 'few pages', render: () => { const C = () => { const [p, setP] = React.useState(2); return <Pagination page={p} count={5} onChange={setP} />; }; return <C />; } },
      { name: 'many pages', render: () => { const C = () => { const [p, setP] = React.useState(8); return <Pagination page={p} count={20} onChange={setP} />; }; return <C />; } },
    ],
    a11y: [
      'Wrapped in <code>&lt;nav aria-label="Pagination"&gt;</code>; the current page carries <code>aria-current="page"</code>.',
      'Prev/next buttons are labelled and become disabled at the ends.',
    ],
  });

  /* ---------------- DropdownMenu ---------------- */
  window.story({
    id: 'dropdown-menu', group: G, name: 'DropdownMenu', status: 'new',
    tagline: 'An actions menu with roving focus, icons, shortcuts, dividers and a destructive item. Arrow keys + Enter + Esc.',
    importLine: "const { DropdownMenu } = F2;",
    keywords: ['menu', 'dropdown', 'actions', 'context'],
    props: [
      { name: 'trigger', type: 'ReactNode', description: 'Element that opens the menu.' },
      { name: 'items', type: 'Array<{label,icon?,shortcut?,onClick?,danger?,disabled?,divider?}>', description: 'Menu items; use { divider: true } for a separator.' },
      { name: 'align', type: "'start' | 'end'", default: 'start', control: 'select', options: ['start', 'end'], description: 'Align the menu to the trigger.' },
      { name: 'width', type: 'number', default: 220, description: 'Menu width in px.' },
    ],
    render: (v) => (
      <DropdownMenu align={v.align} trigger={<IconButton variant="solid" aria-label="Actions"><Icon name="MoreHorizontal" size={18} /></IconButton>}
        items={[
          { label: 'Open run', icon: 'ExternalLink', shortcut: '↵' },
          { label: 'Duplicate', icon: 'Copy', shortcut: '⌘D' },
          { label: 'Rename', icon: 'PenLine' },
          { divider: true },
          { label: 'Pause agent', icon: 'Pause' },
          { label: 'Delete', icon: 'Trash2', danger: true, shortcut: '⌫' },
        ]} />
    ),
    code: (v) => `<DropdownMenu\n  align="${v.align}"\n  trigger={<IconButton aria-label="Actions"><Icon name="MoreHorizontal" /></IconButton>}\n  items={[\n    { label: 'Open run', icon: 'ExternalLink', shortcut: '↵' },\n    { label: 'Duplicate', icon: 'Copy', onClick: dup },\n    { divider: true },\n    { label: 'Delete', icon: 'Trash2', danger: true },\n  ]}\n/>`,
    a11y: [
      'Menu uses <code>role="menu"</code> / <code>role="menuitem"</code>; opening focuses the first item.',
      '<kbd>↑</kbd>/<kbd>↓</kbd> move, <kbd>Enter</kbd> activates, <kbd>Esc</kbd> / outside-click closes.',
      'The destructive item is coloured <em>and</em> labelled "Delete" — not red alone.',
    ],
  });

  /* ---------------- CommandPalette ---------------- */
  function PaletteDemo() {
    const [open, setOpen] = React.useState(false);
    return (
      <Stage h={400}>
        <Button iconLeft={<Icon name="Command" size={16} />} onClick={() => setOpen(true)}>Open palette <kbd style={{ fontFamily: 'var(--f2-font-mono)', fontSize: 11, marginLeft: 6, opacity: 0.7 }}>⌘K</kbd></Button>
        <CommandPalette contained open={open} onClose={() => setOpen(false)} groups={[
          { label: 'Automations', items: [
            { label: 'Deploy invoice agent', icon: 'Rocket', hint: 'Action' },
            { label: 'Pause lead routing', icon: 'Pause', hint: 'Action' },
            { label: 'View support triage runs', icon: 'Play' },
          ] },
          { label: 'Navigate', items: [
            { label: 'Go to Dashboard', icon: 'LayoutDashboard' },
            { label: 'Go to Billing', icon: 'CreditCard' },
            { label: 'Open Docs', icon: 'BookOpen', hint: '↗' },
          ] },
        ]} />
      </Stage>
    );
  }
  window.story({
    id: 'command-palette', group: G, name: 'CommandPalette', status: 'new',
    tagline: 'A ⌘K launcher — fuzzy-filter grouped commands, navigate with arrows, run with Enter.',
    importLine: "const { CommandPalette } = F2;",
    keywords: ['command', 'palette', 'cmdk', 'search', 'launcher'],
    props: [
      { name: 'open', type: 'boolean', description: 'Controls visibility.' },
      { name: 'onClose', type: '() => void', description: 'Called on Esc / backdrop / selection.' },
      { name: 'groups', type: 'Array<{label, items:[{label,icon?,hint?,onSelect?}]}>', description: 'Grouped commands.' },
      { name: 'placeholder', type: 'string', default: 'Type a command or search…', description: 'Search input placeholder.' },
    ],
    render: () => <PaletteDemo />,
    code: () => `const [open, setOpen] = useState(false);\n// wire ⌘K to setOpen(true)\n<CommandPalette\n  open={open}\n  onClose={() => setOpen(false)}\n  groups={[\n    { label: 'Automations', items: [\n      { label: 'Deploy invoice agent', icon: 'Rocket', onSelect: deploy },\n    ]},\n    { label: 'Navigate', items: [\n      { label: 'Go to Dashboard', icon: 'LayoutDashboard', onSelect: goDash },\n    ]},\n  ]}\n/>`,
    a11y: [
      'The input is auto-focused on open; results filter live and the active item follows <kbd>↑</kbd>/<kbd>↓</kbd>.',
      '<kbd>Enter</kbd> runs the active command, <kbd>Esc</kbd> closes.',
      'Selection is reinforced by a surface change on the active row, not color alone.',
    ],
  });

  /* ---------------- Stepper ---------------- */
  function StepperDemo(v) {
    const steps = [{ label: 'Connect data', description: 'Stripe, ERP' }, { label: 'Define agent', description: 'Prompt & tools' }, { label: 'Test run', description: 'Dry run' }, { label: 'Deploy', description: 'Go live' }];
    return <Stepper orientation={v.orientation} current={v.current} steps={steps} style={{ width: v.orientation === 'horizontal' ? 520 : undefined }} />;
  }
  window.story({
    id: 'stepper', group: G, name: 'Stepper', status: 'new',
    tagline: 'Shows progress through a multi-step flow — completed steps fill amber with a check, the current step is ringed.',
    importLine: "const { Stepper } = F2;",
    keywords: ['stepper', 'wizard', 'progress', 'onboarding'],
    props: [
      { name: 'steps', type: 'Array<{label,description?}> | string[]', description: 'Ordered steps.' },
      { name: 'current', type: 'number', default: 2, control: 'number', min: 0, max: 3, step: 1, description: 'Zero-based index of the active step.' },
      { name: 'orientation', type: "'horizontal' | 'vertical'", default: 'horizontal', control: 'select', options: ['horizontal', 'vertical'], description: 'Layout direction.' },
    ],
    render: (v) => <StepperDemo {...v} />,
    code: (v) => `<Stepper\n  orientation="${v.orientation}"\n  current={${v.current}}\n  steps={[\n    { label: 'Connect data', description: 'Stripe, ERP' },\n    { label: 'Define agent', description: 'Prompt & tools' },\n    { label: 'Test run', description: 'Dry run' },\n    { label: 'Deploy', description: 'Go live' },\n  ]}\n/>`,
    examples: [
      { name: 'horizontal', render: () => <StepperDemo orientation="horizontal" current={1} /> },
      { name: 'vertical', render: () => <div style={{ width: 220 }}><StepperDemo orientation="vertical" current={2} /></div> },
    ],
    a11y: [
      'The active step circle carries <code>aria-current="step"</code>.',
      'Completed steps show a check icon in addition to the amber fill, so progress is not color-only.',
    ],
  });
})();
