/**
 * Generate the contents of `themes.generated.css` from the project's
 * themes config. Emits only the Tailwind scaffolding needed at compile
 * time — the `@custom-variant dark (…)` selector list — so the `dark:`
 * utility variant is aware of every configured surface attribute
 * (`data-sb-<surface>-theme`) and the legacy `<html>` attribute set.
 *
 * No CSS-variable values are emitted here. Components own their own
 * variable mappings in tailwind.css / core-ui-colors.css / per-component CSS.
 *
 * Theme ids whose key starts with "dark" trip the variant via prefix match
 * (`[data-sb-…-theme^="dark"]`), so new dark variants like "dark_midnight"
 * just work without changing this rule.
 *
 * This module is consumed by:
 *   - packages/storyboard/src/internals/vite/data-plugin.js — writes the
 *     file on dev boot and on storyboard.config.json changes.
 *   - packages/storyboard/scripts/gen-themes-css.mjs — pre-step for the
 *     standalone `tailwindcss` CLI invoked by `build:css`.
 */

export const GENERATED_THEMES_CSS_FILENAME = 'themes.generated.css'

export const GENERATED_BANNER =
  '/* Auto-generated by @dfosco/storyboard data plugin — do not edit. */'

const LEGACY_SURFACE_ATTRS = [
  'data-sb-toolbar-theme',
  'data-sb-code-theme',
  'data-sb-canvas-theme',
]

export function generateThemesCss(themesCfg) {
  const surfaces = Object.keys(themesCfg?.surfaces || {})
  const selectors = ['[data-sb-theme^="dark"]', '[data-sb-theme^="dark"] *']

  for (const id of surfaces) {
    const attr = `data-sb-${id.toLowerCase()}-theme`
    if (!selectors.includes(`[${attr}^="dark"]`)) {
      selectors.push(`[${attr}^="dark"]`, `[${attr}^="dark"] *`)
    }
  }

  // Legacy <html> attrs — kept in the selector list even when the
  // corresponding surface is removed from config so existing CSS that
  // selects on the legacy attribute names continues to participate in
  // the `dark:` variant.
  for (const attr of LEGACY_SURFACE_ATTRS) {
    if (!selectors.includes(`[${attr}^="dark"]`)) {
      selectors.push(`[${attr}^="dark"]`, `[${attr}^="dark"] *`)
    }
  }

  return [
    GENERATED_BANNER,
    '@custom-variant dark (',
    '  &:where(',
    '    ' + selectors.join(',\n    '),
    '  )',
    ');',
    '',
  ].join('\n')
}
