"use client";

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

export default function TitleGuardian() {
  const { t } = useTranslation("common");
  const pathname = usePathname();
  const defaultTitle = t("header.logoAlt");
  const lastValidTitle = useRef(defaultTitle);

  useEffect(() => {
    lastValidTitle.current = defaultTitle;
  }, [defaultTitle]);

  useEffect(() => {
    if (document.title.trim()) {
      lastValidTitle.current = document.title;
    }

    const observer = new MutationObserver(() => {
      const currentTitle = document.title.trim();
      if (currentTitle) {
        lastValidTitle.current = currentTitle;
        return;
      }

      if (lastValidTitle.current.trim()) {
        document.title = lastValidTitle.current;
      }
    });

    const titleElement = document.querySelector("title");
    if (titleElement) {
      observer.observe(titleElement, {
        childList: true,
        characterData: true,
        subtree: true,
      });
    }

    return () => observer.disconnect();
  }, [pathname]);

  return null;
}
