import { useEffect, useState } from 'react'

export type ThemePreference = 'light' | 'dark' | 'system'

const OPTIONS: Array<{ pref: ThemePreference; icon: string; label: string }> = [
  { pref: 'light', icon: '☀', label: 'Light' },
  { pref: 'dark', icon: '◐', label: 'Dark' },
  { pref: 'system', icon: '⟳', label: 'System' },
]

export function ThemeToggle() {
  const [pref, setPref] = useState<ThemePreference>('dark')
  const [hydrated, setHydrated] = useState(false)

  useEffect(() => {
    setPref(window.overdeckTheme?.get() ?? 'dark')
    setHydrated(true)
  }, [])

  function choose(next: ThemePreference) {
    window.overdeckTheme?.set(next)
    setPref(next)
  }

  return (
    <div
      className="mt-auto flex gap-1.5 p-2.5"
      role="radiogroup"
      aria-label="Theme"
      data-hydrated={hydrated || undefined}
    >
      {OPTIONS.map(({ pref: p, icon, label }) => (
        <button
          key={p}
          type="button"
          role="radio"
          aria-checked={pref === p}
          onClick={() => choose(p)}
          className={
            'flex-1 rounded-md border px-0 py-1.5 text-xs ' +
            (pref === p
              ? 'border-border-strong bg-surface-raised text-fg'
              : 'border-border text-fg-muted')
          }
        >
          {icon} {label}
        </button>
      ))}
    </div>
  )
}
