'use client';

/**
 * Primitives - section 2 of /design-system.
 *
 * Renders every primitive from src/components/ui/primitives/** with all
 * variants, plus tokens, a11y notes, and import snippets.
 */

import { useState } from 'react';
import { Button } from '@/components/ui/primitives/Button';
import { ImageUploadField } from '@/components/ui/primitives/ImageUploadField';
import { Input } from '@/components/ui/primitives/Input';
import { Textarea } from '@/components/ui/primitives/Textarea';
import { Label } from '@/components/ui/primitives/Label';
import { FormField } from '@/components/ui/primitives/FormField';
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from '@/components/ui/primitives/Select';
import { Combobox } from '@/components/ui/inputs/Combobox';
import { Checkbox } from '@/components/ui/primitives/Checkbox';
import { Switch } from '@/components/ui/primitives/Switch';
import { RadioGroup, RadioItem, RadioCard } from '@/components/ui/primitives/RadioGroup';
import { Pill } from '@/components/ui/primitives/Pill';
import { Badge } from '@/components/ui/primitives/Badge';
import { NumberInput } from '@/components/ui/primitives/NumberInput';
import { Image } from '@/components/ui/primitives/Image';
import { Table } from '@/components/ui/primitives/Table';
import { JsonLd } from '@/components/ui/primitives/JsonLd';
import { FilterChip } from '@/components/ui/primitives/FilterChip';
import { Icon } from '@/components/ui/icons/Icon';
import { Stack } from '@/components/ui/layout/Stack';
import { Row } from '@/components/ui/layout/Row';
import { useT } from '@/lib/i18n/react';
import { LabelWithTooltip } from '@/components/ui/primitives/LabelWithTooltip';
import { IconButton } from '@/components/ui/primitives/IconButton';
import { SegmentedControl } from '@/components/ui/primitives/SegmentedControl';
import { RichTextEditor } from '@/components/ui/primitives/RichTextEditor/RichTextEditor';
import { StarRating } from '@/components/ui/primitives/StarRating';
import { Slider } from '@/components/ui/primitives/Slider';
import { formatShekelFloat } from '@/lib/money.js';
import { LaunchModePicker } from '@/components/ui/primitives/LaunchModePicker';
import type { LaunchMode } from '@/components/ui/primitives/LaunchModePicker';
import { ComponentEntry } from '../../components/ComponentEntry';
import { SectionShell } from '../../components/SectionShell';

const SAMPLE_JSONLD = {
  '@context': 'https://schema.org',
  '@type': 'LocalBusiness',
  name: 'Multideal',
  url: 'https://multideal.co.il',
  address: {
    '@type': 'PostalAddress',
    streetAddress: 'Rothschild 22',
    addressLocality: 'Tel Aviv',
    addressCountry: 'IL',
  },
};

