<script lang="ts">
    import "../app.pcss";
    import {afterNavigate, beforeNavigate, goto} from "$app/navigation";
    import {is_active} from "$lib/session";
    import type {Navigation} from "@sveltejs/kit";

    async function redirect_if_necessary(ticket: Navigation) {
        const sessionIsValid = await is_active();
        const isPublicRoute = ticket.to?.routeId?.startsWith("(public)");
        if (sessionIsValid && isPublicRoute) {
            await goto("/home");
        } else if (!sessionIsValid && !isPublicRoute) {
            await goto("/login");
        }
    }

    // This should probably be removed in favor of the logic in layout.server.ts.
    // That requires a more sophisticated server side implementation of session handling,
    // and i don't want that tbh, i want to stay as much in the browser as possible.
    afterNavigate(redirect_if_necessary);
    beforeNavigate(redirect_if_necessary);
</script>
<slot></slot>