'use client';

import { useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from '@/components/id/auth-provider';

export function useRequireAuth() {
  const router = useRouter();
  const pathname = usePathname();
  const { user, isLoading, isApiReady, isSessionReady, isPinLocked, hasStoredSession, token } = useAuth();

  const authResolved = !isLoading && isSessionReady;
  const isAuthenticated = Boolean(user || isPinLocked);

  useEffect(() => {
    if (!authResolved) return;
    if (isAuthenticated || hasStoredSession || token) return;
    if (pathname.startsWith('/auth/')) return;
    router.replace('/auth/login');
  }, [authResolved, hasStoredSession, isAuthenticated, pathname, router, token]);

  return {
    user,
    isLoading,
    isPinLocked,
    isApiReady,
    isSessionReady,
    authResolved,
    isReady: authResolved && isAuthenticated && isApiReady
  };
}
