import { useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuthStore } from '../../lib/auth';

interface RequireAuthProps {
  children: ReactNode;
}

export function RequireAuth({ children }: RequireAuthProps) {
  const { isAuthenticated, isLoading, refreshAuth } = useAuthStore();
  const [hasAttemptedRefresh, setHasAttemptedRefresh] = useState(false);

  // Try to refresh auth on mount if not authenticated
  useEffect(() => {
    if (!isAuthenticated && !isLoading && !hasAttemptedRefresh) {
      setHasAttemptedRefresh(true);
      refreshAuth().catch(() => {
        // Refresh failed, user will be redirected to login
      });
    }
  }, [isAuthenticated, isLoading, hasAttemptedRefresh, refreshAuth]);

  // Show loading spinner while checking auth or attempting refresh
  if (isLoading || (!isAuthenticated && !hasAttemptedRefresh)) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
      </div>
    );
  }

  // After refresh attempt, redirect if still not authenticated
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
}