'use client';

/**
 * Tokens - section 1 of /design-system.
 *
 * Renders every Multideal design token with a visual sample, value, and the
 * variable name. The page itself does not hardcode any colors / sizes /
 * spacing / shadows - every cell uses CSS variables via Tailwind classes.
 */

import { useSyncExternalStore } from 'react';
import { Pill } from '@/components/ui/primitives/Pill';
import { Stack } from '@/components/ui/layout/Stack';
import { Grid } from '@/components/ui/layout/Grid';
import { useT } from '@/lib/i18n/react';
import { SectionShell } from '../../components/SectionShell';
import { contrastRatio, readToken } from '../../lib/contrast';

// ─── Token catalogs ─────────────────────────────────────────────────────────

const COLOR_RAMPS: { label: string; ramp: string; shades: number[] }[] = [
  {
    label: 'Brand primary (Blue)',
    ramp: 'brand-primary',
    shades: [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950],
  },
  {
    label: 'Vendor accent (Green)',
    ramp: 'mode-vendor',
    shades: [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950],
  },
  {
    label: 'Neutral',
    ramp: 'neutral',
    shades: [0, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950],
  },
  {
    label: 'Success',
    ramp: 'success',
    shades: [50, 500, 600, 700],
  },
  {
    label: 'Warning',
    ramp: 'warning',
    shades: [50, 500, 600, 700],
  },
  {
    label: 'Danger',
    ramp: 'danger',
    shades: [50, 500, 600, 700],
  },
  {
    label: 'Info',
    ramp: 'info',
    shades: [50, 500, 600, 700],
  },
];

const SEMANTIC_COLORS = [
  '--color-surface-base',
  '--color-surface-raised',
  '--color-surface-inset',
  '--color-text-primary',
  '--color-text-secondary',
  '--color-text-muted',
  '--color-text-link',
  '--color-text-on-brand',
  '--color-border-default',
  '--color-border-strong',
  '--color-border-focus-primary',
  '--color-border-focus-vendor',
  '--color-timer-neutral',
  '--color-timer-warm',
  '--color-timer-urgent',
];

const SPACING_TOKENS = [
  { name: '0', value: '0' },
  { name: 'px', value: '1px' },
  { name: '0_5', value: '0.125rem' },
  { name: '1', value: '0.25rem' },
  { name: '1_5', value: '0.375rem' },
  { name: '2', value: '0.5rem' },
  { name: '2_5', value: '0.625rem' },
  { name: '3', value: '0.75rem' },
  { name: '4', value: '1rem' },
  { name: '5', value: '1.25rem' },
  { name: '6', value: '1.5rem' },
  { name: '7', value: '1.75rem' },
  { name: '8', value: '2rem' },
  { name: '10', value: '2.5rem' },
  { name: '12', value: '3rem' },
  { name: '14', value: '3.5rem' },
  { name: '16', value: '4rem' },
  { name: '20', value: '5rem' },
  { name: '24', value: '6rem' },
  { name: '32', value: '8rem' },
];

const RADIUS_TOKENS = [
  { name: 'xs', value: '0.125rem' },
  { name: 'sm', value: '0.25rem' },
  { name: 'md', value: '0.5rem' },
  { name: 'lg', value: '0.75rem' },
  { name: 'xl', value: '1rem' },
  { name: '2xl', value: '1.5rem' },
  { name: '3xl', value: '2rem' },
  { name: 'full', value: 'var(--radius-full)' },
];

const FONT_SIZE_TOKENS = [
  { name: 'xs', sample: 'Aa גג' },
  { name: 'sm', sample: 'Aa גג' },
  { name: 'base', sample: 'Aa גג' },
  { name: 'md', sample: 'Aa גג' },
  { name: 'lg', sample: 'Aa גג' },
  { name: 'xl', sample: 'Aa גג' },
  { name: '2xl', sample: 'Aa גג' },
  { name: '3xl', sample: 'Aa גג' },
  { name: '4xl', sample: 'Aa גג' },
];

const FONT_SCALE_STATES: { label: string; scale: string }[] = [
  { label: 'S - 0.9×', scale: '0.9' },
  { label: 'M - 1×', scale: '1' },
  { label: 'L - 1.125×', scale: '1.125' },
  { label: 'XL - 1.25×', scale: '1.25' },
];

