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

let {
    log_lvl = $bindable(0),
    lq__event_obj,
    obj_changed = $bindable(false)
}: Props = $props();

// *** Import Svelte specific
import { onMount, untrack } from 'svelte';
import { fade } from 'svelte/transition';
import { browser } from '$app/environment';
import { goto } from '$app/navigation';

// *** 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 { core_func } from '$lib/ae_core/ae_core_functions';
import { api } from '$lib/ae_api/api';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import {
    idaa_loc,
    idaa_sess,
    idaa_slct,
    idaa_trig
} from '$lib/stores/ae_idaa_stores';
import { events_func } from '$lib/ae_events/ae_events_functions';
import AE_Comp_Editor_TipTap from '$lib/elements/element_editor_tiptap.svelte';
import { liveQuery } from 'dexie';
import { db_lookups } from '$lib/ae_core/db_lookups';

if (!$idaa_slct.event_obj) {
    $idaa_slct.event_obj = {};
}
// Create a copy of the event object to track unsaved changes
let orig_event_obj: any = { ...$idaa_slct.event_obj };
if (browser) {
    console.log(`$idaa_slct.event_obj = `, $idaa_slct.event_obj);
    console.log(`orig_event_obj = `, orig_event_obj);
}

if ($idaa_loc.recovery_meetings.edit__event_obj) {
    $idaa_sess.recovery_meetings.edit__event_obj =
        $idaa_loc.recovery_meetings.edit__event_obj;
    $idaa_loc.recovery_meetings.edit__event_obj = false;
}

let prom_api__event_obj: any = $state();

// Rich text fields — tracked separately because TipTap doesn't bind directly to the object
let description_new_html = $state($idaa_slct.event_obj?.description ?? '');
let description_changed = $state(false);
let location_text_new_html = $state($idaa_slct.event_obj?.location_text ?? '');
let location_text_changed = $state(false);
let attend_text_new_html = $state($idaa_slct.event_obj?.attend_text ?? '');
let attend_text_changed = $state(false);
let recurring_text_new_html = $state(
    $idaa_slct.event_obj?.recurring_text ?? ''
);
let recurring_text_changed = $state(false);
let notes_new_html = $state($idaa_slct.event_obj?.notes ?? '');
let notes_changed = $state(false);

let disable_submit_btn = $state(true);

// Weekday chip state — local $state is required because Svelte 5 does not reliably
// propagate reactivity through dynamic bracket notation ($store[dynamicKey]) on
// writable stores. Direct property access (.physical, .virtual) works fine; loop-variable
// bracket access does not trigger class re-renders. $state is deep-reactive and does.
const WEEKDAY_KEYS = [
    'weekday_sunday',
    'weekday_monday',
    'weekday_tuesday',
    'weekday_wednesday',
    'weekday_thursday',
    'weekday_friday',
    'weekday_saturday'
] as const;
let weekdays = $state<Record<string, boolean>>({
    weekday_sunday: false,
    weekday_monday: false,
    weekday_tuesday: false,
    weekday_wednesday: false,
    weekday_thursday: false,
    weekday_friday: false,
    weekday_saturday: false
});
// Seed once from liveQuery when data first arrives. Plain JS flag (not $state) so
// it doesn't cause the effect to re-run after the one-time init.
let weekdays_initialized = false;
$effect(() => {
    if (!weekdays_initialized && $lq__event_obj?.event_id) {
        untrack(() => {
            for (const key of WEEKDAY_KEYS) {
                weekdays[key] = !!$lq__event_obj[key];
            }
            weekdays_initialized = true;
        });
    }
});

// Contact 1 is locked by default on existing meetings for non-trusted users.
// This prevents accidental override of the meeting owner's contact info.
// Trusted+ users see no lock UI; new meetings start unlocked.
let contact_1_locked = $state(!!$idaa_slct.event_id && !$ae_loc.trusted_access);

// Admin Options section collapsed by default — trusted users rarely need these fields.
let show_admin_options = $state(false);

// Auto-expand Contact 2 if the meeting already has data in that slot,
// so existing contact info is never silently hidden on load.
let show_contact_2 = $state(
    !!(
        $idaa_slct.event_obj?.contact_li_json?.[1]?.full_name ||
        $idaa_slct.event_obj?.contact_li_json?.[1]?.email
    )
);

if ($idaa_slct.event_id) {
    $slct_trigger = 'load__event_obj';
    disable_submit_btn = false;
} else {
    $idaa_slct.event_id = null;
    $idaa_slct.event_obj = {
        account_id: $ae_loc.account_id,

        name: null,
        description: null,
        type: null,
        physical: false,
        virtual: false,

        address_name: null,
        address_line_1: null,
        address_line_2: null,
        address_line_3: null,
        address_city: null,
        address_country_subdivision_code: null,
        address_country_subdivision_name: null,
        address_postal_code: null,
        address_country_alpha_2_code: null,
        address_country_name: null,

        location_text: null,

        attend_platform: null,
        attend_url: null,
        attend_url_code: null,
        attend_url_passcode: null,
        attend_phone: null,
        attend_phone_passcode: null,

        attend_text: null,

        attend_json: {},

        timezone: null,

        recurring_text: null,

        contact_li_json: [
            {
                full_name: $idaa_loc.novi_full_name,
                email: $idaa_loc.novi_email,
                phone_mobile: null,
                phone_home: null,
                phone_office: null
            },
            {
                full_name: null,
                email: null,
                phone_mobile: null,
                phone_home: null,
                phone_office: null
            }
        ],

        sort: null,
        notes: null,

        external_person_id: $idaa_loc.novi_uuid,
        external_person_full_name: $idaa_loc.novi_full_name,
        external_person_email: $idaa_loc.novi_email
    };
    console.log(`Event Object started: ${$idaa_slct.event_obj}`);
}

// Lookup lists — reactive IDB queries (SWR via db_lookups + liveQuery)
// Data persists in IndexedDB with a 24h TTL; onMount triggers a background
// refresh if IDB is empty or stale. No localStorage or $ae_loc involved.
// Note: orderBy() requires a declared Dexie index. For fields not in the schema index,
// use toArray() + in-memory sort instead to avoid a silent liveQuery error.
// Sort convention matches the Aether backend: sort DESC (higher = first, NULL=0 last), then name ASC.
const lq__lu_country = liveQuery(() =>
    db_lookups.lu_country.toArray().then((arr) =>
        arr.sort((a, b) => {
            const s_diff = Number(b['sort'] ?? 0) - Number(a['sort'] ?? 0);
            if (s_diff !== 0) return s_diff;
            return (a.english_short_name ?? a.name ?? '').localeCompare(
                b.english_short_name ?? b.name ?? ''
            );
        })
    )
);
const lq__lu_country_subdivision = liveQuery(() =>
    db_lookups.lu_country_subdivision.toArray().then((arr) =>
        arr.sort((a, b) => {
            const s_diff = Number(b['sort'] ?? 0) - Number(a['sort'] ?? 0);
            if (s_diff !== 0) return s_diff;
            return (a.name ?? '').localeCompare(b.name ?? '');
        })
    )
);
const lq__lu_time_zone = liveQuery(() =>
    db_lookups.lu_time_zone.toArray().then((arr) =>
        arr.sort((a, b) => {
            const s_diff = Number(b['sort'] ?? 0) - Number(a['sort'] ?? 0);
            if (s_diff !== 0) return s_diff;
            return (a.name ?? '').localeCompare(b.name ?? '');
        })
    )
);

onMount(() => {
    // Trigger background IDB refresh for all three lookup lists if stale/empty.
    // liveQuery subscribers above will react automatically when IDB is written.
    core_func.load_ae_obj_li__country({ api_cfg: $ae_api, log_lvl });
    core_func.load_ae_obj_li__country_subdivision({
        api_cfg: $ae_api,
        log_lvl
    });
    core_func.load_ae_obj_li__time_zone({ api_cfg: $ae_api, log_lvl });
});

$effect(() => {
    if ($idaa_slct.event_obj) {
        if ($idaa_slct.event_obj == null) {
            $idaa_slct.event_obj = { contact_li_json: [] };
        } else {
            disable_submit_btn = false;
        }
    }
});

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

