<script lang="ts">
    /**
     * Badge Print Controls — right-panel for the print page (landscape layout).
     *
     * Renders a per-field accordion panel: each field shows its current value, font
     * size controls (if applicable), and an inline edit form gated by access level.
     *
     * Access levels:
     *   Basic authenticated → can edit professional_title_override, affiliations_override,
     *                         location_override only; all fields have font controls.
     *   Trusted / Admin     → can edit all fields (same scope as Badge Review page).
     *
     * Font sizes flow back to the parent via $bindable() props so the badge render
     * (ae_comp__badge_obj_view.svelte) stays in sync without prop-drilling through
     * a third component.
     */

    import type { key_val } from '$lib/stores/ae_stores';
    import { ae_api, ae_loc } from '$lib/stores/ae_stores';
    import { events_func } from '$lib/ae_events_functions';
    import { Pencil, Check, X, LoaderCircle, ChevronDown } from 'lucide-svelte';

    interface Props {
        event_id: string;
        event_badge_id: string;
        lq__event_badge_obj?: any;
        lq__event_badge_template_obj?: any;
        /** Font size for name field (px). null = auto. $bindable so parent can forward to badge render. */
        font_size_name?: number | null;
        /** Font size for professional title (px). null = auto. */
        font_size_title?: number | null;
        /** Font size for affiliations (px). null = auto. */
        font_size_affiliations?: number | null;
        /** Font size for location (px). null = auto. */
        font_size_location?: number | null;
        log_lvl?: number;
    }

    let {
        event_id,
        event_badge_id,
        lq__event_badge_obj,
        lq__event_badge_template_obj,
        font_size_name      = $bindable(null),
        font_size_title     = $bindable(null),
        font_size_affiliations = $bindable(null),
        font_size_location  = $bindable(null),
        log_lvl = 0
    }: Props = $props();

    // --- Access level ---
    // trusted_access is true for Trusted and every level above it (Administrator,
    // Manager, Super). No need to OR in administrator_access — it's already covered.
    // Basic authenticated users (trusted_access === false) can only edit
    // professional_title_override, affiliations_override, and location_override.
    let is_trusted = $derived($ae_loc.trusted_access === true);

    // --- Badge type list from template ---
    // Each item: { code: string, name: string }. Used for the badge type dropdown.
    let badge_type_code_li = $derived.by((): { code: string; name: string }[] => {
        const raw = $lq__event_badge_template_obj?.badge_type_list;
        if (!raw) return [];
        try { return JSON.parse(raw); } catch { return []; }
    });

    // --- Font size configuration ---
    const FONT_SIZE_STEP = 2;
    const FONT_SIZE_DEFAULTS = { name: 58, title: 34, affiliations: 38, location: 34 } as const;
    const FONT_SIZE_MIN      = { name: 20, title: 14, affiliations: 14, location: 14 } as const;
    const FONT_SIZE_MAX      = { name: 80, title: 56, affiliations: 60, location: 56 } as const;

    function font_size_adjust(field: 'name' | 'title' | 'affiliations' | 'location', delta: number) {
        const cur =
            field === 'name'         ? font_size_name :
            field === 'title'        ? font_size_title :
            field === 'affiliations' ? font_size_affiliations : font_size_location;
        const next = cur === null
            ? FONT_SIZE_DEFAULTS[field]
            : Math.max(FONT_SIZE_MIN[field], Math.min(FONT_SIZE_MAX[field], cur + delta));
        if      (field === 'name')         font_size_name = next;
        else if (field === 'title')        font_size_title = next;
        else if (field === 'affiliations') font_size_affiliations = next;
        else if (field === 'location')     font_size_location = next;
    }

    function font_size_reset(field: 'name' | 'title' | 'affiliations' | 'location') {
        if      (field === 'name')         font_size_name = null;
        else if (field === 'title')        font_size_title = null;
        else if (field === 'affiliations') font_size_affiliations = null;
        else if (field === 'location')     font_size_location = null;
    }

    // --- Accordion: one field section open at a time ---
    let active_field: string | null = $state(null);

    function toggle_field(key: string) {
        active_field = active_field === key ? null : key;
    }

    // --- Editable field state ---
    // Initialized from badge obj; reset when badge obj changes (same pattern as
    // ae_comp__badge_obj_view.svelte). The effective value (override ?? base) is
    // pre-merged so the input shows what would actually print.
    let edit_full_name_override: string          = $state('');
    let edit_professional_title_override: string = $state('');
    let edit_affiliations_override: string       = $state('');
    let edit_location_override: string           = $state('');
    let edit_pronouns_override: string           = $state('');
    let edit_allow_tracking: boolean             = $state(false);
    // Effective badge type code (badge_type_code_override ?? badge_type_code)
    let edit_badge_type_code: string | null      = $state(null);

    $effect(() => {
        if ($lq__event_badge_obj) {
            edit_full_name_override          = $lq__event_badge_obj.full_name_override          ?? $lq__event_badge_obj.full_name          ?? '';
            edit_professional_title_override = $lq__event_badge_obj.professional_title_override ?? $lq__event_badge_obj.professional_title ?? '';
            edit_affiliations_override       = $lq__event_badge_obj.affiliations_override       ?? $lq__event_badge_obj.affiliations       ?? '';
            edit_location_override           = $lq__event_badge_obj.location_override           ?? $lq__event_badge_obj.location           ?? '';
            edit_pronouns_override           = $lq__event_badge_obj.pronouns_override           ?? $lq__event_badge_obj.pronouns           ?? '';
            edit_allow_tracking              = $lq__event_badge_obj.allow_tracking              ?? false;
            edit_badge_type_code             = $lq__event_badge_obj.badge_type_code_override    ?? $lq__event_badge_obj.badge_type_code    ?? null;
        }
    });

    // --- Per-field save status ---
    type SaveStatus = 'idle' | 'saving' | 'done' | 'error';
    let field_save_status: Record<string, SaveStatus> = $state({});

    async function save_field(field_key: string, data_kv: key_val) {
        if (!$lq__event_badge_obj?.event_badge_id) return;
        field_save_status = { ...field_save_status, [field_key]: 'saving' };
        try {
            await events_func.update_ae_obj__event_badge({
                api_cfg: $ae_api,
                event_id,
                event_badge_id: $lq__event_badge_obj.event_badge_id,
                data_kv,
                log_lvl
            });
            field_save_status = { ...field_save_status, [field_key]: 'done' };
            // liveQuery auto-refreshes the badge; close the accordion after a brief confirmation.
            setTimeout(() => {
                field_save_status = { ...field_save_status, [field_key]: 'idle' };
                active_field = null;
            }, 1200);
        } catch (err) {
            console.error(`Badge print controls: save error for "${field_key}":`, err);
            field_save_status = { ...field_save_status, [field_key]: 'error' };
            setTimeout(() => {
                field_save_status = { ...field_save_status, [field_key]: 'idle' };
            }, 2500);
        }
    }

    function cancel_field(field_key: string) {
        if (!$lq__event_badge_obj) { active_field = null; return; }
        switch (field_key) {
            case 'name':           edit_full_name_override          = $lq__event_badge_obj.full_name_override          ?? $lq__event_badge_obj.full_name          ?? ''; break;
            case 'title':          edit_professional_title_override = $lq__event_badge_obj.professional_title_override ?? $lq__event_badge_obj.professional_title ?? ''; break;
            case 'affiliations':   edit_affiliations_override       = $lq__event_badge_obj.affiliations_override       ?? $lq__event_badge_obj.affiliations       ?? ''; break;
            case 'location':       edit_location_override           = $lq__event_badge_obj.location_override           ?? $lq__event_badge_obj.location           ?? ''; break;
            case 'pronouns':       edit_pronouns_override           = $lq__event_badge_obj.pronouns_override           ?? $lq__event_badge_obj.pronouns           ?? ''; break;
            case 'allow_tracking': edit_allow_tracking              = $lq__event_badge_obj.allow_tracking              ?? false; break;
            case 'badge_type':     edit_badge_type_code             = $lq__event_badge_obj.badge_type_code_override    ?? $lq__event_badge_obj.badge_type_code    ?? null; break;
        }
        active_field = null;
    }

    // --- Display helpers ---
    function get_display(override_key: string, base_key: string): string {
        return $lq__event_badge_obj?.[override_key] ?? $lq__event_badge_obj?.[base_key] ?? '';
    }

    // Effective badge type display name: priority matches ae_comp__badge_obj_view.svelte
    let badge_type_display = $derived(
        $lq__event_badge_obj?.badge_type_override
        ?? $lq__event_badge_obj?.badge_type
        ?? badge_type_code_li.find(item => item.code === ($lq__event_badge_obj?.badge_type_code_override ?? $lq__event_badge_obj?.badge_type_code))?.name
        ?? $lq__event_badge_obj?.badge_type_code_override
        ?? $lq__event_badge_obj?.badge_type_code
        ?? ''
    );
