<script lang="ts">
    /**
     * ae_comp__badge_obj_view_v2.svelte
     *
     * V2 badge render component — replaces the manual longest_str_part() heuristic
     * with element_fit_text.svelte (binary-search auto-scaling) for all four text
     * fields (name, title, affiliations, location).
     *
     * Auto-scaling is suppressed in edit mode (inputs need fixed size, not auto-scale).
     * Manual override props (font_size_*) from print controls still work — they are
     * forwarded to Element_fit_text as manual_size, which disables auto-scale for
     * that field and sets the size directly.
     *
     * Differences from v1 (ae_comp__badge_obj_view.svelte):
     *   - Imports Element_fit_text
     *   - Removed: full_name_class_size, professional_title_class_size,
     *              affiliations_class_size, location_class_size state vars
     *   - Removed: longest_str_part() function
     *   - Removed: the $effect block that computed those size classes
     *   - Text fields in display mode are wrapped with <Element_fit_text>
     *   - Edit mode uses plain divs (no auto-scaling on inputs)
     */

    interface Props {
        event_id: string;
        event_badge_id: string;
        lq__event_badge_obj?: any;
        lq__event_badge_template_obj?: any;
        update_status?: string;
        update_complete?: boolean;
        is_review_mode?: boolean;
        /** Optional px override for name font size. When undefined/null, auto-scaling runs. */
        font_size_name?: number | null;
        /** Optional px override for professional title font size. When undefined/null, auto-scaling runs. */
        font_size_title?: number | null;
        /** Optional px override for affiliations font size. When undefined/null, auto-scaling runs. */
        font_size_affiliations?: number | null;
        /** Optional px override for location font size. When undefined/null, auto-scaling runs. */
        font_size_location?: number | null;
        log_lvl?: number;
    }

    let {
        event_id,
        event_badge_id,
        lq__event_badge_obj,
        lq__event_badge_template_obj,
        update_status = $bindable('idle'),
        update_complete = $bindable(true),
        is_review_mode = false,
        // V2: no numeric defaults — undefined → auto-scale runs via Element_fit_text.
        // When the user adjusts a field in the print controls panel, a number is pushed
        // here via the $bindable binding, which disables auto-scale for that field.
        // Reset (×) in the print controls panel restores null → auto-scale resumes.
        font_size_name,
        font_size_title,
        font_size_affiliations,
        font_size_location,
        log_lvl = 0
    }: Props = $props();

    // Badge layout CSS — compiled in, hot-reloads in dev.
    // Each file scopes rules under [data-layout="..."] on the wrapper section.
    // @page rules (paper size) are injected per-template in print/+page.svelte.
    import '$lib/ae_events/badges/css/badge_layout_epson_4x5_fanfold.css';
    import '$lib/ae_events/badges/css/badge_layout_zebra_zc10l_pvc.css';

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

    import type { key_val } from '$lib/stores/ae_stores';
    import { core_func } from '$lib/ae_core/ae_core_functions';
    import {
        ae_snip,
        ae_loc,
        ae_sess,
        ae_api,
        ae_trig,
        slct,
        slct_trigger
    } from '$lib/stores/ae_stores';
    import { events_func } from '$lib/ae_events_functions';

    // V2: auto-scaling text component
    import Element_fit_text from '$lib/elements/element_fit_text.svelte';

    // *** Variables
    let ae_triggers: key_val = $state({});

    // Badge type list is derived from the template — each event/template defines its own set.
    // Falls back to empty array if template not loaded or badge_type_list is invalid JSON.
    let badge_type_code_li = $derived.by(() => {
        const raw = $lq__event_badge_template_obj?.badge_type_list;
        if (!raw) return [];
        try {
            return JSON.parse(raw);
        } catch {
            console.warn('badge_type_list is not valid JSON:', raw);
            return [];
        }
    });

    // Human-readable name for the current badge type, printed on the badge footer.
    // Priority: badge_type_override (staff custom name) → badge_type (base import name)
    // → template badge_type_list lookup by effective code → code itself as last resort.
    //
    // Why separate from code: the code is the CSS class hook for per-event stylesheets.
    // A special-case attendee can share a code (and thus styling) with "Member" but have a
    // custom displayed name like "Life Member" stored in badge_type_override.
    let badge_type_name = $derived.by(() => {
        // Staff override name takes priority
        const override_name = $lq__event_badge_obj?.badge_type_override;
        if (override_name) return override_name;
        // Base name from import/registration system
        const base_name = $lq__event_badge_obj?.badge_type;
        if (base_name) return base_name;
        // Fall back to template list lookup using the effective code
        const found = (badge_type_code_li as { code: string; name: string }[])
            .find(item => item.code === editable_badge_type_code);
        return found?.name ?? editable_badge_type_code ?? '';
    });

    // Show the badge back section when duplex=1 (or when duplex is not yet set, as a safe default).
    // duplex=0/false → single-sided print (e.g. Zebra ZC10L PVC cards); back section is hidden.
    let show_badge_back = $derived(
        $lq__event_badge_template_obj?.duplex == null || !!$lq__event_badge_template_obj?.duplex
    );

    // Receipt and ticket sections are currently disabled pending redesign.
    let show_receipt = $derived(false);
    let show_tickets = $derived(false);

    /**
     * Layout-aware section heights for Element_fit_text.
     *
     * Structure per layout:
     *   grp_name_title      — height of the person_name container (name + title together)
     *   grp_name_title_flex — how name vs title are distributed within that container
     *   name                — height of the name Element_fit_text
     *   title               — height of the title Element_fit_text
     *   grp_aff_loc         — height of the affiliations_location container
     *   grp_aff_loc_flex    — how affiliations vs location are distributed within that container
     *   affiliations        — height of the affiliations Element_fit_text
     *   location            — height of the location Element_fit_text
     *
     * Flex values: 'around' | 'between' | 'even' | 'center' | 'start' | 'end'
     * (mapped to space-around, space-between, space-evenly, center, flex-start, flex-end)
     *
     * Layout codes (from ae_events/badges/css/):
     *   badge_3.5x5.5_pvc   — Zebra ZC10L PVC card, 3.5" × 5.5", single-sided
     *   badge_4x5_fanfold    — Epson 4" × 5" fanfold, duplex
     *   badge_4x6_fanfold    — Default 4" × 6" fanfold, duplex
     *
     * TODO: Move to badge template config (cfg_json) once multi-layout events are needed.
     * Tune these values with real badge data and a ruler.
     */
    let fit_heights = $derived.by(() => {
        const layout = $lq__event_badge_template_obj?.layout ?? 'badge_4x6_fanfold';
        if (layout === 'badge_3.5x5.5_pvc') {
            // 3.5" × 5.5" PVC card — single-sided, compact
            return {
                grp_name_title:      '1.8in',
                grp_name_title_flex: 'around',
                name:                '1.4in',
                title:               '0.55in',
                grp_aff_loc:         '1.5in',
                grp_aff_loc_flex:    'around',
                affiliations:        '0.75in',
                location:            '0.75in',
            };
        } else if (layout === 'badge_4x5_fanfold') {
            // 4" × 5" fanfold — slightly taller, duplex
            return {
                grp_name_title:      '2.1in',
                grp_name_title_flex: 'around',
                name:                '1.6in',
                title:               '0.6in',
                grp_aff_loc:         '1.65in',
                grp_aff_loc_flex:    'between',
                affiliations:        '1.1in',
                location:            '0.5in',
            };
        } else {
            // Default: badge_4x6_fanfold — 4" × 6", most room
            return {
                grp_name_title:      '2.5in',
                grp_name_title_flex: 'around',
                name:                '1.9in',
                title:               '0.7in',
                grp_aff_loc:         '1.9in',
                grp_aff_loc_flex:    'between',
                affiliations:        '1.3in',
                location:            '0.55in',
            };
        }
    });

    /**
     * Maps fit_heights flex shorthand to CSS justify-content values.
     * Used on the group container divs (person_name, affiliations_location).
     */
    function flex_justify(val: string): string {
        const map: Record<string, string> = {
            around:  'space-around',
            between: 'space-between',
            even:    'space-evenly',
            center:  'center',
            start:   'flex-start',
            end:     'flex-end',
        };
        return map[val] ?? 'space-around';
    }

    // *** Set initial variables
    $effect(() => {
        $slct.event_badge_id = event_badge_id;
    });
    let trigger = $state(null);

    let initial_loading_promise = $state(null);

    let event_badge_obj_load_promise = $state(null);
    let event_badge_obj_update_promise = $state(null);

    let event_badge_qr_mecard_get_promise = $state(null);
    let event_badge_qr_id_get_promise = $state(null);

    let show_event_badge_tools_modal: boolean = $state(false);
    let show_restricted_fields: boolean = $state(false);

    // Editable fields
    let editable_full_name_override: string | null = $state(null);
    let editable_professional_title_override: string | null = $state(null);
    let editable_affiliations_override: string | null = $state(null);
    let editable_location_override: string | null = $state(null);
    let editable_allow_tracking: boolean | null = $state(null);
    let editable_email: string | null = $state(null);
    let editable_badge_type_code: string | null = $state(null);

    // Manage edit state locally
    let edit_mode_active: boolean = $state(false);

    // Initialize editable fields when lq__event_badge_obj changes
    $effect(() => {
        if ($lq__event_badge_obj) {
            if (log_lvl) {
                console.log('Initializing editable fields from lq__event_badge_obj');
            }
            editable_full_name_override =
                $lq__event_badge_obj.full_name_override ??
                $lq__event_badge_obj.full_name;
            editable_professional_title_override =
                $lq__event_badge_obj.professional_title_override ??
                $lq__event_badge_obj.professional_title;
            editable_affiliations_override =
                $lq__event_badge_obj.affiliations_override ??
                $lq__event_badge_obj.affiliations;
            editable_location_override =
                $lq__event_badge_obj.location_override ??
                $lq__event_badge_obj.location;
            editable_allow_tracking =
                $lq__event_badge_obj.allow_tracking ?? null;
            editable_email = $lq__event_badge_obj.email ?? null;
            // Use staff override code if set; base code from import/registration otherwise.
            editable_badge_type_code =
                $lq__event_badge_obj.badge_type_code_override ??
                $lq__event_badge_obj.badge_type_code ?? null;

            // Only set the local edit state — never touch $ae_loc.edit_mode here.
            // $ae_loc.edit_mode is a user preference; this component must not override it.
            if (is_review_mode) {
                edit_mode_active = true;
            } else {
                edit_mode_active = false;
            }
        }
    });

    let show_print_msg: null | boolean = $state(null);
    let hide_qr: null | boolean = $state(null);

    let use_badge_type_code = $state('');
    let option_ticket_1_override = $state('');
    let option_ticket_2_override = $state('');
    let option_ticket_3_override = $state('');
    let option_other_1_override = $state('');
    let option_other_2_override = $state('');

    let slct_badge_type = '';

    /* *** BEGIN *** This should be moved out */
    let option_ticket_1_display_opt = 'front_bool';
    let option_ticket_2_display_opt = 'front_bool';
    let option_ticket_3_display_opt = 'front_bool';

    let option_other_1_display_opt = 'back_html';
    let option_other_2_display_opt = 'back_html';

    let code_to_html: any = { option_1: {}, option_2: {} };
    code_to_html.option_1['1'] = '<span class="fas fa-biohazard"></span>';
    code_to_html.option_1['true'] = '<span class="fas fa-biohazard"></span>';
    code_to_html.option_1['True'] = '<span class="fas fa-biohazard"></span>';
    code_to_html.option_1['Dairy Free'] = '<span class="fas fa-utensils"></span>';
    code_to_html.option_1['Gluten Free'] = '<span class="fas fa-utensils"></span>';
    code_to_html.option_1['Halal'] = '<span class="fas fa-utensils"></span>';
    code_to_html.option_1['Kosher'] = '<span class="fas fa-utensils"></span>';
    code_to_html.option_1['Meat'] = '<span class="fas fa-bone"></span>';
    code_to_html.option_1['Pescatarian'] = '<span class="fas fa-fish"></span>';
    code_to_html.option_1['Vegan'] = '<span class="fas fa-utensils"></span>';
    code_to_html.option_1['Vegetarian'] = '<span class="fas fa-carrot"></span>';

    code_to_html.option_2['1'] = '<span class="fas fa-star-of-life"></span>';
    code_to_html.option_2['true'] = '<span class="fas fa-star-of-life"></span>';
    code_to_html.option_2['True'] = '<span class="fas fa-star-of-life"></span>';
    code_to_html.option_2['First Time '] = '<span class="fas fa-hand-paper"></span>';
    /* *** END *** This should be moved out */

    let qr_data_url: any = $state('');
    let qr_error_message = $state('');

    // Trigger doing a update for event badge
    $effect(() => {
        if (ae_triggers.event_badge_update) {
            ae_triggers.event_badge_update = false;
            update_status = 'loading';
            update_complete = false;
        }
    });

    $effect(() => {
        if (browser && $lq__event_badge_obj?.event_badge_id) {
            qr_error_message = '';
            qr_data_url = '';

            let params: any = {};
            params.obj_type = 'event_badge';
            params.obj_id = $lq__event_badge_obj?.event_badge_id;

            try {
                qr_data_url = core_func.js_generate_qr_code('obj', params);
            } catch (error: any) {
                qr_error_message = error?.message || 'Unknown error';
                console.error(error);
            }
        }
    });

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

    async function handle_save_changes() {
        if (!$lq__event_badge_obj?.event_badge_id) {
            console.error('Cannot save changes: event_badge_id is missing.');
            return;
        }

        update_status = 'loading';
        update_complete = false;

        const data_to_update: key_val = {};

        // Only include fields that have actually changed
        if (
            editable_full_name_override !==
            ($lq__event_badge_obj.full_name_override ??
                $lq__event_badge_obj.full_name)
        ) {
            data_to_update.full_name_override = editable_full_name_override;
        }
        if (
            editable_professional_title_override !==
            ($lq__event_badge_obj.professional_title_override ??
                $lq__event_badge_obj.professional_title)
        ) {
            data_to_update.professional_title_override =
                editable_professional_title_override;
        }
        if (
            editable_affiliations_override !==
            ($lq__event_badge_obj.affiliations_override ??
                $lq__event_badge_obj.affiliations)
        ) {
            data_to_update.affiliations_override =
                editable_affiliations_override;
        }
        if (
            editable_location_override !==
            ($lq__event_badge_obj.location_override ??
                $lq__event_badge_obj.location)
        ) {
            data_to_update.location_override = editable_location_override;
        }
        if (editable_allow_tracking !== $lq__event_badge_obj.allow_tracking) {
            data_to_update.allow_tracking = editable_allow_tracking;
        }
        if (editable_email !== $lq__event_badge_obj.email) {
            data_to_update.email = editable_email;
        }
        // Compare against the effective code (override ?? base) to detect a real change.
        // Staff edits go to badge_type_code_override — the base import code is never overwritten.
        const stored_effective_code =
            $lq__event_badge_obj.badge_type_code_override ??
            $lq__event_badge_obj.badge_type_code;
        if (editable_badge_type_code !== stored_effective_code) {
            data_to_update.badge_type_code_override = editable_badge_type_code;
            // Keep badge_type_override in sync — look up the name from the template list.
            // Edge case: if a badge needs a custom name that differs from the template list
            // (e.g. "Life Member" for a "member" code), set badge_type_override manually
            // in the DB. Do not use the dropdown — it will overwrite the custom name.
            data_to_update.badge_type_override =
                (badge_type_code_li as { code: string; name: string }[])
                    .find(item => item.code === editable_badge_type_code)?.name
                    ?? editable_badge_type_code;
        }

        if (Object.keys(data_to_update).length === 0) {
            console.log('No changes to save.');
            update_status = 'done';
            update_complete = true;
            if (!is_review_mode) {
                edit_mode_active = false;
            }
            return;
        }

        try {
            await events_func.update_ae_obj__event_badge({
                api_cfg: $ae_api,
                event_id: event_id,
                event_badge_id: $lq__event_badge_obj.event_badge_id,
                data_kv: data_to_update,
                log_lvl: log_lvl
            });
            update_status = 'done';
            update_complete = true;
            if (!is_review_mode) {
                edit_mode_active = false;
            }
        } catch (error) {
            console.error('Error saving changes:', error);
            update_status = 'error';
            update_complete = true;
        }
    }

    function handle_cancel_changes() {
        if ($lq__event_badge_obj) {
            editable_full_name_override =
                $lq__event_badge_obj.full_name_override ??
                $lq__event_badge_obj.full_name;
            editable_professional_title_override =
                $lq__event_badge_obj.professional_title_override ??
                $lq__event_badge_obj.professional_title;
            editable_affiliations_override =
                $lq__event_badge_obj.affiliations_override ??
                $lq__event_badge_obj.affiliations;
            editable_location_override =
                $lq__event_badge_obj.location_override ??
                $lq__event_badge_obj.location;
            editable_allow_tracking =
                $lq__event_badge_obj.allow_tracking ?? null;
            editable_email = $lq__event_badge_obj.email ?? null;
            editable_badge_type_code =
                $lq__event_badge_obj.badge_type_code_override ??
                $lq__event_badge_obj.badge_type_code ?? null;
        }
        if (!is_review_mode) {
            edit_mode_active = false;
        }
        update_status = 'idle';
        update_complete = true;
    }

    let print_status = $state('idle'); // 'idle' | 'loading' | 'done' | 'error'

    async function handle_print_badge() {
        if (!$lq__event_badge_obj?.event_badge_id) {
            console.error('Cannot print badge: event_badge_id is missing.');
            return;
        }

        print_status = 'loading';

        const now = new Date().toISOString();
        const current_print_count = $lq__event_badge_obj.print_count ?? 0;
        const is_first_print = current_print_count === 0;

        const data_to_update: key_val = {
            print_count: current_print_count + 1,
            print_last_datetime: now
        };

        if (is_first_print) {
            data_to_update.print_first_datetime = now;
        }

        try {
            await events_func.update_ae_obj__event_badge({
                api_cfg: $ae_api,
                event_id: event_id,
                event_badge_id: $lq__event_badge_obj.event_badge_id,
                data_kv: data_to_update,
                log_lvl: log_lvl
            });
            print_status = 'done';
            console.log(`Badge printed. Count: ${data_to_update.print_count}`);

            // Trigger browser print dialog (records the print count first so it's always logged)
            if (browser) window.print();

            // Brief success flash, then return to badge search
            setTimeout(() => {
                goto(`/events/${event_id}/badges`);
            }, 1000);
        } catch (error) {
            console.error('Error printing badge:', error);
            print_status = 'error';
            setTimeout(() => {
                print_status = 'idle';
            }, 3000);
        }
    }