export function Primitives() {
  const t = useT('design_system');
  const [qty, setQty] = useState(1);
  const [checked, setChecked] = useState(true);
  const [switched, setSwitched] = useState(true);
  const [radioValue, setRadioValue] = useState('a');
  const [radioCardValue, setRadioCardValue] = useState('one');
  const [selectValue, setSelectValue] = useState('a');
  const [comboboxValue, setComboboxValue] = useState('stored-legacy-model');
  const [segValue, setSegValue] = useState('S');
  const [segSmValue, setSegSmValue] = useState('B');
  const [rteRtlValue, setRteRtlValue] = useState('');
  const [rteLtrValue, setRteLtrValue] = useState('');
  const [sliderRange, setSliderRange] = useState<[number, number]>([0, 2000]);
  const [dsHistoRange, setDsHistoRange] = useState<[number, number]>([200, 800]);
  const [launchModeValue, setLaunchModeValue] = useState<LaunchMode>('now');

  return (
    <SectionShell id="primitives" title={t('sidebar_primitives')} description={t('section_intro')}>
      {/* Button */}
      <ComponentEntry
        name="Button"
        id="button-primitive"
        path="src/components/ui/primitives/Button"
        description="Primary interactive trigger. 5 variants × 3 sizes, plus loading + icon slots."
        tokens={[
          'color-brand-primary-600',
          'color-mode-vendor-600',
          'color-danger-600',
          'space-3',
          'space-4',
          'radius-md',
          'font-size-sm',
          'shadow-focus-primary',
        ]}
        a11yNotes={[
          'Always a real <button> element',
          'Keyboard reachable, focus ring visible',
          'aria-busy when loading',
          'disabled state has 50% opacity + pointer-events-none',
        ]}
        importSnippet={`import { Button } from '@/components/ui/primitives/Button';`}
      >
        <Stack gap="3">
          <Row gap="3" wrap>
            {(['primary', 'secondary', 'ghost', 'ghost-inverted', 'danger'] as const).map((v) => (
              <Button
                key={v}
                variant={v}
                aria-label={v === 'primary' ? 'Primary recipe' : undefined}
              >
                {v === 'primary' ? 'Primary recipe' : v}
              </Button>
            ))}
          </Row>
          <Row gap="3" wrap align="center">
            <Button size="sm">Small</Button>
            <Button size="md">Medium</Button>
            <Button size="lg">Large</Button>
          </Row>
          <Row gap="3" wrap align="center">
            <Button loading>Loading…</Button>
            <Button iconStart={<Icon name="Plus" size="sm" />}>With icon start</Button>
            <Button iconEnd={<Icon name="ChevronLeft" size="sm" mirror />}>With icon end</Button>
            <Button disabled>Disabled</Button>
          </Row>
        </Stack>
      </ComponentEntry>

      {/* Input */}
      <ComponentEntry
        name="Input"
        id="input-primitive"
        path="src/components/ui/primitives/Input"
        description="Single-line text input with optional start/end slots and invalid state."
        tokens={[
          'color-neutral-200',
          'color-brand-primary-500',
          'color-danger-500',
          'radius-md',
          'space-3',
        ]}
        a11yNotes={[
          'Forwards ref for react-hook-form',
          'aria-invalid on error',
          'Logical start/end slots (RTL-aware)',
        ]}
        importSnippet={`import { Input } from '@/components/ui/primitives/Input';`}
      >
        <Stack gap="3">
          <Input type="text" autoDir placeholder={t('sample_input_placeholder')} />
          <Input type="tel" placeholder="050-0000000" />
          <Input type="email" placeholder="me@multideal.co.il" />
          <Input
            type="number"
            placeholder="0"
            startSlot={<Icon name="Phone" size="sm" />}
            endSlot={<Icon name="Check" size="sm" />}
          />
          <Input invalid placeholder="Invalid value" />
        </Stack>
      </ComponentEntry>

      {/* Textarea */}
      <ComponentEntry
        name="Textarea"
        id="textarea-primitive"
        path="src/components/ui/primitives/Textarea"
        description="Multi-line text input with the same skin as Input."
        tokens={['color-neutral-200', 'color-brand-primary-500', 'radius-md']}
        a11yNotes={['Forwards ref for forms', 'aria-invalid on error', 'min-height set via tokens']}
        importSnippet={`import { Textarea } from '@/components/ui/primitives/Textarea';`}
      >
        <Textarea rows={4} autoDir placeholder={t('sample_textarea_placeholder')} />
      </ComponentEntry>

      {/* Label */}
      <ComponentEntry
        name="Label"
        id="label-primitive"
        path="src/components/ui/primitives/Label"
        description="Form label with optional required asterisk."
        tokens={['color-neutral-700', 'font-size-sm', 'color-danger-600']}
        a11yNotes={[
          'Wraps Radix Label',
          'asterisk is aria-hidden - required announced via aria-required',
        ]}
        importSnippet={`import { Label } from '@/components/ui/primitives/Label';`}
      >
        <Stack gap="2">
          <Label htmlFor="ds-label-1">{t('sample_label')}</Label>
          <Label htmlFor="ds-label-2" required>
            {t('sample_label')}
          </Label>
        </Stack>
      </ComponentEntry>

      {/* FormField */}
      <ComponentEntry
        name="FormField"
        id="formfield-primitive"
        path="src/components/ui/primitives/FormField"
        description="Composes Label + control + hint + error with auto aria-describedby wiring."
        tokens={['color-neutral-700', 'color-danger-600', 'space-1']}
        a11yNotes={[
          'htmlFor or auto-generated id',
          'aria-describedby links hint + error',
          'role=alert on error message',
        ]}
        importSnippet={`import { FormField } from '@/components/ui/primitives/FormField';`}
      >
        <Stack gap="3">
          <FormField label={t('sample_label')} hint="Helper text" htmlFor="ds-ff-1">
            <Input id="ds-ff-1" type="text" />
          </FormField>
          <FormField label={t('sample_label')} required error="Required field" htmlFor="ds-ff-2">
            <Input id="ds-ff-2" type="text" invalid />
          </FormField>
        </Stack>
      </ComponentEntry>

      {/* Select */}
      <ComponentEntry
        name="Select"
        id="select-primitive"
        path="src/components/ui/primitives/Select"
        description="Radix Select dropdown with Multideal skin."
        tokens={['color-neutral-200', 'color-brand-primary-500', 'radius-md', 'shadow-md']}
        a11yNotes={[
          'Native keyboard nav',
          'Portaled, positioned via popper',
          'data-[placeholder] muted color',
        ]}
        importSnippet={`import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from '@/components/ui/primitives/Select';`}
      >
        <Select value={selectValue} onValueChange={setSelectValue}>
          <SelectTrigger className="w-64">
            <SelectValue placeholder={t('sample_select_placeholder')} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="a">{t('sample_option_a')}</SelectItem>
            <SelectItem value="b">{t('sample_option_b')}</SelectItem>
            <SelectItem value="c">{t('sample_option_c')}</SelectItem>
          </SelectContent>
        </Select>
      </ComponentEntry>

      {/* Combobox */}
      <ComponentEntry
        name="Combobox"
        id="combobox-input"
        path="src/components/ui/inputs/Combobox"
        description="Strict searchable single-select composed from Popover + cmdk. Filters on type; only listed values can be selected."
        tokens={['color-neutral-200', 'color-brand-primary-500', 'radius-md', 'shadow-lg']}
        a11yNotes={[
          'Trigger is a combobox button with aria-expanded and aria-haspopup=listbox',
          'cmdk provides listbox/option roles and keyboard navigation',
          'Focus ring visible on trigger and search input',
          'Pinned stored values stay visible when absent from the current options list',
        ]}
        importSnippet={`import { Combobox } from '@/components/ui/inputs/Combobox';`}
      >
        <Combobox
          id="ds-combobox"
          dir="ltr"
          className="w-64"
          value={comboboxValue}
          onValueChange={setComboboxValue}
          options={[
            { value: 'gemini-3-flash-preview', label: 'gemini-3-flash-preview' },
            { value: 'gemini-2.5-pro', label: 'gemini-2.5-pro' },
            { value: 'gpt-4o-mini', label: 'gpt-4o-mini' },
          ]}
          placeholder={t('sample_select_placeholder')}
          searchPlaceholder={t('sample_input_placeholder')}
          emptyText="No matches"
        />
      </ComponentEntry>

      {/* Checkbox */}
      <ComponentEntry
        name="Checkbox"
        id="checkbox-primitive"
        path="src/components/ui/primitives/Checkbox"
        description="Radix checkbox with checked / indeterminate states."
        tokens={['color-brand-primary-600', 'color-neutral-300', 'radius-sm']}
        a11yNotes={[
          'Native keyboard activation (Space)',
          'Focus ring visible',
          'Pair with <Label htmlFor>',
        ]}
        importSnippet={`import { Checkbox } from '@/components/ui/primitives/Checkbox';`}
      >
        <Row gap="3" align="center">
          <Checkbox
            id="ds-cb-1"
            checked={checked}
            onCheckedChange={(v) => setChecked(v === true)}
          />
          <Label htmlFor="ds-cb-1">{t('sample_label')}</Label>
        </Row>
      </ComponentEntry>

      {/* Switch */}
      <ComponentEntry
        name="Switch"
        id="switch-primitive"
        path="src/components/ui/primitives/Switch"
        description="Radix toggle switch with RTL-aware thumb translation."
        tokens={['color-brand-primary-600', 'color-neutral-200', 'radius-full']}
        a11yNotes={['role=switch', 'Space/Enter toggles', 'Thumb flips direction in RTL']}
        importSnippet={`import { Switch } from '@/components/ui/primitives/Switch';`}
      >
        <Row gap="3" align="center">
          <Switch id="ds-sw-1" checked={switched} onCheckedChange={setSwitched} />
          <Label htmlFor="ds-sw-1">{t('sample_label')}</Label>
        </Row>
      </ComponentEntry>

      {/* RadioGroup + RadioCard */}
      <ComponentEntry
        name="RadioGroup / RadioCard"
        id="radiogroup-primitive"
        path="src/components/ui/primitives/RadioGroup"
        description="Radix radio group plus a fat RadioCard variant for the deal-type picker."
        tokens={['color-brand-primary-600', 'color-neutral-300', 'radius-md']}
        a11yNotes={[
          'Arrow-key navigation between options',
          'Single tab stop on selected item',
          'Visible focus ring',
        ]}
        importSnippet={`import { RadioGroup, RadioItem, RadioCard } from '@/components/ui/primitives/RadioGroup';`}
      >
        <Stack gap="4">
          <RadioGroup value={radioValue} onValueChange={setRadioValue}>
            <RadioItem id="ds-r-1" value="a" label={t('sample_option_a')} />
            <RadioItem id="ds-r-2" value="b" label={t('sample_option_b')} />
            <RadioItem id="ds-r-3" value="c" label={t('sample_option_c')} />
          </RadioGroup>
          <RadioGroup value={radioCardValue} onValueChange={setRadioCardValue}>
            <RadioCard
              id="ds-rc-1"
              value="one"
              label={t('sample_option_a')}
              description="Description A"
            />
            <RadioCard
              id="ds-rc-2"
              value="two"
              label={t('sample_option_b')}
              description="Description B"
            />
          </RadioGroup>
        </Stack>
      </ComponentEntry>

      {/* Pill */}
      <ComponentEntry
        name="Pill"
        id="pill-primitive"
        path="src/components/ui/primitives/Pill"
        description="Small status label - 5 tones × 2 sizes."
        tokens={[
          'color-success-50',
          'color-warning-50',
          'color-danger-50',
          'color-info-50',
          'color-neutral-100',
          'radius-full',
        ]}
        a11yNotes={['Pure visual - wrap a screen-reader label when meaning is non-textual']}
        importSnippet={`import { Pill } from '@/components/ui/primitives/Pill';`}
      >
        <Row gap="2" wrap>
          {(['success', 'warning', 'danger', 'info', 'neutral'] as const).map((tone) => (
            <Pill key={tone} tone={tone} size="md">
              {tone}
            </Pill>
          ))}
        </Row>
      </ComponentEntry>

      {/* Badge */}
      <ComponentEntry
        name="Badge"
        id="badge-primitive"
        path="src/components/ui/primitives/Badge"
        description="Inline label with tonal ring - 6 tonal + 2 solid variants."
        tokens={[
          'color-brand-primary-50',
          'color-success-50',
          'color-warning-50',
          'color-neutral-900',
          'color-neutral-0',
          'color-danger-50',
          'color-danger-700',
          'radius-md',
        ]}
        a11yNotes={['Decorative - provide an aria-label or surrounding text for meaning']}
        importSnippet={`import { Badge } from '@/components/ui/primitives/Badge';`}
      >
        <Stack gap="3">
          <Row gap="2" wrap>
            {(['success', 'warning', 'danger', 'info', 'neutral', 'brand'] as const).map((tone) => (
              <Badge key={tone} tone={tone}>
                {tone}
              </Badge>
            ))}
          </Row>
          <Row gap="2" wrap>
            <Badge tone="solid-dark">כמעט אזל</Badge>
            <Badge tone="solid-danger-light">50%-</Badge>
          </Row>
        </Stack>
      </ComponentEntry>

      {/* NumberInput */}
      <ComponentEntry
        name="NumberInput"
        id="numberinput-primitive"
        path="src/components/ui/primitives/NumberInput"
        description="Number input with inc/dec buttons + arrow-key support."
        tokens={['color-neutral-200', 'color-brand-primary-500', 'radius-md']}
        a11yNotes={[
          'Buttons have aria-labels',
          'ArrowUp / ArrowDown adjust value',
          'Clamped to min/max',
        ]}
        importSnippet={`import { NumberInput } from '@/components/ui/primitives/NumberInput';`}
      >
        <NumberInput min={0} max={100} step={1} value={qty} onChange={setQty} />
      </ComponentEntry>

      {/* Image */}
      <ComponentEntry
        name="Image"
        id="image-primitive"
        path="src/components/ui/primitives/Image"
        description="<picture> wrapper that emits AVIF → WebP → JPEG sources via Cloudflare Images."
        tokens={['radius-md']}
        a11yNotes={[
          'alt text required (throws in dev if missing)',
          'decorative={true} marks aria-hidden',
          'Above-fold uses loading=eager + fetchpriority=high',
        ]}
        importSnippet={`import { Image } from '@/components/ui/primitives/Image';`}
      >
        <Image
          src="data:image/svg+xml,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 width%3D%22400%22 height%3D%22300%22%3E%3Crect fill%3D%22%23ddd%22 width%3D%22100%25%22 height%3D%22100%25%22%2F%3E%3C%2Fsvg%3E"
          alt="Sample burger"
          width={400}
          height={300}
          variant="card"
          className="rounded-md"
        />
      </ComponentEntry>

      {/* SeoHead - preview as text */}
      <ComponentEntry
        name="SeoHead"
        id="seohead-primitive"
        path="src/components/ui/primitives/SeoHead"
        description="Renders all SEO meta tags into <head>: title, description, canonical, OG (WebP), hreflang, JSON-LD."
        tokens={[]}
        a11yNotes={[
          'Adds <html lang> via SeoHead consumers',
          'noindex flag for non-indexed routes',
        ]}
        importSnippet={`import { SeoHead } from '@/components/ui/primitives/SeoHead';`}
      >
        <pre className="overflow-x-auto rounded-md bg-neutral-900 p-3 font-mono text-xs text-neutral-50">
          {`<title>Multideal - discounted deals</title>
<meta name="description" content="Discover transparent discounted deals…" />
<link rel="canonical" href="https://multideal.co.il/" />
<meta property="og:title" content="Multideal" />
<meta property="og:image" content=".../og.webp" />
<link rel="alternate" hreflang="he" href="https://multideal.co.il/" />
<link rel="alternate" hreflang="en" href="https://multideal.co.il/en/" />`}
        </pre>
      </ComponentEntry>

      {/* ImageUploadField */}
      <ComponentEntry
        name="ImageUploadField"
        id="imageuploadfield-primitive"
        path="src/components/ui/primitives/ImageUploadField"
        description="Drag-and-drop image uploader using the R2 + Cloudflare Images pipeline. Validates MIME type and file size client-side, requests an upload token, uploads to R2, then resolves a CF Images WebP variant URL. Shows thumbnail preview after upload with a remove button."
        tokens={[
          'color-brand-primary-50',
          'color-brand-primary-600',
          'color-danger-600',
          'radius-xl',
          'spacing-4',
          'font-size-sm',
        ]}
        a11yNotes={[
          'Drop zone is a <button> - keyboard and pointer reachable',
          'aria-label on the drop zone button',
          'Hidden <input type="file"> linked to drop zone',
          'role="status" on progress/uploading indicator',
          'Remove button has aria-label',
        ]}
        importSnippet={`import { ImageUploadField } from '@/components/ui/primitives/ImageUploadField';`}
      >
        <div className="flex flex-col gap-6">
          <ImageUploadField
            label="Logo (1:1)"
            value={null}
            onChange={() => {}}
            purpose="vendor_logo"
            aspectRatio="1:1"
          />
          <ImageUploadField
            label="Hero image (16:9)"
            value={null}
            onChange={() => {}}
            purpose="vendor_hero"
            aspectRatio="16:9"
          />
        </div>
      </ComponentEntry>

      {/* LabelWithTooltip */}
      <ComponentEntry
        name="LabelWithTooltip"
        id="labelwithtooltip-primitive"
        path="src/components/ui/primitives/LabelWithTooltip"
        description="Inline label text + focusable info-icon button that opens a Radix tooltip explaining the field. Used for form field labels that need contextual help without cluttering the UI."
        tokens={[
          'var(--font-size-sm) — label text size',
          'var(--duration-fast) — color transition on hover',
          'var(--radius-full) — info-button border-radius',
          'text-neutral-400 / text-neutral-600 — icon color states',
          'outline-brand-primary-600 — focus ring color',
        ]}
        a11yNotes={[
          'Info button is a <button type="button"> — keyboard reachable via Tab, activates on Enter/Space',
          'aria-label on info button reads from common.more_info ("מידע נוסף" / "More information")',
          'Tooltip content has role="tooltip" (Radix manages this automatically)',
          'Focus ring always visible — focus-visible:outline applied',
          'prefers-reduced-motion: Radix TooltipContent has motion-reduce:animate-none',
          'Works in both dir="rtl" and dir="ltr" — icon always sits at inline-end of label via ms-1',
        ]}
        importSnippet={`import { LabelWithTooltip } from '@/components/ui/primitives/LabelWithTooltip';`}
      >
        <Stack gap="4">
          <div>
            <p className="mb-2 text-xs text-neutral-500">
              With htmlFor (renders as &lt;label&gt;):
            </p>
            <LabelWithTooltip
              label="מגבלת פריטים"
              tooltip="מספר הפריטים המרבי שיוצגו בשורה (1–30). המערכת תציג עד המספר הזה גם אם יש יותר דילים זמינים."
              htmlFor="demo-input"
            />
          </div>
          <div>
            <p className="mb-2 text-xs text-neutral-500">
              Without htmlFor (renders as &lt;span&gt;):
            </p>
            <LabelWithTooltip
              label="Item limit"
              tooltip="Maximum number of items shown in the row (1–30)."
            />
          </div>
          <div>
            <p className="mb-2 text-xs text-neutral-500">Required (asterisk is aria-hidden):</p>
            <LabelWithTooltip
              label="Item limit"
              tooltip="Maximum number of items shown in the row (1–30)."
              required
            />
          </div>
          <div>
            <p className="mb-2 text-xs text-neutral-500">In LTR context:</p>
            <div dir="ltr">
              <LabelWithTooltip
                label="Category filter"
                tooltip="The filter category — the row shows only deals in this category."
              />
            </div>
          </div>
        </Stack>
      </ComponentEntry>

      {/* JsonLd */}
      <ComponentEntry
        name="JsonLd"
        id="jsonld-primitive"
        path="src/components/ui/primitives/JsonLd"
        description="Safely renders JSON-LD structured data via a sanitized inline <script>."
        tokens={[]}
        a11yNotes={[
          'Hidden script tag - invisible to screen readers',
          'JSON.stringify with HTML escaping',
        ]}
        importSnippet={`import { JsonLd } from '@/components/ui/primitives/JsonLd';`}
      >
        <Stack gap="2">
          <pre className="overflow-x-auto rounded-md bg-neutral-900 p-3 font-mono text-xs text-neutral-50">
            {JSON.stringify(SAMPLE_JSONLD, null, 2)}
          </pre>
          <JsonLd data={SAMPLE_JSONLD} />
        </Stack>
      </ComponentEntry>

      {/* FilterChip */}
      <ComponentEntry
        name="FilterChip"
        id="filterchip-primitive"
        path="src/components/ui/primitives/FilterChip"
        description="Toggling chip button with aria-pressed. Two visual contexts: default (light surface) and hero (dark brand header). Used for category and deal-type filter bars."
        tokens={[
          'color-brand-primary-50',
          'color-brand-primary-600',
          'color-brand-primary-700',
          'color-surface-base',
          'color-surface-inset',
          'color-text-secondary',
          'color-border-default',
          'shadow-sm',
        ]}
        a11yNotes={[
          'Uses aria-pressed for toggled state (not role="radio")',
          'Focus ring visible in both contexts',
          'Keyboard: Space/Enter to toggle',
        ]}
        importSnippet={`import { FilterChip } from '@/components/ui/primitives/FilterChip';`}
      >
        <Stack gap="4">
          <div>
            <p className="text-text-muted mb-2 text-sm">context=default</p>
            <div className="flex flex-wrap gap-2">
              <FilterChip context="default" pressed={false}>
                כל הסוגים
              </FilterChip>
              <FilterChip context="default" pressed={true}>
                ארוחה יומית
              </FilterChip>
              <FilterChip context="default" pressed={false}>
                חוויה
              </FilterChip>
              <FilterChip context="default" pressed={false}>
                All Types
              </FilterChip>
              <FilterChip context="default" pressed={true}>
                Daily Meal
              </FilterChip>
            </div>
          </div>
          <div className="bg-brand-primary-700 rounded-md p-4">
            <p className="mb-2 text-sm text-white/75">context=hero</p>
            <div className="flex flex-wrap gap-2">
              <FilterChip context="hero" pressed={false}>
                כל הסוגים
              </FilterChip>
              <FilterChip context="hero" pressed={true}>
                ארוחה יומית
              </FilterChip>
              <FilterChip context="hero" pressed={false}>
                חוויה
              </FilterChip>
              <FilterChip context="hero" pressed={false}>
                All
              </FilterChip>
              <FilterChip context="hero" pressed={true}>
                Daily Meal
              </FilterChip>
            </div>
          </div>
        </Stack>
      </ComponentEntry>

      {/* IconButton */}
      <ComponentEntry
        name="IconButton"
        id="iconbutton-primitive"
        path="src/components/ui/primitives/IconButton"
        description="Icon-only button with required aria-label. 4 variants × 3 sizes × 2 shapes. Used for back/close navigation, carousel controls, and toolbar toggles."
        tokens={[
          'color-surface-inset',
          'color-surface-hover',
          'color-surface-overlay',
          'color-brand-on-primary',
          'radius-full',
          'radius-md',
          'shadow-focus-primary',
        ]}
        a11yNotes={[
          'aria-label is TypeScript-required — cannot render without it',
          'Always a real <button> or Radix Slot',
          'Focus ring always visible',
          'Keyboard reachable (Tab + Enter/Space)',
          'IS 5568 / WCAG 2.1 AA compliant',
        ]}
        importSnippet={`import { IconButton } from '@/components/ui/primitives/IconButton';`}
      >
        <Stack gap="3">
          <p className="text-text-secondary text-sm font-medium">Variants</p>
          <Row gap="3" wrap align="center">
            <IconButton aria-label="Default icon button">
              <Icon name="Star" size="sm" />
            </IconButton>
            <IconButton variant="ghost" aria-label="Ghost icon button">
              <Icon name="Star" size="sm" />
            </IconButton>
            <div className="bg-brand-primary-600 flex items-center rounded-md p-2">
              <IconButton variant="on-brand" aria-label="On-brand icon button">
                <Icon name="ChevronRight" size="md" mirror />
              </IconButton>
            </div>
            <div className="relative h-10 w-24 overflow-hidden rounded-md">
              <div className="absolute inset-0 bg-gradient-to-r from-neutral-400 to-neutral-600" />
              <div className="absolute inset-0 flex items-center justify-center">
                <IconButton variant="overlay" aria-label="Overlay icon button">
                  <Icon name="ChevronLeft" size="md" mirror />
                </IconButton>
              </div>
            </div>
          </Row>
          <p className="text-text-secondary text-sm font-medium">Sizes</p>
          <Row gap="3" wrap align="center">
            <IconButton size="sm" aria-label="Small">
              <Icon name="X" size="xs" />
            </IconButton>
            <IconButton size="md" aria-label="Medium">
              <Icon name="X" size="sm" />
            </IconButton>
            <IconButton size="lg" aria-label="Large">
              <Icon name="X" size="md" />
            </IconButton>
          </Row>
          <p className="text-text-secondary text-sm font-medium">Shapes</p>
          <Row gap="3" wrap align="center">
            <IconButton shape="circle" aria-label="Circle shape">
              <Icon name="Plus" size="sm" />
            </IconButton>
            <IconButton shape="square" aria-label="Square shape">
              <Icon name="Plus" size="sm" />
            </IconButton>
          </Row>
        </Stack>
      </ComponentEntry>

      {/* SegmentedControl */}
      <ComponentEntry
        name="SegmentedControl"
        id="segmentedcontrol-primitive"
        path="src/components/ui/primitives/SegmentedControl"
        description="Horizontal radiogroup-style segmented button. Keyboard: Tab into the group, Arrow keys cycle selection (RTL-aware). role=radiogroup + role=radio + aria-checked."
        tokens={[
          'color-surface-inset',
          'color-surface-base',
          'color-border-default',
          'color-text-primary',
          'color-text-secondary',
          'radius-md',
          'font-size-sm',
          'font-size-xs',
          'shadow-sm',
        ]}
        a11yNotes={[
          'Container: role="radiogroup" + aria-label (required in TypeScript)',
          'Each button: role="radio" + aria-checked',
          'Selected option is highlighted by an in-place indicator element',
          'Roving tabIndex — Tab reaches the selected option only',
          'ArrowLeft/ArrowRight cycle selection; RTL-aware via computed dir',
          'Focus ring always visible (focus-visible:outline)',
          'prefers-reduced-motion: transition-none applied',
          'IS 5568 / WCAG 2.1 AA compliant',
        ]}
        importSnippet={`import { SegmentedControl } from '@/components/ui/primitives/SegmentedControl';`}
      >
        <Stack gap="4">
          <p className="text-text-secondary text-sm font-medium">Size: md (default)</p>
          <SegmentedControl
            aria-label="Text size"
            value={segValue}
            onChange={setSegValue}
            options={[
              { value: 'S', label: 'Small' },
              { value: 'M', label: 'Medium' },
              { value: 'L', label: 'Large' },
              { value: 'XL', label: 'X-Large' },
            ]}
          />
          <p className="text-text-secondary text-sm font-medium">Size: sm</p>
          <SegmentedControl
            aria-label="Section"
            size="sm"
            value={segSmValue}
            onChange={setSegSmValue}
            options={[
              { value: 'A', label: 'Option A' },
              { value: 'B', label: 'Option B' },
              { value: 'C', label: 'Option C' },
            ]}
          />
          <p className="text-text-secondary text-sm font-medium">With disabled option</p>
          <SegmentedControl
            aria-label="Plan"
            value="free"
            onChange={() => {}}
            options={[
              { value: 'free', label: 'Free' },
              { value: 'pro', label: 'Pro', disabled: true },
            ]}
          />
        </Stack>
      </ComponentEntry>

      {/* RichTextEditor */}
      <ComponentEntry
        name="RichTextEditor"
        id="richtexteditor-primitive"
        path="src/components/ui/primitives/RichTextEditor/RichTextEditor"
        description="Tiptap-based rich text editor with minimal toolbar (Bold, Italic, H2, Bullet list). RTL-aware via tiptap-text-direction. Used in page-organizer ConfigEditors."
        tokens={[
          'border-border-default',
          'bg-surface-base',
          'bg-surface-raised',
          'border-border-subtle',
          'text-text-secondary',
          'bg-surface-hover',
        ]}
        a11yNotes={[
          'role=toolbar on the toolbar strip',
          'Each toolbar button has aria-label and aria-pressed',
          'Editor region has role=textbox + aria-multiline=true',
          'aria-label prop threads through to the editor element',
        ]}
        importSnippet={`import { RichTextEditor } from '@/components/ui/primitives/RichTextEditor/RichTextEditor';`}
      >
        <Stack gap="4">
          <p className="text-text-secondary text-sm font-medium">{t('richtexteditor_rtl_label')}</p>
          <RichTextEditor
            value={rteRtlValue}
            onChange={setRteRtlValue}
            dir="rtl"
            aria-label={t('richtexteditor_rtl_label')}
          />
          <p className="text-text-secondary text-sm font-medium">{t('richtexteditor_ltr_label')}</p>
          <RichTextEditor
            value={rteLtrValue}
            onChange={setRteLtrValue}
            dir="ltr"
            aria-label={t('richtexteditor_ltr_label')}
          />
        </Stack>
      </ComponentEntry>

      {/* StarRating */}
      <ComponentEntry
        name="StarRating"
        id="starrating-primitive"
        path="src/components/ui/primitives/StarRating"
        description="Inline, read-only star rating with optional review count. Partial fill via clip-path for half stars. RTL-safe logical gap."
        tokens={[
          'color-warning-500',
          'color-text-subtle',
          'color-text-default',
          'color-text-muted',
        ]}
        a11yNotes={[
          'role=img on wrapper span with descriptive aria-label',
          'Stars rendered aria-hidden — screen readers get full text (e.g. "דירוג 4.7 מתוך 5, 124 ביקורות")',
          'Not interactive — no keyboard events, no focus handling needed',
        ]}
        importSnippet={`import { StarRating } from '@/components/ui/primitives/StarRating';`}
      >
        <Stack gap="4">
          <Row gap="4" wrap align="center">
            <StarRating value={5} count={312} size="md" />
            <StarRating value={4.7} count={124} size="md" />
            <StarRating value={3.5} count={48} size="md" />
            <StarRating value={2} count={7} size="md" />
            <StarRating value={0} size="md" />
          </Row>
          <Row gap="4" wrap align="center">
            <StarRating value={4.7} count={124} size="sm" />
            <StarRating value={3.5} size="sm" />
            <StarRating value={1} count={1} size="sm" />
          </Row>
        </Stack>
      </ComponentEntry>

      {/* Slider */}
      <ComponentEntry
        name="Slider"
        id="slider-primitive"
        path="src/components/ui/primitives/Slider"
        description="Dual-handle range slider. RTL-aware via locale context. Uses @radix-ui/react-slider."
        tokens={['color-brand-primary-600', 'color-brand-primary-500', 'color-neutral-200']}
        a11yNotes={[
          'Radix provides role=slider on each thumb',
          'aria-valuenow, aria-valuemin, aria-valuemax on each thumb',
          'Keyboard: ArrowLeft/Right/Up/Down move handle; Home/End jump to min/max',
          'RTL direction passed to Radix Root — layout flips automatically',
          'Focus ring always visible (focus-visible:ring)',
        ]}
        importSnippet={`import { Slider } from '@/components/ui/primitives/Slider';`}
      >
        <div className="flex max-w-sm flex-col gap-4 rounded-xl border p-6">
          <span className="text-sm font-medium">Price range</span>
          <Slider
            min={0}
            max={2000}
            value={sliderRange}
            step={50}
            onChange={setSliderRange}
            formatLabel={formatShekelFloat}
            aria-label="Price range"
          />
          <p className="text-text-secondary text-sm">
            <code>histogram</code> — availability bars; in-range bars are brand-colored.
          </p>
          <Slider
            min={0}
            max={1000}
            step={10}
            value={dsHistoRange}
            onChange={setDsHistoRange}
            histogram={[
              2, 4, 7, 12, 18, 22, 28, 24, 19, 14, 16, 11, 8, 6, 9, 5, 4, 3, 2, 3, 1, 2, 1, 1, 0, 1,
              0, 1,
            ]}
            formatBarTooltip={(count, lo, hi) =>
              `${count} deals · ${formatShekelFloat(Math.round(lo))}–${formatShekelFloat(Math.round(hi))}`
            }
            showRangeInput
            aria-label="Price range with histogram"
          />
        </div>
      </ComponentEntry>
      {/* LaunchModePicker */}
      <ComponentEntry
        name="LaunchModePicker"
        id="launchmodepicker-primitive"
        path="src/components/ui/primitives/LaunchModePicker"
        description="Two-option segmented toggle for deal launch mode: 'Launch now' vs 'Scheduled launch'. Thin wrapper over SegmentedControl — inherits all keyboard/RTL/a11y behaviour. Used in the vendor deal creation form above the DealDurationPicker."
        tokens={[
          'color-surface-inset',
          'color-surface-base',
          'color-border-default',
          'color-text-primary',
          'color-text-secondary',
          'radius-md',
          'font-size-sm',
          'shadow-sm',
        ]}
        a11yNotes={[
          'role="radiogroup" + aria-label on the container (required prop)',
          'Each option: role="radio" + aria-checked',
          'Roving tabIndex — Tab reaches the selected option; Arrow keys cycle',
          'RTL-aware: Arrow direction reverses in RTL locale',
          'Focus ring always visible (focus-visible:outline)',
          'IS 5568 / WCAG 2.1 AA compliant via SegmentedControl base',
        ]}
        importSnippet={`import { LaunchModePicker } from '@/components/ui/primitives/LaunchModePicker';`}
      >
        <Stack gap="4">
          <p className="text-text-secondary text-sm font-medium">Launch now (default)</p>
          <LaunchModePicker
            value={launchModeValue}
            onChange={setLaunchModeValue}
            nowLabel="התחל מיד"
            scheduledLabel="התחלה מתוזמנת"
            ariaLabel="מועד פתיחת הדיל"
          />
          <p className="text-text-secondary text-sm font-medium">English / LTR</p>
          <LaunchModePicker
            value={launchModeValue}
            onChange={setLaunchModeValue}
            nowLabel="Launch now"
            scheduledLabel="Scheduled launch"
            ariaLabel="Deal launch mode"
          />
          <p className="text-text-secondary text-sm font-medium">
            Selected: <span className="font-mono">{launchModeValue}</span>
          </p>
        </Stack>
      </ComponentEntry>
      {/* PaginationLinks */}
      <ComponentEntry
        name="PaginationLinks"
        id="paginationlinks-primitive"
        path="src/components/ui/primitives/PaginationLinks/PaginationLinks.astro"
        description="SSR-only `<a>`-based numbered pagination. Sibling of the callback-based Pagination.tsx React component. Renders Prev / page numbers (with ellipsis collapse) / Next as plain `<a>` anchors — zero client JS required. Used in DealsBrowser for /deals/all."
        tokens={[
          'color-surface-base',
          'color-surface-inset',
          'color-border-default',
          'color-border-subtle',
          'color-text-primary',
          'color-text-muted',
          'color-brand-primary-500',
          'color-text-on-brand',
        ]}
        a11yNotes={[
          '`<nav aria-label={ariaLabel}>` wraps the entire control',
          'Current page: `aria-current="page"` on active span',
          'Disabled Prev/Next: rendered as `<span aria-hidden>` (not focusable)',
          'Active Prev/Next `<a>` carry `aria-label` prop for screen-reader clarity',
          '`rel="prev"` / `rel="next"` on adjacent page links for browser preload hints',
          'Ellipsis `<span aria-hidden>` — decorative, skipped by screen readers',
          'RTL: Prev/Next icons swap via `dir` prop (ChevronRight ↔ ChevronLeft)',
          'Focus rings always visible (focus-visible:outline-brand-primary-500)',
        ]}
        importSnippet={`// Astro SSR component — import in .astro files only
---
import PaginationLinks from '@/components/ui/primitives/PaginationLinks/PaginationLinks.astro';
---
<PaginationLinks
  page={currentPage}
  totalPages={totalPages}
  buildHref={(p) => \`/deals/all?page=\${p}\`}
  ariaLabel="ניווט בין עמודים"
  prevLabel="הקודם"
  nextLabel="הבא"
  dir="rtl"
/>`}
      >
        {/* Static JSX mirror — Astro component cannot be imported in React islands */}
        <nav
          aria-label="ניווט בין עמודים (preview)"
          className="flex items-center justify-center gap-1 py-4"
        >
          <span
            className="border-border-subtle text-text-muted inline-flex h-9 items-center gap-1 rounded-md border px-3 text-sm"
            aria-hidden="true"
          >
            ‹ <span className="hidden sm:inline">הקודם</span>
          </span>
          {[1, 2, 3, '…', 10, 11, 12].map((p, i) =>
            p === '…' ? (
              <span
                key={i}
                className="text-text-muted inline-flex h-9 w-9 items-center justify-center text-sm"
                aria-hidden="true"
              >
                …
              </span>
            ) : p === 5 ? (
              <span
                key={i}
                className="bg-brand-primary-500 text-text-on-brand inline-flex h-9 min-w-9 items-center justify-center rounded-md px-3 text-sm font-semibold"
                aria-current="page"
              >
                {p}
              </span>
            ) : (
              <a
                key={i}
                href={`?page=${String(p)}`}
                className="border-border-default text-text-primary hover:bg-surface-inset focus-visible:outline-brand-primary-500 inline-flex h-9 min-w-9 items-center justify-center rounded-md border px-3 text-sm font-medium focus-visible:outline-2"
              >
                {p}
              </a>
            ),
          )}
          <a
            href="?page=6"
            aria-label="הבא"
            rel="next"
            className="border-border-default text-text-primary hover:bg-surface-inset focus-visible:outline-brand-primary-500 inline-flex h-9 items-center gap-1 rounded-md border px-3 text-sm font-medium focus-visible:outline-2"
          >
            <span className="hidden sm:inline">הבא</span> ›
          </a>
        </nav>
      </ComponentEntry>

      {/* Table */}
      <ComponentEntry
        name="Table"
        id="table-primitive"
        path="src/components/ui/primitives/Table"
        description="Compound table primitive with horizontal-scroll wrapper and token-driven borders/typography. Replaces all raw `<table>` markup. Subcomponents: Table.Head, Table.Body, Table.Row, Table.HeadCell, Table.Cell."
        tokens={['color-border-default', 'color-text-muted', 'color-text-primary']}
        a11yNotes={[
          'Header cells render as `<th scope="col">` for screen-reader column association',
          'Logical `text-start` alignment — flips correctly under RTL',
          'Wrapper `overflow-x-auto` keeps wide tables reachable without breaking page layout',
        ]}
        importSnippet={`import { Table } from '@/components/ui/primitives/Table';

<Table>
  <Table.Head>
    <Table.Row>
      <Table.HeadCell>שם</Table.HeadCell>
      <Table.HeadCell>סטטוס</Table.HeadCell>
    </Table.Row>
  </Table.Head>
  <Table.Body>
    <Table.Row>
      <Table.Cell>דיל א׳</Table.Cell>
      <Table.Cell>פעיל</Table.Cell>
    </Table.Row>
  </Table.Body>
</Table>`}
      >
        <Table>
          <Table.Head>
            <Table.Row>
              <Table.HeadCell>שם</Table.HeadCell>
              <Table.HeadCell>סטטוס</Table.HeadCell>
              <Table.HeadCell>כמות</Table.HeadCell>
            </Table.Row>
          </Table.Head>
          <Table.Body>
            <Table.Row>
              <Table.Cell>דיל א׳</Table.Cell>
              <Table.Cell>פעיל</Table.Cell>
              <Table.Cell>12</Table.Cell>
            </Table.Row>
            <Table.Row>
              <Table.Cell>דיל ב׳</Table.Cell>
              <Table.Cell>טיוטה</Table.Cell>
              <Table.Cell>0</Table.Cell>
            </Table.Row>
          </Table.Body>
        </Table>
      </ComponentEntry>
    </SectionShell>
  );
}