const SHADOW_TOKENS = ['none', 'sm', 'md', 'lg', 'xl'];

const MOTION_TOKENS = [
  { name: 'fast', value: '120ms' },
  { name: 'base', value: '200ms' },
  { name: 'slow', value: '320ms' },
  { name: 'slower', value: '500ms' },
];

const Z_INDEX_TOKENS = [
  { name: 'base', value: '0' },
  { name: 'raised', value: '1' },
  { name: 'dropdown', value: '1000' },
  { name: 'sticky', value: '1100' },
  { name: 'overlay', value: '1200' },
  { name: 'modal', value: '1300' },
  { name: 'popover', value: '1400' },
  { name: 'toast', value: '1500' },
  { name: 'a11y-trigger', value: '1600' },
];

// ─── Sub-components ────────────────────────────────────────────────────────

function ColorSwatch({ token }: { token: string }) {
  // CSS vars don't change at runtime; no subscription needed.
  // useSyncExternalStore provides a safe SSR snapshot ('') and client value.
  const resolved = useSyncExternalStore(
    () => () => {},
    () => readToken(token),
    () => '',
  );

  const ratioWhite = resolved ? contrastRatio(resolved, '#ffffff').toFixed(2) : '-';
  const ratioBlack = resolved ? contrastRatio(resolved, '#111111').toFixed(2) : '-';

  return (
    <div className="border-border-default flex flex-col gap-1 rounded-md border p-2">
      <div
        className="border-border-default h-[var(--spacing-12)] rounded-sm border"
        style={{ background: `var(${token})` }}
        aria-label={token}
      />
      <code className="text-text-primary text-xs">{token.replace('--color-', '')}</code>
      <span className="text-text-muted font-mono text-xs">{resolved || '-'}</span>
      <div className="text-text-muted flex justify-between text-xs">
        <span>vs #fff: {ratioWhite}</span>
        <span>vs #111: {ratioBlack}</span>
      </div>
    </div>
  );
}

function ColorRamp({ label, ramp, shades }: { label: string; ramp: string; shades: number[] }) {
  return (
    <div className="flex flex-col gap-2">
      <h4 className="text-text-primary text-sm font-bold">{label}</h4>
      <Grid cols={6} gap="2">
        {shades.map((shade) => (
          <ColorSwatch key={shade} token={`--color-${ramp}-${shade}`} />
        ))}
      </Grid>
    </div>
  );
}

function SpacingRow({ name, value }: { name: string; value: string }) {
  return (
    <div className="flex items-center gap-3">
      <code className="text-text-secondary w-24 text-xs">space-{name}</code>
      <code className="text-text-muted w-20 text-xs">{value}</code>
      <div
        className="bg-brand-primary-600 h-[var(--spacing-2)] rounded-xs"
        style={{ width: `var(--spacing-${name})` }}
        aria-hidden="true"
      />
    </div>
  );
}

function RadiusBox({ name, value }: { name: string; value: string }) {
  return (
    <div className="flex flex-col items-center gap-1">
      <div
        className="bg-brand-primary-100 border-border-strong h-[var(--spacing-12)] w-[var(--spacing-12)] border"
        style={{ borderRadius: `var(--radius-${name})` }}
        aria-hidden="true"
      />
      <code className="text-text-secondary text-xs">radius-{name}</code>
      <code className="text-text-muted text-xs">{value}</code>
    </div>
  );
}

function FontSizeRow({ name, sample }: { name: string; sample: string }) {
  return (
    <div className="flex items-baseline gap-4">
      <code className="text-text-secondary w-24 shrink-0 text-xs">font-size-{name}</code>
      <span className="text-text-primary" style={{ fontSize: `var(--font-size-${name})` }}>
        {sample}
      </span>
    </div>
  );
}

function FontScaleDemo({ scale, label }: { scale: string; label: string }) {
  return (
    <div className="border-border-default flex flex-col gap-2 rounded-md border p-3">
      <code className="text-text-secondary text-xs">{label}</code>
      <div style={{ ['--font-scale' as string]: scale }}>
        <p className="text-text-primary text-xs">xs · אבגד</p>
        <p className="text-text-primary text-base">base · אבגד</p>
        <p className="text-text-primary text-lg">lg · אבגד</p>
        <p className="text-text-primary text-2xl">2xl · אבגד</p>
      </div>
    </div>
  );
}

