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

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

let log_lvl: number = 0;

// *** Import Svelte specific
import { onMount, onDestroy, untrack } from 'svelte';

// *** Import other supporting libraries
import { liveQuery } from 'dexie';

// *** Import Aether specific variables and functions
import { ae_util } from '$lib/ae_utils/ae_utils';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import { db_events } from '$lib/ae_events/db_events';
import { events_func } from '$lib/ae_events/ae_events_functions';
import {
    idaa_loc,
    idaa_sess,
    idaa_slct,
    idaa_trig,
    idaa_prom
} from '$lib/stores/ae_idaa_stores';

import Event_obj_id_edit from '../ae_idaa_comp__event_obj_id_edit.svelte';
import Event_obj_id_view from '.././ae_idaa_comp__event_obj_id_view.svelte';
import Help_tech from '$lib/app_components/e_app_help_tech.svelte';
import { api } from '$lib/ae_api/api';

// *** Quickly pull out data from parent(s)
let ae_acct = $derived(data[data.account_id]);

// Favorites stored in data_store (code: idaa_meetings_favorites, scoped to IDAA account_id).
// Same shared record used by the meeting list view; see ae_idaa_comp__event_obj_li.svelte.
let ds_fav_id = $state<string | null>(null);
let ds_fav_json = $state<Record<string, string[]>>({});
let fav_in_progress = $state(false);

let event_id_for_fav = $derived(ae_acct?.slct?.event_id ?? null);
let is_fav = $derived.by(() => {
    const my_uuid = $idaa_loc.novi_uuid;
    if (!my_uuid || !event_id_for_fav) return false;
    const my_favs = ds_fav_json[my_uuid];
    return Array.isArray(my_favs) && my_favs.includes(event_id_for_fav);
});

$idaa_sess.recovery_meetings.edit__event_obj = null;
$effect(() => {
    if (!ae_acct) return;
    if (log_lvl) console.log(`ae_acct = `, ae_acct);
    untrack(() => {
        $idaa_slct.event_id = ae_acct.slct.event_id;
        // $idaa_trig.event_id = ae_acct.slct.event_id;
        // $idaa_slct.event_obj = ae_acct.slct.event_obj;
    });
});

// Load single event — gated on auth.
// WHY $effect and not +page.ts: +page.ts runs during SvelteKit link prefetch,
// causing private IDAA data to be written to IDB before Novi auth runs.
// $effect only runs post-mount, after the layout has completed Novi verification.
$effect(() => {
    if (!$idaa_loc.novi_verified && !$ae_loc.trusted_access) return;
    const event_id = ae_acct?.slct?.event_id;
    if (!event_id) return;
    untrack(() => {
        events_func.load_ae_obj_id__event({
            api_cfg: $ae_api,
            event_id: event_id,
            log_lvl: log_lvl
        }).then((results) => {
            if (!results) {
                console.warn(
                    `IDAA Recovery Meetings [event_id] $effect: Event ${event_id} not found via API or Cache.`
                );
            }
        });
    });
});

// *** Functions and Logic
let lq__event_obj = $derived(
    liveQuery(async () => {
        if (log_lvl) {
            console.log(`lq__event_obj: event_id = ${$idaa_slct?.event_id}`);
        }
        let results = await db_events.event.get($idaa_slct?.event_id ?? ''); // null or undefined does not reset things like '' does

        // Check if results are different than the current $idaa_slct.event_obj.
        // Skip the sync while the edit form is open — overwriting would discard
        // the user's in-progress changes (e.g. weekday chips, pattern, times).
        if (
            $idaa_slct.event_obj &&
            results &&
            !$idaa_sess.recovery_meetings.edit__event_obj
        ) {
            if (
                JSON.stringify($idaa_slct.event_obj) !== JSON.stringify(results)
            ) {
                $idaa_slct.event_obj = { ...results };
                if (log_lvl) {
                    console.log(
                        `$idaa_slct.event_obj = `,
                        $idaa_slct.event_obj
                    );
                }
            } else {
                if (log_lvl) {
                    console.log(
                        `Event object has not changed for event_id: ${$idaa_slct.event_id}`
                    );
                }
            }
        }

        return results;
    })
);

// NOTE: onMount runs in browser only, so no browser guard needed.
// Use data[data.account_id].slct.event_id (from the load function / URL params),
// NOT $idaa_slct.event_id (the store) — the store is set by a $effect and may not
// reflect the correct value yet at this point.
onMount(() => {
    let message = { event_id: data[data.account_id]?.slct?.event_id ?? null };
    window.parent.postMessage(message, '*');

    if ($ae_loc?.iframe) {
        console.log(
            'In iframe, sending message to parent window to scroll to top as well'
        );
        window.parent.postMessage({ scroll_to: 0 }, '*'); // This should be in pixels
    }
});

