import type { EffectiveTokens } from './types'
import { cssVarFor } from './css-var'

/** Apply resolved tokens to an element as inline custom properties + data attributes. Idempotent. */
export function applyTheme(
  el: HTMLElement,
  tokens: EffectiveTokens,
  themeId: string,
  mode: 'light' | 'dark',
): void {
  el.dataset.theme = themeId
  el.dataset.mode = mode
  el.style.colorScheme = mode
  for (const [key, value] of Object.entries(tokens)) {
    el.style.setProperty(cssVarFor(key), value)
  }
}

/**
 * THE single owner of the `(prefers-color-scheme: dark)` media-query listener.
 * Returns an unsubscribe fn. No-ops + returns a noop unsubscribe under SSR (no matchMedia).
 */
export function subscribeToSystemMode(cb: (prefersDark: boolean) => void): () => void {
  if (typeof globalThis.matchMedia !== 'function') return () => {}
  const mql = globalThis.matchMedia('(prefers-color-scheme: dark)')
  const handler = (e: MediaQueryListEvent | { matches: boolean }) => cb(e.matches)
  mql.addEventListener('change', handler as (e: MediaQueryListEvent) => void)
  return () => mql.removeEventListener('change', handler as (e: MediaQueryListEvent) => void)
}