async function handle_submit_form(event: any) {
    console.log('*** handle_submit_form() ***');
    log_lvl = 1;
    disable_submit_btn = true;

    let form_data = new FormData(event.target);

    let event_meeting_fd = ae_util.extract_prefixed_form_data({
        prefix: null,
        form_data: form_data,
        trim_values: true,
        bool_tf_str: true,
        log_lvl: log_lvl
    });

    let event_do: key_val = {};

    if (!$idaa_slct.event_id) {
        event_do['account_id'] = $ae_loc.account_id;
        event_do['enable'] = true;
    }

    event_do['name'] = event_meeting_fd.name;

    if (typeof description_new_html === 'string') {
        event_do['description'] = description_new_html;
    }

    event_do['type'] = event_meeting_fd.type;
    event_do['physical'] = !!event_meeting_fd.physical;
    event_do['virtual'] = !!event_meeting_fd.virtual;

    let address: key_val = {};
    address['name'] = event_meeting_fd.address_name;
    address['line_1'] = event_meeting_fd.address_line_1;
    address['line_2'] = event_meeting_fd.address_line_2;
    address['line_3'] = event_meeting_fd.address_line_3;
    address['city'] = event_meeting_fd.address_city;
    address['country_subdivision_code'] =
        event_meeting_fd.address_country_subdivision_code;
    if (event_meeting_fd.address_country_subdivision_code) {
        address['country_subdivision_code'] =
            event_meeting_fd.address_country_subdivision_code;
        let country_subdivision_data = ae_util.get_obj_li_w_match_prop({
            obj_li: $lq__lu_country_subdivision ?? [],
            property: 'code',
            value: event_meeting_fd.address_country_subdivision_code
        });
        address['state_province'] = country_subdivision_data[0].name;
    }
    address['postal_code'] = event_meeting_fd.address_postal_code;
    if (event_meeting_fd.address_country_alpha_2_code) {
        address['country_alpha_2_code'] =
            event_meeting_fd.address_country_alpha_2_code;
        let country_data = ae_util.get_obj_li_w_match_prop({
            obj_li: $lq__lu_country ?? [],
            property: 'alpha_2_code',
            value: event_meeting_fd.address_country_alpha_2_code
        });
        address['country'] = country_data[0].english_short_name;
    }
    event_do['location_address_json'] = address;

    if (typeof location_text_new_html === 'string') {
        event_do['location_text'] = location_text_new_html;
    }

    event_do['attend_url'] = event_meeting_fd.attend_url;
    event_do['attend_url_code'] = event_meeting_fd.attend_url_code;
    event_do['attend_url_passcode'] = event_meeting_fd.attend_url_passcode;
    event_do['attend_phone'] = event_meeting_fd.attend_phone;
    event_do['attend_phone_passcode'] = event_meeting_fd.attend_phone_passcode;

    if (typeof attend_text_new_html === 'string') {
        event_do['attend_text'] = attend_text_new_html;
    }

    if ($idaa_sess.recovery_meetings?.attend_platform === 'Zoom') {
        let zoom_attend_domain = event_meeting_fd.attend_domain ?? 'zoom.us';
        let zoom_meeting_id = event_do['attend_url_code']
            ? event_do['attend_url_code'].replace(/[^0-9]/g, '').trim()
            : null;
        let zoom_passcode = event_do['attend_url_passcode']
            ? event_do['attend_url_passcode'].trim()
            : null;
        let zoom_passcode_enc = event_meeting_fd.attend_url_passcode_enc
            ? event_meeting_fd.attend_url_passcode_enc
                  .replace(/[^a-zA-Z0-9]/g, '')
                  .trim()
            : '';
        // Defensive: prevent saving the literal strings 'null' or 'undefined'
        if (zoom_passcode_enc === 'null' || zoom_passcode_enc === 'undefined') {
            zoom_passcode_enc = '';
        }
        let zoom_url = event_meeting_fd.zoom_attend_url
            ? event_meeting_fd.zoom_attend_url.trim()
            : null;

        event_do['attend_json'] = {
            zoom: {
                domain: zoom_attend_domain,
                meeting_id: zoom_meeting_id,
                passcode: zoom_passcode,
                passcode_enc: zoom_passcode_enc,
                full_url: zoom_url
            }
        };

        event_do['attend_url'] = zoom_url;
        event_do['attend_url_text'] =
            `Join Zoom Meeting: ${zoom_meeting_id ? zoom_url : ''}`;
        event_do['attend_url_passcode'] = zoom_passcode;
        event_do['attend_url_code'] = zoom_meeting_id;
    } else if ($idaa_sess.recovery_meetings?.attend_platform === 'Jitsi') {
        let jitsi_full_url = event_meeting_fd.attend_url
            ? event_meeting_fd.attend_url.trim()
            : null;
        let jitsi_name = event_meeting_fd.attend_url_code
            ? event_meeting_fd.attend_url_code.trim()
            : null;
        let jitsi_passcode = event_meeting_fd.attend_url_passcode
            ? event_meeting_fd.attend_url_passcode.trim()
            : null;

        event_do['attend_json'] = {
            jitsi: {
                full_url: jitsi_full_url,
                name: jitsi_name,
                passcode: jitsi_passcode
            }
        };

        event_do['attend_url'] = jitsi_full_url;
        event_do['attend_url_text'] =
            `Join Jitsi Meeting: ${jitsi_name ? jitsi_full_url : ''}`;
        event_do['attend_url_passcode'] = jitsi_passcode;
        event_do['attend_url_code'] = jitsi_name;
    } else {
        event_do['attend_json'] = {};
    }

    event_do['timezone'] = event_meeting_fd.timezone;

    // Meetings are always recurring — recurring=true is hardcoded per 2024-10 decision
    event_do['recurring'] = true;
    event_do['recurring_pattern'] = event_meeting_fd.recurring_pattern;

    // Read weekdays from local $state (not FormData) — bind:checked with dynamic bracket
    // notation in {#each} is unreliable in Svelte 5; explicit onchange handlers update
    // the weekdays $state object directly, so read from there instead.
    event_do['weekday_sunday'] = weekdays.weekday_sunday;
    event_do['weekday_monday'] = weekdays.weekday_monday;
    event_do['weekday_tuesday'] = weekdays.weekday_tuesday;
    event_do['weekday_wednesday'] = weekdays.weekday_wednesday;
    event_do['weekday_thursday'] = weekdays.weekday_thursday;
    event_do['weekday_friday'] = weekdays.weekday_friday;
    event_do['weekday_saturday'] = weekdays.weekday_saturday;

    // Send null explicitly so the user can clear a time once set.
    // An empty string from the time input means "no time" — map that to null.
    event_do['recurring_start_time'] =
        event_meeting_fd.recurring_start_time || null;
    event_do['recurring_end_time'] =
        event_meeting_fd.recurring_end_time || null;

    if (typeof recurring_text_new_html === 'string') {
        event_do['recurring_text'] = recurring_text_new_html;
    }

    // Auto-generate recurring_text if blank or still has the *gen* placeholder prefix
    if (
        !event_do['recurring_text'] ||
        event_do['recurring_text'].includes('*gen*')
    ) {
        let days_of_week = [];
        if (event_do['weekday_sunday']) days_of_week.push('Sunday');
        if (event_do['weekday_monday']) days_of_week.push('Monday');
        if (event_do['weekday_tuesday']) days_of_week.push('Tuesday');
        if (event_do['weekday_wednesday']) days_of_week.push('Wednesday');
        if (event_do['weekday_thursday']) days_of_week.push('Thursday');
        if (event_do['weekday_friday']) days_of_week.push('Friday');
        if (event_do['weekday_saturday']) days_of_week.push('Saturday');

        let current_date_iso = ae_util.iso_datetime_formatter(
            new Date(),
            'YYYY-MM-DD'
        );

        event_do['recurring_text'] =
            `*gen* ${event_do['recurring_pattern'] ?? ''}: ${days_of_week.join(', ')} at ${ae_util.iso_datetime_formatter(`${current_date_iso} ${event_do['recurring_start_time']}`, 'time_12_short_no_leading')} ${event_do['timezone'] ?? ''}`;
    }

    event_do['external_person_id'] = event_meeting_fd.external_person_id;

    event_do['contact_li_json'] = [];
    let contact_1: key_val = {};
    contact_1['full_name'] = event_meeting_fd.contact_1_full_name;
    contact_1['email'] = event_meeting_fd.contact_1_email;
    if (event_meeting_fd.contact_1_phone_mobile) {
        contact_1['phone_mobile'] = event_meeting_fd.contact_1_phone_mobile;
    }
    if (event_meeting_fd.contact_1_phone_home) {
        contact_1['phone_home'] = event_meeting_fd.contact_1_phone_home;
    }
    if (event_meeting_fd.contact_1_phone_office) {
        contact_1['phone_office'] = event_meeting_fd.contact_1_phone_office;
    }
    event_do['contact_li_json'].push(contact_1);

    let contact_2: key_val = {};
    contact_2['full_name'] = event_meeting_fd.contact_2_full_name;
    contact_2['email'] = event_meeting_fd.contact_2_email;
    if (event_meeting_fd.contact_2_phone_mobile) {
        contact_2['phone_mobile'] = event_meeting_fd.contact_2_phone_mobile;
    }
    if (event_meeting_fd.contact_2_phone_home) {
        contact_2['phone_home'] = event_meeting_fd.contact_2_phone_home;
    }
    if (event_meeting_fd.contact_2_phone_office) {
        contact_2['phone_office'] = event_meeting_fd.contact_2_phone_office;
    }
    event_do['contact_li_json'].push(contact_2);

    event_do['status'] = event_meeting_fd.status ?? null;
    event_do['hide'] = !!event_meeting_fd.hide;
    event_do['priority'] = !!event_meeting_fd.priority;
    if (event_meeting_fd['sort']) {
        event_do['sort'] = Number(event_meeting_fd.sort);
    }
    event_do['group'] = event_meeting_fd['group']
        ? event_meeting_fd.group
        : null;

    // Only set enable if the input is defined (avoid overriding on edits where field is absent)
    if (typeof event_meeting_fd.enable !== 'undefined') {
        event_do.enable = event_meeting_fd.enable;
    }

    if (typeof notes_new_html === 'string') {
        event_do['notes'] = notes_new_html;
    }

    if (log_lvl) {
        console.log('Event object data:', event_do);
    }

    if (!$idaa_slct.event_id) {
        prom_api__event_obj = events_func
            .create_ae_obj__event({
                api_cfg: $ae_api,
                account_id: $ae_loc.account_id,
                data_kv: event_do,
                log_lvl: log_lvl
            })
            .then(function (result) {
                if (!result) return false;
                $idaa_slct.event_id = result.event_id;
                $idaa_slct.event_obj = result;
                if ($ae_loc.site_cfg_json?.recovery_mtg_send_staff_new_email) {
                    send_staff_notification_email(result);
                }
                return result;
            })
            .catch(function (error: any) {
                console.log('Something went wrong.', error);
                return false;
            })
            .finally(() => {
                disable_submit_btn = false;
                // Clear both modal and direct-page edit flags so save closes
                // the form in both the modal context and the [event_id] page context
                $idaa_sess.recovery_meetings.show__modal_edit = false;
                $idaa_sess.recovery_meetings.edit__event_obj = false;
                $idaa_sess.recovery_meetings.show__modal_view = true;
            });

        return prom_api__event_obj;
    } else {
        prom_api__event_obj = events_func
            .update_ae_obj__event({
                api_cfg: $ae_api,
                event_id: $idaa_slct.event_id,
                data_kv: event_do,
                log_lvl: log_lvl
            })
            .then(function (result) {
                if (!result) return false;
                $idaa_slct.event_obj = result;
                if (
                    $ae_loc.site_cfg_json?.recovery_mtg_send_staff_update_email
                ) {
                    send_staff_notification_email(result);
                }
                return result;
            })
            .catch(function (error: any) {
                console.log('Something went wrong.', error);
                return false;
            })
            .finally(() => {
                disable_submit_btn = false;
                // Clear both modal and direct-page edit flags
                $idaa_sess.recovery_meetings.show__modal_edit = false;
                $idaa_sess.recovery_meetings.edit__event_obj = false;
                $idaa_sess.recovery_meetings.show__modal_view = true;
            });

        return prom_api__event_obj;
    }
}

