<script lang="ts">
interface Props {
    data: any;
}

let { data }: Props = $props();

import { browser } from '$app/environment';
import { goto } from '$app/navigation';
import { ae_api } from '$lib/stores/ae_stores';
import { db_events } from '$lib/ae_events/db_events';
import { events_func } from '$lib/ae_events/ae_events_functions';

// Magic redirect: when ?session_id= is present but no event_location_id is in the route
// (e.g. navigating here from the Presenter View which has no location context),
// look up the session's location and redirect to the proper location-specific launcher URL.
// The [event_location_id] page handles the normal case where location is already in the route.
$effect(() => {
    if (!browser) return;

    const session_id = data.url.searchParams.get('session_id');
    const event_id = data.params.event_id;
    if (!session_id || !event_id) return;

    // Snapshot API config to avoid making it a reactive dependency of this effect
    const api_cfg = $ae_api;

    (async () => {
        // Check Dexie cache first — sessions are typically cached from prior page visits
        // Typed as any: Dexie returns Session|undefined, API returns ae_EventSession|null — both duck-type fine
        let session: any = await db_events.session.get(session_id);
        if (!session) {
            // Not cached — fetch from API and save to Dexie
            session = await events_func.load_ae_obj_id__event_session({
                api_cfg,
                event_session_id: session_id,
                try_cache: false,
                log_lvl: 0
            });
        }

        if (session?.event_location_id) {
            // Session has a location — redirect to the location-specific launcher URL.
            // replaceState: true so the user doesn't need to hit back twice to leave the launcher.
            goto(
                `/events/${event_id}/launcher/${session.event_location_id}?session_id=${session_id}`,
                { replaceState: true }
            );
        }
        // If the session has no location set, the user stays on the base launcher page
        // and the "Please select a location from the menu" prompt is shown by the layout.
    })();
});
</script>
