"use client";

import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { formatLocalizedSeoTitle } from "@/lib/i18n/seo";
import { DEFAULT_LANGUAGE, type AppLanguage } from "@/lib/i18n/registry";

function resolveLang(code?: string): AppLanguage {
  return code === "en" ? "en" : DEFAULT_LANGUAGE;
}

export function formatPageTitle(title: string, lang: AppLanguage = DEFAULT_LANGUAGE) {
  const trimmed = title.trim();
  if (!trimmed) {
    return formatLocalizedSeoTitle("", lang);
  }
  return formatLocalizedSeoTitle(trimmed, lang);
}

export function usePageTitle(title?: string | null) {
  const { i18n } = useTranslation("seo");
  const lang = resolveLang(i18n.language);
  const siteName = i18n.t("site.name");

  useEffect(() => {
    if (!title?.trim()) return;
    const trimmed = title.trim();
    if (trimmed.includes(siteName)) {
      document.title = trimmed;
      return;
    }
    document.title = formatPageTitle(trimmed, lang);
  }, [title, lang, siteName]);
}
