import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import Sidebar from "./components/Sidebar"; 
import Login from "./pages/Login";
import Register from "./pages/Register";
import Dashboard from "./pages/Dashboard";
import DynamicPage from "./pages/DynamicPage";
import Reports from "./pages/Reports";
import { frontendConfig } from "./change";

export default function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const evaluateAuthenticationToken = () => {
    const isAuth = localStorage.getItem("isAuthenticated") === "true";
    const userToken = localStorage.getItem("username");
    setIsLoggedIn(isAuth && !!userToken);
  };

  useEffect(() => {
    evaluateAuthenticationToken();
    window.addEventListener("storage", evaluateAuthenticationToken);
    return () => window.removeEventListener("storage", evaluateAuthenticationToken);
  }, []);

  const ProtectedRoute = ({ children }) => {
    return isLoggedIn ? children : <Navigate to="/login" replace />;
  };

  return (
    <Router>
  
   
      <div className="flex min-h-screen bg-slate-50 selection:bg-blue-100 selection:text-blue-900">
        
    
        {isLoggedIn && (
          <Sidebar onLogout={() => setIsLoggedIn(false)} />
        )}
        
        <div className={`flex-1 flex flex-col ${isLoggedIn ? "w-0" : ""}`}>
          <Routes>
            <Route path="/login" element={<Login onLoginSuccess={() => setIsLoggedIn(true)} />} />
            <Route path="/register" element={<Register />} />
            
            <Route path="/" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
            <Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
            <Route path="/Dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
            
            {frontendConfig.menuItems
              .filter(item => item !== "Dashboard" && item !== "Reports")
              .map((item) => (
                <Route 
                  key={item}
                  path={`/${item}`} 
                  element={
                    <ProtectedRoute>
                      <DynamicPage moduleName={item} />
                    </ProtectedRoute>
                  } 
                />
              ))}

            <Route path="/reports" element={<ProtectedRoute><Reports /></ProtectedRoute>} />
            <Route path="/Reports" element={<ProtectedRoute><Reports /></ProtectedRoute>} />

            <Route path="*" element={<Navigate to={isLoggedIn ? "/dashboard" : "/login"} replace />} />
          </Routes>
        </div>
      </div>
    </Router>
  );
}