<script lang="ts">
import type { key_val } from '$lib/stores/ae_stores';

interface Props {
    mod_badges_json: key_val | null | undefined;
    onsave?: (data: key_val) => void;
}

let { mod_badges_json = $bindable({}), onsave }: Props = $props();

/**
 * edit_permissions — controls which fields each access level may edit in the badge review form.
 * Stored as mod_badges_json.edit_permissions.
 *
 * Structure:
 *   authenticated.can_edit  — fields attendees (passcode-validated) may edit
 *   trusted.can_edit        — fields trusted staff may edit
 *   administrator.can_edit  — '*' (all) or a specific field list
 *
 * Default attendee fields: full_name_override, professional_title_override,
 *   affiliations_override, location_override
 * Default trusted fields: above + email, badge_type_code
 */

const all_attendee_fields = [
    { key: 'full_name_override', label: 'Full Name (override)' },
    {
        key: 'professional_title_override',
        label: 'Professional Title (override)'
    },
    { key: 'affiliations_override', label: 'Affiliations (override)' },
    { key: 'location_override', label: 'Location (override)' }
];

const all_staff_fields = [
    ...all_attendee_fields,
    { key: 'email', label: 'Email' },
    { key: 'badge_type_code', label: 'Badge Type Code' }
];

// Ensure edit_permissions sub-object exists
function ensure_permissions() {
    if (!mod_badges_json) return;
    if (!mod_badges_json.edit_permissions) {
        mod_badges_json.edit_permissions = {};
    }
    if (!mod_badges_json.edit_permissions.authenticated) {
        mod_badges_json.edit_permissions.authenticated = {
            can_edit: [
                'full_name_override',
                'professional_title_override',
                'affiliations_override',
                'location_override'
            ]
        };
    }
    if (!mod_badges_json.edit_permissions.trusted) {
        mod_badges_json.edit_permissions.trusted = {
            can_edit: [
                'full_name_override',
                'professional_title_override',
                'affiliations_override',
                'location_override',
                'email',
                'badge_type_code'
            ]
        };
    }
    if (!mod_badges_json.edit_permissions.administrator) {
        mod_badges_json.edit_permissions.administrator = { can_edit: '*' };
    }
}

function is_field_enabled(
    level: 'authenticated' | 'trusted',
    field_key: string
): boolean {
    const cfg = mod_badges_json?.edit_permissions?.[level]?.can_edit;
    if (!cfg) return false;
    if (cfg === '*') return true;
    return Array.isArray(cfg) && cfg.includes(field_key);
}

function toggle_field(level: 'authenticated' | 'trusted', field_key: string) {
    ensure_permissions();
    if (!mod_badges_json?.edit_permissions?.[level]) return;
    let fields: string[] = mod_badges_json.edit_permissions[level].can_edit;
    if (!Array.isArray(fields)) fields = [];
    if (fields.includes(field_key)) {
        mod_badges_json.edit_permissions[level].can_edit = fields.filter(
            (f: string) => f !== field_key
        );
    } else {
        mod_badges_json.edit_permissions[level].can_edit = [
            ...fields,
            field_key
        ];
    }
}

function save() {
    if (onsave && mod_badges_json) onsave(mod_badges_json);
}
</script>

<div class="space-y-4">
    {#if mod_badges_json}
        <div class="grid grid-cols-2 gap-4">
            <div>
                <label class="label">
                    <input
                        type="checkbox"
                        class="checkbox"
                        bind:checked={mod_badges_json.enable_mass_print} />
                    <span>Enable Mass Print</span>
                </label>
            </div>
            <div>
                <label class="label">
                    <input
                        type="checkbox"
                        class="checkbox"
                        bind:checked={mod_badges_json.enable_add_badge_btn} />
                    <span>Enable Add Badge Button</span>
                </label>
            </div>
            <div>
                <label class="label">
                    <input
                        type="checkbox"
                        class="checkbox"
                        bind:checked={
                            mod_badges_json.enable_upload_badge_li_btn
                        } />
                    <span>Enable Upload Badge List Button</span>
                </label>
            </div>
            <div>
                <label class="label">
                    <input
                        type="checkbox"
                        class="checkbox"
                        bind:checked={mod_badges_json.enable_search_qr} />
                    <span>Enable Search by QR</span>
                </label>
            </div>
        </div>

        <div class="space-y-2">
            <div>
                <label class="label">
                    <span>QR Type</span>
                    <input
                        type="text"
                        class="input"
                        bind:value={mod_badges_json.qr_type} />
                </label>
            </div>
            <div>
                <label class="label">
                    <span>Trusted Passcode</span>
                    <input
                        type="text"
                        class="input"
                        bind:value={mod_badges_json.trusted_passcode} />
                </label>
            </div>
            <div>
                <label class="label">
                    <span>Administrator Passcode</span>
                    <input
                        type="text"
                        class="input"
                        bind:value={mod_badges_json.administrator_passcode} />
                </label>
            </div>
        </div>

        <details class="space-y-3">
            <summary class="cursor-pointer text-sm font-medium">
                Badge Review — Editable Field Permissions
            </summary>
            <div class="space-y-4 pt-2 pl-2">
                <p class="text-xs text-gray-500">
                    Controls which fields each access level may edit on the
                    Badge Review page. Staff (Trusted) defaults include all
                    attendee fields plus Email and Badge Type Code.
                    Administrators can always edit everything.
                </p>

                <!-- Attendee (passcode-validated) -->
                <div class="space-y-1">
                    <p class="text-sm font-medium">Attendees (passcode link)</p>
                    <div class="grid grid-cols-2 gap-x-4 gap-y-1">
                        {#each all_attendee_fields as field (field.key)}
                            <label
                                class="label flex items-center gap-2 text-sm">
                                <input
                                    type="checkbox"
                                    class="checkbox"
                                    checked={is_field_enabled(
                                        'authenticated',
                                        field.key
                                    )}
                                    onchange={() =>
                                        toggle_field(
                                            'authenticated',
                                            field.key
                                        )} />
                                <span>{field.label}</span>
                            </label>
                        {/each}
                    </div>
                </div>

                <!-- Staff (Trusted) -->
                <div class="space-y-1">
                    <p class="text-sm font-medium">Staff (Trusted access)</p>
                    <div class="grid grid-cols-2 gap-x-4 gap-y-1">
                        {#each all_staff_fields as field (field.key)}
                            <label
                                class="label flex items-center gap-2 text-sm">
                                <input
                                    type="checkbox"
                                    class="checkbox"
                                    checked={is_field_enabled(
                                        'trusted',
                                        field.key
                                    )}
                                    onchange={() =>
                                        toggle_field('trusted', field.key)} />
                                <span>{field.label}</span>
                            </label>
                        {/each}
                    </div>
                </div>

                <!-- Administrator note -->
                <p class="text-xs text-gray-400 italic">
                    Administrators always have access to all fields (not
                    configurable).
                </p>
            </div>
        </details>
    {/if}
    <!-- end {#if mod_badges_json} -->

    <button type="button" class="btn preset-tonal-primary" onclick={save}
        >Save</button>
</div>
