import React, {
  createContext,
  useCallback,
  useContext,
  useMemo,
  useState,
} from "react";
import { languageForHomePathname } from "./languageRoutes";
import type { Dict } from "./locales/types";
import { zhDict } from "./locales/zh-CN";
import { enDict } from "./locales/en";
import { koDict } from "./locales/ko";

export type Lang = "zh-CN" | "en" | "ja" | "ko" | "vi" | "id" | "ms";

const languageNames: Record<Lang, Dict> = {
  "zh-CN": {
    lang_zh_CN: "中文",
    lang_en: "English",
    lang_ja: "日本語",
    lang_ko: "한국어",
    lang_vi: "Tiếng Việt",
    lang_id: "Bahasa Indonesia",
    lang_ms: "Bahasa Melayu",
  },
  en: {
    lang_zh_CN: "Chinese",
    lang_en: "English",
    lang_ja: "Japanese",
    lang_ko: "Korean",
    lang_vi: "Vietnamese",
    lang_id: "Indonesian",
    lang_ms: "Malay",
  },
  ja: {
    brand: "ARK ライブラリー",
    showMore: "すべて表示",
    showLess: "閉じる",
    lang_zh_CN: "中国語",
    lang_en: "英語",
    lang_ja: "日本語",
    lang_ko: "韓国語",
    lang_vi: "ベトナム語",
    lang_id: "インドネシア語",
    lang_ms: "マレー語",
  },
  ko: {
    brand: "ARK 라이브러리",
    showMore: "모두 보기",
    showLess: "접기",
    lang_zh_CN: "중국어",
    lang_en: "영어",
    lang_ja: "일본어",
    lang_ko: "한국어",
    lang_vi: "베트남어",
    lang_id: "인도네시아어",
    lang_ms: "말레이어",
  },
  vi: {
    brand: "Thư viện ARK",
    showMore: "Xem tất cả",
    showLess: "Thu gọn",
    lang_zh_CN: "Tiếng Trung",
    lang_en: "Tiếng Anh",
    lang_ja: "Tiếng Nhật",
    lang_ko: "Tiếng Hàn",
    lang_vi: "Tiếng Việt",
    lang_id: "Tiếng Indonesia",
    lang_ms: "Tiếng Mã Lai",
  },
  id: {
    brand: "Perpustakaan ARK",
    showMore: "Lihat semua",
    showLess: "Tutup",
    lang_zh_CN: "Bahasa Tionghoa",
    lang_en: "Bahasa Inggris",
    lang_ja: "Bahasa Jepang",
    lang_ko: "Bahasa Korea",
    lang_vi: "Bahasa Vietnam",
    lang_id: "Bahasa Indonesia",
    lang_ms: "Bahasa Melayu",
  },
  ms: {
    brand: "Perpustakaan ARK",
    showMore: "Lihat semua",
    showLess: "Tutup",
    lang_zh_CN: "Bahasa Cina",
    lang_en: "Bahasa Inggeris",
    lang_ja: "Bahasa Jepun",
    lang_ko: "Bahasa Korea",
    lang_vi: "Bahasa Vietnam",
    lang_id: "Bahasa Indonesia",
    lang_ms: "Bahasa Melayu",
  },
};

const dict: Record<Lang, Dict> = {
  "zh-CN": { ...zhDict, ...languageNames["zh-CN"] },
  en: { ...enDict, ...languageNames.en },
  ja: { ...enDict, ...languageNames.ja },
  ko: koDict,
  vi: { ...enDict, ...languageNames.vi },
  id: { ...enDict, ...languageNames.id },
  ms: { ...enDict, ...languageNames.ms },
};

/** Fixed locale lookup (admin UI uses Simplified Chinese). */
export function tLang(lang: Lang, key: string): string {
  return dict[lang][key] || dict.en[key] || key;
}

type Ctx = { lang: Lang; setLang: (l: Lang) => void; t: (k: string) => string };

const I18nCtx = createContext<Ctx | null>(null);

const LANG_KEY = "ark_lang";

export function I18nProvider({ children }: { children: React.ReactNode }) {
  const [lang, setLangState] = useState<Lang>(() => {
    const routeLang = languageForHomePathname(window.location.pathname);
    if (routeLang) return routeLang;
    if (window.location.pathname === "/") return "en";

    const s = localStorage.getItem(LANG_KEY);
    if (s === "zh" || s === "zh-TW") return "zh-CN";
    if (
      s === "zh-CN" ||
      s === "en" ||
      s === "ja" ||
      s === "ko" ||
      s === "vi" ||
      s === "id" ||
      s === "ms"
    )
      return s;
    return "en";
  });
  const setLang = useCallback((l: Lang) => {
    localStorage.setItem(LANG_KEY, l);
    setLangState(l);
  }, []);
  const t = useCallback(
    (k: string) => dict[lang][k] || dict.en[k] || k,
    [lang],
  );
  const v = useMemo(() => ({ lang, setLang, t }), [lang, t]);
  return <I18nCtx.Provider value={v}>{children}</I18nCtx.Provider>;
}

export function useI18n() {
  const v = useContext(I18nCtx);
  if (!v) throw new Error("I18nProvider missing");
  return v;
}

export function langQuery(lang: Lang) {
  return lang;
}
