"use client";

import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import { defaultSEOConfig } from "@/config/seoConfig";

const DEFAULT_TITLE =
  typeof defaultSEOConfig.title === "string"
    ? defaultSEOConfig.title
    : "مدستاگرام";

export default function TitleGuardian() {
  const pathname = usePathname();
  const lastValidTitle = useRef(DEFAULT_TITLE);

  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;
}
