import React, { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import { useWallet } from '../context/WalletContext';
import SplashScreen from './SplashScreen';

const ProtectedRoute = ({ children }) => {
  const { isAuthenticated, loading, activeWallet } = useWallet();
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);

  useEffect(() => {
    if (!loading) {
      setInitialLoadComplete(true);
    }
  }, [loading]);

  const waitingForFirstWallet =
    !initialLoadComplete || (loading && !activeWallet);

  if (waitingForFirstWallet) {
    return <SplashScreen message="Загрузка кошелька..." />;
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return children;
};

export default ProtectedRoute;
