/**
 * Font stacks + Google Fonts on-demand loader for the theme engine.
 *
 * @countermeasure-platform/web-components/services/theme-engine
 */

import type { FontId, FontStack } from './types'

export const FONT_STACKS: Record<FontId, FontStack> = {
  inter: {
    id: 'inter',
    label: 'Inter',
    sample: 'Aa Bb Cc 123',
    description: 'Default — neutral, professional',
    display: "'Inter', system-ui, -apple-system, sans-serif",
    mono: "'IBM Plex Mono', ui-monospace, 'SF Mono', Menlo, monospace",
    google: 'Inter:wght@400;500;600;700|IBM+Plex+Mono:wght@400;500;600',
  },
  sora: {
    id: 'sora',
    label: 'Sora',
    sample: 'Aa Bb Cc 123',
    description: 'Geometric, modern',
    display: "'Sora', system-ui, sans-serif",
    mono: "'JetBrains Mono', ui-monospace, monospace",
    google: 'Sora:wght@400;500;600;700|JetBrains+Mono:wght@400;500;600',
  },
  roboto: {
    id: 'roboto',
    label: 'Roboto',
    sample: 'Aa Bb Cc 123',
    description: 'Friendly, classic web',
    display: "'Roboto', system-ui, sans-serif",
    mono: "'Roboto Mono', ui-monospace, monospace",
    google: 'Roboto:wght@400;500;700|Roboto+Mono:wght@400;500;600',
  },
  jetbrainsMono: {
    id: 'jetbrainsMono',
    label: 'JetBrains Mono',
    sample: 'Aa Bb Cc 123',
    description: 'Mono everywhere — IDE feel',
    display: "'JetBrains Mono', ui-monospace, monospace",
    mono: "'JetBrains Mono', ui-monospace, monospace",
    google: 'JetBrains+Mono:wght@400;500;600;700',
  },
  system: {
    id: 'system',
    label: 'System',
    sample: 'Aa Bb Cc 123',
    description: 'Use OS native fonts',
    display: 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
    mono: 'ui-monospace, "SF Mono", Menlo, monospace',
    google: null,
  },
}

/**
 * Idempotent injector for a Google Fonts `<link>` tag. Safe to call repeatedly
 * with the same `spec` — returns early if a `<link id="cm-gfont-${spec}">`
 * already exists. Returns early in non-DOM environments (SSR-safe).
 */
export function ensureGoogleFont(spec: string | null): void {
  if (!spec) return
  if (typeof document === 'undefined') return
  const id = `cm-gfont-${spec}`
  if (document.getElementById(id)) return
  const link = document.createElement('link')
  link.id = id
  link.rel = 'stylesheet'
  link.href =
    'https://fonts.googleapis.com/css2?' +
    spec
      .split('|')
      .map(s => `family=${s}`)
      .join('&') +
    '&display=swap'
  document.head.appendChild(link)
}
