'use client';

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

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

  // Re-run reveal observer on every route change so client-side navigation
  // also animates elements on the new page.
  useEffect(() => {
    const revealEls = document.querySelectorAll<Element>('.reveal:not(.visible)');
    if (!revealEls.length) return;

    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add('visible');
            obs.unobserve(e.target);
          }
        });
      },
      { threshold: 0.1, rootMargin: '0px 0px -50px 0px' }
    );
    revealEls.forEach((el) => obs.observe(el));

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

  // Smooth scroll for anchor links (set up once)
  useEffect(() => {
    const handleAnchorClick = (e: Event) => {
      const target = e.target as HTMLAnchorElement;
      if (target.tagName === 'A' && target.getAttribute('href')?.startsWith('#')) {
        const href = target.getAttribute('href');
        const targetEl = href ? document.querySelector(href) : null;
        if (targetEl) {
          e.preventDefault();
          const navbar = document.getElementById('navbar');
          const offset = (navbar?.offsetHeight || 70) + 12;
          window.scrollTo({
            top: targetEl.getBoundingClientRect().top + window.scrollY - offset,
            behavior: 'smooth',
          });
        }
      }
    };

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

  return null;
}
