import { useState, useEffect, useRef } from 'react';
import { Navigate, Outlet, useNavigate } from 'react-router-dom';

const INACTIVITY_LIMIT_MS = 10 * 60 * 1000; // 10 minutes

export default function AuthGuard({ children }) {
  const navigate = useNavigate();
  const loggedIn = localStorage.getItem('logged_in');
  const timerRef = useRef(null);

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

    const logout = () => {
      localStorage.removeItem('logged_in');
      localStorage.removeItem('auth_token');
      localStorage.removeItem('user_data');
      navigate('/login', { replace: true });
    };

    const resetTimer = () => {
      if (timerRef.current) clearTimeout(timerRef.current);
      timerRef.current = setTimeout(logout, INACTIVITY_LIMIT_MS);
    };

    const events = ['mousemove', 'keydown', 'scroll', 'click'];
    
    events.forEach(event => window.addEventListener(event, resetTimer));
    resetTimer(); // Start the timer initially

    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
      events.forEach(event => window.removeEventListener(event, resetTimer));
    };
  }, [loggedIn, navigate]);

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

  return children || <Outlet />;
}
