import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import Navbar from "./components/Navbar";
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() {
  // 1. Reactive state engine to toggle Navbar visibility and route security globally
  const [isLoggedIn, setIsLoggedIn] = useState(false);

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

  useEffect(() => {
    evaluateAuthenticationToken();
    // Synchronizes authentication states instantly across duplicate browser windows/tabs
    window.addEventListener("storage", evaluateAuthenticationToken);
    return () => window.removeEventListener("storage", evaluateAuthenticationToken);
  }, []);

  // 2. Authentication Access Shield Wrapper Component
  const ProtectedRoute = ({ children }) => {
    return isLoggedIn ? children : <Navigate to="/login" replace />;
  };

  return (
    <Router>
      <div className="min-h-screen bg-slate-50">
        
        {/* ✅ CONDITION: Navbar completely unmounts when logged out */}
        {isLoggedIn && <Navbar onLogout={() => setIsLoggedIn(false)} />}
        
        <div className={isLoggedIn ? "py-6" : ""}>
          <Routes>
            {/* Open Paths */}
            <Route path="/login" element={<Login onLoginSuccess={() => setIsLoggedIn(true)} />} />
            <Route path="/register" element={<Register />} />
            
            {/* Static Guarded Dashboard Fallbacks */}
            <Route path="/" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
            <Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
            <Route path="/Dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
            
            {/* 🔄 100% TRULY DYNAMIC COMPONENT ROUTER MATRIX */}
            {frontendConfig.menuItems
              .filter(item => item.toLowerCase() !== "dashboard" && item.toLowerCase() !== "reports")
              .map((item) => (
                <Route 
                  key={item}
                  // Handles variations by matching both raw and lowercase structural names
                  path={`/${item}`} 
                  element={
                    <ProtectedRoute>
                      <DynamicPage moduleName={item} />
                    </ProtectedRoute>
                  } 
                />
              ))}

            {/* Static Guarded Reports Layout */}
            <Route path="/reports" element={<ProtectedRoute><Reports /></ProtectedRoute>} />
            <Route path="/Reports" element={<ProtectedRoute><Reports /></ProtectedRoute>} />

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