<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/ae_events_functions';

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

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

// Predefined limit steps for the +/- stepper. Trusted staff get larger options
// since they often query with disabled/hidden meetings included.
let limit_steps = $derived($ae_loc.trusted_access ? [25, 50, 75, 100, 150, 200, 500] : [25, 50, 75, 100, 150]);
let limit_idx = $derived.by(() => {
    const idx = limit_steps.indexOf($idaa_loc.recovery_meetings.qry__limit);
    return idx >= 0 ? idx : limit_steps.length - 1;
});

// *** 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() {
    $idaa_sess.recovery_meetings.search_version++;
}

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

const sort_modes = [
    { mode: 'updated_on', label: 'Last Updated', icon: 'fa-clock',             order_by_li: { priority: 'DESC', sort: 'DESC', updated_on: 'DESC', created_on: 'DESC', name: 'ASC'  } },
    { mode: 'name_asc',   label: 'Name A→Z',     icon: 'fa-sort-alpha-down',   order_by_li: { priority: 'DESC', sort: 'DESC', name: 'ASC',        updated_on: 'DESC', created_on: 'DESC' } },
    { mode: 'name_desc',  label: 'Name Z→A',     icon: 'fa-sort-alpha-up-alt', order_by_li: { priority: 'DESC', sort: 'DESC', name: 'DESC',       updated_on: 'DESC', created_on: 'DESC' } }
];

let sort_cycle_idx = $derived.by(() => {
    const idx = sort_modes.findIndex(m => m.mode === $idaa_loc.recovery_meetings.qry__order_by);
    return idx >= 0 ? idx : 0;
});
let current_sort = $derived(sort_modes[sort_cycle_idx]);

function cycle_sort() {
    const next = sort_modes[(sort_cycle_idx + 1) % sort_modes.length];
    $idaa_loc.recovery_meetings.qry__order_by = next.mode;
    $idaa_loc.recovery_meetings.qry__order_by_li = next.order_by_li;
    handle_search_trigger();
}
</script>