</script>

<!-- Template debug info: screen-only. Reads from the template prop where $store subscription is reliable. -->
<div class="print:hidden flex items-center gap-2 text-xs text-gray-400 font-mono mb-1">
    <span title="Badge template name">{$lq__event_badge_template_obj?.name ?? '—'}</span>
    <span class="text-gray-300">|</span>
    <span title="Layout code">{$lq__event_badge_template_obj?.layout ?? '(no layout)'}</span>
    <span class="text-gray-300">|</span>
    <span class="text-blue-400" title="V2 — auto-scaling text">v2</span>
</div>

<section
    id="event_badge_{$lq__event_badge_obj?.event_badge_id}"
    data-layout={$lq__event_badge_template_obj?.layout ?? 'badge_4x6_fanfold'}
    class="event_badge_wrapper event_badge print_area
        flex flex-row flex-wrap gap-4
        items-stretch justify-center
        p-2 m-0
        outline-2 outline-dashed outline-blue-500
        min-h-[6.0in]
        max-w-[8.5in] overflow-visible
        "
>

    {#if $lq__event_badge_obj && $lq__event_badge_template_obj}
        <!-- *** badge_front section start *** -->
        <section
            class="badge_front badge_type__{use_badge_type_code.toLowerCase()}
        flex flex-col gap-1
        items-stretch justify-between
        min-h-[6.0in]
        max-h-[6.0in]
        w-[4in]
        max-w-fit
        p-0 m-0 overflow-visible
        text-center
        relative
        outline-4 outline-red-500/50 hover:outline-red-700/75
        group
        "
        >
            <span
                class="
            print:hidden absolute top-1 left-4
            text-xs italic
            text-gray-500 group-hover:text-red-800
            transition-all
            "
            >
                Front of badge
            </span>

            <div
                class="
            print:hidden absolute top-1 right-4
            hover:preset-tonal-secondary
            transition-all group
            flex flex-col gap-1 items-center justify-center
            "
                class:preset-outlined-warning-200-800={edit_mode_active}
                class:preset-tonal-warning={edit_mode_active}
            >
                {#if edit_mode_active}
                    <button
                        type="button"
                        class="
                btn btn-sm text-xs
                preset-tonal-success preset-outlined-success-100-900 hover:preset-filled-success-500
                transition-all group
                "
                        onclick={handle_save_changes}
                        title="Save Changes"
                        data-testid="badge-save-btn"
                    >
                        <span class="fas fa-save m-1"></span>
                        <span
                            class="
                    hidden
                    group-hover:inline-block
                    text-xs
                    "
                        >
                            Save Changes
                        </span>
                    </button>
                    <button
                        type="button"
                        class="
                btn btn-sm text-xs
                preset-tonal-tertiary preset-outlined-tertiary-100-900 hover:preset-filled-tertiary-500
                transition-all group
                "
                        onclick={handle_cancel_changes}
                        title="Cancel Editing"
                        data-testid="badge-cancel-btn"
                    >
                        <span class="fas fa-times m-1"></span>
                        <span
                            class="
                    hidden
                    group-hover:inline-block
                    text-xs
                    "
                        >
                            Cancel
                        </span>
                    </button>
                {:else}
                    <button
                        type="button"
                        class="
                btn btn-sm text-xs
                preset-tonal-warning preset-outlined-warning-100-900 hover:preset-filled-secondary-500
                transition-all group
                "
                        onclick={() => {
                            edit_mode_active = true;
                        }}
                        title="Edit Badge Information"
                        data-testid="badge-edit-btn"
                    >
                        <span class="fas fa-edit m-1"></span>
                        <span
                            class="
                    hidden
                    group-hover:inline-block
                    text-xs
                    "
                        >
                            Edit Badge Information
                        </span>
                    </button>
                {/if}

                <!-- Print Button -->
                <button
                    type="button"
                    class="
                btn btn-sm text-xs
                preset-outlined-primary-100-900 hover:preset-filled-primary-500
                transition-all group
                "
                    class:preset-tonal-primary={print_status === 'loading'}
                    class:preset-filled-success-500={print_status === 'done'}
                    class:preset-filled-error-500={print_status === 'error'}
                    onclick={handle_print_badge}
                    disabled={print_status === 'loading'}
                    title="Print Badge (Increment Count)"
                    data-testid="badge-print-btn"
                >
                    {#if print_status === 'loading'}
                        <span class="fas fa-spinner fa-spin m-1"></span>
                    {:else if print_status === 'done'}
                        <span class="fas fa-check m-1"></span>
                    {:else if print_status === 'error'}
                        <span class="fas fa-exclamation-triangle m-1"></span>
                    {:else}
                        <span class="fas fa-print m-1"></span>
                    {/if}
                    <span
                        class="
                    hidden
                    group-hover:inline-block
                    text-xs
                    "
                    >
                        {#if print_status === 'done'}
                            Printed!
                        {:else if print_status === 'error'}
                            Error
                        {:else}
                            Print Badge
                            {#if $lq__event_badge_obj?.print_count}
                                ({$lq__event_badge_obj.print_count})
                            {/if}
                        {/if}
                    </span>
                </button>

                <div
                    class="w-md max-w-lg m-1 p-1"
                    class:hidden={!edit_mode_active}
                >
                    <p class="text-xs italic text-gray-500">
                        Show list of fields that they can edit here. This may
                        need to broken down in to sections that can be
                        collapsed.
                    </p>
                    <ul class="text-left list-disc list-inside text-sm">
                        <li>Full Name</li>
                        <li>Professional Title</li>
                        <li>Affiliations</li>
                        <li>Location</li>
                        <li>Option Ticket 1</li>
                        <li>Option Ticket 2</li>
                        <li>Option Ticket 3</li>
                        <li>Option Other 1</li>
                        <li>Option Other 2</li>
                        <li>Badge Type</li>
                        <li>Allow Tracking</li>
                        <li>Show Print Message</li>
                        <li>Hide QR Code</li>
                    </ul>
                </div>
            </div>

            {#if $lq__event_badge_template_obj.header_path}
                <div
                    class="badge_header
                image
                min-h-[.50in]
                max-h-[1.00in]
                max-w-full
                m-0 p-0
                overflow-hidden
                hover:outline-2 hover:outline-dashed hover:outline-gray-500/75
                "
                >
                    <img
                        class="header_image"
                        src={$lq__event_badge_template_obj.header_path}
                        alt="check header path"
                    />
                </div>
            {:else}
                <div class="badge_header logo_text">
                    <img
                        class="badge_logo"
                        src={$lq__event_badge_template_obj.logo_path}
                        alt="check badge logo"
                    />
                    <div class="banner_text">
                        <div class="row_one">
                            {@html $lq__event_badge_template_obj.header_row_1}
                        </div>
                        <div class="row_two">
                            {@html $lq__event_badge_template_obj.header_row_2}
                        </div>
                    </div>
                </div>
            {/if}

            <div
                class="badge_body
            grow
            max-h-[4in] m-0 p-0
            overflow-clip
            flex flex-col gap-1
            items-stretch justify-between
            "
            >
                <div
                    class="person_name
                m-0 p-0
                overflow-hidden
                flex flex-col
                hover:outline-2 hover:outline-dashed hover:outline-gray-500/75
                "
                    style="height: {fit_heights.grp_name_title}; justify-content: {flex_justify(fit_heights.grp_name_title_flex)}"
                >
                    <!--
                        V2: Element_fit_text wraps display mode only.
                        Edit mode uses a plain div so inputs are not auto-scaled.
                        manual_size={font_size_name ?? null} disables auto-scaling
                        when the print-controls panel is setting a fixed size.
                        Bounds: min=20 (readable at small sizes) max=80 (fills badge width for short names).
                    -->
                    {#if edit_mode_active}
                        <div class="full_name_override_all leading-none">
                            <input
                                type="text"
                                bind:value={editable_full_name_override}
                                class="input w-full text-center"
                            />
                        </div>
                    {:else}
                        <Element_fit_text
                            min={36}
                            max={80}
                            manual_size={font_size_name ?? null}
                            height={fit_heights.name}
                            class="full_name_override_all hover:bg-pink-100/50"
                        >
                            <span class="full_name_override">
                                {#if editable_full_name_override}
                                    {@html editable_full_name_override.trim()}
                                {:else}
                                    -- no name --
                                {/if}
                            </span>
                        </Element_fit_text>
                    {/if}

                    {#if editable_professional_title_override || edit_mode_active}
                        <!--
                            Bounds: min=14 (small italic fine at small sizes) max=38 (fills badge width for short titles).
                        -->
                        {#if edit_mode_active}
                            <div class="professional_title leading-none italic">
                                <input
                                    type="text"
                                    bind:value={editable_professional_title_override}
                                    class="input w-full text-center"
                                    data-testid="badge-professional-title-input"
                                />
                            </div>
                        {:else}
                            <Element_fit_text
                                min={18}
                                max={38}
                                manual_size={font_size_title ?? null}
                                height={fit_heights.title}
                                class="professional_title italic hover:bg-pink-100/50"
                            >
                                {@html editable_professional_title_override}
                            </Element_fit_text>
                        {/if}
                    {/if}
                </div>

                {#if editable_affiliations_override || editable_location_override || edit_mode_active || editable_email || edit_mode_active || editable_allow_tracking !== null || edit_mode_active}
                    <div
                        class="affiliations_location
                m-0 p-0
                w-full
                overflow-hidden
                flex flex-col
                hover:outline-2 hover:outline-dashed hover:outline-gray-500/75
                "
                        style="height: {fit_heights.grp_aff_loc}; justify-content: {flex_justify(fit_heights.grp_aff_loc_flex)}"
                    >
                        {#if editable_affiliations_override || edit_mode_active}
                            <!--
                                Bounds: min=12 (multi-line affiliations can be small) max=40 (fills badge for short org names).
                            -->
                            {#if edit_mode_active}
                                <div class="affiliations leading-none">
                                    <textarea
                                        bind:value={editable_affiliations_override}
                                        class="textarea w-full text-center"
                                        rows="2"
                                    ></textarea>
                                </div>
                            {:else}
                                <Element_fit_text
                                    min={18}
                                    max={40}
                                    manual_size={font_size_affiliations ?? null}
                                    height={fit_heights.affiliations}
                                    class="affiliations hover:bg-pink-100/50"
                                >
                                    {@html editable_affiliations_override}
                                </Element_fit_text>
                            {/if}
                        {/if}

                        {#if editable_location_override || edit_mode_active}
                            <!--
                                Bounds: min=12 (long city/country strings) max=34 (matches title upper bound).
                            -->
                            {#if edit_mode_active}
                                <div class="location leading-none">
                                    <input
                                        type="text"
                                        bind:value={editable_location_override}
                                        class="input w-full text-center"
                                    />
                                </div>
                            {:else}
                                <Element_fit_text
                                    min={18}
                                    max={34}
                                    manual_size={font_size_location ?? null}
                                    height={fit_heights.location}
                                    class="location hover:bg-pink-100/50"
                                >
                                    <span class="city state_province country"
                                        >{@html editable_location_override}</span
                                    >
                                </Element_fit_text>
                            {/if}
                        {/if}

                        {#if edit_mode_active}
                            <!-- Email: editable in review/edit mode only — never printed on badge -->
                            <div class="email-field text-sm">
                                <label>Email: <input
                                    type="email"
                                    bind:value={editable_email}
                                    class="input w-full"
                                /></label>
                            </div>
                        {/if}

                        {#if edit_mode_active}
                            <!-- Allow tracking: editable in review/edit mode only — never printed on badge -->
                            <div class="allow-tracking-field text-sm flex items-center justify-center gap-2">
                                <label>Allow Tracking: <input
                                    type="checkbox"
                                    bind:checked={editable_allow_tracking}
                                    class="checkbox"
                                /></label>
                            </div>
                        {/if}
                    </div>
                {/if}

                {#if ['front_bool', 'front_back_bool'].includes(option_ticket_1_display_opt) || ['front_bool', 'front_back_bool'].includes(option_ticket_2_display_opt) || ['front_bool', 'front_back_bool'].includes(option_ticket_3_display_opt) || $lq__event_badge_template_obj?.show_qr_front || edit_mode_active}
                    <!-- flex-col so ticket icons row and QR stack vertically; QR is centered -->
                    <div class="special flex flex-col items-center w-full">
                        <div class="flex flex-row justify-between w-full">
                            <span class="badge_body_special_left">
                                {#if option_ticket_1_override}<span
                                        class="ticket_1_code fg_green fas fa-star"
                                    ></span>{/if}
                            </span>
                            <span class="badge_body_special_right">
                                {#if option_ticket_2_override}
                                    <span class=" ticket_2_code fg_red fas fa-star"
                                    ></span>
                                {/if}
                                {#if option_ticket_3_override}
                                    <span class="ticket_3_code fg_blue fas fa-star"
                                    ></span>
                                {/if}
                            </span>
                        </div>
                        {#if $lq__event_badge_template_obj?.show_qr_front}
                            {#await qr_data_url}
                                <!-- QR generating — show nothing to avoid layout shift -->
                            {:then result}
                                {#if result}
                                    <img
                                        class="qr_code mecard_qr w-[0.75in] max-w-[0.75in]"
                                        src={result}
                                        alt="Badge QR code"
                                    />
                                {/if}
                            {/await}
                        {/if}
                    </div>
                {/if}
            </div>

            <div
                class="badge_footer
            {editable_badge_type_code?.toLowerCase()}
            justify-self-end
            max-h-[.50in]
            max-w-full
            m-0 p-0
            overflow-hidden
            flex flex-row gap-1 items-center justify-center
            hover:outline-2 hover:outline-dashed hover:outline-gray-500/75
            "
                title={editable_badge_type_code}
            >
                {#if edit_mode_active && badge_type_code_li.length > 0}
                    <label
                        >Badge Type:
                        <select
                            bind:value={editable_badge_type_code}
                            class="select text-xs px-1 max-w-fit"
                        >
                            {#each badge_type_code_li as badge_type_code_item (badge_type_code_item.code)}
                                <option value={badge_type_code_item.code}
                                    >{badge_type_code_item.name}</option
                                >
                            {/each}
                        </select>
                    </label>
                {:else}
                    {#if option_other_1_override && ['front_bool', 'front_back_bool'].includes(option_other_1_display_opt)}
                        <span class="badge_footer_special_left"
                            ><span class="fas fa-biohazard"></span></span
                        >
                    {:else if option_other_1_override && ['front_html', 'front_back_html'].includes(option_other_1_display_opt)}
                        <span class="badge_footer_special_left"
                            >{@html option_other_1_override}</span
                        >
                    {/if}

                    <!-- badge_type_code is the CSS class hook for per-event stylesheets;
                         badge_type_name is what's actually printed on the badge. -->
                    <span
                        class="badge_footer_center {editable_badge_type_code?.toLowerCase()}"
                        >{badge_type_name}</span
                    >

                    {#if option_other_2_override && ['front_bool', 'front_back_bool'].includes(option_other_2_display_opt)}
                        <span class="badge_footer_special_right"
                            ><span class="fas fa-star-of-life"></span></span
                        >
                    {:else if option_other_2_override && ['front_html', 'front_back_html'].includes(option_other_2_display_opt)}
                        <span class="badge_footer_special_right"
                            >{@html option_other_2_override}</span
                        >
                    {/if}
                {/if}
            </div>

            <!-- badge class div end -->
        </section>
        <!-- *** badge section end *** -->

        <!-- *** badge_back (fold under) section start *** -->
        <!-- duplex=0 on the template hides this entire section (single-sided print) -->
        {#if show_badge_back}
        <section
            class="badge_back
        flex flex-col gap-1
        items-center justify-between
        max-h-[6.0in]
        w-[4in]
        max-w-fit
        p-0 m-0 overflow-visible
        text-left text-sm
        relative
        outline-4 outline-green-500/50 hover:outline-green-700/75
        group
        "
        >
            <span
                class="
            print:hidden absolute top-1 right-4
            text-xs italic
            text-gray-500 group-hover:text-green-800
            "
            >
                Back of badge
            </span>

            {#if $lq__event_badge_template_obj.secondary_header_path}
                <div
                    class="badge_back_header
                image
                max-h-[1.00in]
                max-w-full
                m-0 p-0
                overflow-hidden
                hover:outline-2 hover:outline-dashed hover:outline-gray-500/75
                "
                >
                    <img
                        class="header_image"
                        src={$lq__event_badge_template_obj.secondary_header_path}
                        alt="check secondary header path"
                    />
                </div>
            {:else if $lq__event_badge_template_obj.header_path}
                <div class="badge_back_header image max-w-xl">
                    <img
                        class="header_image"
                        src={$lq__event_badge_template_obj.header_path}
                        alt="check primary header path"
                    />
                </div>
            {:else}
                <div class="badge_back_header logo_text">
                    <img
                        class="badge_logo"
                        src={$lq__event_badge_template_obj.logo_path}
                        alt="check badge logo"
                    />
                    <div class="banner_text">
                        <div class="row_one">
                            {@html $lq__event_badge_template_obj.header_row_1}
                        </div>
                        <div class="row_two">
                            {@html $lq__event_badge_template_obj.header_row_2}
                        </div>
                    </div>
                </div>
            {/if}

            <div
                class="badge_back_content
            grow
            max-h-[6in] m-0 p-0
            overflow-visible
            flex flex-col gap-1
            items-stretch justify-between
            text-xs px-1
            hover:outline-2 hover:outline-dashed hover:outline-gray-500/75
            "
            >
                <div
                    class="wifi_information
                    flex flex-row gap-4 items-center justify-center
                    "
                >
                    {#if $lq__event_badge_template_obj.wireless_ssid}
                        <div
                            class="grow flex flex-col gap-0 items-center justify-end"
                        >
                            <span
                                class="w-full flex flex-row gap-1 items-center justify-start"
                            >
                                <span class="w-20 text-gray-500 italic">
                                    Signal Name
                                </span>
                                <strong
                                    class="wifi_ssid font-bold font-mono text-lg tracking-widest leading-none"
                                >
                                    {$lq__event_badge_template_obj.wireless_ssid}
                                </strong>
                            </span>
                            <span
                                class="w-full flex flex-row gap-1 items-center justify-start"
                            >
                                <span class="w-20 text-gray-500 italic">
                                    Access Code
                                </span>
                                <strong
                                    class="wifi_code font-bold font-mono text-lg tracking-widest leading-none"
                                >
                                    {$lq__event_badge_template_obj.wireless_password}
                                </strong>
                            </span>
                        </div>
                        <div
                            class="wifi_label flex flex-row-reverse gap-1 items-center justify-center text-xl text-gray-500"
                        >
                            <span class="fas fa-wifi"></span>
                            WiFi
                        </div>
                    {/if}

                    <div class="network_username_password hidden">
                        Username = <span class="network_username">username</span
                        ><br />
                        Password =
                        <span class="network_password">password</span>
                    </div>
                </div>

                <div class="app_information text-xs">
                    <strong>Download Meeting App:</strong>
                    <ol style="margin: 0; padding-top: 0; padding-bottom: 0;">
                        <li style="">
                            Use QR code or search your app store for "<strong
                                >App Name</strong
                            >"
                        </li>
                        <li style="">
                            Once downloaded, use the search feature to find "<strong
                                >999<sup style="font-size:.5em;">th</sup> Meeting</strong
                            >" guide
                        </li>
                        <li style="">
                            You may also go to <a href="https://oneskyit.com/"
                                >OneSkyIT.com</a
                            >
                        </li>
                    </ol>
                </div>

                {#if $lq__event_badge_obj.other_1 || $lq__event_badge_obj.other_2 || $lq__event_badge_obj.ticket_1_code || $lq__event_badge_obj.ticket_2_code || $lq__event_badge_obj.ticket_3_code || $lq__event_badge_obj.ticket_4_code || $lq__event_badge_obj.ticket_5_code}
                    <div class="attendee_information">
                        <ul>
                            {#if $lq__event_badge_obj.ticket_1_code}
                                <li>
                                    {@html $lq__event_badge_template_obj.ticket_1_text}
                                </li>
                            {/if}
                            {#if $lq__event_badge_obj.ticket_2_code}
                                <li>
                                    {@html $lq__event_badge_template_obj.ticket_2_text}
                                </li>
                            {/if}
                            {#if $lq__event_badge_obj.ticket_3_code}
                                <li>
                                    {@html $lq__event_badge_template_obj.ticket_3_text}
                                </li>
                            {/if}
                            {#if $lq__event_badge_obj.ticket_4_code}
                                <li>
                                    {@html $lq__event_badge_template_obj.ticket_4_text}
                                </li>
                            {/if}
                            {#if $lq__event_badge_obj.ticket_5_code}
                                <li>
                                    {@html $lq__event_badge_template_obj.ticket_5_text}
                                </li>
                            {/if}
                        </ul>

                        {#if $ae_loc.administrator_access}
                            {#if $lq__event_badge_obj.other_1}
                                <div class="other_1">
                                    Other 1: {$lq__event_badge_obj.other_1}
                                    {#if option_other_1_override && ['back_bool', 'front_back_bool'].includes(option_other_1_display_opt)}
                                        - {option_other_1_override}
                                    {:else if option_other_1_override && ['back_html', 'front_back_html'].includes(option_other_1_display_opt)}
                                        - {@html option_other_1_override}
                                    {/if}
                                </div>
                            {/if}
                            {#if $lq__event_badge_obj.other_2}
                                <div class="other_2">
                                    Other 2: {$lq__event_badge_obj.other_2}
                                    {#if option_other_2_override && ['back_bool', 'front_back_bool'].includes(option_other_2_display_opt)}
                                        - {option_other_2_override}
                                    {:else if option_other_2_override && ['back_html', 'front_back_html'].includes(option_other_2_display_opt)}
                                        - {@html option_other_2_override}
                                    {/if}
                                </div>
                            {/if}
                        {/if}
                    </div>
                {/if}

                {#if $lq__event_badge_template_obj.exhibitor_info}
                    <div class="container exhibitor_information">
                        <strong>Exhibitor Info:</strong>
                    </div>
                {/if}

                {#if $lq__event_badge_template_obj.presenter_info}
                    <div class="container presenter_information">
                        <strong>Presenter Info:</strong>
                    </div>
                {/if}

                {#if $lq__event_badge_template_obj.staff_info}
                    <div class="container staff_information">
                        <strong>Staff Info:</strong>
                    </div>
                {/if}

                {#if $lq__event_badge_template_obj.vip_info}
                    <div class="container vip_information">
                        <strong>VIP Info:</strong>
                    </div>
                {/if}

                {#if $lq__event_badge_template_obj.vote_info}
                    <div class="container vote_information">
                        <div><strong>Voting Info:</strong></div>
                    </div>
                {/if}

                {#if $lq__event_badge_template_obj.show_qr_back}
                    <div
                        class="person_information qr_badge_id
                "
                    >
                        <div class="qr_badge_id_label text-center">
                            <strong>
                                {$lq__event_badge_obj.given_name}'s
                            </strong>
                            Badge ID and QR Code:
                        </div>
                        <div class="text-center">
                            <span
                                class="event_badge_id
                        uppercase font-bold font-mono text-lg tracking-widest leading-tight
                        hover:scale-200 transition-transform duration-200 ease-in-out hover:p-4 hover:border-2 hover:border-red-500 hover:bg-white
                        z-10
                        "
                            >
                                {$lq__event_badge_obj.event_badge_id}
                            </span>
                        </div>
                        {#await qr_data_url}
                            Generating...
                        {:then result}
                            {#if result}
                                <div
                                    class="qr_badge_id_part_1 flex flex-row items-center justify-between"
                                >
                                    <img
                                        class="qr_code mecard_qr
                            image
                            w-[1.5in]
                            max-w-48
                            hover:scale-200 transition-transform duration-200 ease-in-out hover:p-4 hover:border-2 hover:border-red-500 hover:bg-white
                            z-10
                            "
                                        class:v_hide_print={hide_qr}
                                        src={result}
                                        alt="badge QR code"
                                        ondblclick={() => {
                                            hide_qr
                                                ? (hide_qr = false)
                                                : (hide_qr = true);
                                        }}
                                    />
                                    <div
                                        class="qr_badge_id_agreement fs_xs f_align_justify
                            text-xs
                            italic
                            "
                                    >
                                        {#if $lq__event_badge_obj.allow_tracking}
                                            <p>
                                                This was <strong>allowed</strong
                                                > at the time your badge was printed.
                                                You may opt-out at anytime.
                                            </p>
                                            <p>
                                                By allowing this QR code to be
                                                scanned by an exhibitor or
                                                staff, you understand and agree
                                                that they may use your personal
                                                information.
                                            </p>
                                        {:else}
                                            <p>
                                                Tracking was <strong>not</strong
                                                > allowed at the time your badge was
                                                printed. You may opt-in at anytime.
                                            </p>
                                            <p>
                                                If this QR code is scanned by an
                                                exhibitor or staff, they will <strong
                                                    >not</strong
                                                > have access to your information.
                                            </p>
                                        {/if}
                                    </div>
                                </div>
                            {/if}
                        {/await}
                    </div>
                {/if}
            </div>

            <div class="badge_back_footer text-xxs italic text-gray-500">
                <!-- IMPORTANT: This will need to be rotated with CSS for printing on the fanfold badges. -->
                Fold in half here
            </div>
        </section>
        {/if}
        <!-- *** fold under section end *** -->

        <!-- *** receipt section start *** -->
        {#if show_receipt}
        <section class="receipt hidden">
            <div class="receipt_header">
                <img
                    class="badge_logo max-w-sm"
                    src={$lq__event_badge_template_obj.logo_path}
                    alt="check badge logo"
                />
                <div class="banner_text">
                    <div class="row_one">
                        {$lq__event_badge_template_obj.header_row_1}
                    </div>
                    <div class="row_two">
                        {$lq__event_badge_template_obj.header_row_2}
                    </div>
                </div>
            </div>
            <div class="receipt_content">
                <div>
                    Account Number: <span class="BT_ID">BT_ID</span><br />
                    Order Number:
                    <span class="Order_Number">Order_Number</span><br />
                </div>
            </div>
            <div class="receipt_footer">
                <p class="printed">Receipt Printed</p>
            </div>
        </section>
        {/if}
        <!-- *** receipt section end *** -->

        <!-- *** ticket section start *** -->
        {#if show_tickets}
        <section class="tickets_left_container hidden">
            <div class="tickets">
                <div class="ticket_container ticket_1">
                    <div class="ticket_body">
                        {#if $lq__event_badge_obj.ticket_1_code}{@html $lq__event_badge_template_obj.ticket_1_text}{/if}
                    </div>
                </div>
                <div class="ticket_container ticket_2">
                    <div class="ticket_body">
                        {#if $lq__event_badge_obj.ticket_2_code}{@html $lq__event_badge_template_obj.ticket_2_text}{/if}
                    </div>
                </div>
                <div class="ticket_container ticket_3">
                    <div class="ticket_body">
                        {#if $lq__event_badge_obj.ticket_3_code}{@html $lq__event_badge_template_obj.ticket_3_text}{/if}
                    </div>
                </div>
                <div class="ticket_container ticket_4">
                    <div class="ticket_body">
                        {#if $lq__event_badge_obj.ticket_4_code}{@html $lq__event_badge_template_obj.ticket_4_text}{/if}
                    </div>
                </div>
            </div>
        </section>

        <section class="tickets_right_container hidden">
            <div class="tickets">
                <div class="ticket_container ticket_5">
                    <div class="ticket_body">
                        {#if $lq__event_badge_obj.ticket_5_code}{@html $lq__event_badge_template_obj.ticket_5_text}{/if}
                    </div>
                </div>
                <div class="ticket_container ticket_6">
                    <div class="ticket_body">
                        {#if $lq__event_badge_obj.ticket_6_code}{@html $lq__event_badge_template_obj.ticket_6_text}{/if}
                    </div>
                </div>
                <div class="ticket_container ticket_7">
                    <div class="ticket_body">
                        {#if $lq__event_badge_obj.ticket_7_code}{@html $lq__event_badge_template_obj.ticket_7_text}{/if}
                    </div>
                </div>
                <div class="ticket_container ticket_8">
                    <div class="ticket_body">
                        {#if $lq__event_badge_obj.ticket_8_code}{@html $lq__event_badge_template_obj.ticket_8_text}{/if}
                    </div>
                </div>
            </div>
        </section>
        {/if}
        <!-- *** ticket section end *** -->
    {/if}
    <!-- End if for $lq__event_badge_template_obj -->
</section>

<div>
    <h1 class="text-lg font-bold mt-4">Debug Information</h1>
    <pre
        class="whitespace-pre-wrap break-words text-xs max-h-32 overflow-auto p-2 bg-surface-200 border border-surface-300 rounded
        mt-4
        print:hidden
        ">
    {JSON.stringify($lq__event_badge_obj, null, 2)}
</pre>

    <pre
        class="whitespace-pre-wrap break-words text-xs max-h-32 overflow-auto p-2 bg-surface-200 border border-surface-300 rounded
        mt-4
        print:hidden
        ">
    {JSON.stringify($lq__event_badge_template_obj, null, 2)}
</pre>
</div>
