import { useLanguage, AppLanguage } from "@/context/LanguageContext";
import { useEffect, useRef, useState } from "react";
import { ChevronDown, Check } from "lucide-react";

/**
 * SVG flags used by the switcher. Inline so no extra network request
 * is needed and they render crisply at any size.
 */
function FlagUK({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 60 30" className={className} aria-hidden="true">
      <clipPath id="ls-uk-clip">
        <path d="M0,0 v30 h60 v-30 z" />
      </clipPath>
      <clipPath id="ls-uk-clip2">
        <path d="M30,15 h30 v15 z v15 h-30 z h-30 v-15 z v-15 h30 z" />
      </clipPath>
      <g clipPath="url(#ls-uk-clip)">
        <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(#ls-uk-clip2)"
          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 FlagSA({ className }: { className?: string }) {
  // Simplified Saudi Arabia flag (green with white strip — stylized).
  return (
    <svg viewBox="0 0 60 30" className={className} aria-hidden="true">
      <rect width="60" height="30" fill="#006C35" />
      <g fill="#fff">
        {/* Stylized shahada line */}
        <rect x="8" y="9" width="44" height="2" rx="1" />
        {/* Stylized sword */}
        <path d="M8,20 L52,20 L50,22 L10,22 Z" />
        <circle cx="9" cy="21" r="1.4" />
      </g>
    </svg>
  );
}

interface LangOption {
  code: AppLanguage;
  label: string;
  short: string;
  Flag: (props: { className?: string }) => JSX.Element;
}

const OPTIONS: LangOption[] = [
  { code: "en", label: "English", short: "EN", Flag: FlagUK },
  { code: "ar", label: "العربية", short: "AR", Flag: FlagSA },
];

/**
 * Desktop / tablet language switcher — a compact pill button with a
 * flag + short code that opens a small dropdown of options.
 *
 * The `transparent` prop lets the button adapt to the transparent
 * homepage header (white text on hero) vs. the normal solid header
 * (dark text on white).
 */
export function LanguageSwitcher({ transparent = false }: { transparent?: boolean }) {
  const { lang, setLang } = useLanguage();
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement | null>(null);

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

  const current = OPTIONS.find((o) => o.code === lang) ?? OPTIONS[0];
  const CurrentFlag = current.Flag;

  const btnClass = transparent
    ? "text-white border-white/40 hover:border-white hover:bg-white/10"
    : "text-slate-800 border-slate-300 hover:border-[#0b6e3e] hover:text-[#0b6e3e] bg-white";

  return (
    <div className="relative" ref={rootRef}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label="Change language"
        className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1.5 text-xs font-semibold transition ${btnClass}`}
      >
        <CurrentFlag className="w-5 h-[14px] rounded-[2px] ring-1 ring-black/10 shrink-0" />
        <span className="tracking-wide">{current.short}</span>
        <ChevronDown
          className={`w-3.5 h-3.5 transition-transform ${open ? "rotate-180" : ""}`}
        />
      </button>

      {open && (
        <ul
          role="listbox"
          className="absolute top-full mt-2 ltr:right-0 rtl:left-0 min-w-[170px] bg-white rounded-xl shadow-[0_20px_48px_-16px_rgba(15,23,41,0.24)] ring-1 ring-slate-900/5 border border-slate-100 py-1 z-50"
        >
          {OPTIONS.map((opt) => {
            const Flag = opt.Flag;
            const active = opt.code === lang;
            return (
              <li key={opt.code} role="option" aria-selected={active}>
                <button
                  type="button"
                  onClick={() => {
                    setLang(opt.code);
                    setOpen(false);
                  }}
                  className={`w-full flex items-center gap-2.5 px-3 py-2 text-sm transition ${
                    active
                      ? "bg-emerald-50 text-[#0b6e3e]"
                      : "text-slate-700 hover:bg-slate-50"
                  }`}
                >
                  <Flag className="w-6 h-[16px] rounded-[2px] ring-1 ring-black/10 shrink-0" />
                  <span className="flex-1 text-start font-medium">
                    {opt.label}
                  </span>
                  {active && <Check className="w-4 h-4 text-[#0b6e3e]" />}
                </button>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

/**
 * Inline language switcher used inside the mobile drawer.
 * Renders both options side-by-side as segmented buttons.
 */
export function InlineLanguageSwitcher() {
  const { lang, setLang } = useLanguage();
  return (
    <div className="flex items-center gap-2 bg-slate-100 rounded-full p-1">
      {OPTIONS.map((opt) => {
        const Flag = opt.Flag;
        const active = opt.code === lang;
        return (
          <button
            key={opt.code}
            type="button"
            onClick={() => setLang(opt.code)}
            className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition ${
              active
                ? "bg-white text-[#0b6e3e] shadow"
                : "text-slate-600 hover:text-slate-900"
            }`}
            aria-pressed={active}
          >
            <Flag className="w-5 h-[14px] rounded-[2px] ring-1 ring-black/10" />
            <span>{opt.short}</span>
          </button>
        );
      })}
    </div>
  );
}