onMount(async () => {
    if (!$idaa_loc.novi_uuid || !$ae_api?.base_url) return;
    try {
        const result = await api.get_data_store({
            api_cfg: $ae_api,
            code: 'idaa_meetings_favorites'
        });
        const rec_id = result?.data_store_id || result?.id;
        if (rec_id) {
            ds_fav_id = rec_id;
            let raw = result.json ?? result.json_str ?? null;
            if (typeof raw === 'string') {
                try { raw = JSON.parse(raw); } catch { raw = {}; }
            }
            ds_fav_json = (raw as Record<string, string[]>) ?? {};
        }
    } catch (err) {
        console.warn('[favorites] Failed to load favorites data store:', err);
    }
});

async function toggle_favorite() {
    const my_uuid = $idaa_loc.novi_uuid;
    const event_id = event_id_for_fav;
    if (!my_uuid || !event_id || !ds_fav_id || fav_in_progress) return;
    fav_in_progress = true;
    const current_user_list: string[] = Array.isArray(ds_fav_json[my_uuid])
        ? [...ds_fav_json[my_uuid]] : [];
    const new_user_list = is_fav
        ? current_user_list.filter((id) => id !== event_id)
        : [...current_user_list, event_id];
    const prev_json = ds_fav_json;
    const new_full_json = { ...ds_fav_json, [my_uuid]: new_user_list };
    ds_fav_json = new_full_json;
    try {
        await api.update_ae_obj({
            api_cfg: $ae_api,
            obj_type: 'data_store',
            obj_id: ds_fav_id,
            fields: { json: JSON.stringify(new_full_json) }
        });
    } catch (err) {
        console.warn('[favorites] API persist failed, rolling back:', err);
        ds_fav_json = prev_json;
    } finally {
        fav_in_progress = false;
    }
}

onDestroy(() => {
    if (log_lvl) {
        console.log(
            `Destroying recovery meetings page for event_id: ${$idaa_slct?.event_id}`
        );
    }

    let message = { event_id: null };
    window.parent.postMessage(message, '*');

    // $idaa_slct.event_id = null;
    // $idaa_slct.event_obj = null;
});
</script>

<svelte:head>
    <title>
        IDAA Recovery Mtgs:
        {$lq__event_obj?.name
            ? ae_util.shorten_string({
                  string: $lq__event_obj?.name,
                  max_length: 20,
                  begin_length: 10,
                  end_length: 4
              })
            : ''}
        - Novi - {$ae_loc?.title}
    </title>
</svelte:head>

