/**
 * Font Stack Picker — 5 typography tiles (Inter / Sora / Roboto / JetBrains Mono / System).
 *
 * Each tile renders the actual font, a sample line, and a one-line description.
 * Hovering preloads the Google Font so the click feels instant. Clicking
 * commits the selection to the theme engine.
 */

import {
  FONT_STACKS,
  ensureGoogleFont,
  getTheme,
  setThemePartial,
} from '../../services/theme-engine'
import type { FontId } from '../../services/theme-engine'

export class FontStackPicker {
  public readonly el: HTMLElement

  constructor() {
    this.el = document.createElement('div')
    this.el.className = 'theme-studio-fonts'
    this.render()
    document.addEventListener('cm:theme-change', () => this.updateActive())
  }

  private render(): void {
    this.el.innerHTML = ''
    const current = getTheme().font
    for (const id of Object.keys(FONT_STACKS) as FontId[]) {
      const stack = FONT_STACKS[id]
      const tile = document.createElement('button')
      tile.type = 'button'
      tile.className = 'theme-studio-font-tile'
      tile.dataset.font = id
      if (id === current) tile.classList.add('is-active')
      tile.setAttribute('aria-pressed', String(id === current))
      tile.setAttribute('aria-label', `Use ${stack.label} typeface`)
      tile.style.fontFamily = stack.display

      const name = document.createElement('div')
      name.className = 'theme-studio-font-tile__name'
      name.textContent = stack.label
      tile.appendChild(name)

      const sample = document.createElement('div')
      sample.className = 'theme-studio-font-tile__sample'
      sample.textContent = stack.sample
      tile.appendChild(sample)

      const desc = document.createElement('div')
      desc.className = 'theme-studio-font-tile__desc'
      desc.textContent = stack.description
      tile.appendChild(desc)

      tile.addEventListener('mouseenter', () => ensureGoogleFont(stack.google), { once: true })
      tile.addEventListener('focus', () => ensureGoogleFont(stack.google), { once: true })
      tile.addEventListener('click', () => setThemePartial({ font: id }))

      this.el.appendChild(tile)
    }
  }

  private updateActive(): void {
    const current = getTheme().font
    const tiles = this.el.querySelectorAll<HTMLButtonElement>('.theme-studio-font-tile')
    for (const tile of tiles) {
      const isActive = tile.dataset.font === current
      tile.classList.toggle('is-active', isActive)
      tile.setAttribute('aria-pressed', String(isActive))
    }
  }
}
