'use client'

import { ButtonArrow } from '@/components/icons/button-icon'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils/cn'
import { useChangeLocale, useCurrentLocale, useScopedI18n } from '@/locales/client'
import { AnimatePresence, motion } from 'framer-motion'
import { useEffect, useRef, useState } from 'react'



type Locale = 'en' | 'ru' | 'es'

// явно фиксированный список локалей
const LOCALES = ['en', 'ru', 'es'] as const
type LOCALES_T = typeof LOCALES
// элемент типа 'en' | 'ru' | 'es'
type LocaleFromList = LOCALES_T[number]

interface LanguageSwitcherProps {
  className?: string
}

export const LanguageSwitcher = ({ className }: LanguageSwitcherProps) => {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false)
  // приводим результат хука к нашему union-типу
  const locale = useCurrentLocale() as LocaleFromList
  const changeLocale = useChangeLocale()
  const t = useScopedI18n('language')

  const handleDropdownToggle = () => {
    setIsDropdownOpen(!isDropdownOpen)
  }

  // параметр явно типизирован
  const handleChangeLocale = (newLocale: LocaleFromList) => {
    changeLocale(newLocale)
    setIsDropdownOpen(false)
  }

  const wrapperRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
      function handleClickOutside(event: MouseEvent) {
        const target = event.target as Node
        if (
          isDropdownOpen &&
          wrapperRef.current &&
          !wrapperRef.current.contains(target)
        ) {
          setIsDropdownOpen(false)
        }
      }
      document.addEventListener('mousedown', handleClickOutside)
      return () => document.removeEventListener('mousedown', handleClickOutside)
    }, [isDropdownOpen])

  return (
    <div className={cn('relative', className)} ref={wrapperRef}>
      <Button
        className=""
        sizes="btn-sm"
        variant="tertiary"
        isRightIcon
        RightIcon={<ButtonArrow className="text-base-white rotate-90" width={10} height={12} />}
        onClick={handleDropdownToggle}
      >
        <div className="block leading-[10px] w-[68px]">
          {/* приводим к нужному типу */}
          {String(t(locale)).toUpperCase()}
        </div>
      </Button>

      <AnimatePresence>
      {isDropdownOpen && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="absolute text-base-white mt-[10px] top-full left-1/2 -translate-x-1/2 w-2/3 bg-transparent-white-20  shadow-md rounded-md overflow-hidden">
          <ul>
            {LOCALES.map((loc) => (
              <li key={loc}>
                <p
                  className="cursor-pointer block w-full px-4 py-2 text-center bg-transparent transition-all duration-300 ease-in-out hover:bg-grey-500 button-small-medium "
                  onClick={() => handleChangeLocale(loc)}
                >
                  {/* loc уже типизирован как 'en'|'ru'|'es' */}
                  {t(loc).toUpperCase()}
                </p>
              </li>
            ))}
          </ul>
        </motion.div>
      )}
      </AnimatePresence>
    </div>
  )
}