<div
    class="ae_header flex w-full flex-row flex-wrap items-center justify-evenly gap-2">
    <h2
        class="
            ae_title event__title
            h3
            flex max-w-full
            min-w-1/2 flex-row items-center justify-center gap-2
            text-2xl
            font-bold
            ">
        <!-- <span class="ae_icon fas fa-calendar-alt"></span> -->
        <span class="ae_icon fas fa-calendar-day"></span>
        {$lq__event_obj?.name ? $lq__event_obj?.name : 'Recovery Meeting'}
    </h2>

    <div
        class="
            flex max-w-full min-w-1/4 flex-row items-center
            justify-evenly
            gap-2
        ">
        {#if $lq__event_obj?.status == 'unknown'}
            <span
                class="badge badge-warning preset-tonal-error"
                title="This meeting has not been confirmed by IDAA Central Office. Please reach out to the chair for current meeting list info. Meeting attendees can reach out to info@idaa.org if they know this is information is accurate and this meeting is still taking place.">
                <span class="fas fa-exclamation-triangle m-1"></span>
                Not Confirmed by IDAA
                <!-- Unknown Status -->
                <span class="fas fa-exclamation-triangle m-1"></span>
            </span>
        {/if}

        <span
            class="float-right flex flex-row flex-wrap items-center justify-end gap-1">
            <span class="badge badge-info preset-tonal-tertiary">
                {#if $lq__event_obj?.physical && $lq__event_obj?.virtual}
                    <span class="fas fa-home m-1"></span> F2F and
                    <span class="fas fa-laptop m-1"></span> Virtual
                {:else if $lq__event_obj?.physical}
                    <span class="fas fa-home m-1"></span> F2F
                {:else if $lq__event_obj?.virtual}
                    <span class="fas fa-laptop m-1"></span> Virtual
                {/if}
            </span>
            {#if $lq__event_obj?.type}
                <span class="badge badge-info preset-tonal-secondary"
                    ><span class="fas fa-user-md m-1"></span>
                    {$lq__event_obj?.type}</span>
            {/if}
            {#if $ae_loc.trusted_access && $lq__event_obj?.hide}
                <span class="badge badge-warning"
                    ><span class="fas fa-exclamation-triangle m-1"></span> Hidden</span>
            {/if}
            {#if $ae_loc.administrator_access && !$lq__event_obj?.enable}
                <span class="badge badge-warning preset-tonal-warning"
                    ><span class="fas fa-exclamation-triangle m-1"></span> Not enabled</span>
            {/if}
        </span>
    </div>

    <Help_tech
        e_class=""
        e_class_h1="novi_m0"
        e_class_h2="novi_m0"
        btn_class="novi_btn"
        show_btn_class="absolute top-0 right-0 float-right z-10"
        additional_kv={{
            novi_uuid: $idaa_loc.novi_uuid,
            novi_email: $idaa_loc.novi_email,
            novi_full_name: $idaa_loc.novi_full_name
        }}></Help_tech>
</div>

<div
    class="
        border-b-surface-300-700 mb-2 flex w-full flex-row
        items-center
        justify-evenly gap-2 border-b
        p-1 pb-2
        ">
    <a
        href="/idaa/recovery_meetings"
        class="
            novi_btn btn btn-secondary btn-sm
            preset-tonal-tertiary border-tertiary-500 hover:preset-filled-tertiary-500
            border
            transition
            ">
        <span class="fas fa-arrow-left m-1 text-neutral-800/80"></span> Back to
        Meeting List
        <!-- <span class="fas fa-times m-1"></span> View Other Meetings -->
    </a>

    {#if $idaa_loc.novi_uuid && ds_fav_id}
        <button
            type="button"
            onclick={toggle_favorite}
            disabled={fav_in_progress}
            aria-pressed={is_fav}
            style="background:none; border:none; box-shadow:none; padding:4px 8px; cursor:pointer; line-height:1; opacity:{is_fav ? '1' : '0.5'}; transition:opacity 0.15s, color 0.15s;"
            title={is_fav ? 'Remove from My Meetings' : 'Add to My Meetings'}>
            {#if fav_in_progress}
                <span class="fas fa-spinner fa-spin" style="font-size:1rem;"></span>
            {:else}
                <span class="fas fa-star" style="font-size:1rem; color:{is_fav ? '#d97706' : 'currentColor'};"></span>
            {/if}
            <span style="font-size:0.85rem; margin-left:3px;">{is_fav ? 'In My Meetings' : 'Add to My Meetings'}</span>
        </button>
    {/if}

    <!-- View (default)/Edit event_id toggle -->
    {#if $idaa_sess.recovery_meetings.edit__event_obj}
        <button
            type="button"
            class="
                novi_btn
                btn btn-sm
                preset-filled-warning-200-800 hover:preset-filled-success-200-800
                transition
                "
            onclick={() => {
                $idaa_sess.recovery_meetings.edit__event_obj = false;
                if (log_lvl) {
                    console.log(
                        `Toggle edit__event_obj: ${$idaa_sess.recovery_meetings.edit__event_obj}`
                    );
                }
            }}
            title="View this Recovery Meeting">
            <!-- <span class="far fa-window-close m-1"></span> -->
            <span class="fas fa-times m-1 text-neutral-800/80"></span>
            Cancel Edit
        </button>
    {:else}
        <!-- This checks if the currently logged in Novi user has a matching UUID or email address. -->
        {#if ($ae_loc.trusted_access && $ae_loc.edit_mode) || $lq__event_obj?.external_person_id === $idaa_loc.novi_uuid || ($lq__event_obj?.contact_li_json && $lq__event_obj.contact_li_json.length > 0 && $lq__event_obj.contact_li_json[0]?.email === $idaa_loc.novi_email)}
            <button
                type="button"
                class="
                    novi_btn
                    btn btn-sm preset-tonal-warning
                    hover:preset-filled-warning-500 transition
                    "
                onclick={() => {
                    $idaa_sess.recovery_meetings.edit__event_obj =
                        $idaa_slct.event_id;
                    if (log_lvl) {
                        console.log(
                            `Toggle edit__event_obj: ${$idaa_sess.recovery_meetings.edit__event_obj}`
                        );
                    }
                }}
                title="Edit this Recovery Meeting">
                <span class="fas fa-edit m-1 text-neutral-800/80"></span>
                Edit Meeting
            </button>
        {/if}
    {/if}
</div>

{#if $idaa_sess.recovery_meetings.edit__event_obj || $idaa_loc.recovery_meetings.edit__event_obj}
    <Event_obj_id_edit
        {lq__event_obj}
        bind:obj_changed={$idaa_sess.recovery_meetings.obj_changed} />
{:else}
    <Event_obj_id_view {lq__event_obj} />
{/if}
