'use client';

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

const RouteHandler = () => {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const layoutSegment = useSelectedLayoutSegment();

  useEffect(() => {
    window.parent.postMessage(
      {
        type: 'ROUTE_CHANGE_COMPLETE',
        url: `${pathname}?${searchParams}`,
        layoutSegment: layoutSegment === null ? 'home' : layoutSegment
      },
      '*'
    );
  }, [pathname, searchParams]);

  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      const anchor = target.closest('a[href]');

      if (anchor) {
        const isMenuToggle =
          anchor.getAttribute('data-is-menu-toggle') === 'true';
        if (!isMenuToggle) {
          window.parent.postMessage(
            { type: 'ROUTE_CHANGE_START', url: anchor.getAttribute('href') },
            '*'
          );
        }
      }
    };

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

  return null;
};

export default RouteHandler;