<!-- preset-filled-surface-200-800 -->
<section
    class="
        ae_section ae_options filters_and_search
        preset-outlined-surface-300-700 d-flex align-items-center justify-content-center my-2 flex
        flex-col flex-wrap
        items-center
        justify-center
        gap-1
        rounded-lg p-2
        ">
    <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
            m-auto flex w-full max-w-2xl flex-col flex-wrap items-center justify-center
            gap-1
            ">
        <div
            class="ae_group border-surface-300-700 flex w-full flex-row flex-wrap items-center justify-center gap-2 border-b 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 preset-tonal-tertiary preset-outline-tertiary-200-800 form-control w-80 font-mono
                    text-sm
                    font-semibold
                    transition-all
                    hover:text-2xl
                " />

            <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
                    w-48 text-2xl font-bold
                    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 text-success-800-200 mx-1"
                    ></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>

        <!-- Filter chips: My Meetings + Location + Type -->
        <div
            class="border-surface-300-700 flex w-full max-w-2xl flex-row flex-wrap items-center justify-center gap-x-4 gap-y-1 border-b p-1">

            <!-- My Meetings: favorites filter — shown only to logged-in Novi members -->
            {#if $idaa_loc.novi_uuid}
                <button
                    type="button"
                    onclick={() => {
                        $idaa_loc.recovery_meetings.qry__favorites_only =
                            !$idaa_loc.recovery_meetings.qry__favorites_only;
                    }}
                    class="novi_btn btn-star btn btn-sm transition-all
                        {$idaa_loc.recovery_meetings.qry__favorites_only
                            ? 'preset-filled-warning-300-700'
                            : 'preset-outlined-surface-300-700 opacity-60 hover:opacity-100'}"
                    title={$idaa_loc.recovery_meetings.qry__favorites_only
                        ? 'Showing My Meetings only — click to show all'
                        : 'Show only My Meetings (starred)'}>
                    <span class="fas fa-star m-1 {$idaa_loc.recovery_meetings.qry__favorites_only ? 'text-yellow-600' : ''}"></span>
                    My Meetings
                </button>
            {/if}

            <!-- Location: independent toggles (a meeting can be both virtual and in-person) -->
            <div class="flex flex-row flex-wrap items-center gap-1">
                <span class="sr-only">Location:</span>
                <button
                    type="button"
                    onclick={() => { $idaa_loc.recovery_meetings.qry__virtual = !$idaa_loc.recovery_meetings.qry__virtual; }}
                    aria-pressed={$idaa_loc.recovery_meetings.qry__virtual}
                    title="Show virtual / online meetings"
                    class="novi_btn btn btn-sm transition-all
                        {$idaa_loc.recovery_meetings.qry__virtual
                            ? 'preset-filled-tertiary-400-600'
                            : 'preset-outlined-surface-300-700 opacity-60 hover:opacity-100'}">
                    <span class="fas fa-laptop mr-1"></span>Virtual
                </button>
                <button
                    type="button"
                    onclick={() => { $idaa_loc.recovery_meetings.qry__physical = !$idaa_loc.recovery_meetings.qry__physical; }}
                    aria-pressed={$idaa_loc.recovery_meetings.qry__physical}
                    title="Show in-person / face-to-face meetings"
                    class="novi_btn btn btn-sm transition-all
                        {$idaa_loc.recovery_meetings.qry__physical
                            ? 'preset-filled-tertiary-400-600'
                            : 'preset-outlined-surface-300-700 opacity-60 hover:opacity-100'}">
                    <span class="fas fa-home mr-1"></span>In-Person
                </button>
            </div>

            <!-- Type: mutually exclusive; clicking the active chip deselects (goes back to All) -->
            <div class="flex flex-row flex-wrap items-center gap-1">
                <span class="sr-only">Type:</span>
                {#each [
                    ['', 'All', 'Show all meeting types'],
                    ['IDAA', 'IDAA', 'Open to IDAA members only'],
                    ['Caduceus', 'Caduceus', 'Open to all healthcare workers including those who do not qualify for IDAA'],
                    ['Family Recovery', 'Family Recovery', 'Open to spouses, parents, and children of medical professionals in recovery']
                ] as [val, label, tip] (val)}
                    {@const active = val === '' ? !$idaa_loc.recovery_meetings.qry__type : $idaa_loc.recovery_meetings.qry__type === val}
                    <button
                        type="button"
                        onclick={() => {
                            $idaa_loc.recovery_meetings.qry__type =
                                (val !== '' && $idaa_loc.recovery_meetings.qry__type === val) ? '' : val;
                        }}
                        aria-pressed={active}
                        title={tip}
                        class="novi_btn btn btn-sm transition-all
                            {active
                                ? 'preset-filled-secondary-400-600'
                                : 'preset-outlined-surface-300-700 opacity-60 hover:opacity-100'}">
                        {label}
                    </button>
                {/each}
            </div>

            {#if $ae_loc.edit_mode}
                <label
                    class="flex flex-row items-center gap-1 text-xs opacity-60 cursor-pointer"
                    title="When enabled, search results are fetched directly from the server first. Disable for instant local results with background revalidation.">
                    <input
                        name="qry_remote_first"
                        type="checkbox"
                        bind:checked={$idaa_loc.recovery_meetings.qry__remote_first}
                        class="checkbox form-check-input d-inline-block" />
                    Remote First
                </label>
            {/if}
        </div>

        <div
            class="ae_group ae_row flex w-full flex-row flex-wrap items-center justify-center gap-2 p-1">
        <!-- Sort: single cycling button -->
        <div class="flex flex-row items-center gap-1">
            <span class="sr-only">Sort:</span>
            <button
                type="button"
                onclick={cycle_sort}
                title="Currently: {current_sort.label} — click to change sort order"
                class="novi_btn btn btn-sm preset-outlined-surface-300-700 opacity-80 hover:opacity-100 transition-all min-w-36">
                <span class="fas {current_sort.icon} mr-1"></span>{current_sort.label}
                <span class="fas fa-redo fa-xs ml-1 opacity-40"></span>
            </button>
        </div>

        <!-- Max results: +/- stepper through predefined steps -->
        <div class="flex flex-row items-center gap-1">
            <span class="sr-only">Max results:</span>
            <button
                type="button"
                onclick={() => { if (limit_idx > 0) $idaa_loc.recovery_meetings.qry__limit = limit_steps[limit_idx - 1]; }}
                disabled={limit_idx <= 0}
                title="Show fewer results"
                class="novi_btn btn btn-sm preset-outlined-surface-300-700 transition-all
                    {limit_idx <= 0 ? 'opacity-30 cursor-not-allowed' : 'opacity-60 hover:opacity-100'}">
                <span class="fas fa-minus"></span>
            </button>
            <span
                class="min-w-10 text-center text-sm font-semibold tabular-nums"
                title="Max results shown">
                {$idaa_loc.recovery_meetings.qry__limit}
            </span>
            <button
                type="button"
                onclick={() => { if (limit_idx < limit_steps.length - 1) $idaa_loc.recovery_meetings.qry__limit = limit_steps[limit_idx + 1]; }}
                disabled={limit_idx >= limit_steps.length - 1}
                title="Show more results"
                class="novi_btn btn btn-sm preset-outlined-surface-300-700 transition-all
                    {limit_idx >= limit_steps.length - 1 ? 'opacity-30 cursor-not-allowed' : 'opacity-60 hover:opacity-100'}">
                <span class="fas fa-plus"></span>
            </button>
        </div>

        <!-- Staff: toggle hidden events visibility (trusted + edit mode) -->
        {#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}

        <!-- Staff: toggle disabled events visibility (manager + edit mode) -->
        {#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}

        <!-- Create new meeting (Novi members and trusted staff in edit mode) -->
        {#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 novi_uuid = $idaa_loc.novi_uuid;
                    if (!novi_uuid && typeof localStorage !== 'undefined') {
                        try {
                            const ls_val = localStorage.getItem('ae_idaa_loc');
                            if (ls_val) {
                                const ls_json = JSON.parse(ls_val);
                                novi_uuid = ls_json.novi_uuid;
                            }
                        } catch {
                            // Ignore storage errors
                        }
                    }

                    let data_kv = {
                        name: 'Change NEW Recovery Meeting Name',
                        external_person_id: novi_uuid
                    };
                    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 btn btn-sm preset-tonal-warning
                    preset-outlined-warning-200-800 hover:preset-filled-warning-200-800 text-xs transition"
                disabled={!$ae_loc.authenticated_access}>
                <span class="fas fa-plus m-1"></span> Create New Meeting
            </button>
        {/if}

        <!-- Staff: export all meeting data to Excel (trusted + edit mode) -->
        {#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 btn btn-sm preset-tonal-warning
                    preset-outlined-warning-200-800 hover:preset-filled-warning-200-800 text-xs 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}
        </div>
    </form>
</section>
