<script lang="ts">
    /**
     * src/routes/events/[event_id]/(leads)/leads/lead/[exhibit_tracking_id]/+page.svelte
     * Lead Detail View - Basic Read-Only version.
     */
    import { page } from '$app/state';
    import { liveQuery } from 'dexie';
    import { db_events } from '$lib/ae_events/db_events';
    import { ae_util } from '$lib/ae_utils/ae_utils';
    import { ae_api, ae_loc } from '$lib/stores/ae_stores';
    import Element_ae_crud_v2 from '$lib/elements/element_ae_crud_v2.svelte';
    import Comp_lead_detail_form from './ae_comp__lead_detail_form.svelte';
    import {
        User,
        Mail,
        MapPin,
        FileText,
        ChevronLeft,
        Store,
        Briefcase,
        CalendarDays,
        ShieldCheck,
        Star,
        LoaderCircle,
        ListTodo,
        SquarePen,
        Eye
    } from 'lucide-svelte';

    const exhibit_tracking_id = $derived(page.params.exhibit_tracking_id);

    let lq__lead_obj = $derived(
        liveQuery(async () => {
            if (!exhibit_tracking_id) return null;
            return await db_events.exhibit_tracking.get(exhibit_tracking_id);
        })
    );

    let lq__exhibit_obj = $derived(
        liveQuery(async () => {
            const exhibit_id = page.params.exhibit_id;
            if (!exhibit_id) return null;
            return await db_events.exhibit.get(exhibit_id);
        })
    );

    let is_edit_mode = $state(false);

    // Helper to format date using Aether utility
    function format_date(date: any) {
        if (!date) return '';
        return ae_util.iso_datetime_formatter(date, 'datetime_iso_12_no_seconds');
    }
</script>

<svelte:head>
    <title>Lead: {$lq__lead_obj?.event_badge_full_name ?? 'Loading...'}</title>
</svelte:head>