async function handle_delete_event_obj({
    event_id,
    method = 'disable'
}: {
    event_id: string;
    method?: string;
}) {
    prom_api__event_obj = events_func
        .delete_ae_obj_id__event({
            api_cfg: $ae_api,
            event_id: event_id,
            method: method as any,
            log_lvl: log_lvl
        })
        .then(function () {
            $idaa_sess.recovery_meetings.edit__event_obj = false;
        })
        .catch(function (error: any) {
            console.log('Delete failed.', error);
        })
        .finally(() => {
            $idaa_slct.event_id = null;
            $idaa_slct.event_obj = null;
            goto('/idaa/recovery_meetings', { replaceState: true });
        });

    return prom_api__event_obj;
}

// Send notification email to staff when a meeting is created or updated.
// Controlled by site config flags: recovery_mtg_send_staff_new_email / recovery_mtg_send_staff_update_email
function send_staff_notification_email(event_do: key_val) {
    let link_base_url =
        $ae_loc.site_cfg_json.novi_meetings_base_url ??
        `${$ae_loc.url_origin}/idaa/recovery_meetings`;

    let subject = `IDAA Recovery Meeting: ${event_do.name} (ID: ${event_do.event_id})`;

    let body_html = `
<div>
<p>A recovery meeting has been created or updated named "${event_do.name}".</p>
</div>
<br>
<div>
IDAA Recovery Meeting ID: ${event_do.event_id}<br>
<p>Use this link to view the meeting.<br>
Copy and paste link: <a href="${link_base_url}?event_id=${event_do.event_id}">${link_base_url}?event_id=${event_do.event_id}</a></p>
</div>`;

    api.send_email({
        api_cfg: $ae_api,
        from_email:
            $ae_loc.site_cfg_json?.noreply_email ??
            'noreply+recmtg@oneskyit.com',
        from_name:
            $ae_loc.site_cfg_json?.noreply_name ?? 'IDAA Rec Mtg NoReply',
        to_email:
            $ae_loc.site_cfg_json?.admin_email ?? 'admin+recmtg@oneskyit.com',
        to_name:
            $ae_loc.site_cfg_json?.admin_name ?? 'IDAA Recovery Meeting Admin',
        subject: subject,
        body_html: body_html,
        log_lvl: log_lvl
    });
}

// Track whether the form has unsaved changes relative to the original loaded object.
// weekdays is checked separately since it's a local $state, not part of $idaa_slct.event_obj.
$effect(() => {
    const weekdays_changed = WEEKDAY_KEYS.some(
        (k) => !!weekdays[k] !== !!orig_event_obj?.[k]
    );
    if (orig_event_obj === null || orig_event_obj === undefined) {
        obj_changed = false;
    } else if (
        !obj_changed &&
        orig_event_obj?.id &&
        (JSON.stringify($idaa_slct.event_obj) !==
            JSON.stringify(orig_event_obj) ||
            description_changed ||
            notes_changed ||
            weekdays_changed)
    ) {
        obj_changed = true;
    } else if (
        obj_changed &&
        orig_event_obj?.id &&
        JSON.stringify($idaa_slct.event_obj) ===
            JSON.stringify(orig_event_obj) &&
        !description_changed &&
        !notes_changed &&
        !weekdays_changed
    ) {
        obj_changed = false;
    }
});

// Detect the current virtual platform from attend_json on load
if (browser && $idaa_slct.event_obj?.attend_json) {
    if ($idaa_slct.event_obj?.attend_json?.zoom) {
        $idaa_sess.recovery_meetings.attend_platform = 'Zoom';
    } else if ($idaa_slct.event_obj?.attend_json?.jitsi) {
        $idaa_sess.recovery_meetings.attend_platform = 'Jitsi';
    } else {
        $idaa_sess.recovery_meetings.attend_platform = null;
    }
}

