<script lang="ts">
    /**
     * src/routes/events/[event_id]/(leads)/leads/exhibit/[exhibit_id]/ae_comp__exhibit_custom_questions.svelte
     * Exhibitor Custom Questions Editor - Handles leads_custom_questions_json.
     */
    import { untrack } from 'svelte';
    import { ae_api } from '$lib/stores/ae_stores';
    import { events_func } from '$lib/ae_events_functions';
    import { Plus, Trash2, Save, LoaderCircle, MessageSquare, List } from 'lucide-svelte';

    interface Props {
        exhibit_id: string;
        event_id: string;
        custom_questions_json?: string;
    }

    let { exhibit_id, event_id, custom_questions_json = '[]' }: Props = $props();

    let questions: any[] = $state([]);
    let is_saving = $state(false);
    // Track the JSON as it was last saved so we can detect unsaved changes
    let saved_json = $state('[]');

    $effect(() => {
        const incoming = custom_questions_json; // reactive dependency
        try {
            const parsed = JSON.parse(incoming || '[]');
            untrack(() => {
                if (Array.isArray(parsed) && parsed.length > 0) {
                    // Incoming prop has real content — load it (initial load or external update)
                    questions = parsed;
                    saved_json = JSON.stringify(parsed);
                } else if (questions.length === 0) {
                    // Both empty — initialize state cleanly
                    saved_json = '[]';
                }
                // If parsed is empty but we already have questions: the API response
                // stripped leads_custom_questions_json from its return object and
                // overwrote Dexie with null. Keep our in-memory questions intact.
            });
        } catch (e) {
            untrack(() => { if (questions.length === 0) { questions = []; saved_json = '[]'; } });
        }
    });

    // True whenever the current questions differ from the last saved state
    let is_dirty = $derived(JSON.stringify(questions) !== saved_json);

    async function save_questions() {
        if (!exhibit_id) return;
        is_saving = true;
        try {
            await events_func.update_ae_obj__exhibit({
                api_cfg: $ae_api,
                event_id: event_id,
                exhibit_id: exhibit_id,
                data_kv: {
                    leads_custom_questions_json: JSON.stringify(questions)
                }
            });
            saved_json = JSON.stringify(questions);
        } finally {
            is_saving = false;
        }
    }

    function add_question() {
        questions.push({
            // code: machine key used as the responses_json property name
            // question: human-readable label shown to the exhibitor/scanner
            // option_li: array of choices; first element is always '' (blank/no-selection default)
            code: '',
            question: '',
            type: 'text',
            option_li: ['']
        });
    }

    function remove_question(index: number) {
        questions.splice(index, 1);
    }

    // Helpers for option_li ↔ comma-string conversion in the UI
    function get_options_str(q: any): string {
        const li: string[] = Array.isArray(q.option_li) ? q.option_li : [];
        return li.filter((o: string) => o !== '').join(', ');
    }

    function set_options_str(q: any, val: string) {
        // Always prepend empty string so the select has a blank default option
        q.option_li = ['', ...val.split(',').map((s: string) => s.trim()).filter(Boolean)];
    }
</script>

<div class="custom-questions-editor space-y-4">
    <div class="flex items-center justify-between">
        <h3 class="text-sm font-bold uppercase tracking-widest opacity-50">Lead Qualifiers</h3>
        <span class="text-xs opacity-40 italic">Define questions for lead capture</span>
    </div>

    <div class="space-y-3">
        {#each questions as q, i (i)}
            <div class="card p-4 variant-soft border border-surface-500/10 space-y-3 animate-in fade-in slide-in-from-right-2">
                <!-- Question header row: number + delete (always visible for mobile) -->
                <div class="flex items-center justify-between">
                    <span class="text-[10px] uppercase font-black opacity-30 tracking-widest">Question {i + 1}</span>
                    <button
                        class="btn btn-sm variant-ghost-error px-2 py-1"
                        onclick={() => remove_question(i)}
                        title="Remove question"
                    >
                        <Trash2 size="1em" />
                    </button>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <!-- Question / display label -->
                    <div class="space-y-1">
                        <label class="text-[10px] uppercase font-bold opacity-40" for="custom-q-{i}-question">Question / Label</label>
                        <div class="flex items-center gap-2">
                            <MessageSquare size="1em" class="opacity-30 flex-none" />
                            <input id="custom-q-{i}-question" type="text" bind:value={q.question} placeholder="e.g. Purchasing Authority?" class="bg-transparent border-b border-surface-500/20 outline-none flex-1 text-sm font-bold" />
                        </div>
                    </div>

                    <!-- Code / machine key -->
                    <div class="space-y-1">
                        <label class="text-[10px] uppercase font-bold opacity-40" for="custom-q-{i}-code">Field Code <span class="normal-case font-normal opacity-70">(key in export)</span></label>
                        <input id="custom-q-{i}-code" type="text" bind:value={q.code} placeholder="e.g. purchasing_authority" class="bg-transparent border-b border-surface-500/20 outline-none w-full text-xs font-mono" />
                    </div>
                </div>

                <!-- Response Type -->
                <div class="space-y-1">
                    <label class="text-[10px] uppercase font-bold opacity-40" for="custom-q-{i}-type">Response Type</label>
                    <select id="custom-q-{i}-type" bind:value={q.type} class="select variant-filled-surface text-xs p-1 rounded w-full">
                        <option value="text">Short Text</option>
                        <option value="textarea">Long Text</option>
                        <option value="toggle">Yes / No (Toggle)</option>
                        <option value="option">Multiple Choice (Select)</option>
                    </select>
                </div>

                {#if q.type === 'option'}
                    <div class="space-y-1 pt-2 border-t border-surface-500/10">
                        <label class="text-[10px] uppercase font-bold opacity-40" for="custom-q-{i}-options">Options (comma-separated)</label>
                        <div class="flex items-center gap-2">
                            <List size="1em" class="opacity-30 flex-none" />
                            <input
                                id="custom-q-{i}-options"
                                type="text"
                                value={get_options_str(q)}
                                oninput={(e) => set_options_str(q, (e.target as HTMLInputElement).value)}
                                placeholder="Hot, Warm, Cold"
                                class="bg-transparent border-b border-surface-500/20 outline-none flex-1 text-xs"
                            />
                        </div>
                    </div>
                {/if}
            </div>
        {/each}

        {#if questions.length === 0}
            <div class="p-8 text-center border-2 border-dashed border-surface-500/20 rounded-xl opacity-30">
                <Plus size="2em" class="mx-auto mb-2" />
                <p class="text-sm italic">No custom questions defined yet.</p>
            </div>
        {/if}
    </div>

    <!-- Unsaved changes warning -->
    {#if is_dirty}
        <p class="text-xs text-warning-500 font-bold text-center animate-pulse">Unsaved changes</p>
    {/if}

    <div class="flex gap-2 pt-2">
        <button class="btn btn-sm variant-filled-secondary flex-1" onclick={add_question}>
            <Plus size="1.2em" class="mr-2" /> Add Question
        </button>
        <button
            class="btn btn-sm flex-1 transition-all"
            class:variant-filled-primary={is_dirty}
            class:variant-ghost-surface={!is_dirty}
            onclick={save_questions}
            disabled={is_saving || !is_dirty}
        >
            {#if is_saving}
                <LoaderCircle size="1.2em" class="animate-spin mr-2" />
            {:else}
                <Save size="1.2em" class="mr-2" />
            {/if}
            {is_dirty ? 'Save Questions' : 'Saved'}
        </button>
    </div>
</div>
