import { useEffect } from "react";
import { useAuth } from "./contexts/AuthContext";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import Login from "./components/Login";
import Dashboard from "./components/Dashboard";
import AdminPage from "./components/AdminPage";
import ManagerPage from "./components/ManagerPage";
import HealthCheck from "./components/HealthCheck";

function App() {
  const { user, loading } = useAuth();

  const ProtectedAdminRoute = ({ children }) => {
    return user && user.role === "admin" ? children : <Navigate to="/" />;
  };

  const ProtectedManagerRoute = ({ children }) => {
    return user && (user.role === "admin" || user.role === "manager") ? (
      children
    ) : (
      <Navigate to="/" />
    );
  };

  // Диагностические логи для отладки размера интерфейса
  useEffect(() => {
    console.log("App Debug - Container dimensions:", {
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight,
      rootElement: document.getElementById("root")?.getBoundingClientRect(),
      bodyElement: document.body.getBoundingClientRect(),
    });

    const handleResize = () => {
      console.log("App Debug - Resize event:", {
        windowWidth: window.innerWidth,
        windowHeight: window.innerHeight,
      });
    };

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  if (loading) {
    return (
      <div className="d-flex justify-content-center mt-5">
        <div className="spinner-border" role="status"></div>
      </div>
    );
  }

  return (
    <BrowserRouter>
      <div className="container-fluid px-3" style={{ marginTop: "2rem" }}>
        <HealthCheck />
        {user ? (
          <Routes>
            <Route path="/" element={<Dashboard />} />
            <Route
              path="/admin"
              element={
                <ProtectedAdminRoute>
                  <AdminPage />
                </ProtectedAdminRoute>
              }
            />
            <Route
              path="/manager"
              element={
                <ProtectedManagerRoute>
                  <ManagerPage />
                </ProtectedManagerRoute>
              }
            />
          </Routes>
        ) : (
          <Login />
        )}
      </div>
    </BrowserRouter>
  );
}

export default App;
