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

let log_lvl: number = $state(0);

// *** Import Svelte specific
// import { page } from '$app/state';
import { browser } from '$app/environment';

// *** Import other supporting libraries
import { db_events } from '$lib/ae_events/db_events';
import {
    idaa_loc,
    idaa_sess,
    idaa_slct,
    idaa_trig
} from '$lib/stores/ae_idaa_stores';
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import { events_func } from '$lib/ae_events/ae_events_functions';

import Element_data_store from '$lib/elements/element_data_store.svelte';
import Comp__event_obj_qry from './ae_idaa_comp__event_obj_qry.svelte';
import Comp__event_obj_li_wrapper from './ae_idaa_comp__event_obj_li_wrapper.svelte';

if (browser) {
    $idaa_slct.event_id = null;
    window.parent.postMessage({ event_id: null }, '*');

    // Use versioning instead of boolean to avoid loops
    if ($idaa_loc.recovery_meetings.search_version === undefined) {
        $idaa_loc.recovery_meetings.search_version = 0;
    }
    $idaa_loc.recovery_meetings.search_version++;
}

let event_id_li: Array<string> = $state([]);
let search_debounce_timer: any = null;
let last_search_id = 0;

// Standardized Reactive Search Pattern (Aether UI V3)
// This effect manages the orchestration between UI state and data fetching.
$effect(() => {
    // 1. Reactive Dependencies
    const account_id = $ae_loc.account_id;
    if (!account_id) return; // Wait for account context

    // Auth gate: do not fetch IDAA events for unauthenticated users.
    // WHY $effect and not +layout.ts: layout load functions fire on SvelteKit link prefetch,
    // causing private data to be written to IDB before Novi auth runs.
    if (!$idaa_loc.novi_verified && !$ae_loc.trusted_access) return;

    // Track filters and the search version (trigger)
    const qry_params = {
        v: $idaa_loc.recovery_meetings.search_version,
        str: $idaa_loc.recovery_meetings.qry__fulltext_str,
        phys: $idaa_loc.recovery_meetings.qry__physical,
        virt: $idaa_loc.recovery_meetings.qry__virtual,
        type: $idaa_loc.recovery_meetings.qry__type,
        limit: $idaa_loc.recovery_meetings.qry__limit,
        order: $idaa_loc.recovery_meetings.qry__order_by,
        remote: $idaa_loc.recovery_meetings.qry__remote_first
    };

    // 2. Debounce Logic
    if (search_debounce_timer) clearTimeout(search_debounce_timer);
    search_debounce_timer = setTimeout(() => {
        // 3. Execution (Untracked to prevent loops)
        untrack(() => {
            handle_search_refresh();
        });
    }, 250);

    return () => {
        if (search_debounce_timer) clearTimeout(search_debounce_timer);
    };
});

/**
 * SWR (Stale-While-Revalidate) Search Orchestrator
 *
 * GOAL: Render matching meetings in < 50ms, then update with perfect server data.
 */
