<!-- #region ProtectedRoute [C:3] [TYPE Component] [SEMANTICS auth, route-guard, permission, session, redirect] -->
<!-- @ingroup Components -->
<!-- @BRIEF Enforces authenticated and authorized access before protected slot content is rendered. -->
<!-- @LAYER UI -->
<!-- @RELATION BINDS_TO -> [EXT:frontend:authStore] -->
<!-- @RELATION CALLS -> [EXT:frontend:goto] -->
<!-- @RELATION DEPENDS_ON -> [EXT:frontend:PermissionsModule] -->
<!-- @RELATION CALLS -> [EXT:frontend:fetchApi] -->
<!-- @INVARIANT Unauthenticated users are redirected to /login, unauthorized to fallbackPath, protected slot renders only when access is verified. -->
<!-- @UX_STATE: Loading -> Spinner rendered while auth/session/permission validation is in progress. -->
<!-- @UX_STATE: Error -> Session validation failure triggers logout and /login redirect. -->
<!-- @UX_STATE: Success -> Protected slot content rendered for authenticated users with valid access. -->
<!-- @UX_FEEDBACK Spinner during Loading; navigation redirect on Error/Unauthorized. -->
<!-- @UX_RECOVERY Re-authenticate via /login after logout; retry on next protected navigation. -->
<!-- @UX_REACTIVITY Props -> $props(); local state -> $state(); auth store -> $auth subscription. -->
<!-- @RATIONALE Uses log() from $lib/cot-logger for all belief markers; replaces inline belief_scope function and console.* calls per MolecularCoTLogging protocol. -->
<script lang="ts">
    import { onMount } from "svelte";
    import { auth } from "$lib/auth/store.svelte.js";
    import { fetchApi } from "$lib/api";
    import { goto } from "$app/navigation";
    import { ROUTES } from "$lib/routes";
    import { hasPermission } from "$lib/auth/permissions.js";
    import { log } from "$lib/cot-logger";

    const { requiredPermission = null, fallbackPath = "/profile", children } = $props<{
        requiredPermission?: string | null;
        fallbackPath?: string;
        children?: import("svelte").Snippet;
    }>();

    let hasRouteAccess = $state(false);
    let isCheckingAccess = $state(true);

    // #region verifySessionAndAccess [C:3] [TYPE Function] [SEMANTICS auth,session,permission]
// @ingroup Components
    // @BRIEF Validates session and optional permission gate before allowing protected content render.
    // @PRE auth store is initialized and can provide token/user state; navigation is available.
    // @POST hasRouteAccess=true only when user identity is valid and permission check (if provided) passes.
    // @SIDE_EFFECT Mutates auth loading/user state, performs API I/O to /auth/me, and may redirect.
    async function verifySessionAndAccess() {
        log("ProtectedRoute.verifySessionAndAccess", "REASON", "Starting route access verification");

        isCheckingAccess = true;

        try {
            if (!$auth.token) {
                auth.setLoading(false);
                log("ProtectedRoute.verifySessionAndAccess", "REFLECT", "Missing token, redirecting to /login");
                await goto(ROUTES.login());
                return;
            }

            let currentUser = $auth.user;
            if (!currentUser) {
                auth.setLoading(true);
                try {
                    const user = await fetchApi("/auth/me");
                    auth.setUser(user);
                    currentUser = user;
                    log("ProtectedRoute.verifySessionAndAccess", "REASON", "Session user hydrated from /auth/me");
                } catch (error) {
                    log("ProtectedRoute.verifySessionAndAccess", "EXPLORE", "Session validation failed",
                        {}, error instanceof Error ? error.message : "Unknown error");
                    auth.logout();
                    await goto(ROUTES.login());
                    return;
                } finally {
                    auth.setLoading(false);
                }
            }

            if (!currentUser) {
                auth.logout();
                log("ProtectedRoute.verifySessionAndAccess", "REFLECT", "User unresolved, redirecting to /login");
                await goto(ROUTES.login());
                return;
            }

            if (requiredPermission && !hasPermission(currentUser, requiredPermission, "READ")) {
                log("ProtectedRoute.verifySessionAndAccess", "REFLECT", "Permission denied, redirecting to fallback",
                    { requiredPermission, fallbackPath });
                hasRouteAccess = false;
                await goto(fallbackPath);
                return;
            }

            hasRouteAccess = true;
            log("ProtectedRoute.verifySessionAndAccess", "REFLECT", "Access granted");
        } finally {
            isCheckingAccess = false;
            log("ProtectedRoute.verifySessionAndAccess", "REFLECT", "Verification cycle completed",
                { isCheckingAccess, hasRouteAccess });
        }
    }
    // #endregion verifySessionAndAccess

    onMount(() => {
        void verifySessionAndAccess();
    });
</script>

{#if $auth.loading || isCheckingAccess}
    <div class="flex items-center justify-center min-h-screen">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-ring"></div>
    </div>
{:else if $auth.isAuthenticated && hasRouteAccess}
    {@render children?.()}
{/if}
<!-- #endregion ProtectedRoute -->
