import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Check, Globe } from "lucide-react";
import { LANGUAGES, type LangCode } from "../i18n";

// Compact language picker (globe + current code). Presentational: the parent decides what
// changing the language does (set it; persist server-side when signed in).
//
// Two variants: "header" (legacy inline dropdown, opens below) and "rail" (used in the left
// nav's bottom icon cluster — an icon-only button whose menu is portaled to <body> and
// anchored to the right + above the button, escaping the nav's backdrop-filter which would
// otherwise trap an absolutely-positioned popover).
export default function LanguageSwitcher({
  value,
  onChange,
  align = "right",
  variant = "header",
}: {
  value: LangCode;
  onChange: (code: LangCode) => void;
  align?: "left" | "right";
  variant?: "header" | "rail";
}) {
  const [open, setOpen] = useState(false);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const btnRef = useRef<HTMLButtonElement | null>(null);
  const panelRef = useRef<HTMLDivElement | null>(null);
  const [pos, setPos] = useState<{ left: number; bottom: number }>({ left: 0, bottom: 0 });
  const current = LANGUAGES.find((l) => l.code === value) ?? LANGUAGES[0];

  function openNow() {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setOpen(true);
  }
  function closeSoon() {
    closeTimer.current = setTimeout(() => setOpen(false), 200);
  }
  function toggleRail() {
    if (!open) {
      const r = btnRef.current?.getBoundingClientRect();
      if (r) setPos({ left: r.right + 8, bottom: window.innerHeight - r.bottom });
    }
    setOpen((o) => !o);
  }

  // Rail popover: dismiss on outside click / Escape (it's portaled, so a contains() check
  // spans both the button and the floating panel).
  useEffect(() => {
    if (variant !== "rail" || !open) return;
    function onDoc(e: MouseEvent) {
      const target = e.target as Node;
      if (panelRef.current?.contains(target) || btnRef.current?.contains(target)) return;
      setOpen(false);
    }
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [variant, open]);

  const menu = (
    <div
      ref={panelRef}
      className="glass-menu w-40 rounded-xl p-1.5 animate-[popIn_0.16s_ease]"
    >
      {LANGUAGES.map((l) => (
        <button
          key={l.code}
          onClick={() => {
            onChange(l.code);
            setOpen(false);
          }}
          className="w-full flex items-center justify-between gap-2 text-sm px-2 py-2 rounded-lg text-muted hover:text-fg hover:bg-card transition"
        >
          <span>{l.label}</span>
          {l.code === value && <Check className="w-4 h-4 text-accent" />}
        </button>
      ))}
    </div>
  );

  if (variant === "rail") {
    return (
      <>
        <button
          ref={btnRef}
          onClick={toggleRail}
          title={current.label}
          aria-label={current.label}
          className="relative p-2 rounded-lg text-muted hover:text-fg hover:bg-card transition"
        >
          <Globe className="w-5 h-5" />
          {/* Current-language badge (HU/EN) so the active language reads at a glance without
              opening the menu. The ring matches the page background to detach it from the icon. */}
          <span className="absolute -bottom-1 -right-1 text-[8px] font-bold leading-none px-1 py-[1px] rounded bg-accent text-accent-fg ring-2 ring-bg">
            {current.code.toUpperCase()}
          </span>
        </button>
        {open &&
          createPortal(
            <div style={{ position: "fixed", left: pos.left, bottom: pos.bottom, zIndex: 40 }}>
              {menu}
            </div>,
            document.body
          )}
      </>
    );
  }

  return (
    <div className="relative" onMouseEnter={openNow} onMouseLeave={closeSoon}>
      <button
        onClick={() => setOpen((o) => !o)}
        title={current.label}
        className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-sm text-muted hover:text-fg hover:bg-card transition"
      >
        <Globe className="w-4 h-4" />
        <span className="text-xs font-semibold uppercase">{current.code}</span>
      </button>

      {open && (
        <div
          className={`glass-menu absolute ${
            align === "right" ? "right-0" : "left-0"
          } mt-1 w-40 rounded-xl p-1.5 z-40 animate-[popIn_0.16s_ease]`}
        >
          {LANGUAGES.map((l) => (
            <button
              key={l.code}
              onClick={() => {
                onChange(l.code);
                setOpen(false);
              }}
              className="w-full flex items-center justify-between gap-2 text-sm px-2 py-2 rounded-lg text-muted hover:text-fg hover:bg-card transition"
            >
              <span>{l.label}</span>
              {l.code === value && <Check className="w-4 h-4 text-accent" />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
