"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";

export function GlobalLoader() {
  const [loading, setLoading] = useState(false);
  const pathname = usePathname();

  // Active le loader lors des changements de page
  useEffect(() => {
    setLoading(false);
  }, [pathname]);

  // Intercepte les clics sur tous les liens avec timeout de sécurité
  useEffect(() => {
    let timeoutId: NodeJS.Timeout | null = null;

    const handleClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement | null;
      const link = target?.closest("a");
      
      if (link && link.href && link.target !== "_blank") {
        try {
          const url = new URL(link.href, window.location.href);
          if (url.origin === window.location.origin && url.pathname !== window.location.pathname) {
            setLoading(true);
            if (timeoutId) clearTimeout(timeoutId);
            timeoutId = setTimeout(() => setLoading(false), 3000);
          }
        } catch {
          // ignore
        }
      }
    };

    window.addEventListener("click", handleClick);
    return () => {
      window.removeEventListener("click", handleClick);
      if (timeoutId) clearTimeout(timeoutId);
    };
  }, []);

  if (!loading) return null;

  return (
    <div className="fixed inset-0 z-[99999] bg-[#070406] flex items-center justify-center pointer-events-auto select-none overflow-hidden">
      <div className="animate-[breathe_1.2s_ease-in-out_infinite] text-4xl md:text-6xl font-black italic tracking-tighter text-white drop-shadow-[0_0_35px_rgba(224,90,104,0.5)]">
        MT<span className="text-[#e05a68]">BR</span>
      </div>
    </div>
  );
}
