/**
 * Density Switcher — three-state pill (compact / comfortable / cozy).
 * Drives `density` on the theme engine; the engine writes `--density-row`.
 *
 * Mirrors Theme.jsx density step: 32 / 36 / 42px row heights.
 */

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

const DENSITIES: ReadonlyArray<{ id: Density; label: string; px: number }> = [
  { id: 'compact', label: 'Compact', px: 32 },
  { id: 'comfortable', label: 'Comfortable', px: 36 },
  { id: 'cozy', label: 'Cozy', px: 42 },
]

export class DensitySwitcher {
  public readonly el: HTMLElement

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

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

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

    for (const d of DENSITIES) {
      const btn = document.createElement('button')
      btn.type = 'button'
      btn.className = 'preview-density-switcher__btn'
      btn.dataset.density = d.id
      btn.textContent = d.label
      btn.title = `${d.label} (${d.px}px)`
      btn.setAttribute('aria-label', `Use ${d.label} density`)
      btn.addEventListener('click', () => {
        setThemePartial({ density: d.id })
      })
      buttons.appendChild(btn)
    }

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

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