"use client";

import { useState, useRef, useEffect } from "react";
import { LOCALE_LABELS, SUPPORTED_LOCALES } from "@/lib/constants/locales";
import { useLocale } from "@/hooks/useLocale";

const LOCALE_CODES: Record<string, string> = {
  en: "EN",
  gu: "GU",
  hi: "HI",
  ar: "AR",
};

export function LocaleSwitcher() {
  const { locale } = useLocale();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

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

  function switchLocale(newLocale: string) {
    document.cookie = `NEXT_LOCALE=${newLocale};path=/;max-age=31536000`;
    setOpen(false);
    window.location.reload();
  }

  return (
    <div className="locale-switcher" ref={ref}>
      <button
        className="locale-btn"
        onClick={() => setOpen((v) => !v)}
        aria-haspopup="listbox"
        aria-expanded={open}
      >
        <svg viewBox="0 0 24 24">
          <circle cx="12" cy="12" r="10" />
          <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
          <path d="M2 12h20" />
        </svg>
        <span>{LOCALE_CODES[locale] ?? locale.toUpperCase()}</span>
        <svg
          className="locale-chev"
          viewBox="0 0 24 24"
          style={open ? { transform: "rotate(180deg)" } : undefined}
        >
          <path d="M6 9l6 6 6-6" />
        </svg>
      </button>

      {open && (
        <div className="locale-dropdown" role="listbox">
          {SUPPORTED_LOCALES.map((loc) => (
            <button
              key={loc}
              role="option"
              aria-selected={locale === loc}
              className={`locale-option${locale === loc ? " active" : ""}`}
              onClick={() => switchLocale(loc)}
            >
              <span className="locale-name">{LOCALE_LABELS[loc]}</span>
              <span className="locale-code">{LOCALE_CODES[loc]}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