function ShadowBox({ name }: { name: string }) {
  return (
    <div className="flex flex-col items-center gap-2">
      <div
        className="bg-surface-base h-[var(--spacing-16)] w-[var(--spacing-16)] rounded-md"
        style={{ boxShadow: `var(--shadow-${name})` }}
        aria-hidden="true"
      />
      <code className="text-text-secondary text-xs">shadow-{name}</code>
    </div>
  );
}

function MotionBar({ name, value }: { name: string; value: string }) {
  return (
    <div className="flex items-center gap-3">
      <code className="text-text-secondary w-32 text-xs">duration-{name}</code>
      <code className="text-text-muted w-16 text-xs">{value}</code>
      <div
        className="bg-brand-primary-100 relative h-[var(--spacing-3)] flex-1 overflow-hidden rounded-full"
        aria-hidden="true"
      >
        <div
          className="bg-brand-primary-600 absolute inset-y-0 start-0 w-[40%]"
          style={{ transition: `transform var(--duration-${name}) var(--ease-emphasized)` }}
        />
      </div>
    </div>
  );
}

function ZIndexRow({ name, value }: { name: string; value: string }) {
  return (
    <div className="flex items-center gap-3">
      <code className="text-text-secondary w-40 text-xs">z-{name}</code>
      <code className="text-text-muted text-xs">{value}</code>
    </div>
  );
}

// ─── Section ────────────────────────────────────────────────────────────────

export function Tokens() {
  const t = useT('design_system');

  return (
    <SectionShell id="tokens" title={t('sidebar_tokens')} description={t('section_intro')}>
      {/* Color ramps */}
      <Stack gap="6">
        <h3 className="text-text-primary text-xl font-bold">Colors - ramps</h3>
        {COLOR_RAMPS.map((r) => (
          <ColorRamp key={r.ramp} {...r} />
        ))}

        <h3 className="text-text-primary text-xl font-bold">Colors - semantic</h3>
        <Grid cols={4} gap="2">
          {SEMANTIC_COLORS.map((token) => (
            <ColorSwatch key={token} token={token} />
          ))}
        </Grid>

        {/* Spacing */}
        <h3 className="text-text-primary text-xl font-bold">Spacing</h3>
        <Stack gap="2">
          {SPACING_TOKENS.map((s) => (
            <SpacingRow key={s.name} {...s} />
          ))}
        </Stack>

        {/* Radii */}
        <h3 className="text-text-primary text-xl font-bold">Radii</h3>
        <Grid cols={4} gap="3">
          {RADIUS_TOKENS.map((r) => (
            <RadiusBox key={r.name} {...r} />
          ))}
        </Grid>

        {/* Font sizes */}
        <h3 className="text-text-primary text-xl font-bold">Font sizes</h3>
        <Stack gap="2">
          {FONT_SIZE_TOKENS.map((f) => (
            <FontSizeRow key={f.name} {...f} />
          ))}
        </Stack>

        {/* Font scale states */}
        <h3 className="text-text-primary text-xl font-bold">Font scale states (a11y trigger)</h3>
        <Grid cols={2} gap="3">
          {FONT_SCALE_STATES.map((s) => (
            <FontScaleDemo key={s.scale} {...s} />
          ))}
        </Grid>

        {/* Shadows */}
        <h3 className="text-text-primary text-xl font-bold">Shadows</h3>
        <Grid cols={5} gap="4">
          {SHADOW_TOKENS.map((s) => (
            <ShadowBox key={s} name={s} />
          ))}
        </Grid>

        {/* Motion */}
        <h3 className="text-text-primary text-xl font-bold">Motion</h3>
        <Stack gap="2">
          {MOTION_TOKENS.map((m) => (
            <MotionBar key={m.name} {...m} />
          ))}
        </Stack>

        {/* Z-index */}
        <h3 className="text-text-primary text-xl font-bold">Z-index</h3>
        <Stack gap="1">
          {Z_INDEX_TOKENS.map((z) => (
            <ZIndexRow key={z.name} {...z} />
          ))}
        </Stack>
      </Stack>

      <p className="text-text-muted text-xs">
        <Pill tone="neutral" size="sm">
          tokens.css
        </Pill>{' '}
        is the only file that may hold raw values. Every other file references these via Tailwind
        token classes or <code>var(--*)</code>.
      </p>
    </SectionShell>
  );
}
