<script lang="ts">
interface Props {
    /** @type {import('./$types').PageData} */
    data: any;
}

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

let log_lvl: number = $state(0);

// Imports
import { untrack } from 'svelte';
import { browser } from '$app/environment';
import { ae_util } from '$lib/ae_utils/ae_utils';

import { liveQuery } from 'dexie';
import { db_events } from '$lib/ae_events/db_events';
import {
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import {
    events_sess,
    events_slct,
    events_trigger,
    events_trig_kv
} from '$lib/stores/ae_events_stores';
import { events_func } from '$lib/ae_events/ae_events_functions';

import Comp_event_files_upload from '../../../../ae_comp__event_files_upload.svelte';
import Comp_event_session_obj_li from '../../../../ae_comp__event_session_obj_li.svelte';
import Element_manage_event_file_li_wrap from '$lib/elements/element_manage_event_file_li_direct.svelte';
import Location_view from './ae_comp__location_view.svelte';
import Location_page_menu from './ae_comp__location_page_menu.svelte';
import { LoaderCircle, TriangleAlert } from '@lucide/svelte';
// Variables
// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
let ae_acct = $derived(data[data.account_id]);

$effect(() => {
    if (browser) {
        console.log('Browser environment detected.');
    }
});

$effect(() => {
    if (!ae_acct) return;
    untrack(() => {
        $ae_loc.url_origin = data.url.origin;

        $events_slct.event_id = ae_acct.slct.event_id;
        $events_slct.event_location_id = ae_acct.slct.event_location_id;
        $events_slct.event_session_id = null;
        $events_slct.event_session_obj_li = ae_acct.slct.event_session_obj_li;



        if (!$events_sess.pres_mgmt) {
            $events_sess.pres_mgmt = {};
        }
    });
});

// WHY: Dexie starts empty on first load — liveQuery returns nothing until files are fetched.
// The upload component and refresh button are targeted, but nothing triggers the initial load.
$effect(() => {
    const location_id = ae_acct?.slct?.event_location_id;
    if (!location_id || !$ae_api) return;
    events_func.load_ae_obj_li__event_file({
        api_cfg: $ae_api,
        for_obj_type: 'event_location',
        for_obj_id: location_id,
        enabled: 'all',
        hidden: 'all',
        try_cache: true
    });
});

let lq__event_obj = $derived(
    liveQuery(async () => {
        if (!ae_acct?.slct.event_id) return null;
        return await db_events.event.get(ae_acct.slct.event_id);
    })
);

// Sync server-side pres_mgmt config into local PersistedState.
// WHY: this page can be reached directly without first visiting the pres_mgmt
// overview or a session page — the only other places this sync runs. Without
// it, pres_mgmt_loc.current keeps stale defaults for the session list rendered
// below (e.g. hide__session_poc, show__session_li_poc_field).
$effect(() => {
    const remote_cfg = $lq__event_obj?.mod_pres_mgmt_json;
    if (remote_cfg) {
        untrack(() => {
            events_func.sync_config__event_pres_mgmt({
                pres_mgmt_cfg_remote: remote_cfg,
                log_lvl: 0
            });
        });
    }
});

let lq__event_location_obj = $derived(
    liveQuery(async () => {
        if (!ae_acct?.slct.event_location_id) return null;
        return await db_events.location.get(ae_acct.slct.event_location_id);
    })
);

let lq__event_session_obj_li = $derived(
    liveQuery(async () => {
        if (!ae_acct?.slct.event_location_id) return [];
        return await db_events.session
            .where('event_location_id')
            .equals(ae_acct.slct.event_location_id)
            .sortBy('start_datetime');
    })
);
</script>

<svelte:head>
    <title>
        Location: {ae_util.shorten_string({
            string: $lq__event_location_obj?.name ?? 'Loading...',
            max_length: 12
        })} - Pres Mgmt
    </title>
</svelte:head>

<div
    class="ae_events_pres_mgmt_event_location mx-auto w-full max-w-7xl space-y-6">
    <Location_page_menu {lq__event_location_obj} {lq__event_obj} />

    {#if !$lq__event_location_obj}
        <div class="flex items-center justify-center py-10">
            <LoaderCircle size="1em" class="mr-2 animate-spin" />
            <span>Loading location...</span>
        </div>
    {:else if !$lq__event_location_obj.enable && !$ae_loc.trusted_access}
        <div class="bg-warning-100 border-warning-300 rounded-md border p-4">
            <h2 class="h3">
                <TriangleAlert size="1em" class="text-warning-500 m-1" />
                Location Disabled
            </h2>
            <p>
                This location is currently disabled. Please contact the event
                organizer for more information.
            </p>
        </div>
    {:else}
        <div
            class="bg-surface-50-950 border-surface-200-800 rounded-xl border p-4 shadow-sm">
            <Location_view {lq__event_location_obj} />
        </div>

        <div class="space-y-4">
            <h3 class="h3 border-surface-500/20 border-b pb-2 font-bold">
                Sessions at this Location
            </h3>
            <Comp_event_session_obj_li
                {lq__event_session_obj_li}
                hide__session_location={true}
                {log_lvl} />
        </div>

        {#if $ae_loc.trusted_access}
            <div class="space-y-4">
                <h3 class="h3 border-surface-500/20 border-b pb-2 font-bold">
                    Location Files
                </h3>
                <Comp_event_files_upload
                    link_to_type="event_location"
                    link_to_id={$lq__event_location_obj.event_location_id} />
                <Element_manage_event_file_li_wrap
                    link_to_type="event_location"
                    link_to_id={$lq__event_location_obj.event_location_id} />
            </div>
        {/if}
    {/if}
</div>
