"use client";
/**
 * LanguageDialog 语言切换弹窗
 *
 * 
 *
 * 简化版：单语种列表选择（保留可扩展性）
 *   - 支持未来添加更多语言
 *   - 当前选中状态高亮
 *   - ESC / 点击外部 → 关闭
 */
import { useEffect } from "react";

import styles from "./language-dialog.module.css";

export interface LanguageItem {
  code: string;
  label: string;
  nativeLabel: string;
}

export const DEFAULT_LANGUAGES: readonly LanguageItem[] = [
  { code: "en", label: "English", nativeLabel: "English" },
  { code: "zh", label: "Chinese (Simplified)", nativeLabel: "简体中文" },
  { code: "zh-TW", label: "Chinese (Traditional)", nativeLabel: "繁體中文" },
  { code: "ja", label: "Japanese", nativeLabel: "日本語" },
  { code: "ko", label: "Korean", nativeLabel: "한국어" },
  { code: "es", label: "Spanish", nativeLabel: "Español" },
  { code: "fr", label: "French", nativeLabel: "Français" },
  { code: "de", label: "German", nativeLabel: "Deutsch" },
];

export interface LanguageDialogProps {
  open: boolean;
  onClose: () => void;
  currentLanguageCode?: string;
  languages?: readonly LanguageItem[];
  onSelect: (code: string) => void;
}

export function LanguageDialog({
  open,
  onClose,
  currentLanguageCode = "en",
  languages = DEFAULT_LANGUAGES,
  onSelect,
}: LanguageDialogProps) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      className={styles.overlay}
      role="dialog"
      aria-modal="true"
      onClick={onClose}
    >
      <div className={styles.dialog} onClick={(e) => e.stopPropagation()}>
        <h2 className={styles.title}>Select Language</h2>
        <div className={styles.list} role="listbox">
          {languages.map((lang) => {
            const isActive = currentLanguageCode === lang.code;
            return (
              <button
                key={lang.code}
                type="button"
                role="option"
                aria-selected={isActive}
                className={`${styles.item} ${isActive ? styles.itemActive : ""}`}
                onClick={() => {
                  onSelect(lang.code);
                  onClose();
                }}
              >
                <span>
                  {lang.nativeLabel}{" "}
                  <span style={{ opacity: 0.5 }}>({lang.label})</span>
                </span>
                {isActive && <span className={styles.check}>✓</span>}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}
