"use client";

import { useState } from "react";

const LANGUAGES = [
  { code: "en", label: "English", flag: "🇬🇧" },
  { code: "es", label: "Español", flag: "🇪🇸" },
  { code: "de", label: "Deutsch", flag: "🇩🇪" },
  { code: "fr", label: "Français", flag: "🇫🇷" },
];

export default function LanguageSwitcher() {
  const [open, setOpen] = useState(false);
  const [current, setCurrent] = useState(() => {
    try {
      if (typeof document !== "undefined") {
        const match = document.cookie.match(/locale=(\w+)/);
        return match ? match[1] : "en";
      }
    } catch {
      // cookie reading failed
    }
    return "en";
  });

  async function switchLocale(code: string) {
    setCurrent(code);
    setOpen(false);
    try {
      await fetch("/api/locale", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ locale: code }),
      });
    } catch {
      // fetch failed — set cookie manually as fallback
      document.cookie = `locale=${code};path=/;max-age=${60 * 60 * 24 * 365}`;
    }
    window.location.reload();
  }

  const currentLang = LANGUAGES.find((l) => l.code === current) || LANGUAGES[0];

  return (
    <div className="relative">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1.5 text-text-muted hover:text-gold transition-colors text-sm"
      >
        <span>{currentLang.flag}</span>
        <span className="hidden sm:inline">{currentLang.code.toUpperCase()}</span>
        <svg className={`w-3 h-3 transition-transform ${open ? "rotate-180" : ""}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {open && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
          <div className="absolute right-0 top-full mt-2 z-50 bg-surface border border-surface-light rounded-lg shadow-elevated py-1 min-w-[140px]">
            {LANGUAGES.map((lang) => (
              <button
                key={lang.code}
                onClick={() => switchLocale(lang.code)}
                className={`w-full text-left px-3 py-2 text-sm flex items-center gap-2 hover:bg-surface-light transition-colors ${
                  current === lang.code ? "text-gold" : "text-text-muted"
                }`}
              >
                <span>{lang.flag}</span>
                <span>{lang.label}</span>
                {current === lang.code && (
                  <svg className="w-4 h-4 ml-auto text-gold" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                  </svg>
                )}
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}