<section class="lead-detail-view w-full flex flex-col items-center">
    <!-- Local Header -->
    <header class="w-full bg-surface-100-900 border-b border-surface-500/20 px-4 py-3 sticky top-0 z-10 flex items-center justify-between gap-4 shadow-sm">
        <div class="flex items-center gap-4">
            <a
                href={`/events/${page.params.event_id}/leads/exhibit/${page.params.exhibit_id}`}
                class="btn btn-sm variant-ghost-surface"
            >
                <ChevronLeft size="1.2em" />
                <span class="hidden sm:inline ml-1">Back</span>
            </a>
            <h1 class="text-lg font-bold">Lead Profile</h1>
        </div>
        
        <div class="flex items-center gap-2">
            {#if $lq__lead_obj}
                <button 
                    class="btn btn-sm"
                    class:variant-filled-primary={is_edit_mode}
                    class:variant-ghost-surface={!is_edit_mode}
                    onclick={() => is_edit_mode = !is_edit_mode}
                >
                    {#if is_edit_mode}
                        <Eye size="1.2em" class="mr-1" /> View
                    {:else}
                        <SquarePen size="1.2em" class="mr-1" /> Edit
                    {/if}
                </button>
            {/if}

            {#if $lq__lead_obj?.priority}
                <span class="badge variant-filled-warning font-bold flex items-center gap-1">
                    <Star size="1em" fill="currentColor" />
                    Priority
                </span>
            {/if}
        </div>
    </header>

    <div class="w-full max-w-5xl p-4 sm:p-6 space-y-6">
        {#if !$lq__lead_obj}
            <div class="flex flex-col items-center justify-center p-20 opacity-50 text-center">
                <LoaderCircle size="3em" class="animate-spin mb-4 mx-auto" />
                <p class="text-xl">Loading lead details...</p>
            </div>
        {:else}
            <!-- Main Grid -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                
                <!-- Left: Profile Info -->
                <div class="lg:col-span-2 space-y-6">
                    <!-- Attendee Core Identity -->
                    <div class="card p-4 variant-soft shadow-lg border-l-4 border-primary-500 space-y-2">
                        <!-- Name row: small inline icon -->
                        <div class="flex items-center gap-2">
                            <User size="1.4em" class="text-primary-500 flex-none" />
                            <h2 class="text-2xl font-black leading-tight">
                                {@html $lq__lead_obj.event_badge_full_name || $lq__lead_obj.event_badge_full_name_override || 'Unknown Attendee'}
                            </h2>
                        </div>

                        <!-- Key details — all visible above the fold on mobile -->
                        <div class="space-y-1.5 pl-1">
                            {#if $lq__lead_obj.event_badge_professional_title || $lq__lead_obj.event_badge_professional_title_override}
                                <div class="flex items-center gap-2 text-sm opacity-80">
                                    <Briefcase size="1em" class="flex-none opacity-60" />
                                    <span>{@html $lq__lead_obj.event_badge_professional_title || $lq__lead_obj.event_badge_professional_title_override}</span>
                                </div>
                            {/if}
                            {#if $lq__lead_obj.event_badge_affiliations || $lq__lead_obj.event_badge_affiliations_override}
                                <div class="flex items-center gap-2 text-sm font-semibold text-primary-500">
                                    <MapPin size="1em" class="flex-none" />
                                    <span>{@html $lq__lead_obj.event_badge_affiliations || $lq__lead_obj.event_badge_affiliations_override}</span>
                                </div>
                            {/if}
                            <div class="flex items-center gap-2 text-sm opacity-70">
                                <Mail size="1em" class="flex-none" />
                                <span class="font-mono truncate">{$lq__lead_obj.event_badge_email || 'No email on file'}</span>
                            </div>
                            <div class="flex items-center gap-2 text-sm opacity-60">
                                <CalendarDays size="1em" class="flex-none" />
                                <span>Captured {format_date($lq__lead_obj.created_on)}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Custom Responses Section -->
                    <div class="card p-6 space-y-4 shadow-md">
                        <div class="flex items-center gap-2 border-b border-surface-500/10 pb-3">
                            <ListTodo size="1.2em" class="text-primary-500" />
                            <h3 class="text-lg font-bold uppercase tracking-wider">Custom Responses / Qualifiers</h3>
                        </div>

                        {#if is_edit_mode}
                            <Comp_lead_detail_form
                                exhibit_tracking_id={exhibit_tracking_id ?? ''}
                                exhibit_id={page.params.exhibit_id ?? ''}
                                custom_questions_json={$lq__exhibit_obj?.leads_custom_questions_json ?? '[]'}
                                current_responses_json={$lq__lead_obj.responses_json ?? '{}'}
                            />
                        {:else if $lq__lead_obj.responses_json}
                            {@const responses = typeof $lq__lead_obj.responses_json === 'string' ? JSON.parse($lq__lead_obj.responses_json) : $lq__lead_obj.responses_json}
                            {#if Object.keys(responses).length > 0}
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 animate-in fade-in">
                                    {#each Object.entries(responses) as [question, answer]}
                                        {@const display_value = (answer !== null && typeof answer === 'object') ? (answer as any).response ?? '' : String(answer ?? '')}
                                        <div class="p-3 bg-surface-500/5 rounded-lg border border-surface-500/10">
                                            <div class="text-[10px] uppercase font-black opacity-40 tracking-widest mb-1 leading-tight">{question}</div>
                                            <div class="font-semibold text-sm">{display_value || '—'}</div>
                                        </div>
                                    {/each}
                                </div>
                            {:else}
                                <p class="text-center opacity-30 italic py-4">No responses captured for this lead.</p>
                            {/if}
                        {:else}
                            <p class="text-center opacity-30 italic py-4">No responses captured for this lead.</p>
                        {/if}
                    </div>

                    <!-- Notes Section -->
                    <div class="card p-6 space-y-4 shadow-md">
                        <div class="flex items-center gap-2 border-b border-surface-500/10 pb-3">
                            <FileText size="1.2em" class="text-secondary-500" />
                            <h3 class="text-lg font-bold uppercase tracking-wider">Exhibitor Notes</h3>
                        </div>
                        <div class="bg-surface-500/5 p-5 rounded-xl border border-surface-500/10 min-h-[120px]">
                            {#if is_edit_mode}
                                <Element_ae_crud_v2
                                    api_cfg={$ae_api}
                                    object_type="event_exhibit_tracking"
                                    object_id={exhibit_tracking_id ?? ''}
                                    field_name="exhibitor_notes"
                                    field_type="tiptap"
                                    current_field_value={$lq__lead_obj.exhibitor_notes}
                                    object_reload={true}
                                    display_block={true}
                                />
                            {:else if $lq__lead_obj.exhibitor_notes}
                                <div class="prose dark:prose-invert max-w-none leading-relaxed">
                                    {@html $lq__lead_obj.exhibitor_notes}
                                </div>
                            {:else}
                                <div class="h-full flex items-center justify-center italic opacity-30 text-sm">
                                    No notes have been added for this lead yet.
                                </div>
                            {/if}
                        </div>
                    </div>
                </div>

                <!-- Right: Metadata & Stats -->
                <div class="space-y-6">
                    <!-- exhibit association -->
                    <div class="card p-5 space-y-4 shadow-md bg-surface-100-900 border border-surface-500/10">
                        <div class="flex items-center gap-2 text-primary-500">
                            <Store size="1.2em" />
                            <h3 class="font-bold uppercase text-xs tracking-widest">Exhibit Context</h3>
                        </div>
                        <div class="space-y-3">
                            {#if is_edit_mode}
                                <div class="flex justify-between items-center">
                                    <span class="text-sm opacity-60">Exhibit Name</span>
                                    <span class="font-bold">{$lq__lead_obj.event_exhibit_name || '...'}</span>
                                </div>
                            {/if}
                            <div class="flex justify-between items-center">
                                <span class="text-sm opacity-60">Captured By</span>
                                <span class="font-mono text-[10px]">{$lq__lead_obj.external_person_id || 'Unknown'}</span>
                            </div>
                            
                            {#if is_edit_mode}
                                <div class="flex justify-between items-center pt-2 border-t border-surface-500/10">
                                    <span class="text-xs opacity-60 font-bold">Priority Lead</span>
                                    <Element_ae_crud_v2
                                        api_cfg={$ae_api}
                                        object_type="event_exhibit_tracking"
                                        object_id={exhibit_tracking_id ?? ''}
                                        field_name="priority"
                                        field_type="boolean"
                                        current_field_value={$lq__lead_obj.priority}
                                    />
                                </div>
                            {/if}
                        </div>
                    </div>

                    <!-- System Info -->
                    <div class="card p-5 space-y-4 shadow-inner bg-surface-500/5 text-[10px] font-mono opacity-60">
                        <div class="font-black uppercase tracking-[0.2em] border-b border-surface-500/10 pb-2 mb-2">System Audit</div>
                        <div class="flex flex-col gap-2">
                            <div><span class="opacity-50">LEAD ID:</span> {$lq__lead_obj.event_exhibit_tracking_id}</div>
                            <div><span class="opacity-50">BADGE ID:</span> {$lq__lead_obj.event_badge_id}</div>
                            <div><span class="opacity-50">PERSON ID:</span> {$lq__lead_obj.event_person_id}</div>
                            <div><span class="opacity-50">MODIFIED:</span> {format_date($lq__lead_obj.updated_on)}</div>
                        </div>
                    </div>

                    <!-- Status Indicator -->
                    <div class="card p-4 flex items-center gap-3 variant-soft shadow-sm">
                        {#if is_edit_mode}
                            <div class="flex-1 flex items-center justify-between">
                                <div class="font-bold text-sm">Enabled</div>
                                <Element_ae_crud_v2
                                    api_cfg={$ae_api}
                                    object_type="event_exhibit_tracking"
                                    object_id={exhibit_tracking_id ?? ''}
                                    field_name="enable"
                                    field_type="boolean"
                                    current_field_value={$lq__lead_obj.enable}
                                />
                            </div>
                        {:else}
                            <ShieldCheck size="1.5em" class={$lq__lead_obj.enable ? 'text-success-500' : 'text-error-500'} />
                            <div>
                                <div class="font-bold">{$lq__lead_obj.enable ? 'Record Enabled' : 'Record Disabled'}</div>
                                <div class="text-[10px] opacity-50 uppercase font-black">Visibility Status</div>
                            </div>
                        {/if}
                    </div>
                </div>

            </div>
        {/if}
    </div>
</section>

<style lang="postcss">
    .lead-detail-view {
        /* Ensure we match the theme's background */
        @apply bg-transparent;
    }
</style>