<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/ae_events_functions';
import {
    List,
    LoaderCircle,
    MessageSquare,
    Plus,
    Save,
    Trash2
} 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 tracking-widest uppercase opacity-50">
            Lead Qualifiers
        </h3>
        <span class="text-xs italic opacity-40"
            >Define questions for lead capture</span>
    </div>

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

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

                    <!-- Code / machine key -->
                    <div class="space-y-1">
                        <label
                            class="text-[10px] font-bold uppercase opacity-40"
                            for="custom-q-{i}-code"
                            >Field Code <span
                                class="font-normal normal-case 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="border-surface-500/20 w-full border-b bg-transparent font-mono text-xs outline-none" />
                    </div>
                </div>

                <!-- Response Type -->
                <div class="space-y-1">
                    <label
                        class="text-[10px] font-bold uppercase opacity-40"
                        for="custom-q-{i}-type">Response Type</label>
                    <select
                        id="custom-q-{i}-type"
                        bind:value={q.type}
                        class="select preset-tonal-surface w-full rounded p-1 text-xs">
                        <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="border-surface-500/10 space-y-1 border-t pt-2">
                        <label
                            class="text-[10px] font-bold uppercase opacity-40"
                            for="custom-q-{i}-options"
                            >Options (comma-separated)</label>
                        <div class="flex items-center gap-2">
                            <List size="1em" class="flex-none opacity-30" />
                            <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="border-surface-500/20 flex-1 border-b bg-transparent text-xs outline-none" />
                        </div>
                    </div>
                {/if}
            </div>
        {/each}

        {#if questions.length === 0}
            <div
                class="border-surface-500/20 rounded-xl border-2 border-dashed p-8 text-center 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-warning-500 animate-pulse text-center text-xs font-bold">
            Unsaved changes
        </p>
    {/if}

    <div class="flex gap-2 pt-2">
        <button
            class="btn btn-sm preset-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:preset-filled-primary={is_dirty}
            class:preset-outlined-surface={!is_dirty}
            onclick={save_questions}
            disabled={is_saving || !is_dirty}>
            {#if is_saving}
                <LoaderCircle size="1.2em" class="mr-2 animate-spin" />
            {:else}
                <Save size="1.2em" class="mr-2" />
            {/if}
            {is_dirty ? 'Save Questions' : 'Saved'}
        </button>
    </div>
</div>