async function handle_search_refresh() {
    const current_search_id = ++last_search_id;
    const account_id = $ae_loc.account_id;
    const remote_first = $idaa_loc.recovery_meetings.qry__remote_first;

    if (!account_id) return;

    if (log_lvl)
        console.log(
            `[Search #${current_search_id}] Refreshing recovery meetings (remote_first=${remote_first}) for account: ${account_id}...`
        );

    $idaa_sess.recovery_meetings.qry__status = 'loading';

    // If 'Remote First' is toggled (Admin only), we clear results immediately to show fresh state.
    if (remote_first) {
        event_id_li = [];
    }

    // Snapshot parameters to ensure the Fast Path and Revalidation are using the same criteria.
    const qry_str = ($idaa_loc.recovery_meetings.qry__fulltext_str ?? '')
        .toLowerCase()
        .trim();
    const qry_physical = $idaa_loc.recovery_meetings.qry__physical;
    const qry_virtual = $idaa_loc.recovery_meetings.qry__virtual;
    const qry_type = $idaa_loc.recovery_meetings.qry__type;

    let local_ids: string[] = [];

    // 1. FAST PATH: Local IDB Search
    // We query Dexie first to show results from the 499-item cache pool instantly.
    if (!remote_first) {
        try {
            let local_results = await db_events.event
                .filter((ev) => {
                    // Resilient account check
                    const acct_match = ev.account_id === account_id;
                    if (!acct_match) return false;

                    if (qry_type && ev.type !== qry_type) return false;
                    if (qry_physical || qry_virtual) {
                        let match = false;
                        // Loose equality to handle 1, '1', true from DB
                        if (qry_physical && ev.physical == true) match = true;
                        if (qry_virtual && ev.virtual == true) match = true;
                        if (!match) return false;
                    }
                    if (qry_str) {
                        const name = (ev.name ?? '').toLowerCase();
                        const desc = (ev.description ?? '').toLowerCase();
                        const loc = (ev.location_text ?? '').toLowerCase();
                        const dqs = (ev.default_qry_str ?? '').toLowerCase();
                        return (
                            name.includes(qry_str) ||
                            desc.includes(qry_str) ||
                            loc.includes(qry_str) ||
                            dqs.includes(qry_str)
                        );
                    }
                    return true;
                })
                .toArray();

            // Sort local results matching UI selection (Refactored 2026-02-16)
            const sort_mode = $idaa_loc.recovery_meetings.qry__order_by;
            if (sort_mode === 'name_asc' || sort_mode === 'name') {
                local_results.sort((a, b) =>
                    (a.name ?? '').localeCompare(b.name ?? '')
                );
            } else if (sort_mode === 'name_desc') {
                local_results.sort((a, b) =>
                    (b.name ?? '').localeCompare(a.name ?? '')
                );
            } else {
                // Robust Chronological Sort using pre-computed tmp_sort_1
                // Handles Priority, Manual Sort, and the updated_on/created_on fallback
                local_results.sort((a, b) =>
                    (b.tmp_sort_1 ?? '').localeCompare(a.tmp_sort_1 ?? '')
                );
            }

            local_ids = local_results.map((e) => String(e.id)).filter(Boolean);

            // Update UI immediately. This eliminates the "white page" during searching.
            if (current_search_id === last_search_id) {
                if (log_lvl)
                    console.log(
                        `[Search #${current_search_id}] Fast Path complete. Found ${local_ids.length} items locally.`
                    );
                event_id_li = local_ids;
                if (local_ids.length > 0) {
                    $idaa_sess.recovery_meetings.qry__status = 'done';
                }
            }
        } catch (e) {
            if (log_lvl)
                console.warn('Fast Path failed, waiting for API...', e);
        }
    }

    // 2. REVALIDATE: Server API Search
    // This hits the full database, bypassing the "cache pool" limitation.
    try {
        const results = await events_func.search__event({
            api_cfg: $ae_api,
            for_obj_type: 'account',
            for_obj_id: account_id,
            qry_conference: false,
            qry_physical: qry_physical,
            qry_virtual: qry_virtual,
            qry_type: qry_type,
            qry_str: qry_str || null,
            enabled: $idaa_loc.recovery_meetings.qry__enabled,
            hidden: $idaa_loc.recovery_meetings.qry__hidden,
            limit: $idaa_loc.recovery_meetings.qry__limit,
            order_by_li: $idaa_loc.recovery_meetings.qry__order_by_li,
            log_lvl: 0
        });

        if (current_search_id === last_search_id) {
            let api_results = results || [];

            // SECONDARY FILTER: Ensure API results respect exact UI filters (handles backend broadness)
            api_results = api_results.filter((ev: any) => {
                if (qry_type && ev.type !== qry_type) return false;
                if (qry_physical || qry_virtual) {
                    let match = false;
                    if (qry_physical && ev.physical == true) match = true;
                    if (qry_virtual && ev.virtual == true) match = true;
                    if (!match) return false;
                }
                if (qry_str && qry_str.length >= 3) {
                    const name = (ev.name ?? '').toLowerCase();
                    const desc = (ev.description ?? '').toLowerCase();
                    const loc = (ev.location_text ?? '').toLowerCase();
                    const dqs = (ev.default_qry_str ?? '').toLowerCase();
                    if (
                        !name.includes(qry_str) &&
                        !desc.includes(qry_str) &&
                        !loc.includes(qry_str) &&
                        !dqs.includes(qry_str)
                    )
                        return false;
                }
                return true;
            });

            // RE-SORT: Ensure perfect chronological order even if API puts NULLs last (Refactored 2026-02-16)
            if ($idaa_loc.recovery_meetings.qry__order_by === 'name') {
                api_results.sort((a, b) =>
                    (a.name ?? '').localeCompare(b.name ?? '')
                );
            } else {
                api_results.sort((a, b) =>
                    (b.tmp_sort_1 ?? '').localeCompare(a.tmp_sort_1 ?? '')
                );
            }

            const api_ids = api_results
                .map((e: any) => String(e.id))
                .filter(Boolean);

            // UI PROTECTION: Preserve results if API returns nothing (0 results)
            // BUT only if it was a successful empty response, not a failure.
            // ALSO: Only protect if qry_str was the primary change.
            // If Type or Location changed, we want to see the 0.
            const filter_changed =
                qry_type !==
                    $idaa_sess.recovery_meetings.status_qry__last_type ||
                qry_physical !==
                    $idaa_sess.recovery_meetings.status_qry__last_phys ||
                qry_virtual !==
                    $idaa_sess.recovery_meetings.status_qry__last_virt;

            if (
                api_ids.length === 0 &&
                local_ids.length > 0 &&
                !remote_first &&
                !filter_changed
            ) {
                if (log_lvl)
                    console.warn(
                        `[Search #${current_search_id}] API returned 0 matching results. Preserving local cache view.`
                    );
                $idaa_sess.recovery_meetings.qry__status = 'done';
                return;
            }

            $idaa_slct.event_obj_li = api_results;
            event_id_li = api_ids;

            // Snapshot last used filters for future protection checks
            $idaa_sess.recovery_meetings.status_qry__last_request_str = qry_str;
            $idaa_sess.recovery_meetings.status_qry__last_type = qry_type;
            $idaa_sess.recovery_meetings.status_qry__last_phys = qry_physical;
            $idaa_sess.recovery_meetings.status_qry__last_virt = qry_virtual;

            $idaa_sess.recovery_meetings.qry__status = 'done';
            if (log_lvl)
                console.log(
                    `[Search #${current_search_id}] Revalidation Complete. Found ${api_ids.length} items.`
                );
        }
    } catch (error) {
        if (current_search_id === last_search_id) {
            console.error('Revalidation failed:', error);
            $idaa_sess.recovery_meetings.qry__status = 'error';

            // If the API failed (e.g. 400/500), we should NOT preserve results from a
            // previous successful search as it's misleading.
            // We clear the list so the 'No recovery meetings found' / Error message shows.
            event_id_li = [];
        }
    }
}

