// Path: Frontend/src/app.tsx

import { Router, useLocation, useNavigate } from "@solidjs/router";
import { FileRoutes } from "@solidjs/start/router";
import { Suspense, createEffect, type ParentComponent } from "solid-js";
import { AuthProvider, useAuth } from "./context/auth/context";
import { ThemeProvider } from "./context/theme/context";
import { getPostAuthRedirectHref, isPublicRoute } from "./lib/routes";
import "./styles/main.scss";

const AppRoot: ParentComponent = (props) => {
	const location = useLocation();
	const navigate = useNavigate();
	const auth = useAuth();
	const routeIsPublic = () => isPublicRoute(location.pathname);

	createEffect(() => {
		if (!auth.isReady()) return;

		const pathname = location.pathname;
		if (pathname === "/") return;

		if (pathname.startsWith("/auth/")) {
			if (auth.user()) {
				navigate(getPostAuthRedirectHref(auth.user()!.role), { replace: true });
			}
			return;
		}

		if (!auth.user()) {
			navigate("/auth/login", { replace: true });
		}
	});

	return (
		<Suspense>
			{!auth.isReady() && !routeIsPublic() ? (
				<div class="app-route-shell app-route-shell-viewport-locked">
					<div style={{ display: "grid", "place-items": "center", padding: "2rem", color: "var(--text-muted)" }}>
						Loading your session…
					</div>
				</div>
			) : (
				<div classList={{
					"app-route-shell": true,
					"app-route-shell-viewport-locked": routeIsPublic(),
				}}>
					{props.children}
				</div>
			)}
		</Suspense>
	);
};

export default function App() {
	return (
		<ThemeProvider>
			<AuthProvider>
				<Router root={AppRoot}>
					<FileRoutes />
				</Router>
			</AuthProvider>
		</ThemeProvider>
	);
}
