"use client";

import { useEffect, useRef, useState } from "react";
import { ChevronDown, Languages } from "lucide-react";
import { useI18n, type Language } from "@/lib/i18n";

const languageOptions: Language[] = ["pl", "en"];

export function LanguageToggle() {
  const { language, setLanguage, t } = useI18n();
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);
  const labels: Record<Language, string> = {
    pl: t("language.polish"),
    en: t("language.english"),
  };

  useEffect(() => {
    if (!open) return;

    function handlePointerDown(event: PointerEvent) {
      if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
    }

    function handleKeyDown(event: KeyboardEvent) {
      if (event.key === "Escape") setOpen(false);
    }

    document.addEventListener("pointerdown", handlePointerDown);
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("pointerdown", handlePointerDown);
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [open]);

  return (
    <div ref={rootRef} className="relative inline-flex">
      <Languages className="pointer-events-none absolute left-3.5 size-4 text-accent" />
      <button
        type="button"
        aria-label={t("language.label")}
        aria-expanded={open}
        aria-haspopup="listbox"
        onClick={() => setOpen((current) => !current)}
        className="surface-control flex h-11 min-w-36 items-center rounded-control py-2 pl-10 pr-10 text-left text-sm font-medium text-foreground transition hover:bg-surface-raised/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
      >
        {labels[language]}
      </button>
      <ChevronDown className="pointer-events-none absolute right-3.5 size-4 text-muted" />
      {open && (
        <div
          role="listbox"
          aria-label={t("language.label")}
          className="surface-control absolute right-0 top-[calc(100%+0.5rem)] z-30 w-44 overflow-hidden rounded-panel p-1.5 shadow-card"
        >
          {languageOptions.map((option) => (
            <button
              key={option}
              type="button"
              role="option"
              aria-selected={language === option}
              onClick={() => {
                setLanguage(option);
                setOpen(false);
              }}
              className={`flex w-full items-center justify-between rounded-card px-3 py-2.5 text-left text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
                language === option
                  ? "bg-accent/10 font-semibold text-accent"
                  : "text-foreground hover:bg-surface-muted/70"
              }`}
            >
              {labels[option]}
              {language === option && <span className="size-1.5 rounded-full bg-accent" aria-hidden="true" />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