if (browser) {
    console.log('Browser environment ready.');
    window.parent.postMessage({ event_id: $idaa_slct?.event_id ?? null }, '*');
}
</script>

<svelte:head>
    <title>
        IDAA Recovery Meetings - Novi - {$ae_loc?.title}
    </title>
</svelte:head>

<Comp__event_obj_qry />

<Element_data_store
    ds_code="recovery_meetings_info"
    ds_type="html"
    class_li="rounded-lg preset-outlined-surface-200-800 m-auto p-2 space-y-2 w-full max-w-xl"
    show_edit_btn={true} />

{#if Array.isArray(event_id_li) && event_id_li.length}
    <Comp__event_obj_li_wrapper
        {event_id_li}
        link_to_type={'account'}
        link_to_id={$ae_loc.account_id}
        limit={$idaa_loc.recovery_meetings.qry__limit}
        {log_lvl} />
{:else}
    <div class="space-y-2">
        {#if $idaa_sess.recovery_meetings.qry__status === 'loading'}
            <div
                class="ae_highlight ae_padding_md ae_row ae_flex_justify_center">
                <span class="fas fa-spinner fa-spin m-1"></span>
                Searching...
            </div>
        {:else}
            <div
                class="ae_highlight ae_padding_md ae_row ae_flex_justify_center">
                No recovery meetings found matching your criteria.
            </div>
        {/if}
    </div>
{/if}
