import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import type { AppLocale } from "@/i18n";
import { useLocationSearch } from "@/hooks/useLocationSearch";
import { parseLangParam } from "@/lib/urlLang";
import { useCountryCodeQuery } from "@/queries/getCountryCode";

/** Applies resolved locale from `?lang=` or getCountryCode; syncs `<html lang>`. */
export function LocaleSync() {
  const { i18n } = useTranslation();
  const search = useLocationSearch();
  const langFromUrl = parseLangParam(new URLSearchParams(search).get("lang"));
  const { data, isSuccess, isError } = useCountryCodeQuery();

  useEffect(() => {
    if (langFromUrl) {
      void i18n.changeLanguage(langFromUrl);
      document.documentElement.lang = langFromUrl;
      return;
    }
    if (!isSuccess && !isError) return;

    const locale: AppLocale =
      isSuccess && data?.countryCode === "RU" ? "ru" : "en";
    void i18n.changeLanguage(locale);
    document.documentElement.lang = locale;
  }, [langFromUrl, isSuccess, isError, data, i18n]);

  return null;
}
