'use client';

import { useEffect, useRef } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { useLoader } from '../context/LoaderContext';
import Loader from './atoms/loader';

export default function LoaderHandler() {
  const { loading, setLoading } = useLoader();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const timerRef = useRef(null);

  // Stable helper to stop the loader (clears any pending timer first)
  const stopLoading = () => {
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => setLoading(false), 300);
  };

  // ✅ Now fires on BOTH pathname AND query-string changes
  useEffect(() => {
    stopLoading();
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, [pathname, searchParams]); // <-- key fix: searchParams added here

  // Handle link clicks to start the loader
  useEffect(() => {
    const handleClick = (e) => {
      let el = e.target;
      while (el && el.tagName !== 'A' && el !== document.body) {
        el = el.parentElement;
      }

      if (el?.tagName !== 'A') return;

      const anchor = el;

      // Ignore external links, new-tab links, hash-only links, javascript: links
      if (
        !anchor.href ||
        anchor.target ||
        anchor.href.startsWith('mailto:') ||
        anchor.href.startsWith('tel:') ||
        anchor.href.startsWith('javascript:')
      ) return;

      const currentPath = window.location.pathname + window.location.search;
      const targetUrl   = new URL(anchor.href, window.location.origin);
      const targetPath  = targetUrl.pathname + targetUrl.search;

      // Only show loader when something actually changes (path OR query)
      // Pure hash changes (#section) don't need a loader
      const onlyHashChanged =
        targetUrl.pathname === window.location.pathname &&
        targetUrl.search   === window.location.search &&
        targetUrl.hash     !== '';

      if (!onlyHashChanged && currentPath !== targetPath) {
        if (timerRef.current) clearTimeout(timerRef.current);
        setLoading(true);
      }
    };

    document.addEventListener('click', handleClick, true);
    return () => document.removeEventListener('click', handleClick, true);
  }, [setLoading]);

  if (!loading) return null;

  return <Loader />;
}