'use client';

import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Check, Globe } from 'lucide-react';
import { locales, localeLabel, type Locale } from '@/i18n/config';

// Language switcher dropdown. Keeps the current path when switching locale
// (e.g. /fr/products -> /ar/products).

export function LanguageSwitcher({ locale }: { locale: Locale }) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const pathname = usePathname();
  const rest = pathname?.split('/').slice(2).join('/') ?? '';

  useEffect(() => {
    function onDocClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener('mousedown', onDocClick);
    return () => document.removeEventListener('mousedown', onDocClick);
  }, []);

  return (
    <div ref={ref} className="relative text-sm">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="listbox"
        aria-expanded={open}
        className="flex items-center gap-1.5 rounded-full border border-graphite-800/20 px-3 py-1.5 font-medium text-graphite-900 hover:bg-graphite-900/5"
      >
        <Globe className="h-4 w-4" aria-hidden="true" />
        {localeLabel[locale]}
      </button>

      {open && (
        <div
          role="listbox"
          className="absolute right-0 top-full z-50 mt-2 w-40 rounded-xl border border-graphite-800/10 bg-white p-1 shadow-lg"
        >
          {locales.map((l) => (
            <Link
              key={l}
              href={`/${l}/${rest}`}
              role="option"
              aria-selected={l === locale}
              onClick={() => setOpen(false)}
              className="flex items-center justify-between rounded-lg px-3 py-2 text-graphite-900 hover:bg-graphite-900/5"
            >
              {localeLabel[l]}
              {l === locale && <Check className="h-4 w-4 text-copper-600" aria-hidden="true" />}
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}