"use client";

import { useState } from "react";
import { useLocale } from "@/i18n/LocaleProvider";
import { LOCALES, LOCALE_LABELS } from "@/i18n/config";

// #352 — 헤더용 언어 전환 드롭다운. 44px 터치 영역 + ARIA listbox 패턴.
export default function LanguageSwitcher() {
  const { locale, setLocale } = useLocale();
  const [open, setOpen] = useState(false);

  return (
    <div className="relative">
      <button
        onClick={() => setOpen((v) => !v)}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label="언어 선택 / Select language"
        className="min-h-[44px] min-w-[44px] px-2 py-1.5 flex items-center gap-1 text-sm rounded-lg hover:bg-brand-50 touch-manipulation"
      >
        <span aria-hidden="true">{LOCALE_LABELS[locale].flag}</span>
        <span className="text-xs text-gray-500 uppercase">{locale}</span>
      </button>
      {open && (
        <>
          <button
            aria-hidden="true"
            tabIndex={-1}
            className="fixed inset-0 z-40 cursor-default"
            onClick={() => setOpen(false)}
          />
          <ul
            role="listbox"
            aria-label="언어 목록"
            className="absolute right-0 mt-1 bg-surface rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 py-1 z-50 min-w-[160px]"
          >
            {LOCALES.map((l) => (
              <li key={l}>
                <button
                  role="option"
                  aria-selected={l === locale}
                  onClick={() => { setLocale(l); setOpen(false); }}
                  className={`w-full text-left px-3 py-2 text-sm flex items-center gap-2 hover:bg-brand-50 ${
                    l === locale ? "font-semibold text-brand-700" : "text-gray-700"
                  }`}
                >
                  <span aria-hidden="true">{LOCALE_LABELS[l].flag}</span>
                  <span>{LOCALE_LABELS[l].native}</span>
                </button>
              </li>
            ))}
          </ul>
        </>
      )}
    </div>
  );
}
