import { TOKEN_CONTRACT, TOKEN_NAMES } from '../tokens/contract';
import type { ThemeDefinition } from '../themes/types';

/** Generate a single [data-theme="id"] block */
export function generateThemeCSS(theme: ThemeDefinition): string {
  const vars = TOKEN_NAMES
    .map((name) => `  ${TOKEN_CONTRACT[name]}: ${theme.tokens[name]};`)
    .join('\n');
  const colorScheme = theme.meta.appearance === 'dark' ? 'dark' : 'light';
  return `[data-theme="${theme.meta.id}"] {\n  color-scheme: ${colorScheme};\n${vars}\n}`;
}

/** Generate the full CSS for all themes.
 *  The first theme is merged with :root to avoid duplication. */
export function generateAllThemesCSS(themes: ThemeDefinition[]): string {
  if (themes.length === 0) return '';

  const defaultTheme = themes[0];
  const defaultVars = TOKEN_NAMES
    .map((name) => `  ${TOKEN_CONTRACT[name]}: ${defaultTheme.tokens[name]};`)
    .join('\n');
  const colorScheme = defaultTheme.meta.appearance === 'dark' ? 'dark' : 'light';
  const rootCSS = `:root, [data-theme="${defaultTheme.meta.id}"] {\n  color-scheme: ${colorScheme};\n${defaultVars}\n}`;

  const restCSS = themes.slice(1).map(generateThemeCSS).join('\n\n');
  return `/* Generated by theme system — do not edit manually */\n\n${rootCSS}\n\n${restCSS}\n`;
}
