"use client";
import React, { useState, useRef, useEffect } from "react";
import { useI18n, Language } from "@/lib/i18n";

const LANGUAGES: { code: Language; label: string; flag: string }[] = [
  { code: "en", label: "English", flag: "🇺🇸" },
  { code: "ko", label: "한국어", flag: "🇰🇷" },
  { code: "ja", label: "日本語", flag: "🇯🇵" },
];

export function LanguageSelector() {
  const { lang, setLang } = useI18n();
  const [open, setOpen] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);

  const current = LANGUAGES.find((l) => l.code === lang) || LANGUAGES[0];

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

  return (
    <div className="lang-selector-wrap" ref={wrapRef}>
      <button
        className="lang-btn"
        onClick={() => setOpen((p) => !p)}
        aria-label="Select Language"
        type="button"
      >
        <span style={{ fontSize: 13, lineHeight: 1 }}>🌐</span>
        <span>{current.code.toUpperCase()}</span>
        <svg
          width="10"
          height="10"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2.5"
          style={{ transform: open ? "rotate(180deg)" : "rotate(0deg)", transition: "transform 0.15s" }}
        >
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </button>

      {open && (
        <div className="lang-dropdown">
          {LANGUAGES.map((item) => (
            <div
              key={item.code}
              className={`lang-option${lang === item.code ? " selected" : ""}`}
              onClick={() => {
                setLang(item.code);
                setOpen(false);
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span>{item.flag}</span>
                <span>{item.label}</span>
              </div>
              {lang === item.code && (
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
                  <polyline points="20 6 9 17 4 12" />
                </svg>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}