'use client'

import { useEffect, useState } from 'react'
import { PUBLIC_SITE_LANGUAGE_COOKIE, type PublicSiteLanguage } from '@/lib/i18n'
import { SHARED_LANGUAGE_COOKIE, SHARED_LANGUAGE_KEY, writeScopedPreference } from '@/lib/preferences'

const labels: Record<PublicSiteLanguage, string> = {
  en: 'Language',
  fr: 'Langue',
  ar: 'اللغة',
}

export default function PublicLanguageSwitcher({
  currentLanguage,
}: {
  currentLanguage: PublicSiteLanguage
}) {
  const [language, setLanguage] = useState(currentLanguage)

  useEffect(() => {
    setLanguage(currentLanguage)
  }, [currentLanguage])

  useEffect(() => {
    document.documentElement.lang = language
    document.documentElement.dir = language === 'ar' ? 'rtl' : 'ltr'
    writeScopedPreference(SHARED_LANGUAGE_KEY, language, ['public-site-language'])
  }, [language])

  function handleChange(nextLanguage: PublicSiteLanguage) {
    setLanguage(nextLanguage)
    document.cookie = `${SHARED_LANGUAGE_COOKIE}=${nextLanguage}; path=/; max-age=31536000; samesite=lax`
    document.cookie = `${PUBLIC_SITE_LANGUAGE_COOKIE}=${nextLanguage}; path=/; max-age=31536000; samesite=lax`
    window.location.reload()
  }

  return (
    <div className="flex items-center gap-1 rounded-full border border-slate-200 bg-white px-2 py-1 shadow-sm">
      <span className="px-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">
        {labels[language]}
      </span>
      {(['en', 'fr', 'ar'] as PublicSiteLanguage[]).map((value) => {
        const active = value === language
        return (
          <button
            key={value}
            type="button"
            onClick={() => handleChange(value)}
            className={`rounded-full px-3 py-1.5 text-xs font-semibold transition ${
              active ? 'bg-slate-900 text-white' : 'text-slate-600 hover:bg-slate-100'
            }`}
          >
            {value.toUpperCase()}
          </button>
        )
      })}
    </div>
  )
}
