"use client";

import { useState, useRef, useEffect } from "react";
import { ChevronDown, Globe, Check } from "lucide-react";
import { useTranslations } from "next-intl";
import { useCountry } from "@/src/contexts/CountryContext";

function flag(code: string) {
  return code.toUpperCase().replace(/./g, (c) =>
    String.fromCodePoint(c.charCodeAt(0) + 127397)
  );
}

const NAVY = "#1e1b4b";

export function CountrySelector() {
  const { availableCountries, selectedCountry, setSelectedCountry, isOwner } = useCountry();
  const t = useTranslations("country_selector");
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

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

  if (availableCountries.length === 0) return null;

  const showAll = availableCountries.length > 1 || isOwner;
  const label = selectedCountry
    ? `${flag(selectedCountry.country_code)} ${selectedCountry.country_name}`
    : `🌍 ${t("all_countries")}`;

  return (
    <div ref={ref} className="relative">
      {/* Trigger */}
      <button
        onClick={() => setOpen((v) => !v)}
        className="inline-flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition"
        style={{
          background: selectedCountry ? `${NAVY}10` : "rgba(15,23,42,.04)",
          border: `1px solid ${selectedCountry ? `${NAVY}28` : "rgba(15,23,42,.08)"}`,
          color: selectedCountry ? NAVY : "#475569",
          fontWeight: selectedCountry ? 600 : 500,
        }}
      >
        <span className="text-base leading-none">{selectedCountry ? flag(selectedCountry.country_code) : <Globe className="h-4 w-4 inline" />}</span>
        <span className="hidden sm:inline max-w-[120px] truncate">
          {selectedCountry ? selectedCountry.country_name : t("all_countries")}
        </span>
        <ChevronDown
          className="h-3.5 w-3.5 flex-shrink-0 transition-transform"
          style={{ transform: open ? "rotate(180deg)" : "" }}
        />
      </button>

      {/* Dropdown */}
      {open && (
        <div
          className="absolute top-full mt-2 right-0 z-50 bg-white rounded-2xl shadow-xl border border-slate-100 overflow-hidden"
          style={{ minWidth: "200px", maxHeight: "320px", overflowY: "auto" }}
        >
          {showAll && (
            <button
              onClick={() => { setSelectedCountry(null); setOpen(false); }}
              className="w-full flex items-center gap-3 px-4 py-3 text-sm text-left hover:bg-slate-50 transition border-b border-slate-100"
            >
              <span className="text-lg">🌍</span>
              <span className="flex-1 font-medium text-slate-700">{t("all_countries")}</span>
              {!selectedCountry && <Check className="h-4 w-4 text-indigo-600" />}
            </button>
          )}

          {availableCountries.map((c) => {
            const active = selectedCountry?.id === c.id;
            return (
              <button
                key={c.id}
                onClick={() => { setSelectedCountry(c); setOpen(false); }}
                className="w-full flex items-center gap-3 px-4 py-3 text-sm text-left hover:bg-slate-50 transition"
                style={active ? { background: `${NAVY}08` } : {}}
              >
                <span className="text-lg leading-none">{flag(c.country_code)}</span>
                <div className="flex-1 min-w-0">
                  <p className="font-medium text-slate-700 truncate">{c.country_name}</p>
                  {c.manager && (
                    <p className="text-xs text-slate-400 truncate">{c.manager.full_name}</p>
                  )}
                </div>
                {active && <Check className="h-4 w-4 text-indigo-600 flex-shrink-0" />}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}
