import React from "react";
import { BrowserRouter as Router, Routes, Route, Navigate, useLocation } from "react-router-dom";
import PinLoginPage from "./components/PinLoginPage";
import Order from "./components/Order";
import ManagementLoginPage from "./components/ManagementLoginPage";
import ManagementRoutes from "./management/ManagementRoutes";
import { getCurrentUser } from "./api";

function useAuth() {
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState("");
  React.useEffect(() => {
    let active = true;
    (async () => {
      try {
        const u = await getCurrentUser();
        if (active) setUser(u);
      } catch {
        if (active) setUser(null);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, []);
  return { user, loading, error, setUser };
}

function LoadingScreen({ label = "Lade..." }) {
  return <div className="flex items-center justify-center h-screen bg-[#0a0a0a] text-white">{label}</div>;
}

function RequireAuth({ children }) {
  const { user, loading } = useAuth();
  const location = useLocation();
  if (loading) return <LoadingScreen />;
  if (!user) return <Navigate to="/" replace state={{ from: location }} />;
  return React.cloneElement(children, { user });
}

function RequireRole({ roles = ["admin", "manager"], children }) {
  const { user, loading } = useAuth();
  const location = useLocation();
  if (loading) return <LoadingScreen />;
  if (!user) return <Navigate to="/management-login" replace state={{ from: location }} />;
  const role = (user.role || "user").toLowerCase();
  if (!roles.map((r) => r.toLowerCase()).includes(role)) return <Navigate to="/" replace />;
  return React.cloneElement(children, { currentUser: user });
}

export default function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<PinLoginPage />} />
        <Route path="/management-login" element={<ManagementLoginPage />} />
        <Route path="/order" element={<RequireAuth><Order /></RequireAuth>} />
        <Route
          path="/management/*"
          element={
            <RequireRole roles={["admin", "manager", "user"]}>
              <ManagementRoutes />
            </RequireRole>
          }
        />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </Router>
  );
}