// Rebuild the Zoom full URL whenever Meeting ID, Passcode, Encrypted Passcode, or Domain changes.
// IMPORTANT: Guard attend_json.zoom before accessing its sub-properties.
// Background SWR re-fires (load_ae_obj_li__event in +layout.ts) can overwrite
// $idaa_slct.event_obj with a fresh IDB record where attend_json = {} (no zoom key),
// even if the Zoom button was already clicked.  Without the guard, the access to
// attend_json.zoom.passcode_enc below throws a TypeError and crashes the component.
$effect(() => {
    if (
        $idaa_trig.update_zoom_full_url &&
        $idaa_slct.event_obj.attend_url_code &&
        $idaa_slct.event_obj.attend_url_passcode &&
        $idaa_sess.recovery_meetings.attend_platform === 'Zoom' &&
        $idaa_slct.event_obj.attend_json?.zoom // guard: zoom may be undefined after IDB re-fire
    ) {
        $idaa_trig.update_zoom_full_url = false;

        $idaa_slct.event_obj.attend_url_code =
            String($idaa_slct.event_obj.attend_url_code)
                .replace(/[^0-9]/g, '')
                .trim() ?? '';

        $idaa_slct.event_obj.attend_url_passcode =
            String($idaa_slct.event_obj.attend_url_passcode).trim() ?? '';

        // Normalize encrypted passcode: avoid String(null) -> 'null'
        {
            const _enc = $idaa_slct.event_obj.attend_json.zoom.passcode_enc;
            if (_enc == null || _enc === 'null' || _enc === 'undefined') {
                $idaa_slct.event_obj.attend_json.zoom.passcode_enc = '';
            } else {
                $idaa_slct.event_obj.attend_json.zoom.passcode_enc =
                    String(_enc).trim();
            }
        }

        $idaa_slct.event_obj.attend_json.zoom.domain = $idaa_slct.event_obj
            .attend_json.zoom.domain
            ? String($idaa_slct.event_obj.attend_json.zoom.domain)
                  .toLowerCase()
                  .trim()
                  .replace(/^https?:\/\//, '')
                  .replace(/\/.*$/, '')
            : 'zoom.us';

        if (
            $idaa_slct.event_obj.attend_json.zoom.passcode_enc &&
            $idaa_slct.event_obj.attend_json.zoom.passcode_enc.length >= 8
        ) {
            $idaa_slct.event_obj.attend_json.zoom.full_url = `https://${$idaa_slct.event_obj.attend_json.zoom.domain}/j/${$idaa_slct.event_obj.attend_url_code}?pwd=${$idaa_slct.event_obj.attend_json.zoom.passcode_enc}`;
        } else {
            $idaa_slct.event_obj.attend_json.zoom.full_url = `https://${$idaa_slct.event_obj.attend_json.zoom.domain}/j/${$idaa_slct.event_obj.attend_url_code}?pwd=${$idaa_slct.event_obj.attend_url_passcode}`;
        }
    }
});
</script>

<!-- ============================================================
     IDAA Recovery Meeting — Edit Form (v2)
     All fields map to ae_Event. This form is used for both
     creating new meetings and editing existing ones.
     Shown as a modal controlled by $idaa_sess.recovery_meetings.show__modal_edit.
     ============================================================ -->

<section
    class="
        svelte_component ae_section ae_edit event_obj edit__event_obj
        preset-filled-surface-50-950 preset-outlined-warning-400-600
        space-y-3
        rounded-md p-3
    "
    class:ae_create={!$idaa_slct.event_id}
    bind:clientHeight={$ae_loc.iframe_height_modal_body}>
    <form
        onsubmit={prevent_default(handle_submit_form)}
        class="relative space-y-3">
        <!-- Saving overlay indicator -->
        {#await prom_api__event_obj}
            <div class="awaiting alert_msg_pulse" out:fade={{ duration: 2000 }}>
                Saving...
            </div>
        {/await}

        <!-- Top save button — visible on existing meetings only so users don't scroll to the bottom
             of this long form just to save. Mirrors the bottom Save Changes button. -->
        {#if $idaa_slct.event_id}
            <div class="flex justify-end">
                <button
                    type="submit"
                    class="btn btn-sm preset-filled-primary-200-800"
                    disabled={disable_submit_btn}>
                    {#await prom_api__event_obj}
                        <span class="fas fa-spinner fa-spin"></span> Saving...
                    {:then}
                        <span class="fas fa-save"></span> Save Changes
                    {/await}
                </button>
            </div>
        {/if}

        <!-- ============================================================
             SECTION 1 — Meeting Information
             Fields: name, description, type
             ============================================================ -->
        <div
            class="bg-surface-100-900 border-surface-200-800 space-y-3 rounded-md border p-3"
            id="section__general_information">
            <h3
                class="text-surface-600-400 border-surface-200-800 flex items-center gap-2 border-b pb-1 text-lg font-semibold">
                <span class="fas fa-info-circle"></span>
                Meeting Information
            </h3>

            <!-- Name -->
            <label
                class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                for="name">
                <div class="flex items-center gap-1">
                    <span>Name of Recovery Meeting</span>
                    <span class="text-error-500 ml-0.5">*</span>
                </div>
                <input
                    type="text"
                    id="name"
                    name="name"
                    required
                    maxlength="200"
                    value={$lq__event_obj?.name ?? ''}
                    placeholder="Name of Recovery Meeting"
                    autocomplete="off"
                    class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-full" />
            </label>

            <!-- Description (rich text) -->
            <label
                class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                for="description">
                Short Description
                <AE_Comp_Editor_TipTap
                    bind:content={description_new_html}
                    class_li="field-richtext"
                    placeholder="A short description or overview of this recovery meeting" />
            </label>

            <!-- Type -->
            <div class="space-y-1">
                <label
                    class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                    for="type">
                    Type of Recovery Meeting
                    <select
                        id="type"
                        name="type"
                        value={$lq__event_obj?.type}
                        class="select preset-tonal-surface hover:preset-filled-surface-100-900 w-52 p-1">
                        <option value="IDAA">IDAA</option>
                        <option value="Caduceus">Caduceus</option>
                        <option value="Family Recovery">Family Recovery</option>
                    </select>
                </label>
                <ul
                    class="text-surface-500 list-inside list-disc space-y-0.5 text-sm">
                    <li><strong>IDAA</strong> — Open to IDAA members only</li>
                    <li>
                        <strong>Caduceus</strong> — Open to all healthcare workers,
                        including those who do not qualify for IDAA
                    </li>
                    <li>
                        <strong>Family Recovery</strong> — Open to spouses, parents,
                        and adult children of medical professionals who have substance
                        use disorder
                    </li>
                </ul>
            </div>
        </div>

        <!-- ============================================================
             SECTION 2 — How to Attend
             physical and virtual are independent — a meeting can be both.
             Address/location fields shown when physical=true OR more__location_fields=true.
             Virtual platform fields shown when virtual=true OR more__virtual_fields=true.
             attend_text is always shown (applies to both physical and virtual).
             ============================================================ -->
        <div
            class="bg-surface-100-900 border-surface-200-800 space-y-3 rounded-md border p-3"
            id="section__how_to_attend">
            <h3
                class="text-surface-600-400 border-surface-200-800 flex items-center gap-2 border-b pb-1 text-lg font-semibold">
                <span class="fas fa-map-marker-alt"></span>
                How to Attend
            </h3>

            <!-- Physical / Virtual toggles -->
            <fieldset>
                <legend
                    class="text-surface-700-300 mb-1 flex flex-col gap-1 text-sm font-semibold"
                    >Is this meeting in-person, virtual, or both?</legend>
                <div class="flex flex-row flex-wrap gap-2">
                    <label
                        for="physical"
                        class="preset-tonal-surface border-surface-300-700 hover:preset-filled-surface-200-800 flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm font-semibold transition-all {$idaa_slct
                            .event_obj.physical
                            ? 'preset-filled-success-200-800 border-success-400'
                            : ''}">
                        <span class="fas fa-home"></span>
                        Face-to-Face / In Person
                        <input
                            type="checkbox"
                            id="physical"
                            name="physical"
                            bind:checked={$idaa_slct.event_obj.physical}
                            class="sr-only" />
                    </label>
                    <label
                        for="virtual"
                        class="preset-tonal-surface border-surface-300-700 hover:preset-filled-surface-200-800 flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm font-semibold transition-all {$idaa_slct
                            .event_obj.virtual
                            ? 'preset-filled-success-200-800 border-success-400'
                            : ''}">
                        <span class="fas fa-laptop"></span>
                        Virtual / Online
                        <input
                            type="checkbox"
                            id="virtual"
                            name="virtual"
                            bind:checked={$idaa_slct.event_obj.virtual}
                            class="sr-only" />
                    </label>
                </div>
            </fieldset>

            <!-- ── 2a: Physical / In-Person ──────────────────────────── -->

            <!-- Show/hide extra location fields when physical is not checked -->
            {#if !$idaa_slct.event_obj?.physical}
                <button
                    type="button"
                    class="btn btn-sm preset-tonal-surface"
                    onclick={() =>
                        ($idaa_slct.event_obj.more__location_fields =
                            !$idaa_slct.event_obj.more__location_fields)}>
                    <span
                        class="fas fa-{$idaa_slct.event_obj
                            ?.more__location_fields
                            ? 'minus'
                            : 'plus'}"></span>
                    {$idaa_slct.event_obj?.more__location_fields
                        ? 'Hide'
                        : 'Show'} Location Fields
                </button>
            {/if}

            <div
                class="border-surface-300-700 space-y-3 border-l-2 pl-3"
                class:hidden={!$idaa_slct.event_obj?.physical &&
                    !$idaa_slct.event_obj?.more__location_fields}>
                <h4
                    class="text-surface-600-400 flex items-center gap-1.5 text-sm font-semibold">
                    <span class="fas fa-home"></span> Physical Location
                </h4>

                <!-- Address fields — flex wrap so they flow naturally on small screens -->
                <input
                    type="hidden"
                    name="address_location_id"
                    value={$lq__event_obj?.address_location_id} />

                <div class="flex flex-row flex-wrap gap-3">
                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="address_name">
                        Location Name
                        <input
                            type="text"
                            id="address_name"
                            name="address_name"
                            placeholder="Name of the place or building"
                            autocomplete="off"
                            value={$lq__event_obj?.location_address_json
                                ?.name ??
                                $lq__event_obj?.address_name ??
                                ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-72" />
                    </label>

                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="address_line_1">
                        Address Line 1
                        <input
                            type="text"
                            id="address_line_1"
                            name="address_line_1"
                            placeholder="Street address"
                            autocomplete="address-line1"
                            value={$lq__event_obj?.location_address_json
                                ?.line_1 ??
                                $lq__event_obj?.address_line_1 ??
                                ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-72" />
                    </label>

                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="address_line_2">
                        Address Line 2
                        <input
                            type="text"
                            id="address_line_2"
                            name="address_line_2"
                            placeholder="Suite, floor, etc."
                            autocomplete="address-line2"
                            value={$lq__event_obj?.location_address_json
                                ?.line_2 ??
                                $lq__event_obj?.address_line_2 ??
                                ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-72" />
                    </label>

                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="address_line_3">
                        Address Line 3
                        <input
                            type="text"
                            id="address_line_3"
                            name="address_line_3"
                            placeholder="Additional address info"
                            autocomplete="address-line3"
                            value={$lq__event_obj?.location_address_json
                                ?.line_3 ??
                                $lq__event_obj?.address_line_3 ??
                                ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-72" />
                    </label>

                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="address_city">
                        City
                        <input
                            type="text"
                            id="address_city"
                            name="address_city"
                            placeholder="City"
                            autocomplete="address-level2"
                            value={$lq__event_obj?.location_address_json
                                ?.city ??
                                $lq__event_obj?.address_city ??
                                ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-44" />
                    </label>

                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="address_country_subdivision_code">
                        State / Province
                        {#if ($lq__lu_country_subdivision ?? []).length}
                            <select
                                id="address_country_subdivision_code"
                                name="address_country_subdivision_code"
                                value={$lq__event_obj?.location_address_json
                                    ?.country_subdivision_code ??
                                    $lq__event_obj?.address_country_subdivision_code ??
                                    ''}
                                class="select preset-tonal-surface hover:preset-filled-surface-100-900 w-56 p-1">
                                <option value="">-- None --</option>
                                {#each $lq__lu_country_subdivision ?? [] as sub (sub.code)}
                                    <option value={sub.code}
                                        >{sub.country_alpha_2_code} - {sub.name}</option>
                                {/each}
                            </select>
                        {:else}
                            <input
                                type="text"
                                id="address_country_subdivision_code"
                                name="address_country_subdivision_code"
                                placeholder="State or province code"
                                autocomplete="address-level1"
                                value={$lq__event_obj?.location_address_json
                                    ?.country_subdivision_code ??
                                    $lq__event_obj?.address_country_subdivision_code ??
                                    ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-44" />
                        {/if}
                    </label>

                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="address_postal_code">
                        Postal / Zip Code
                        <input
                            type="text"
                            id="address_postal_code"
                            name="address_postal_code"
                            placeholder="Postal or zip code"
                            autocomplete="postal-code"
                            value={$lq__event_obj?.location_address_json
                                ?.postal_code ??
                                $lq__event_obj?.address_postal_code ??
                                ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-36" />
                    </label>

                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="address_country_alpha_2_code">
                        Country
                        {#if ($lq__lu_country ?? []).length}
                            <select
                                id="address_country_alpha_2_code"
                                name="address_country_alpha_2_code"
                                value={$lq__event_obj?.location_address_json
                                    ?.country_alpha_2_code ??
                                    $lq__event_obj?.address_country_alpha_2_code ??
                                    ''}
                                class="select preset-tonal-surface hover:preset-filled-surface-100-900 w-64 p-1">
                                <option value="">-- None --</option>
                                {#each $lq__lu_country ?? [] as country (country.alpha_2_code)}
                                    <option value={country.alpha_2_code}
                                        >{country.english_short_name}</option>
                                {/each}
                            </select>
                        {:else}
                            <input
                                type="text"
                                id="address_country_alpha_2_code"
                                name="address_country_alpha_2_code"
                                placeholder="Country code (e.g. US)"
                                autocomplete="country"
                                value={$lq__event_obj?.location_address_json
                                    ?.country_alpha_2_code ??
                                    $lq__event_obj?.address_country_alpha_2_code ??
                                    ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-36" />
                        {/if}
                    </label>
                </div>

                <!-- Additional location notes (rich text) -->
                <label
                    class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                    for="location_text">
                    Additional Location Information
                    <AE_Comp_Editor_TipTap
                        bind:content={location_text_new_html}
                        class_li="field-richtext"
                        placeholder="Parking, room number, accessibility notes, etc." />
                </label>
            </div>

            <!-- ── 2b: Virtual / Online ───────────────────────────────── -->

            <!-- Show/hide extra virtual fields when virtual is not checked -->
            {#if !$idaa_slct.event_obj?.virtual}
                <button
                    type="button"
                    class="btn btn-sm preset-tonal-surface"
                    onclick={() =>
                        ($idaa_slct.event_obj.more__virtual_fields =
                            !$idaa_slct.event_obj.more__virtual_fields)}>
                    <span
                        class="fas fa-{$idaa_slct.event_obj
                            ?.more__virtual_fields
                            ? 'minus'
                            : 'plus'}"></span>
                    {$idaa_slct.event_obj?.more__virtual_fields
                        ? 'Hide'
                        : 'Show'} Virtual Fields
                </button>
            {/if}

            <div
                class="border-surface-300-700 space-y-3 border-l-2 pl-3"
                class:hidden={!$idaa_slct.event_obj.virtual &&
                    !$idaa_slct.event_obj?.more__virtual_fields}>
                <h4
                    class="text-surface-600-400 flex items-center gap-1.5 text-sm font-semibold">
                    <span class="fas fa-laptop"></span> Virtual / Online
                </h4>

                <!-- Platform selection toggle — Zoom, Jitsi, or generic Other -->
                <div class="space-y-2">
                    <p class="text-surface-500 text-sm">
                        Select the video platform for this meeting:
                    </p>
                    <div class="flex flex-row flex-wrap gap-2">
                        <button
                            type="button"
                            class="btn btn-sm"
                            class:preset-filled-primary-200-800={$idaa_sess
                                .recovery_meetings.attend_platform === 'Zoom'}
                            class:preset-tonal-surface={$idaa_sess
                                .recovery_meetings.attend_platform !== 'Zoom'}
                            onclick={() => {
                                if (
                                    !$idaa_slct.event_obj.attend_json ||
                                    JSON.stringify(
                                        $idaa_slct.event_obj.attend_json
                                    ) === '{}'
                                ) {
                                    $idaa_slct.event_obj.attend_json = {
                                        zoom: {
                                            domain: 'zoom.us',
                                            meeting_id: '',
                                            passcode: '',
                                            passcode_enc: '',
                                            full_url: ''
                                        }
                                    };
                                } else if (
                                    !$idaa_slct.event_obj.attend_json.zoom
                                ) {
                                    $idaa_slct.event_obj.attend_json.zoom = {
                                        domain: 'zoom.us',
                                        meeting_id: '',
                                        passcode: '',
                                        passcode_enc: '',
                                        full_url: ''
                                    };
                                }
                                $idaa_sess.recovery_meetings.attend_platform =
                                    'Zoom';
                                $idaa_trig.update_zoom_full_url = true;
                            }}>
                            <span class="fas fa-video"></span> Zoom
                        </button>
                        <button
                            type="button"
                            class="btn btn-sm"
                            class:preset-filled-primary-200-800={$idaa_sess
                                .recovery_meetings.attend_platform === 'Jitsi'}
                            class:preset-tonal-surface={$idaa_sess
                                .recovery_meetings.attend_platform !== 'Jitsi'}
                            onclick={() => {
                                if (
                                    !$idaa_slct.event_obj.attend_json ||
                                    JSON.stringify(
                                        $idaa_slct.event_obj.attend_json
                                    ) === '{}'
                                ) {
                                    $idaa_slct.event_obj.attend_json = {
                                        jitsi: {
                                            full_url:
                                                $lq__event_obj?.attend_url ??
                                                '',
                                            name:
                                                $lq__event_obj?.attend_url_code ??
                                                '',
                                            passcode:
                                                $lq__event_obj?.attend_url_passcode ??
                                                ''
                                        }
                                    };
                                } else if (
                                    !$idaa_slct.event_obj.attend_json.jitsi
                                ) {
                                    $idaa_slct.event_obj.attend_json.jitsi = {
                                        full_url:
                                            $lq__event_obj?.attend_url ?? '',
                                        name:
                                            $lq__event_obj?.attend_url_code ??
                                            '',
                                        passcode:
                                            $lq__event_obj?.attend_url_passcode ??
                                            ''
                                    };
                                }
                                $idaa_sess.recovery_meetings.attend_platform =
                                    'Jitsi';
                            }}>
                            <span class="fas fa-video"></span> IDAA Jitsi
                        </button>
                        <button
                            type="button"
                            class="btn btn-sm"
                            class:preset-filled-primary-200-800={!$idaa_sess
                                .recovery_meetings.attend_platform ||
                                $idaa_sess.recovery_meetings.attend_platform ===
                                    'other'}
                            class:preset-tonal-surface={$idaa_sess
                                .recovery_meetings.attend_platform &&
                                $idaa_sess.recovery_meetings.attend_platform !==
                                    'other'}
                            onclick={() => {
                                $idaa_sess.recovery_meetings.attend_platform =
                                    'other';
                            }}>
                            <span class="fas fa-link"></span> Other / Generic
                        </button>
                    </div>
                </div>

                <!-- Zoom fields.
                     Guard attend_json.zoom: the Zoom button onclick initializes it, but a background
                     SWR IDB re-fire (load_ae_obj_li__event from +layout.ts) can reset attend_json
                     to {} afterward, leaving attend_json.zoom undefined.  The bind:value bindings
                     below crash with a TypeError if zoom is undefined — the guard prevents that. -->
                {#if $idaa_sess.recovery_meetings.attend_platform === 'Zoom' && $idaa_slct.event_obj.attend_json?.zoom}
                    <div
                        class="bg-surface-50-950 border-surface-200-800 flex flex-row flex-wrap gap-3 rounded border p-2">
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="attend_url_code">
                            <div class="flex items-center gap-1">
                                <span>Zoom Meeting ID</span>
                                <span class="text-error-500 ml-0.5">*</span>
                            </div>
                            <input
                                type="text"
                                inputmode="numeric"
                                pattern="[0-9 ]*"
                                id="attend_url_code"
                                name="attend_url_code"
                                maxlength="20"
                                autocomplete="off"
                                required
                                placeholder="e.g. 123 456 7890"
                                bind:value={
                                    $idaa_slct.event_obj.attend_url_code
                                }
                                onblur={() => {
                                    // Strip all non-digits and update value immediately
                                    if ($idaa_slct.event_obj.attend_url_code) {
                                        $idaa_slct.event_obj.attend_url_code =
                                            String(
                                                $idaa_slct.event_obj
                                                    .attend_url_code
                                            ).replace(/[^0-9]/g, '');
                                    }
                                }}
                                onchange={() => {
                                    // Also trigger update if length is sufficient
                                    if (
                                        $idaa_slct.event_obj.attend_url_code?.replace(
                                            /[^0-9]/g,
                                            ''
                                        ).length > 8
                                    ) {
                                        $idaa_trig.update_zoom_full_url = true;
                                    }
                                }}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="attend_url_passcode">
                            Zoom Passcode
                            <input
                                type="text"
                                id="attend_url_passcode"
                                name="attend_url_passcode"
                                autocomplete="off"
                                placeholder="Passcode shown to participants"
                                bind:value={
                                    $idaa_slct.event_obj.attend_url_passcode
                                }
                                onchange={() => {
                                    if (
                                        $idaa_slct.event_obj.attend_url_passcode
                                            ?.length > 3
                                    ) {
                                        $idaa_trig.update_zoom_full_url = true;
                                    } else {
                                        $idaa_slct.event_obj.attend_url_passcode =
                                            '';
                                    }
                                }}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="attend_url_passcode_enc">
                            Zoom Encrypted Passcode
                            <span
                                class="text-surface-500 -mt-0.5 block text-xs font-normal"
                                >Found in the Zoom invite URL after <code
                                    >?pwd=</code
                                ></span>
                            <input
                                type="text"
                                id="attend_url_passcode_enc"
                                name="attend_url_passcode_enc"
                                autocomplete="off"
                                placeholder="Encrypted passcode from URL"
                                bind:value={
                                    $idaa_slct.event_obj.attend_json.zoom
                                        .passcode_enc
                                }
                                onblur={() => {
                                    // If value is null/undefined or literal 'null'/'undefined', set to empty string
                                    const _v =
                                        $idaa_slct.event_obj.attend_json.zoom
                                            .passcode_enc;
                                    if (
                                        _v == null ||
                                        _v === 'null' ||
                                        _v === 'undefined'
                                    ) {
                                        $idaa_slct.event_obj.attend_json.zoom.passcode_enc =
                                            '';
                                    }
                                }}
                                onchange={() => {
                                    if (
                                        $idaa_slct.event_obj.attend_json.zoom
                                            .passcode_enc?.length >= 8
                                    ) {
                                        $idaa_trig.update_zoom_full_url = true;
                                    }
                                }}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-72" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="attend_domain">
                            Zoom Domain / Vanity URL
                            <span
                                class="text-surface-500 -mt-0.5 block text-xs font-normal"
                                >Default: zoom.us — change only if using a
                                custom domain</span>
                            <input
                                type="text"
                                id="attend_domain"
                                name="attend_domain"
                                autocomplete="url"
                                placeholder="zoom.us"
                                bind:value={
                                    $idaa_slct.event_obj.attend_json.zoom.domain
                                }
                                onchange={() => {
                                    $idaa_slct.event_obj.attend_json.zoom.domain =
                                        $idaa_slct.event_obj.attend_json.zoom
                                            .domain
                                            ? String(
                                                  $idaa_slct.event_obj
                                                      .attend_json.zoom.domain
                                              )
                                                  .toLowerCase()
                                                  .trim()
                                            : 'zoom.us';
                                    $idaa_trig.update_zoom_full_url = true;
                                }}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-56" />
                        </label>
                        <label
                            class="text-surface-700-300 flex w-full flex-col gap-1 text-sm font-semibold"
                            for="zoom_attend_url">
                            Generated Zoom Meeting URL
                            <span
                                class="text-surface-500 -mt-0.5 block text-xs font-normal"
                                >Auto-generated from the fields above — do not
                                edit directly</span>
                            <input
                                type="url"
                                id="zoom_attend_url"
                                name="zoom_attend_url"
                                autocomplete="url"
                                readonly
                                bind:value={
                                    $idaa_slct.event_obj.attend_json.zoom
                                        .full_url
                                }
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-full font-mono text-sm"
                                placeholder="https://zoom.us/j/..." />
                        </label>
                    </div>

                    <!-- Jitsi fields -->
                {:else if $idaa_sess.recovery_meetings.attend_platform === 'Jitsi'}
                    <div
                        class="bg-surface-50-950 border-surface-200-800 flex flex-row flex-wrap gap-3 rounded border p-2">
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="attend_url_code">
                            Jitsi Meeting Name / Code
                            <input
                                type="text"
                                id="attend_url_code"
                                name="attend_url_code"
                                autocomplete="off"
                                placeholder="Meeting room name"
                                bind:value={
                                    $idaa_slct.event_obj.attend_json.jitsi.name
                                }
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-72" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="attend_url_passcode">
                            Jitsi Passcode
                            <input
                                type="text"
                                id="attend_url_passcode"
                                name="attend_url_passcode"
                                autocomplete="off"
                                placeholder="Optional passcode"
                                bind:value={
                                    $idaa_slct.event_obj.attend_json.jitsi
                                        .passcode
                                }
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                        </label>
                        <label
                            class="text-surface-700-300 flex w-full flex-col gap-1 text-sm font-semibold"
                            for="attend_url">
                            Jitsi Meeting URL
                            <input
                                type="url"
                                id="attend_url"
                                name="attend_url"
                                autocomplete="url"
                                placeholder="https://meet.jit.si/..."
                                bind:value={
                                    $idaa_slct.event_obj.attend_json.jitsi
                                        .full_url
                                }
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-full font-mono text-sm" />
                        </label>
                    </div>

                    <!-- Other / Generic virtual platform fields -->
                {:else}
                    <div
                        class="bg-surface-50-950 border-surface-200-800 flex flex-row flex-wrap gap-3 rounded border p-2">
                        <label
                            class="text-surface-700-300 flex w-full flex-col gap-1 text-sm font-semibold"
                            for="attend_url">
                            Meeting URL
                            <input
                                type="url"
                                id="attend_url"
                                name="attend_url"
                                autocomplete="url"
                                placeholder="URL to join the meeting"
                                value={$lq__event_obj?.attend_url ?? ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-full font-mono text-sm" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="attend_url_passcode">
                            URL Passcode
                            <input
                                type="text"
                                id="attend_url_passcode"
                                name="attend_url_passcode"
                                autocomplete="off"
                                placeholder="Passcode to join at URL"
                                value={$lq__event_obj?.attend_url_passcode ??
                                    ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="attend_phone">
                            Dial-In Phone Number
                            <input
                                type="tel"
                                id="attend_phone"
                                name="attend_phone"
                                autocomplete="tel"
                                placeholder="Phone number for dial-in"
                                value={$lq__event_obj?.attend_phone ?? ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="attend_phone_passcode">
                            Dial-In Passcode
                            <input
                                type="text"
                                id="attend_phone_passcode"
                                name="attend_phone_passcode"
                                autocomplete="off"
                                placeholder="Passcode for dial-in"
                                value={$lq__event_obj?.attend_phone_passcode ??
                                    ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                        </label>
                    </div>
                {/if}
            </div>

            <!-- ── Additional attendance notes (applies to any meeting type) ── -->
            <label
                class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                for="attend_text">
                Additional Attendance Information
                <span class="text-surface-500 -mt-0.5 block text-xs font-normal"
                    >Any extra instructions for joining — shown to all members
                    regardless of meeting type</span>
                <AE_Comp_Editor_TipTap
                    bind:content={attend_text_new_html}
                    class_li="field-richtext"
                    placeholder="Additional instructions for joining this meeting" />
            </label>
        </div>

        <!-- ============================================================
             SECTION 3 — Schedule
             Fields: recurring_pattern, weekday_* (Sun–Sat), timezone,
                     recurring_start_time, recurring_end_time, recurring_text (optional)
             recurring=true is always assumed for recovery meetings (hardcoded 2024-10).
             recurring_text is auto-generated with *gen* prefix if left blank.
             Members only see custom recurring_text (no *gen*); admins see both.
             ============================================================ -->
        <div
            class="bg-surface-100-900 border-surface-200-800 space-y-3 rounded-md border p-3"
            id="section__schedule">
            <h3
                class="text-surface-600-400 border-surface-200-800 flex items-center gap-2 border-b pb-1 text-lg font-semibold">
                <span class="fas fa-calendar-alt"></span>
                Schedule
            </h3>

            <!-- Recurring pattern — bind to working copy so user changes aren't
                 overwritten when $lq__event_obj fires during editing -->
            <label
                class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                for="recurring_pattern">
                Repeats
                <select
                    id="recurring_pattern"
                    name="recurring_pattern"
                    bind:value={$idaa_slct.event_obj.recurring_pattern}
                    class="select preset-tonal-surface hover:preset-filled-surface-100-900 w-48 p-1">
                    <option value="weekly">Weekly</option>
                    <option value="every other week">Every Other Week</option>
                    <option value="monthly">Monthly</option>
                    <option value="other">Other</option>
                </select>
            </label>

            <!-- Days of week — toggle chips so selected days are immediately visible,
                 matching how they appear as inline text in the list and detail views -->
            <fieldset>
                <legend
                    class="text-surface-700-300 mb-1 flex flex-col gap-1 text-sm font-semibold"
                    >Days of Week</legend>
                <div class="flex flex-row flex-wrap gap-2">
                    {#each [{ name: 'weekday_sunday', label: 'Sun' }, { name: 'weekday_monday', label: 'Mon' }, { name: 'weekday_tuesday', label: 'Tue' }, { name: 'weekday_wednesday', label: 'Wed' }, { name: 'weekday_thursday', label: 'Thu' }, { name: 'weekday_friday', label: 'Fri' }, { name: 'weekday_saturday', label: 'Sat' }] as day (day.name)}
                        <label
                            for={day.name}
                            class="flex w-12 cursor-pointer items-center justify-center rounded-lg border py-2 text-sm font-semibold transition-all"
                            class:preset-filled-primary-200-800={weekdays[
                                day.name
                            ]}
                            class:border-primary-400={weekdays[day.name]}
                            class:preset-tonal-surface={!weekdays[day.name]}
                            class:border-surface-300-700={!weekdays[day.name]}>
                            {day.label}
                            <input
                                type="checkbox"
                                id={day.name}
                                name={day.name}
                                checked={weekdays[day.name]}
                                onchange={() => {
                                    weekdays[day.name] = !weekdays[day.name];
                                }}
                                class="sr-only" />
                        </label>
                    {/each}
                </div>
            </fieldset>

            <!-- Timezone + Start / End time — grouped together since they form a single
                 logical "when does this meeting happen" unit displayed together in the view -->
            <div class="flex flex-row flex-wrap items-end gap-3">
                <label
                    class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                    for="timezone">
                    <div class="flex items-center gap-1">
                        <span>Timezone</span>
                        <span class="text-error-500 ml-0.5">*</span>
                    </div>
                    {#if ($lq__lu_time_zone ?? []).length}
                        <select
                            id="timezone"
                            name="timezone"
                            required
                            value={$lq__event_obj?.timezone ??
                                $ae_loc?.current_timezone}
                            class="select preset-tonal-surface hover:preset-filled-surface-100-900 w-56 p-1">
                            <option
                                value=""
                                class:hidden={!$ae_loc.trusted_access}
                                >-- None --</option>
                            {#each $lq__lu_time_zone ?? [] as tz (tz.name)}
                                <option value={tz.name}>{tz.name}</option>
                            {/each}
                        </select>
                    {:else}
                        <input
                            type="text"
                            id="timezone"
                            name="timezone"
                            required
                            value={$lq__event_obj?.timezone ??
                                $ae_loc?.current_timezone ??
                                ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-44" />
                    {/if}
                </label>

                <!-- bind to working copy (same reason as recurring_pattern above) -->
                <label
                    class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                    for="recurring_start_time">
                    Start Time
                    <input
                        type="time"
                        id="recurring_start_time"
                        name="recurring_start_time"
                        bind:value={$idaa_slct.event_obj.recurring_start_time}
                        class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-36" />
                </label>

                <label
                    class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                    for="recurring_end_time">
                    End Time
                    <input
                        type="time"
                        id="recurring_end_time"
                        name="recurring_end_time"
                        bind:value={$idaa_slct.event_obj.recurring_end_time}
                        class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-36" />
                </label>
            </div>

            <!-- Additional schedule details (recurring_text).
                 Auto-generated with *gen* prefix on save if not provided.
                 Members only see this if it has been customized (no *gen*).
                 Admins can always see and edit it.
                 The "Add More Details?" button promotes the auto-generated text to
                 a custom editable value by stripping the *gen* prefix. -->
            {#if $ae_loc.administrator_access || ($lq__event_obj && ($idaa_slct.event_obj?.show_recurring_text || ($lq__event_obj?.recurring_text && !$lq__event_obj?.recurring_text.includes('*gen*'))))}
                <div class="border-surface-300-700 space-y-2 border-l-2 pl-3">
                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="recurring_text">
                        Additional Schedule Details
                        <span
                            class="text-surface-500 -mt-0.5 block text-xs font-normal"
                            >Optional — use only if the options above don't
                            fully describe the schedule. This text is shown
                            directly to members.</span>
                        <AE_Comp_Editor_TipTap
                            bind:content={recurring_text_new_html}
                            class_li="field-richtext"
                            placeholder="e.g. First Monday of each month, or Meets on the 3rd Thursday" />
                    </label>
                    <button
                        type="button"
                        class="btn btn-sm preset-tonal-error"
                        onclick={() => {
                            if (
                                confirm(
                                    'Remove the custom schedule text? The schedule will revert to auto-generated text.'
                                )
                            ) {
                                $idaa_slct.event_obj.recurring_text = '';
                                recurring_text_new_html = '';
                                $idaa_slct.event_obj.show_recurring_text = false;
                            }
                        }}>
                        <span class="fas fa-minus"></span> Remove Custom Text
                    </button>
                </div>
            {:else}
                <button
                    type="button"
                    class="btn btn-sm preset-tonal-surface"
                    onclick={prevent_default(() => {
                        // Promote auto-generated text to editable by stripping the *gen* prefix
                        if ($lq__event_obj?.recurring_text?.includes('*gen*')) {
                            recurring_text_new_html =
                                $lq__event_obj.recurring_text.replace(
                                    '*gen* ',
                                    ''
                                );
                            $idaa_slct.event_obj.recurring_text =
                                recurring_text_new_html;
                        }
                        $idaa_slct.event_obj.show_recurring_text = true;
                    })}>
                    <span class="fas fa-plus"></span> Add Custom Schedule Text
                </button>
            {/if}
        </div>

        <!-- ============================================================
             SECTION 4 — Contacts
             Fields: external_person_id (Novi UUID link),
                     contact_li_json[0] (Contact 1 — name/email locked to Novi user by default),
                     contact_li_json[1] (Contact 2 — optional)
             BUSINESS RULE: Trusted+ can edit any meeting. Regular members can only
             edit their own meetings (external_person_id === novi_uuid, or email fallback).
             Contact 1 name/email are locked by default for members to prevent accidental
             override of the meeting owner's identity.
             ============================================================ -->
        <div
            class="bg-surface-100-900 border-surface-200-800 space-y-3 rounded-md border p-3"
            id="section__contacts">
            <h3
                class="text-surface-600-400 border-surface-200-800 flex items-center gap-2 border-b pb-1 text-lg font-semibold">
                <span class="fas fa-address-book"></span>
                Contacts
            </h3>

            <!-- Meeting Owner (external_person_id = Novi UUID of owner) -->
            <!-- Trusted+ can reassign ownership; members see it as read-only context. -->
            {#if $ae_loc.trusted_access}
                <label
                    class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                    for="external_person_id">
                    Meeting Owner — Novi UUID
                    <span
                        class="text-surface-500 -mt-0.5 block text-xs font-normal"
                        >The Novi UUID of the IDAA member who owns this meeting.
                        Determines who may edit it.</span>
                    <input
                        type="text"
                        id="external_person_id"
                        name="external_person_id"
                        autocomplete="off"
                        placeholder="Novi UUID"
                        value={$lq__event_obj?.external_person_id ??
                            $idaa_loc.novi_uuid ??
                            ''}
                        class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-72 font-mono text-sm" />
                </label>
            {:else}
                <!-- Hidden input passes the owner UUID through form submission unchanged -->
                <input
                    type="hidden"
                    name="external_person_id"
                    value={$lq__event_obj?.external_person_id ??
                        $idaa_loc.novi_uuid ??
                        ''} />
                <div class="space-y-1">
                    <p
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold">
                        Meeting Owner
                    </p>
                    <div
                        class="text-surface-600-400 flex items-center gap-2 text-sm">
                        <span class="fas fa-lock text-xs"></span>
                        {#if $lq__event_obj?.external_person_full_name}
                            <span
                                >{$lq__event_obj.external_person_full_name}</span>
                        {:else if $lq__event_obj?.external_person_email}
                            <span>{$lq__event_obj.external_person_email}</span>
                        {:else if $lq__event_obj?.external_person_id}
                            <span class="font-mono text-xs"
                                >{$lq__event_obj.external_person_id}</span>
                        {:else}
                            <span class="text-surface-400 italic">Not set</span>
                        {/if}
                    </div>
                </div>
            {/if}

            <!-- ── Contact 1 (Primary) ────────────────────────────────── -->
            <!-- Name and email default to the logged-in Novi user's identity and are
                 locked readonly for members. This is intentional: the primary contact
                 for a meeting is nearly always the owner. Members unlock via confirm
                 if they truly need different contact details. -->
            <div class="border-surface-300-700 space-y-3 border-l-2 pl-3">
                <div class="flex flex-wrap items-center gap-2">
                    <h4
                        class="text-surface-600-400 flex items-center gap-1.5 text-sm font-semibold">
                        <span class="fas fa-user"></span> Contact 1 (Primary)
                    </h4>
                    {#if !$ae_loc.trusted_access && contact_1_locked}
                        <button
                            type="button"
                            class="btn btn-sm preset-tonal-warning"
                            onclick={() => {
                                if (
                                    confirm(
                                        'The primary contact name and email are pre-filled with your account identity. Do you want to change them to different contact details?'
                                    )
                                ) {
                                    contact_1_locked = false;
                                }
                            }}>
                            <span class="fas fa-lock"></span> Unlock to Edit
                        </button>
                    {:else if !$ae_loc.trusted_access && !contact_1_locked}
                        <button
                            type="button"
                            class="btn btn-sm preset-tonal-surface"
                            onclick={() => {
                                contact_1_locked = true;
                            }}>
                            <span class="fas fa-lock-open"></span> Re-Lock
                        </button>
                    {/if}
                </div>

                <div class="flex flex-row flex-wrap gap-3">
                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="contact_1_full_name">
                        Full Name
                        <input
                            type="text"
                            id="contact_1_full_name"
                            name="contact_1_full_name"
                            autocomplete="name"
                            placeholder="Full name"
                            readonly={!$ae_loc.trusted_access &&
                                contact_1_locked}
                            value={$lq__event_obj?.contact_li_json?.[0]
                                ?.full_name ??
                                $idaa_loc.novi_full_name ??
                                ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-64"
                            class:opacity-60={!$ae_loc.trusted_access &&
                                contact_1_locked} />
                    </label>
                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="contact_1_email">
                        Email
                        <input
                            type="email"
                            id="contact_1_email"
                            name="contact_1_email"
                            autocomplete="email"
                            placeholder="Email address"
                            readonly={!$ae_loc.trusted_access &&
                                contact_1_locked}
                            value={$lq__event_obj?.contact_li_json?.[0]
                                ?.email ??
                                $idaa_loc.novi_email ??
                                ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-64"
                            class:opacity-60={!$ae_loc.trusted_access &&
                                contact_1_locked} />
                    </label>
                </div>

                <div class="flex flex-row flex-wrap gap-3">
                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="contact_1_phone_mobile">
                        Mobile Phone
                        <input
                            type="tel"
                            id="contact_1_phone_mobile"
                            name="contact_1_phone_mobile"
                            autocomplete="tel"
                            placeholder="Mobile / Cell"
                            value={$lq__event_obj?.contact_li_json?.[0]
                                ?.phone_mobile ?? ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                    </label>
                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="contact_1_phone_home">
                        Home Phone
                        <input
                            type="tel"
                            id="contact_1_phone_home"
                            name="contact_1_phone_home"
                            autocomplete="tel"
                            placeholder="Home phone"
                            value={$lq__event_obj?.contact_li_json?.[0]
                                ?.phone_home ?? ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                    </label>
                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="contact_1_phone_office">
                        Office Phone
                        <input
                            type="tel"
                            id="contact_1_phone_office"
                            name="contact_1_phone_office"
                            autocomplete="tel"
                            placeholder="Office phone"
                            value={$lq__event_obj?.contact_li_json?.[0]
                                ?.phone_office ?? ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                    </label>
                </div>
            </div>

            <!-- ── Contact 2 (Optional secondary) ────────────────────── -->
            <div class="border-surface-300-700 space-y-3 border-l-2 pl-3">
                <button
                    type="button"
                    class="flex w-full flex-row items-center gap-2 text-left"
                    onclick={() => (show_contact_2 = !show_contact_2)}>
                    <span
                        class="fas fa-{show_contact_2
                            ? 'caret-down'
                            : 'caret-right'} text-xs opacity-60"></span>
                    <h4
                        class="text-surface-600-400 mb-0! flex items-center gap-1.5 text-sm font-semibold">
                        <span class="fas fa-user-plus"></span> Contact 2 (Optional)
                    </h4>
                </button>

                {#if show_contact_2}
                    <div class="flex flex-row flex-wrap gap-3">
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="contact_2_full_name">
                            Full Name
                            <input
                                type="text"
                                id="contact_2_full_name"
                                name="contact_2_full_name"
                                autocomplete="name"
                                placeholder="Full name"
                                value={$lq__event_obj?.contact_li_json?.[1]
                                    ?.full_name ?? ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-64" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="contact_2_email">
                            Email
                            <input
                                type="email"
                                id="contact_2_email"
                                name="contact_2_email"
                                autocomplete="email"
                                placeholder="Email address"
                                value={$lq__event_obj?.contact_li_json?.[1]
                                    ?.email ?? ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-64" />
                        </label>
                    </div>

                    <div class="flex flex-row flex-wrap gap-3">
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="contact_2_phone_mobile">
                            Mobile Phone
                            <input
                                type="tel"
                                id="contact_2_phone_mobile"
                                name="contact_2_phone_mobile"
                                autocomplete="tel"
                                placeholder="Mobile / Cell"
                                value={$lq__event_obj?.contact_li_json?.[1]
                                    ?.phone_mobile ?? ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="contact_2_phone_home">
                            Home Phone
                            <input
                                type="tel"
                                id="contact_2_phone_home"
                                name="contact_2_phone_home"
                                autocomplete="tel"
                                placeholder="Home phone"
                                value={$lq__event_obj?.contact_li_json?.[1]
                                    ?.phone_home ?? ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="contact_2_phone_office">
                            Office Phone
                            <input
                                type="tel"
                                id="contact_2_phone_office"
                                name="contact_2_phone_office"
                                autocomplete="tel"
                                placeholder="Office phone"
                                value={$lq__event_obj?.contact_li_json?.[1]
                                    ?.phone_office ?? ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                        </label>
                    </div>
                {:else}
                    <!-- Hidden inputs preserve existing Contact 2 data when the section is
                         collapsed. Without these, FormData would omit the fields entirely
                         and the submit handler would overwrite saved contact info with nulls. -->
                    <input
                        type="hidden"
                        name="contact_2_full_name"
                        value={$lq__event_obj?.contact_li_json?.[1]
                            ?.full_name ?? ''} />
                    <input
                        type="hidden"
                        name="contact_2_email"
                        value={$lq__event_obj?.contact_li_json?.[1]?.email ??
                            ''} />
                    <input
                        type="hidden"
                        name="contact_2_phone_mobile"
                        value={$lq__event_obj?.contact_li_json?.[1]
                            ?.phone_mobile ?? ''} />
                    <input
                        type="hidden"
                        name="contact_2_phone_home"
                        value={$lq__event_obj?.contact_li_json?.[1]
                            ?.phone_home ?? ''} />
                    <input
                        type="hidden"
                        name="contact_2_phone_office"
                        value={$lq__event_obj?.contact_li_json?.[1]
                            ?.phone_office ?? ''} />
                {/if}
            </div>
        </div>

        <!-- ============================================================
             SECTION 5 — Admin Options  (trusted_access only)
             Fields: status, hide, priority, sort, group, enable, notes
             ============================================================ -->
        {#if $ae_loc.trusted_access}
            <div
                class="bg-surface-100-900 border-surface-200-800 border-error-400 space-y-3 rounded-md border p-3"
                id="section__admin_options">
                <button
                    type="button"
                    class="flex w-full flex-row items-center gap-2 text-left"
                    onclick={() => (show_admin_options = !show_admin_options)}>
                    <span
                        class="fas fa-{show_admin_options
                            ? 'caret-down'
                            : 'caret-right'} text-xs opacity-60"></span>
                    <h3
                        class="text-surface-600-400 border-surface-200-800 mb-0! flex items-center gap-2 border-b pb-1 text-lg font-semibold">
                        <span class="fas fa-cogs"></span>
                        Admin Options
                    </h3>
                </button>

                {#if show_admin_options}
                    <!-- Status -->
                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="status">
                        Status
                        <input
                            type="text"
                            id="status"
                            name="status"
                            placeholder="e.g. active, pending, closed"
                            value={$lq__event_obj?.status ?? ''}
                            class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-52" />
                    </label>

                    <!-- Enable / Hide / Priority toggles -->
                    <div class="flex flex-row flex-wrap gap-4">
                        <label
                            class="flex cursor-pointer items-center gap-2 text-sm font-semibold"
                            for="enable">
                            <input
                                type="checkbox"
                                id="enable"
                                name="enable"
                                checked={$lq__event_obj?.enable ?? true}
                                class="checkbox" />
                            Enabled
                        </label>
                        <label
                            class="flex cursor-pointer items-center gap-2 text-sm font-semibold"
                            for="hide">
                            <input
                                type="checkbox"
                                id="hide"
                                name="hide"
                                checked={$lq__event_obj?.hide ?? false}
                                class="checkbox" />
                            Hidden
                        </label>
                        <label
                            class="flex cursor-pointer items-center gap-2 text-sm font-semibold"
                            for="priority">
                            <input
                                type="checkbox"
                                id="priority"
                                name="priority"
                                checked={$lq__event_obj?.priority ?? false}
                                class="checkbox" />
                            Priority (Featured)
                        </label>
                    </div>

                    <!-- Sort + Group -->
                    <div class="flex flex-row flex-wrap gap-3">
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="sort">
                            Sort Order
                            <span
                                class="text-surface-500 -mt-0.5 block text-xs font-normal"
                                >Lower numbers appear first</span>
                            <input
                                type="number"
                                id="sort"
                                name="sort"
                                placeholder="0"
                                value={$lq__event_obj?.sort ?? ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-28" />
                        </label>
                        <label
                            class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                            for="group">
                            Group
                            <span
                                class="text-surface-500 -mt-0.5 block text-xs font-normal"
                                >Optional grouping label</span>
                            <input
                                type="text"
                                id="group"
                                name="group"
                                placeholder="e.g. North America"
                                value={$lq__event_obj?.group ?? ''}
                                class="input preset-tonal-surface hover:preset-filled-surface-100-900 w-48" />
                        </label>
                    </div>

                    <!-- Notes — internal, not visible to members -->
                    <label
                        class="text-surface-700-300 flex flex-col gap-1 text-sm font-semibold"
                        for="notes">
                        Admin Notes
                        <span
                            class="text-surface-500 -mt-0.5 block text-xs font-normal"
                            >Internal only — not visible to members</span>
                        <AE_Comp_Editor_TipTap
                            bind:content={notes_new_html}
                            class_li="field-richtext"
                            placeholder="Internal notes about this meeting" />
                    </label>
                {:else}
                    <!-- Hidden inputs preserve admin field values when section is collapsed.
                         Checkboxes are omitted from FormData when unchecked, so we use
                         hidden inputs with '1'/'0' string values that the submit handler
                         already converts via form_data.get(). -->
                    <input
                        type="hidden"
                        name="status"
                        value={$lq__event_obj?.status ?? ''} />
                    <input
                        type="hidden"
                        name="enable"
                        value={$lq__event_obj?.enable ? 'true' : 'false'} />
                    <input
                        type="hidden"
                        name="hide"
                        value={$lq__event_obj?.hide ? 'true' : 'false'} />
                    <input
                        type="hidden"
                        name="priority"
                        value={$lq__event_obj?.priority ? 'true' : 'false'} />
                    <input
                        type="hidden"
                        name="sort"
                        value={$lq__event_obj?.sort ?? ''} />
                    <input
                        type="hidden"
                        name="group"
                        value={$lq__event_obj?.group ?? ''} />
                {/if}
            </div>
        {/if}

        <!-- ============================================================
             SECTION 6 — Form Actions
             Save: always shown. Delete/Disable: trusted+ on existing meetings only.
             Administrator gets a hard-delete option; trusted gets disable.
             Cancel closes the edit modal and returns to the view (if editing).
             ============================================================ -->
        <div
            class="
                border-surface-300-700 flex w-full flex-row flex-wrap items-center justify-between
                gap-2 border-t pt-2
            "
            id="section__actions">
            <!-- Primary: Save -->
            <button
                type="submit"
                class="btn preset-filled-primary-200-800"
                disabled={disable_submit_btn}>
                {#await prom_api__event_obj}
                    <span class="fas fa-spinner fa-spin"></span> Saving...
                {:then}
                    {#if $idaa_slct.event_id}
                        <span class="fas fa-save"></span> Save Changes
                    {:else}
                        <span class="fas fa-plus-circle"></span> Save New Meeting
                    {/if}
                {/await}
            </button>

            <div class="flex flex-row flex-wrap items-center gap-2">
                <!-- Delete / Disable — tiered by permission, only on existing meetings -->
                {#if $idaa_slct.event_id && $ae_loc.trusted_access}
                    {#if $ae_loc.administrator_access}
                        <!-- Administrators: hard delete available -->
                        <button
                            type="button"
                            class="btn preset-tonal-error"
                            onclick={() => {
                                if (
                                    confirm(
                                        'Permanently delete this meeting? This cannot be undone.'
                                    )
                                ) {
                                    handle_delete_event_obj({
                                        event_id: $idaa_slct.event_id,
                                        method: 'delete'
                                    });
                                }
                            }}>
                            <span class="fas fa-trash-alt"></span> Delete
                        </button>
                    {/if}
                    <!-- Trusted: soft disable (keeps data, removes from listing) -->
                    <button
                        type="button"
                        class="btn preset-tonal-warning"
                        onclick={() => {
                            if (
                                confirm(
                                    'Disable this meeting? It will be hidden from the listing but can be re-enabled.'
                                )
                            ) {
                                handle_delete_event_obj({
                                    event_id: $idaa_slct.event_id,
                                    method: 'disable'
                                });
                            }
                        }}>
                        <span class="fas fa-ban"></span> Disable
                    </button>
                {/if}

                <!-- Cancel — closes edit modal, returns to view if editing existing -->
                <button
                    type="button"
                    class="btn preset-tonal-surface"
                    onclick={() => {
                        // Clear both modal and direct-page edit flags
                        $idaa_sess.recovery_meetings.show__modal_edit = false;
                        $idaa_sess.recovery_meetings.edit__event_obj = false;
                        if ($idaa_slct.event_id) {
                            $idaa_sess.recovery_meetings.show__modal_view = true;
                        }
                    }}>
                    <span class="fas fa-times"></span> Cancel
                </button>
            </div>
        </div>
    </form>
</section>
