'use client'

import { useEffect, useState } from 'react'
import type { PublicSiteLanguage } from '@/lib/i18n'

type Theme = 'light' | 'dark'

const labels: Record<PublicSiteLanguage, { theme: string; light: string; dark: string }> = {
  en: { theme: 'Theme', light: 'Light', dark: 'Dark' },
  fr: { theme: 'Mode', light: 'Clair', dark: 'Sombre' },
  ar: { theme: 'الوضع', light: 'فاتح', dark: 'داكن' },
}

export default function PublicThemeSwitcher({
  currentLanguage,
}: {
  currentLanguage: PublicSiteLanguage
}) {
  const [theme, setTheme] = useState<Theme>('light')

  useEffect(() => {
    const storedTheme = window.localStorage.getItem('public-site-theme')
    if (storedTheme === 'light' || storedTheme === 'dark') {
      setTheme(storedTheme)
      return
    }

    if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
      setTheme('dark')
    }
  }, [])

  useEffect(() => {
    document.documentElement.classList.remove('light', 'dark')
    document.documentElement.classList.add(theme)
    document.documentElement.style.colorScheme = theme
    document.body.dataset.theme = theme
    window.localStorage.setItem('public-site-theme', theme)
  }, [theme])

  const copy = labels[currentLanguage]

  return (
    <div className="flex items-center gap-1 rounded-full border border-slate-200 bg-white px-2 py-1 shadow-sm transition-colors dark:border-slate-700 dark:bg-slate-900">
      <span className="px-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500 dark:text-slate-400">
        {copy.theme}
      </span>
      {(['light', 'dark'] as Theme[]).map((value) => {
        const active = value === theme
        return (
          <button
            key={value}
            type="button"
            onClick={() => setTheme(value)}
            className={`rounded-full px-3 py-1.5 text-xs font-semibold transition ${
              active
                ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-950'
                : 'text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800'
            }`}
          >
            {value === 'light' ? copy.light : copy.dark}
          </button>
        )
      })}
    </div>
  )
}
