"use client";

import { useEffect, useId, useRef, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Check, ChevronDown } from "lucide-react";
import { locales } from "@/i18n";

// Inline SVG flags so they render identically on every OS (emoji flags don't
// show on Windows). preserveAspectRatio="none" lets them fill the chip cleanly.
function FlagGB({ className }: { className?: string }) {
  const raw = useId().replace(/[^a-zA-Z0-9]/g, "");
  return (
    <svg
      viewBox="0 0 60 30"
      preserveAspectRatio="none"
      className={className}
      aria-hidden="true"
    >
      <clipPath id={`gb-s-${raw}`}>
        <path d="M0,0 v30 h60 v-30 z" />
      </clipPath>
      <clipPath id={`gb-t-${raw}`}>
        <path d="M30,15 h30 v15 z v15 h-30 z h-30 v-15 z v-15 h30 z" />
      </clipPath>
      <g clipPath={`url(#gb-s-${raw})`}>
        <path d="M0,0 v30 h60 v-30 z" fill="#012169" />
        <path d="M0,0 L60,30 M60,0 L0,30" stroke="#fff" strokeWidth="6" />
        <path
          d="M0,0 L60,30 M60,0 L0,30"
          clipPath={`url(#gb-t-${raw})`}
          stroke="#C8102E"
          strokeWidth="4"
        />
        <path d="M30,0 v30 M0,15 h60" stroke="#fff" strokeWidth="10" />
        <path d="M30,0 v30 M0,15 h60" stroke="#C8102E" strokeWidth="6" />
      </g>
    </svg>
  );
}

function FlagFR({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 3 2"
      preserveAspectRatio="none"
      className={className}
      aria-hidden="true"
    >
      <rect width="3" height="2" fill="#fff" />
      <rect width="1" height="2" fill="#0055A4" />
      <rect width="1" height="2" x="2" fill="#EF4135" />
    </svg>
  );
}

const META: Record<
  string,
  { label: string; Flag: (p: { className?: string }) => React.ReactElement }
> = {
  en: { label: "English", Flag: FlagGB },
  fr: { label: "Français", Flag: FlagFR },
};

export function LocaleSwitcher({ locale }: { locale: string }) {
  const pathname = usePathname() || `/${locale}/`;
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  // Close the menu on outside click or Escape.
  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("mousedown", onClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const swap = (l: string) => {
    const parts = pathname.split("/");
    if (parts.length > 1) parts[1] = l;
    let p = parts.join("/");
    if (!p.endsWith("/")) p += "/";
    return p;
  };

  const current = META[locale] ?? META.en;

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={current.label}
        className="flex items-center gap-2 rounded-sm border border-white/40 px-2.5 py-1.5 text-xs font-semibold uppercase tracking-wide text-white transition hover:bg-white/10"
      >
        <span className="h-3.5 w-5 overflow-hidden rounded-[2px] ring-1 ring-white/30">
          <current.Flag className="h-full w-full" />
        </span>
        <span>{locale}</span>
        <ChevronDown
          className={`size-3.5 transition-transform duration-200 ${
            open ? "rotate-180" : ""
          }`}
        />
      </button>

      {open && (
        <ul
          role="listbox"
          className="absolute right-0 z-50 mt-2 w-44 overflow-hidden rounded-md border border-line bg-white py-1 text-ink shadow-xl"
        >
          {locales.map((l) => {
            const m = META[l] ?? META.en;
            const active = l === locale;
            return (
              <li key={l}>
                <Link
                  href={swap(l)}
                  role="option"
                  aria-selected={active}
                  onClick={() => setOpen(false)}
                  className={`flex items-center gap-2.5 px-3 py-2 text-sm transition hover:bg-brand/5 ${
                    active ? "font-semibold text-brand" : "text-ink"
                  }`}
                >
                  <span className="h-4 w-6 shrink-0 overflow-hidden rounded-[2px] ring-1 ring-black/10">
                    <m.Flag className="h-full w-full" />
                  </span>
                  {m.label}
                  {active && <Check className="ml-auto size-4 text-brand" />}
                </Link>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}
