<script lang="ts">
    interface Props {
        log_lvl?: number;
    }

    let { log_lvl = 0 }: Props = $props();

    // *** Import Svelte specific
    // import { browser } from '$app/environment';
    import { goto } from '$app/navigation';

    // *** Import other supporting libraries

    // *** Import Aether specific variables and functions
    import type { key_val } from '$lib/stores/ae_stores';
    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 { core_func } from '$lib/ae_core/ae_core_functions';
    import {
        idaa_loc,
        idaa_sess,
        idaa_slct,
        idaa_trig,
        idaa_prom
    } from '$lib/stores/ae_idaa_stores';
    import { events_func } from '$lib/ae_events_functions';

    import Help_tech from '$lib/app_components/e_app_help_tech.svelte';

    let ae_promises: key_val = $state({});

    /**
     * Session Persistent Search (Refactored 2026-01-20)
     *
     * WHY: If the user has 'save_search_text' enabled in their local profile,
     * we map the long-term saved strings into the current session store on mount.
     * This ensures the search bar is pre-populated with their last known query.
     */
    if (
        $idaa_loc.recovery_meetings?.save_search_text &&
        $idaa_loc.recovery_meetings?.saved_search__session
    ) {
        $idaa_sess.recovery_meetings.fulltext_search_qry_str =
            $idaa_loc.recovery_meetings.saved_search__session;
    }
    if (
        $idaa_loc.recovery_meetings?.save_search_text &&
        $idaa_loc.recovery_meetings?.saved_search__session_location_name
    ) {
        $idaa_sess.recovery_meetings.location_name_qry_str =
            $idaa_loc.recovery_meetings.saved_search__session_location_name;
    }

    // *** Functions and Logic
    /**
     * Reactive Search Trigger
     *
     * WHY: Instead of calling handle_search_refresh() directly (which can be messy with
     * Svelte 5's fine-grained reactivity), we increment a 'version' number.
     * The $effect in the parent +page.svelte tracks this version and handles the
     * debounced search cycle automatically.
     */
    function handle_search_trigger() {
        if ($idaa_loc.recovery_meetings.search_version === undefined) {
            $idaa_loc.recovery_meetings.search_version = 0;
        }
        $idaa_loc.recovery_meetings.search_version++;
    }

    function prevent_default<T extends Event>(fn: (event: T) => void) {
        return function (event: T) {
            event.preventDefault();
            fn(event);
        };
    }
</script>

<!-- preset-filled-surface-200-800 -->
<section
    class="
        ae_section ae_options filters_and_search
        flex flex-col flex-wrap gap-1 items-center justify-center
        my-2 p-2
        preset-outlined-surface-300-700
        rounded-lg
        d-flex
        align-items-center justify-content-center
        "
