import { useEffect, useState } from "react";
import { LOCALE_STORAGE_KEY } from "../../../../common/core/i18n";
import { t } from "../../lib/i18n";
const SUPPORTED_LOCALES = ["ko", "en"] as const;

type Locale = (typeof SUPPORTED_LOCALES)[number];

function resolveLocale(): Locale {
  if (typeof window === "undefined") {
    return "ko";
  }

  const stored = window.localStorage.getItem(LOCALE_STORAGE_KEY);
  if (stored === "ko" || stored === "en") {
    return stored;
  }

  const pathLocale = window.location.pathname.split("/")[1];
  if (pathLocale === "ko" || pathLocale === "en") {
    return pathLocale;
  }

  const browserLang = window.navigator.language.toLowerCase();
  return browserLang.startsWith("ko") ? "ko" : "en";
}

function LanguageSelector() {
  const [locale, setLocale] = useState<Locale>(resolveLocale());

  useEffect(() => {
    const syncLocale = () => {
      setLocale(resolveLocale());
    };

    window.addEventListener("localechange", syncLocale);
    window.addEventListener("storage", syncLocale);

    return () => {
      window.removeEventListener("localechange", syncLocale);
      window.removeEventListener("storage", syncLocale);
    };
  }, []);

  const handleChange = (next: Locale) => {
    if (next === locale) {
      return;
    }
    window.localStorage.setItem(LOCALE_STORAGE_KEY, next);
    setLocale(next);
    window.dispatchEvent(new Event("localechange"));
  };

  return (
    <select
      value={locale}
      onChange={(event) => handleChange(event.target.value as Locale)}
      className="rounded-full border border-border bg-transparent px-3 py-2 text-sm text-muted-foreground transition hover:bg-muted/20"
      aria-label={t("ui.common.language", "언어")}
    >
      <option value="ko">{t("ui.common.language_ko", "한국어")}</option>
      <option value="en">{t("ui.common.language_en", "English")}</option>
    </select>
  );
}

export default LanguageSelector;
