/**
 * Theme Switcher — color mode chooser (light / dark / monokai / glass).
 *
 * Reads/writes through the theme engine so preset selections, slider changes,
 * etc. all stay in lock-step. Listens to `cm:theme-change` to refresh its
 * pressed state.
 */

import { getThemeLabel } from '../../ui'
import type { ResolvedTheme } from '../../ui'

import { COLOR_MODES, getTheme, setThemePartial } from '../../services/theme-engine'
import type { ColorMode } from '../../services/theme-engine'

const THEMES: ResolvedTheme[] = ['light', 'dark', 'monokai', 'glass']

export class ThemeSwitcher {
  public readonly el: HTMLElement

  constructor() {
    this.el = document.createElement('div')
    this.el.className = 'preview-theme-switcher'

    const label = document.createElement('span')
    label.className = 'preview-theme-switcher__label'
    label.textContent = 'Theme'
    this.el.appendChild(label)

    const buttons = document.createElement('div')
    buttons.className = 'preview-theme-switcher__buttons'

    for (const theme of THEMES) {
      const meta = COLOR_MODES[theme as ColorMode]
      const btn = document.createElement('button')
      btn.type = 'button'
      btn.className = 'preview-theme-switcher__btn'
      btn.dataset.theme = theme
      btn.title = meta.label || getThemeLabel(theme)
      btn.setAttribute('aria-label', `Switch to ${meta.label} theme`)

      const swatch = document.createElement('span')
      swatch.className = `preview-theme-swatch preview-theme-swatch--${theme}`
      btn.appendChild(swatch)

      btn.addEventListener('click', () => {
        setThemePartial({ mode: theme as ColorMode })
      })

      buttons.appendChild(btn)
    }

    this.el.appendChild(buttons)
    document.addEventListener('cm:theme-change', () => this.updateActive())
    this.updateActive()
  }

  private updateActive(): void {
    const current = getTheme().mode
    const buttons = this.el.querySelectorAll<HTMLButtonElement>('.preview-theme-switcher__btn')
    for (const btn of buttons) {
      const isActive = btn.dataset.theme === current
      btn.classList.toggle('preview-theme-switcher__btn--active', isActive)
      btn.setAttribute('aria-pressed', String(isActive))
    }
  }
}