</script>

<!-- ============================================================
     Field card snippets
     ============================================================ -->

<!-- Reusable font size controls row -->
{#snippet font_ctrl(key: 'name' | 'title' | 'affiliations' | 'location')}
    {@const cur =
        key === 'name'         ? font_size_name :
        key === 'title'        ? font_size_title :
        key === 'affiliations' ? font_size_affiliations : font_size_location}
    <div class="flex items-center gap-1 border-t border-gray-100 dark:border-gray-800 px-3 py-1.5"
        role="group"
        aria-label="{key} font size controls"
    >
        <span class="text-[10px] text-gray-400 uppercase w-8 shrink-0">Font</span>
        <button
            type="button"
            class="btn btn-xs px-2 min-h-0 h-7 text-base leading-none"
            onclick={() => font_size_adjust(key, -FONT_SIZE_STEP)}
            disabled={cur !== null && cur <= FONT_SIZE_MIN[key]}
            title="Decrease {key} font size"
            aria-label="Decrease {key} font size"
        >−</button>
        <span class="font-mono text-xs w-12 text-center tabular-nums" aria-live="polite">
            {cur !== null ? `${cur}px` : 'Auto'}
        </span>
        <button
            type="button"
            class="btn btn-xs px-2 min-h-0 h-7 text-base leading-none"
            onclick={() => font_size_adjust(key, FONT_SIZE_STEP)}
            disabled={cur !== null && cur >= FONT_SIZE_MAX[key]}
            title="Increase {key} font size"
            aria-label="Increase {key} font size"
        >+</button>
        {#if cur !== null}
            <button
                type="button"
                class="btn btn-xs px-1.5 min-h-0 h-7 opacity-60"
                onclick={() => font_size_reset(key)}
                title="Reset {key} font size to auto"
                aria-label="Reset {key} font size to auto"
            >↺</button>
        {/if}
    </div>
{/snippet}

<!-- Reusable save/cancel buttons (used inside accordion edit forms) -->
{#snippet field_actions(field_key: string, on_save: () => void, on_cancel: () => void)}
    <div class="flex gap-2 mt-2">
        <button
            type="button"
            class="btn btn-sm flex-1"
            class:preset-filled-primary={!field_save_status[field_key] || field_save_status[field_key] === 'idle'}
            class:preset-filled-success={field_save_status[field_key] === 'done'}
            class:preset-tonal-error={field_save_status[field_key] === 'error'}
            disabled={field_save_status[field_key] === 'saving'}
            onclick={on_save}
            title="Save changes to this field"
            aria-label="Save changes"
        >
            {#if field_save_status[field_key] === 'saving'}
                <LoaderCircle size="14" class="animate-spin mr-1" /> Saving…
            {:else if field_save_status[field_key] === 'done'}
                <Check size="14" class="mr-1" /> Saved
            {:else if field_save_status[field_key] === 'error'}
                Error — retry
            {:else}
                <Check size="14" class="mr-1" /> Save
            {/if}
        </button>
        <button
            type="button"
            class="btn btn-sm preset-tonal-surface"
            onclick={on_cancel}
            title="Cancel editing"
            aria-label="Cancel editing"
        ><X size="14" /></button>
    </div>
{/snippet}

<!-- ============================================================
     Main panel
     ============================================================ -->
<div class="space-y-2 text-sm">

    <!-- === NAME === -->
    <!-- Editable by Trusted+ only; all users have font controls -->
    <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
        <div class="flex items-start gap-2 px-3 pt-2 pb-1.5">
            <div class="flex-1 min-w-0">
                <p class="text-[10px] uppercase tracking-widest text-gray-400 font-semibold mb-0.5">Name</p>
                {#if get_display('full_name_override', 'full_name')}
                    <p class="font-bold leading-snug truncate">{get_display('full_name_override', 'full_name')}</p>
                {:else}
                    <p class="text-gray-400 italic text-xs">Not set{is_trusted ? ' — tap ✎ to add' : ''}</p>
                {/if}
            </div>
            {#if is_trusted}
                <button
                    type="button"
                    class="btn btn-xs preset-tonal-surface shrink-0 mt-0.5"
                    onclick={() => toggle_field('name')}
                    aria-expanded={active_field === 'name'}
                    aria-controls="field-form-name"
                    title="Edit name"
                    aria-label="Edit name"
                >
                    {#if active_field === 'name'}<ChevronDown size="12" />{:else}<Pencil size="12" />{/if}
                </button>
            {/if}
        </div>
        {@render font_ctrl('name')}
        {#if active_field === 'name' && is_trusted}
            <div id="field-form-name" class="px-3 pb-3 pt-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
                <label for="ctrl-full-name" class="text-xs text-gray-500 block mb-1">
                    Name override <span class="text-gray-400">(empty = use original)</span>
                </label>
                <input
                    id="ctrl-full-name"
                    name="ctrl-full-name"
                    type="text"
                    class="input w-full"
                    bind:value={edit_full_name_override}
                    placeholder={$lq__event_badge_obj?.full_name ?? 'Full name'}
                />
                {@render field_actions(
                    'name',
                    () => save_field('name', { full_name_override: edit_full_name_override || null }),
                    () => cancel_field('name')
                )}
            </div>
        {/if}
    </div>

    <!-- === PROFESSIONAL TITLE === -->
    <!-- Editable by all authenticated users -->
    <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
        <div class="flex items-start gap-2 px-3 pt-2 pb-1.5">
            <div class="flex-1 min-w-0">
                <p class="text-[10px] uppercase tracking-widest text-gray-400 font-semibold mb-0.5">Professional Title</p>
                {#if get_display('professional_title_override', 'professional_title')}
                    <p class="leading-snug truncate">{get_display('professional_title_override', 'professional_title')}</p>
                {:else}
                    <p class="text-gray-400 italic text-xs">Not set — tap ✎ to add</p>
                {/if}
            </div>
            <button
                type="button"
                class="btn btn-xs preset-tonal-surface shrink-0 mt-0.5"
                onclick={() => toggle_field('title')}
                aria-expanded={active_field === 'title'}
                aria-controls="field-form-title"
                title="Edit professional title"
                aria-label="Edit professional title"
            >
                {#if active_field === 'title'}<ChevronDown size="12" />{:else}<Pencil size="12" />{/if}
            </button>
        </div>
        {@render font_ctrl('title')}
        {#if active_field === 'title'}
            <div id="field-form-title" class="px-3 pb-3 pt-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
                <label for="ctrl-pro-title" class="text-xs text-gray-500 block mb-1">
                    Professional title override
                </label>
                <input
                    id="ctrl-pro-title"
                    name="ctrl-pro-title"
                    type="text"
                    class="input w-full"
                    bind:value={edit_professional_title_override}
                    placeholder={$lq__event_badge_obj?.professional_title ?? 'Professional title'}
                />
                {@render field_actions(
                    'title',
                    () => save_field('title', { professional_title_override: edit_professional_title_override || null }),
                    () => cancel_field('title')
                )}
            </div>
        {/if}
    </div>

    <!-- === AFFILIATIONS === -->
    <!-- Editable by all authenticated users; textarea (multi-line) -->
    <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
        <div class="flex items-start gap-2 px-3 pt-2 pb-1.5">
            <div class="flex-1 min-w-0">
                <p class="text-[10px] uppercase tracking-widest text-gray-400 font-semibold mb-0.5">Affiliations</p>
                {#if get_display('affiliations_override', 'affiliations')}
                    <p class="leading-snug line-clamp-2">{get_display('affiliations_override', 'affiliations')}</p>
                {:else}
                    <p class="text-gray-400 italic text-xs">Not set — tap ✎ to add</p>
                {/if}
            </div>
            <button
                type="button"
                class="btn btn-xs preset-tonal-surface shrink-0 mt-0.5"
                onclick={() => toggle_field('affiliations')}
                aria-expanded={active_field === 'affiliations'}
                aria-controls="field-form-affiliations"
                title="Edit affiliations"
                aria-label="Edit affiliations"
            >
                {#if active_field === 'affiliations'}<ChevronDown size="12" />{:else}<Pencil size="12" />{/if}
            </button>
        </div>
        {@render font_ctrl('affiliations')}
        {#if active_field === 'affiliations'}
            <div id="field-form-affiliations" class="px-3 pb-3 pt-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
                <label for="ctrl-affiliations" class="text-xs text-gray-500 block mb-1">
                    Affiliations override
                </label>
                <textarea
                    id="ctrl-affiliations"
                    name="ctrl-affiliations"
                    class="textarea w-full"
                    rows="2"
                    bind:value={edit_affiliations_override}
                    placeholder={$lq__event_badge_obj?.affiliations ?? 'Organization / affiliations'}
                ></textarea>
                {@render field_actions(
                    'affiliations',
                    () => save_field('affiliations', { affiliations_override: edit_affiliations_override || null }),
                    () => cancel_field('affiliations')
                )}
            </div>
        {/if}
    </div>

    <!-- === LOCATION === -->
    <!-- Editable by all authenticated users -->
    <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
        <div class="flex items-start gap-2 px-3 pt-2 pb-1.5">
            <div class="flex-1 min-w-0">
                <p class="text-[10px] uppercase tracking-widest text-gray-400 font-semibold mb-0.5">Location</p>
                {#if get_display('location_override', 'location')}
                    <p class="leading-snug truncate">{get_display('location_override', 'location')}</p>
                {:else}
                    <p class="text-gray-400 italic text-xs">Not set — tap ✎ to add</p>
                {/if}
            </div>
            <button
                type="button"
                class="btn btn-xs preset-tonal-surface shrink-0 mt-0.5"
                onclick={() => toggle_field('location')}
                aria-expanded={active_field === 'location'}
                aria-controls="field-form-location"
                title="Edit location"
                aria-label="Edit location"
            >
                {#if active_field === 'location'}<ChevronDown size="12" />{:else}<Pencil size="12" />{/if}
            </button>
        </div>
        {@render font_ctrl('location')}
        {#if active_field === 'location'}
            <div id="field-form-location" class="px-3 pb-3 pt-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
                <label for="ctrl-location" class="text-xs text-gray-500 block mb-1">
                    Location override
                </label>
                <input
                    id="ctrl-location"
                    name="ctrl-location"
                    type="text"
                    class="input w-full"
                    bind:value={edit_location_override}
                    placeholder={$lq__event_badge_obj?.location ?? 'City, State / Country'}
                />
                {@render field_actions(
                    'location',
                    () => save_field('location', { location_override: edit_location_override || null }),
                    () => cancel_field('location')
                )}
            </div>
        {/if}
    </div>

    <!-- === ALLOW TRACKING === -->
    <!-- Editable by all authenticated users -->
    <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
        <div class="flex items-start gap-2 px-3 pt-2 pb-1.5">
            <div class="flex-1 min-w-0">
                <p class="text-[10px] uppercase tracking-widest text-gray-400 font-semibold mb-0.5">Lead Scanning</p>
                <p class="leading-snug text-xs">
                    {$lq__event_badge_obj?.allow_tracking ? 'Allowed' : 'Not allowed'}
                </p>
            </div>
            <button
                type="button"
                class="btn btn-xs preset-tonal-surface shrink-0 mt-0.5"
                onclick={() => toggle_field('allow_tracking')}
                aria-expanded={active_field === 'allow_tracking'}
                aria-controls="field-form-allow-tracking"
                title="Edit lead scanning preference"
                aria-label="Edit lead scanning preference"
            >
                {#if active_field === 'allow_tracking'}<ChevronDown size="12" />{:else}<Pencil size="12" />{/if}
            </button>
        </div>
        {#if active_field === 'allow_tracking'}
            <div id="field-form-allow-tracking" class="px-3 pb-3 pt-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
                <label class="flex items-center gap-2 cursor-pointer select-none">
                    <input
                        id="ctrl-allow-tracking"
                        name="ctrl-allow-tracking"
                        type="checkbox"
                        class="checkbox"
                        bind:checked={edit_allow_tracking}
                    />
                    <span class="text-xs">Allow exhibitor lead scanning</span>
                </label>
                {@render field_actions(
                    'allow_tracking',
                    () => save_field('allow_tracking', { allow_tracking: edit_allow_tracking }),
                    () => cancel_field('allow_tracking')
                )}
            </div>
        {/if}
    </div>

    <!-- === TRUSTED-ONLY FIELDS === -->
    {#if is_trusted}

        <!-- === PRONOUNS === -->
        <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
            <div class="flex items-start gap-2 px-3 pt-2 pb-2">
                <div class="flex-1 min-w-0">
                    <p class="text-[10px] uppercase tracking-widest text-gray-400 font-semibold mb-0.5">Pronouns</p>
                    {#if get_display('pronouns_override', 'pronouns')}
                        <p class="leading-snug truncate">{get_display('pronouns_override', 'pronouns')}</p>
                    {:else}
                        <p class="text-gray-400 italic text-xs">Not set — tap ✎ to add</p>
                    {/if}
                </div>
                <button
                    type="button"
                    class="btn btn-xs preset-tonal-surface shrink-0 mt-0.5"
                    onclick={() => toggle_field('pronouns')}
                    aria-expanded={active_field === 'pronouns'}
                    aria-controls="field-form-pronouns"
                    title="Edit pronouns"
                    aria-label="Edit pronouns"
                >
                    {#if active_field === 'pronouns'}<ChevronDown size="12" />{:else}<Pencil size="12" />{/if}
                </button>
            </div>
            {#if active_field === 'pronouns'}
                <div id="field-form-pronouns" class="px-3 pb-3 pt-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
                    <label for="ctrl-pronouns" class="text-xs text-gray-500 block mb-1">
                        Pronouns override
                    </label>
                    <input
                        id="ctrl-pronouns"
                        name="ctrl-pronouns"
                        type="text"
                        class="input w-full"
                        bind:value={edit_pronouns_override}
                        placeholder={$lq__event_badge_obj?.pronouns ?? 'e.g. they/them'}
                    />
                    {@render field_actions(
                        'pronouns',
                        () => save_field('pronouns', { pronouns_override: edit_pronouns_override || null }),
                        () => cancel_field('pronouns')
                    )}
                </div>
            {/if}
        </div>

        <!-- === BADGE TYPE === -->
        <!-- Only shown when template has a badge_type_list defined -->
        {#if badge_type_code_li.length > 0}
            <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                <div class="flex items-start gap-2 px-3 pt-2 pb-2">
                    <div class="flex-1 min-w-0">
                        <p class="text-[10px] uppercase tracking-widest text-gray-400 font-semibold mb-0.5">Badge Type</p>
                        {#if badge_type_display}
                            <p class="leading-snug truncate">{badge_type_display}</p>
                        {:else}
                            <p class="text-gray-400 italic text-xs">Not set — tap ✎ to assign</p>
                        {/if}
                    </div>
                    <button
                        type="button"
                        class="btn btn-xs preset-tonal-surface shrink-0 mt-0.5"
                        onclick={() => toggle_field('badge_type')}
                        aria-expanded={active_field === 'badge_type'}
                        aria-controls="field-form-badge-type"
                        title="Edit badge type"
                        aria-label="Edit badge type"
                    >
                        {#if active_field === 'badge_type'}<ChevronDown size="12" />{:else}<Pencil size="12" />{/if}
                    </button>
                </div>
                {#if active_field === 'badge_type'}
                    <div id="field-form-badge-type" class="px-3 pb-3 pt-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
                        <label for="ctrl-badge-type" class="text-xs text-gray-500 block mb-1">
                            Badge type override
                        </label>
                        <select
                            id="ctrl-badge-type"
                            name="ctrl-badge-type"
                            class="select w-full"
                            bind:value={edit_badge_type_code}
                        >
                            <option value={null}>— Select badge type —</option>
                            {#each badge_type_code_li as item (item.code)}
                                <option value={item.code}>{item.name}</option>
                            {/each}
                        </select>
                        {@render field_actions(
                            'badge_type',
                            () => save_field('badge_type', {
                                badge_type_code_override: edit_badge_type_code,
                                // Keep badge_type_override in sync (name from template list).
                                // See edge-case note in PROJECT__AE_Events_Badges_Review_Print.md.
                                badge_type_override: edit_badge_type_code
                                    ? (badge_type_code_li.find(item => item.code === edit_badge_type_code)?.name ?? edit_badge_type_code)
                                    : null
                            }),
                            () => cancel_field('badge_type')
                        )}
                    </div>
                {/if}
            </div>
        {/if}

    {/if}<!-- end is_trusted -->

</div>