>
    <Help_tech
        e_class=""
        e_class_h1="novi_m0"
        e_class_h2="novi_m0"
        e_class_form_hidden="float-right"
        e_class_form_showing="float-none"
        btn_class="novi_btn"
        show_btn_class=""
        additional_kv={{
            novi_uuid: $idaa_loc.novi_uuid,
            novi_email: $idaa_loc.novi_email,
            novi_full_name: $idaa_loc.novi_full_name
        }}
    ></Help_tech>

    <!-- WARNING: Using m-auto to work in the Novi iframe -->
    <form
        onsubmit={prevent_default(() => {
            handle_search_trigger();
        })}
        autocomplete="off"
        class="
            search_form
            flex flex-col flex-wrap gap-1 items-center justify-center w-full max-w-2xl
            m-auto
            "
    >
        <div
            class="ae_group flex flex-row flex-wrap gap-2 w-full items-center justify-center border-b border-surface-300-700 p-1"
        >
            <button
                type="button"
                class="
                    novi_btn novi_smallest
                    btn btn-sm
                    preset-tonal-secondary
                    preset-outlined-secondary-200-800 hover:preset-filled-secondary-400-600
                    transition-all *:hover:inline
                    "
                onclick={() => {
                    $idaa_loc.recovery_meetings.qry__fulltext_str = '';
                    $idaa_sess.recovery_meetings.qry__fulltext_str = '';
                    handle_search_trigger();
                }}
                title="Clear search text"
            >
                <!-- <span class="fas fa-backspace"></span> -->
                <!-- <span class="fas fa-broom"></span> -->
                <span class="fas fa-remove-format"></span>
                <span class="hidden">Clear Text</span>
            </button>

            <!-- svelte-ignore a11y_autofocus -->
            <input
                type="search"
                placeholder="Name, location, day of week, contacts, etc."
                id="meeting_qry__fulltext_str"
                name="qry__fulltext_str"
                bind:value={$idaa_loc.recovery_meetings.qry__fulltext_str}
                autofocus
                style="width: 50%;"
                class="
                    input text-sm hover:text-2xl font-semibold font-mono w-80
                    transition-all
                    preset-tonal-tertiary
                    preset-outline-tertiary-200-800
                    form-control
                "
            />

            <button
                type="submit"
                class="
                    novi_btn btn-secondary font-weight-bold
                    btn btn-lg
                    preset-tonal-primary
                    preset-outlined-primary-200-800 hover:preset-filled-primary-400-600
                    text-2xl font-bold w-48
                    transition-all
                    "
                title="Search for meetings by day of week, location, contacts, etc."
            >
                <!-- <span class="fas fa-search m-1"></span> -->
                {#if $idaa_sess.recovery_meetings.qry__status == 'loading'}
                    <span
                        class="fas fa-spinner fa-spin mx-1 text-success-800-200"
                    ></span>
                {:else}
                    <span class="fas fa-search mx-1 text-neutral-800/80"></span>
                    <!-- {#if $idaa_sess.recovery_meetings.qry__status == 'done'}
                        <span class="fas fa-check m-1"></span>
                    {/if} -->
                {/if}
                Search
            </button>
        </div>

        <div
            class="flex flex-row flex-wrap gap-2 w-full max-w-xl items-center justify-start border-b border-surface-300-700 p-1"
        >
            <span class="text-xs form-check-label d-inline-block">
                Location?
            </span>
            <!-- <div class="ae_row ae_flex_justify_around ae_width_md"> -->
            <label
                class="legend w-auto text-sm font-semibold inline form-check-label flex-row gap-1 items-center justify-center d-inline-block"
            >
                <span> Virtual </span>
                <input
                    name="qry_virtual"
                    type="checkbox"
                    bind:checked={$idaa_loc.recovery_meetings.qry__virtual}
                    class="checkbox inline form-check-input d-inline-block"
                />
            </label>
            <label
                class="legend w-auto text-sm font-semibold inline form-check-label flex-row gap-1 items-center justify-center d-inline-block"
            >
                In-person
                <input
                    name="qry_physical"
                    type="checkbox"
                    bind:checked={$idaa_loc.recovery_meetings.qry__physical}
                    class="checkbox inline form-check-input d-inline-block"
                />
            </label>
            <!-- </div> -->
        </div>

        <div
            class="flex flex-row flex-wrap gap-2 w-full max-w-xl items-center justify-start border-b border-surface-300-700 p-1"
        >
            <span class="text-xs form-check-label d-inline-block"> Type? </span>

            <!-- <div class="ae_row ae_flex_justify_around ae_width_100"> -->
            <label
                class="legend w-auto text-sm font-semibold inline form-check-label flex-row gap-1 items-center justify-center d-inline-block"
            >
                <span> All </span>
                <input
                    name="qry_type"
                    type="radio"
                    value=""
                    bind:group={$idaa_loc.recovery_meetings.qry__type}
                    class="radio inline form-check-input d-inline-block"
                    title="Show all meeting types"
                />
            </label>
            <label
                class="legend w-auto text-sm font-semibold inline form-check-label flex-row gap-1 items-center justify-center d-inline-block"
            >
                IDAA
                <input
                    name="qry_type"
                    type="radio"
                    value="IDAA"
                    bind:group={$idaa_loc.recovery_meetings.qry__type}
                    class="radio inline form-check-input d-inline-block"
                    title="Open to IDAA members only"
                />
            </label>
            <label
                class="legend w-auto text-sm font-semibold inline form-check-label flex-row gap-1 items-center justify-center d-inline-block"
            >
                Caduceus
                <input
                    name="qry_type"
                    type="radio"
                    value="Caduceus"
                    bind:group={$idaa_loc.recovery_meetings.qry__type}
                    class="radio inline form-check-input d-inline-block"
                    title="Open to all healthcare workers including those who do not qualify for IDAA"
                />
            </label>
            <label
                class="legend w-auto text-sm font-semibold inline form-check-label flex-row gap-1 items-center justify-center d-inline-block"
            >
                Family Recovery
                <input
                    name="qry_type"
                    type="radio"
                    value="Family Recovery"
                    bind:group={$idaa_loc.recovery_meetings.qry__type}
                    class="radio inline form-check-input d-inline-block"
                    title="Open to spouses, parents, and children of medical professionals who have substance use disorder."
                />
            </label>

            <span class="ml-auto"></span>

            {#if $ae_loc.edit_mode}
                <label
                    class="legend w-auto text-sm font-semibold inline form-check-label flex-row gap-1 items-center justify-center d-inline-block"
                    title="When enabled, search results are fetched directly from the server first. When disabled, local results are shown instantly while revalidating in the background."
                >
                    <span class="text-xs"> Remote First? </span>
                    <input
                        name="qry_remote_first"
                        type="checkbox"
                        bind:checked={
                            $idaa_loc.recovery_meetings.qry__remote_first
                        }
                        class="checkbox inline form-check-input d-inline-block"
                    />
                </label>
            {/if}
        </div>
    </form>

    <div
        class="ae_group ae_row flex flex-row flex-wrap gap-2 w-full max-w-full items-center justify-center p-1"
    >
        <!-- Max events select options -->
        <span class="flex flex-row gap-1 items-center justify-around">
            <label
                class="text-sm w-32 md:w-42 form-group"
                for="qry_limit__events"
            >
                Max results:

                <select
                    id="qry_limit__events"
                    bind:value={$idaa_loc.recovery_meetings.qry__limit}
                    class="
                    select w-20 text-sm inline-block
                    px-1
                    preset-tonal-tertiary
                    preset-outline-tertiary-200-800
                    form-control col-sm-12
                "
                >
                    <option value={10}>10</option>
                    <option value={25}>25</option>
                    <option value={50}>50</option>
                    <option value={75}>75</option>
                    <option value={100}>100</option>
                    <option value={150}>150</option>
                    <option value={200} class:hidden={!$ae_loc.trusted_access}
                        >200</option
                    >
                    <option value={500} class:hidden={!$ae_loc.trusted_access}
                        >500</option
                    >
                </select>
            </label>
            <!-- </span> -->

            <!-- Sort by last updated date or by name -->
            <!-- <span
            class="flex flex-row gap-1 items-center justify-around"
            > -->
            <label
                class="text-sm w-32 md:w-42 form-group"
                for="qry_order_by__events"
            >
                Sort by:

                <select
                    id="qry_order_by__events"
                    bind:value={$idaa_loc.recovery_meetings.qry__order_by}
                    onchange={() => {
                        const mode = $idaa_loc.recovery_meetings.qry__order_by;
                        if (mode === 'updated_on') {
                            $idaa_loc.recovery_meetings.qry__order_by_li = {
                                priority: 'DESC',
                                sort: 'DESC',
                                updated_on: 'DESC',
                                created_on: 'DESC',
                                name: 'ASC'
                            };
                        } else if (mode === 'name_asc') {
                            $idaa_loc.recovery_meetings.qry__order_by_li = {
                                priority: 'DESC',
                                sort: 'DESC',
                                name: 'ASC',
                                updated_on: 'DESC',
                                created_on: 'DESC'
                            };
                        } else if (mode === 'name_desc') {
                            $idaa_loc.recovery_meetings.qry__order_by_li = {
                                priority: 'DESC',
                                sort: 'DESC',
                                name: 'DESC',
                                updated_on: 'DESC',
                                created_on: 'DESC'
                            };
                        }
                        handle_search_trigger();
                    }}
                    class="
                    select w-40 text-sm inline-block
                    px-1
                    preset-tonal-tertiary
                    preset-outline-tertiary-200-800
                    form-control col-sm-12
                "
                >
                    <option value="updated_on">Last Updated</option>
                    <option value="name_asc">Meeting Name (A-Z)</option>
                    <option value="name_desc">Meeting Name (Z-A)</option>
                </select>
            </label>
        </span>

        <span class="flex flex-row gap-1 items-center justify-around">
            {#if $ae_loc.edit_mode && $ae_loc.trusted_access && (!$idaa_loc.recovery_meetings.qry__hidden || $idaa_loc.recovery_meetings.qry__hidden == 'not_hidden')}
                <button
                    type="button"
                    onclick={() => {
                        $idaa_loc.recovery_meetings.qry__hidden = 'all';
                        $idaa_loc.recovery_meetings.qry__limit = 200;
                    }}
                    class="
                    novi_btn btn_show_recovery_mtg_event ae_btn btn-info
                    btn btn-sm
                    preset-tonal-secondary preset-outlined-secondary-200-800 hover:preset-filled-secondary-200-800
                    transition
                    "
                >
                    <span class="fas fa-eye m-1"></span> Show Hidden Events
                </button>
            {:else if $ae_loc.trusted_access && $idaa_loc.recovery_meetings.qry__hidden != 'not_hidden'}
                <button
                    type="button"
                    onclick={() => {
                        $idaa_loc.recovery_meetings.qry__hidden = 'not_hidden';
                    }}
                    class="
                    novi_btn btn_hide_recovery_mtg_event ae_btn btn-info
                    btn btn-sm
                    preset-tonal-secondary preset-outlined-secondary-200-800 hover:preset-filled-secondary-200-800
                    transition
                    "
                >
                    <span class="fas fa-eye-slash m-1"></span> Hide Hidden Events
                </button>
            {/if}

            {#if $ae_loc.edit_mode && $ae_loc.manager_access && (!$idaa_loc.recovery_meetings.qry__enabled || $idaa_loc.recovery_meetings.qry__enabled == 'enabled')}
                <button
                    type="button"
                    onclick={() => {
                        $idaa_loc.recovery_meetings.qry__hidden = 'all';
                        $idaa_loc.recovery_meetings.qry__enabled = 'all';
                        // NOTE: I may re-enable this limit reset later. It is sometimes useful.
                        // $idaa_loc.recovery_meetings.qry__limit = 500;
                    }}
                    class="
                    novi_btn btn_show_recovery_mtg_event ae_btn btn-warning
                    btn btn-sm
                    preset-tonal-warning preset-outlined-warning-200-800 hover:preset-filled-warning-200-800
                    transition
                    "
                >
                    <span class="fas fa-eye m-1"></span> Show Disabled Events
                </button>
            {:else if $ae_loc.edit_mode && $ae_loc.manager_access && $idaa_loc.recovery_meetings.qry__enabled != 'enabled'}
                <button
                    type="button"
                    onclick={() => {
                        $idaa_loc.recovery_meetings.qry__enabled = 'enabled';
                    }}
                    class="
                    novi_btn btn_hide_recovery_mtg_event ae_btn btn-warning
                    btn btn-sm
                    preset-tonal-warning preset-outlined-warning-200-800 hover:preset-filled-warning-200-800
                    transition
                    "
                >
                    <span class="fas fa-eye-slash m-1"></span> Hide Disabled Events
                </button>
            {/if}
        </span>

        <span class="flex flex-row gap-1 items-center justify-around">
            {#if ($ae_loc.trusted_access && $ae_loc.edit_mode) || $idaa_loc.novi_uuid}
                <button
                    type="button"
                    onclick={() => {
                        if (!confirm('Create new meeting?')) {
                            return false;
                        }
                        $idaa_slct.event_id = null;
                        $idaa_slct.event_obj = {};

                        let data_kv = {
                            name: 'Change NEW Recovery Meeting Name'
                        };
                        if (log_lvl) {
                            console.log(
                                'Creating new event (recovery meeting) with data_kv:',
                                data_kv
                            );
                        }

                        events_func
                            .create_ae_obj__event({
                                api_cfg: $ae_api,
                                account_id: $ae_loc.account_id,
                                data_kv: data_kv,
                                log_lvl: log_lvl
                            })
                            .then((results) => {
                                if (results) {
                                    $idaa_slct.event_id =
                                        results.event_id;
                                    $idaa_slct.event_obj = { ...results };
                                    $idaa_sess.recovery_meetings.edit__event_obj =
                                        results.event_id;

                                    if (log_lvl) {
                                        console.log(`New event created with ID: ${results.event_id}`);
                                    }
                                    goto(
                                        `/idaa/recovery_meetings/${results.event_id}`
                                    );
                                }
                            })
                            .catch((error) => {
                                console.error('Error creating event:', error);
                                alert('Failed to create new event.');
                            });
                    }}
                    class="
                novi_btn btn-tertiary
                text-xs
                btn btn-sm
                preset-tonal-warning preset-outlined-warning-200-800 hover:preset-filled-warning-200-800
                transition
                "
                    disabled={!$ae_loc.authenticated_access}
                >
                    <span class="fas fa-plus m-1"></span> Create New Meeting
                </button>
            {/if}

            {#if $ae_loc.edit_mode && $ae_loc.trusted_access}
                <button
                    type="button"
                    onclick={() => {
                        if (!confirm('Download exported data Excel file?')) {
                            return false;
                        }
                        ae_promises.download__events_export =
                            core_func.download_export__obj_type({
                                api_cfg: $ae_api,
                                get_obj_type: 'event',
                                for_obj_type: 'account',
                                for_obj_id: $ae_loc.account_id,
                                exp_alt: 'idaa',
                                file_type: 'Excel',
                                return_file: true,
                                filename: `${$ae_loc.account_code}_IDAA_Recovery_Meetings_export_${ae_util.iso_datetime_formatter()}.xlsx`,
                                auto_download: true,
                                log_lvl: 1
                            });
                    }}
                    class="
                novi_btn btn-tertiary
                text-xs
                btn btn-sm
                preset-tonal-warning preset-outlined-warning-200-800 hover:preset-filled-warning-200-800
                transition
                "
                    title={`Download meeting data for ${$ae_loc.account_name}`}
                >
                    {#await ae_promises.download__events_export}
                        <span class="fas fa-spinner fa-spin m-1"></span>
                    {:then}
                        <span class="fas fa-download m-1"></span>
                    {/await}
                    Export All Data
                </button>
            {/if}
        </span>
    </div>
</section>
