/**
 * Radius Slider — 0..20px slider that drives `radius` on the theme engine.
 *
 * The engine then derives `--radius-sm` (0.5×), `--radius-md` (1×),
 * `--radius-lg` (1.5×), `--radius-xl` (2×).
 */

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

const MIN = 0
const MAX = 20
const STEP = 1

export class RadiusSlider {
  public readonly el: HTMLElement
  private readonly input: HTMLInputElement
  private readonly value: HTMLSpanElement

  constructor() {
    const initial = clamp(getTheme().radius, MIN, MAX)

    this.el = document.createElement('div')
    this.el.className = 'preview-radius-slider'

    const head = document.createElement('div')
    head.className = 'preview-radius-slider__head'

    const label = document.createElement('span')
    label.className = 'preview-radius-slider__label'
    label.textContent = 'Corner radius'
    head.appendChild(label)

    this.value = document.createElement('span')
    this.value.className = 'preview-radius-slider__value'
    this.value.textContent = `${initial}px`
    head.appendChild(this.value)
    this.el.appendChild(head)

    this.input = document.createElement('input')
    this.input.type = 'range'
    this.input.min = String(MIN)
    this.input.max = String(MAX)
    this.input.step = String(STEP)
    this.input.value = String(initial)
    this.input.className = 'preview-radius-slider__input'
    this.input.setAttribute('aria-label', 'Corner radius (px)')
    this.el.appendChild(this.input)
    this.applySliderFill(initial)

    this.input.addEventListener('input', () => {
      const next = clamp(Number(this.input.value), MIN, MAX)
      setThemePartial({ radius: next })
    })

    document.addEventListener('cm:theme-change', () => {
      const r = clamp(getTheme().radius, MIN, MAX)
      if (Number(this.input.value) !== r) this.input.value = String(r)
      this.value.textContent = `${r}px`
      this.applySliderFill(r)
    })
  }

  private applySliderFill(level: number): void {
    const pct = ((level - MIN) / (MAX - MIN)) * 100
    this.input.style.setProperty('--slider-pct', `${pct}%`)
  }
}

function clamp(value: number, min: number, max: number): number {
  if (!Number.isFinite(value)) return min
  return Math.max(min, Math.min(max, value))
}
