import { useEffect } from 'react';
import { useBlocker } from 'react-router-dom';
import { useActiveSessionStore } from '../stores/activeSessionStore';

export function useNavigationGuard() {
  const session = useActiveSessionStore((s) => s.session);
  const hasActiveSession = session !== null && !session.ended_at;

  const blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      hasActiveSession && currentLocation.pathname !== nextLocation.pathname,
  );

  useEffect(() => {
    if (!hasActiveSession) return;

    const handler = (e: BeforeUnloadEvent) => {
      e.preventDefault();
    };

    window.addEventListener('beforeunload', handler);
    return () => window.removeEventListener('beforeunload', handler);
  }, [hasActiveSession]);

  return blocker;
}
