'use client';

import { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';

export function AuthNavigationGuard({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const matches = (root: string) => pathname === root || pathname.startsWith(`${root}/`);
    const guestPage = pathname === '/' || matches('/login') || matches('/register');
    const protectedPage = ['/dashboard', '/agent', '/developer', '/incidents'].some(matches);
    if (!guestPage && !protectedPage) return;

    const controller = new AbortController();
    let checking = false;
    const check = async () => {
      if (checking || controller.signal.aborted) return;
      checking = true;
      try {
        const response = await fetch('/api/auth', { cache: 'no-store', signal: controller.signal });
        if (response.status === 401) {
          if (protectedPage) window.location.replace('/?screen=get_started');
        } else if (response.ok) {
          const data = await response.json();
          if (!data.authenticated || !data.user || typeof data.user.role !== 'string') {
            throw new Error('Unable to verify your session. Please reload the page.');
          }
          const home = data.user.role === 'PU_AGENT' ? '/agent' : '/dashboard';
          if (guestPage || (matches('/dashboard') && home === '/agent') ||
              (matches('/agent') && home === '/dashboard')) {
            window.location.replace(home);
          }
        } else {
          throw new Error('Unable to verify your session. Please reload the page.');
        }
        setError(null);
      } catch (error: unknown) {
        if (!controller.signal.aborted) {
          setError(error instanceof Error ? error.message : 'Unable to verify your session.');
        }
      } finally {
        checking = false;
      }
    };
    const onVisible = () => { if (document.visibilityState === 'visible') void check(); };
    void check();
    window.addEventListener('focus', check);
    window.addEventListener('pageshow', check);
    document.addEventListener('visibilitychange', onVisible);
    return () => {
      controller.abort();
      window.removeEventListener('focus', check);
      window.removeEventListener('pageshow', check);
      document.removeEventListener('visibilitychange', onVisible);
    };
  }, [pathname]);

  return (
    <>
      {error && <div role="alert" className="p-3 bg-rose-50 text-rose-700">{error}</div>}
      {children}
    </>
  );
}
