import { Navigate, useLocation } from "react-router-dom";
import { ReactNode, useEffect, useState } from "react";
import { useLanguage } from "../language/LanguageContext";

interface ProtectedRouteProps {
  children: ReactNode;
  redirectPath?: string;
}

export const ProtectedRoute = ({ 
  children, 
  redirectPath = "/login" 
}: ProtectedRouteProps) => {
  const { t } = useLanguage();
  const location = useLocation();
  const [isChecking, setIsChecking] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  
  useEffect(() => {
    const authAuthority = sessionStorage.getItem('auth_authority');
    setIsAuthenticated(!!authAuthority);
    setIsChecking(false);
  }, []);

  useEffect(() => {
    if (!isChecking) {
      const recheckTimer = setTimeout(() => {
        const authAuthority = sessionStorage.getItem('auth_authority');
        const isAuth = !!authAuthority;
        if (isAuth !== isAuthenticated) {
          setIsAuthenticated(isAuth);
        }
      }, 300);
      return () => clearTimeout(recheckTimer);
    }
  }, [isChecking, isAuthenticated]);
  
  if (isChecking) {
    return <div>{t('Authentifizierung wird geprüft…')}</div>;
  }
  
  if (!isAuthenticated) {
    return <Navigate to={redirectPath} state={{ from: location }} replace />;
  }
  
  return <>{children}</>;
};
