import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';

/**
 * UX-1 / CC.2 / CC.3 guard for the `--bl-*` → admin-OKLCH token bridge.
 *
 * Dark-mode parity is *inherited*: every bridged `--bl-*` token must resolve to
 * an admin shadcn `--*` var (or a `color-mix` of one), which already flips
 * between `:root` and `.dark`. This test pins that contract so a future edit
 * can't silently hardcode a one-mode literal (which would break `.dark` parity
 * and violate the zero-new-color-literals rule).
 */
const css = readFileSync(join(__dirname, '..', 'app', 'globals.css'), 'utf8');

// Isolate the UX-1 bridge block.
const bridge = css.slice(css.indexOf('@bytelyst/ui token bridge'));

const REQUIRED_MAPPINGS: Array<[string, string]> = [
  ['--bl-bg-canvas', 'var(--background)'],
  ['--bl-surface-card', 'var(--card)'],
  ['--bl-surface-muted', 'var(--muted)'],
  ['--bl-text-primary', 'var(--foreground)'],
  ['--bl-text-secondary', 'var(--muted-foreground)'],
  ['--bl-border', 'var(--border)'],
  ['--bl-input', 'var(--input)'],
  ['--bl-accent', 'var(--primary)'],
  ['--bl-accent-foreground', 'var(--primary-foreground)'],
  ['--bl-danger', 'var(--destructive)'],
  ['--bl-focus-ring', 'var(--ring)'],
];

describe('--bl-* token bridge (dark-mode parity)', () => {
  it.each(REQUIRED_MAPPINGS)(
    'maps %s to %s (an admin var that flips under .dark)',
    (token, target) => {
      const re = new RegExp(`${token}\\s*:\\s*${target.replace(/[()]/g, '\\$&')}\\s*;`);
      expect(re.test(bridge)).toBe(true);
    }
  );

  it('introduces no raw color literals in the bridge (only var()/color-mix tokens)', () => {
    // Strip CSS comments, then look for hex / oklch / hsl / rgb literals.
    const code = bridge.replace(/\/\*[\s\S]*?\*\//g, '');
    expect(/#[0-9a-fA-F]{3,8}\b/.test(code)).toBe(false);
    expect(/\boklch\(/.test(code)).toBe(false);
    expect(/\bhsl\(/.test(code)).toBe(false);
    expect(/\brgb\(/.test(code)).toBe(false);
  });

  it('every bridged --bl-* value references an admin var', () => {
    // Each `--bl-foo: <value>;` line inside the bridge must contain `var(--`.
    const declRe = /(--bl-[a-z0-9-]+)\s*:\s*([^;]+);/g;
    let m: RegExpExecArray | null;
    const offenders: string[] = [];
    while ((m = declRe.exec(bridge))) {
      if (!m[2].includes('var(--')) offenders.push(`${m[1]}: ${m[2].trim()}`);
    }
    expect(offenders).toEqual([]);
  });
});
