'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';

function toTitleCase(value: string): string {
  return value
    .split(' ')
    .filter(Boolean)
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}

function humanizeSegment(segment: string): string {
  const decoded = decodeURIComponent(segment);
  const cleaned = decoded.replace(/[\[\]]/g, '').replace(/[-_]+/g, ' ').trim();
  if (!cleaned) return '';
  return toTitleCase(cleaned);
}

function buildPathTitle(pathname: string): string {
  const segments = pathname.split('/').filter(Boolean);
  if (!segments.length) return '';
  return segments.map(humanizeSegment).filter(Boolean).join(' / ');
}

export default function PathnameTitleFallback() {
  const pathname = usePathname();

  useEffect(() => {
    const timer = window.setTimeout(() => {
      const currentTitle = document.title.trim();
      if (!currentTitle) return;

      const appName = currentTitle.includes(' | ')
        ? currentTitle.split(' | ').pop()?.trim() || 'StaffTrack Pro'
        : currentTitle;

      if (pathname === '/') return;

      // Only replace titles that are still the root default app name.
      if (currentTitle !== appName) return;

      const pathTitle = buildPathTitle(pathname);
      if (!pathTitle) return;

      document.title = `${pathTitle} | ${appName}`;
    }, 0);

    return () => window.clearTimeout(timer);
  }, [pathname]);

  return null;
}