"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";
import { useTranslation } from "react-i18next";

import { resolveAdminPageTitle } from "@/lib/admin-page-title";
import { hydrateAdminUiLocale } from "@/lib/admin-locale";
import { normalizeAdminLanguage } from "@/i18n/languages";

/** 随界面语言更新 `document.title`（弥补 Next 静态 metadata 无法按用户语言切换）。 */
export function AdminDocumentTitle() {
  const pathname = usePathname();
  const { t, i18n } = useTranslation();

  useEffect(() => {
    const spec = resolveAdminPageTitle(pathname);
    const appTitle = t("app.title", { ns: "common" });

    if (!spec) {
      document.title = appTitle;
      return;
    }

    const pageTitle = t(spec.key, { ns: spec.ns, ...(spec.params ?? {}) });
    document.title = `${pageTitle} · ${appTitle}`;
  }, [pathname, i18n.language, i18n.resolvedLanguage, t]);

  useEffect(() => {
    const locale = hydrateAdminUiLocale();
    if (!locale) {
      return;
    }
    const normalized = normalizeAdminLanguage(locale);
    const current = normalizeAdminLanguage(i18n.resolvedLanguage ?? i18n.language);
    if (normalized !== current) {
      void i18n.changeLanguage(normalized);
    }
  }, [i18n]);

  return null;
}
