<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 { beforeNavigate, goto } from '$app/navigation';
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 { events_func } from '$lib/ae_events/ae_events_functions';
import AE_Comp_Editor_TipTap from '$lib/elements/element_editor_tiptap.svelte';
import Comp_lead_detail_form from './ae_comp__lead_detail_form.svelte';
import {
    Briefcase,
    CalendarDays,
    Check,
    ChevronLeft,
    Eye,
    FileText,
    ListTodo,
    LoaderCircle,
    Mail,
    MapPin,
    RotateCcw,
    Save,
    ShieldCheck,
    SquarePen,
    Star,
    Trash2,
    User,
    UserCheck
} 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);

// Priority toggle — one-click, saves immediately without entering edit mode.
let priority_saving = $state(false);
async function toggle_priority() {
    if (!exhibit_tracking_id || priority_saving) return;
    priority_saving = true;
    try {
        await events_func.update_ae_obj__exhibit_tracking({
            api_cfg: $ae_api,
            exhibit_id: page.params.exhibit_id ?? '',
            exhibit_tracking_id,
            data: { priority: !$lq__lead_obj?.priority }
        });
    } finally {
        priority_saving = false;
    }
}

// Human-readable label for external_person_id.
// Raw values: 'shared_passcode' (booth shared login), an email (licensed user),
// or an Aether access_type string (trusted/administrator — staff bypass).
function format_captured_by(id: string | null | undefined): string {
    if (!id) return 'Unknown';
    if (id === 'shared_passcode') return 'Booth (Shared)';
    if (id.includes('@')) return id;
    const map: Record<string, string> = {
        trusted: 'Staff',
        administrator: 'Admin',
        edit_mode: 'Staff'
    };
    return map[id] ?? id;
}

// Unsaved-changes guard — warn before navigating away if notes or responses are dirty.
let form_is_dirty = $state(false);
beforeNavigate(({ cancel }) => {
    const notes_dirty =
        is_edit_mode &&
        draft_notes !== ($lq__lead_obj?.exhibitor_notes ?? '');
    if (notes_dirty || form_is_dirty) {
        if (!confirm('You have unsaved changes. Leave without saving?')) {
            cancel();
        }
    }
});

// Notes editing state
let draft_notes = $state('');
let notes_status = $state<'idle' | 'saving' | 'success' | 'error'>('idle');

// Keep draft in sync when viewing (not editing), so it's ready when edit mode opens.
$effect(() => {
    if (!is_edit_mode) {
        draft_notes = $lq__lead_obj?.exhibitor_notes ?? '';
    }
});

async function save_notes() {
    if (!exhibit_tracking_id) return;
    notes_status = 'saving';
    try {
        await events_func.update_ae_obj__exhibit_tracking({
            api_cfg: $ae_api,
            exhibit_id: page.params.exhibit_id ?? '',
            exhibit_tracking_id,
            data: { exhibitor_notes: draft_notes }
        });
        notes_status = 'success';
        setTimeout(() => {
            if (notes_status === 'success') notes_status = 'idle';
        }, 2000);
    } catch {
        notes_status = 'error';
    }
}

// Remove / Restore flow.
// Two-click confirm for remove: idle → confirm → removing → (navigate back).
let remove_status = $state<'idle' | 'confirm' | 'removing' | 'restoring'>(
    'idle'
);

async function remove_lead() {
    const eid = page.params.exhibit_id ?? '';
    if (!exhibit_tracking_id || !eid) return;
    remove_status = 'removing';
    try {
        await events_func.update_ae_obj__exhibit_tracking({
            api_cfg: $ae_api,
            exhibit_id: eid,
            exhibit_tracking_id,
            data: { enable: false }
        });
        // Navigate back to exhibit leads list after removal
        goto(`/events/${page.params.event_id}/leads/exhibit/${eid}`);
    } catch {
        // If update fails, reset so user can try again
        remove_status = 'idle';
    }
}

async function restore_lead() {
    const eid = page.params.exhibit_id ?? '';
    if (!exhibit_tracking_id || !eid) return;
    remove_status = 'restoring';
    try {
        await events_func.update_ae_obj__exhibit_tracking({
            api_cfg: $ae_api,
            exhibit_id: eid,
            exhibit_tracking_id,
            data: { enable: true }
        });
        remove_status = 'idle';
    } catch {
        remove_status = 'idle';
    }
}

// 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 flex w-full flex-col items-center">
    <!-- Local Header -->
    <header
        class="bg-surface-100-900 border-surface-500/20 sticky top-0 z-10 flex w-full items-center justify-between gap-4 border-b px-4 py-3 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 preset-outlined-surface">
                <ChevronLeft size="1.2em" />
                <span class="ml-1 hidden sm:inline">Back</span>
            </a>
            <h1 class="text-lg font-bold">Lead Profile</h1>
        </div>

        <div class="flex items-center gap-2">
            {#if $lq__lead_obj}
                <!-- Remove — leftmost so it never lands on top of Edit/View when it appears.
                     Only shown in edit mode; soft-delete only (enable=false), recoverable. -->
                {#if is_edit_mode && $lq__lead_obj.enable}
                    {#if remove_status === 'confirm'}
                        <button
                            type="button"
                            class="btn btn-sm preset-filled-error font-bold"
                            onclick={remove_lead}>
                            <Trash2 size="1em" />
                            Confirm?
                        </button>
                        <button
                            type="button"
                            class="btn btn-sm preset-outlined-surface"
                            onclick={() => (remove_status = 'idle')}>
                            Cancel
                        </button>
                    {:else}
                        <button
                            type="button"
                            class="btn btn-sm preset-outlined-error"
                            disabled={remove_status === 'removing'}
                            onclick={() => (remove_status = 'confirm')}>
                            {#if remove_status === 'removing'}
                                <LoaderCircle size="1em" class="animate-spin" />
                            {:else}
                                <Trash2 size="1em" />
                            {/if}
                            <span class="hidden sm:inline">Remove</span>
                        </button>
                    {/if}
                {/if}

                <!-- Priority toggle — always visible, one-click, no edit mode needed. -->
                <button
                    type="button"
                    class="btn btn-sm font-bold transition-all"
                    class:preset-filled-warning={$lq__lead_obj.priority}
                    class:preset-outlined-surface={!$lq__lead_obj.priority}
                    class:opacity-40={!$lq__lead_obj.priority}
                    disabled={priority_saving}
                    onclick={toggle_priority}
                    title={$lq__lead_obj.priority ? 'Remove priority flag' : 'Mark as priority lead'}>
                    {#if priority_saving}
                        <LoaderCircle size="1em" class="animate-spin" />
                    {:else}
                        <Star size="1em" class={$lq__lead_obj.priority ? 'fill-current' : ''} />
                    {/if}
                    <span class="hidden sm:inline">Priority</span>
                </button>

                <!-- Edit/View — always rightmost so its position never shifts. -->
                <button
                    class="btn btn-sm"
                    class:preset-filled-primary={is_edit_mode}
                    class:preset-outlined-surface={!is_edit_mode}
                    onclick={() => {
                        is_edit_mode = !is_edit_mode;
                        remove_status = 'idle';
                    }}>
                    {#if is_edit_mode}
                        <Eye size="1.2em" /> <span class="hidden sm:inline ml-1">View</span>
                    {:else}
                        <SquarePen size="1.2em" /> <span class="hidden sm:inline ml-1">Edit</span>
                    {/if}
                </button>
            {/if}
        </div>
    </header>

    <div class="w-full max-w-5xl space-y-6 p-4 sm:p-6">
        {#if !$lq__lead_obj}
            <div
                class="flex flex-col items-center justify-center p-20 text-center opacity-50">
                <LoaderCircle size="3em" class="mx-auto mb-4 animate-spin" />
                <p class="text-xl">Loading lead details...</p>
            </div>
        {:else}
            <!-- Main Grid -->
            <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
                <!-- Left: Profile Info -->
                <div class="space-y-6 lg:col-span-2">
                    <!-- Attendee Core Identity -->
                    <div
                        class="card preset-tonal-surface border-primary-500 space-y-2 border-l-4 p-4 shadow-lg">
                        <!-- 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 leading-tight font-black">
                                {@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="text-primary-500 flex items-center gap-2 text-sm font-semibold">
                                    <MapPin size="1em" class="flex-none" />
                                    <span
                                        >{@html $lq__lead_obj.event_badge_affiliations ||
                                            $lq__lead_obj.event_badge_affiliations_override}</span>
                                </div>
                            {/if}
                            {#if $lq__lead_obj.event_badge_location_override || $lq__lead_obj.event_badge_location || $lq__lead_obj.event_badge_country}
                                <div class="flex items-center gap-2 text-sm opacity-70">
                                    <MapPin size="1em" class="flex-none opacity-60" />
                                    <span>{[
                                        $lq__lead_obj.event_badge_location_override || $lq__lead_obj.event_badge_location,
                                        $lq__lead_obj.event_badge_country
                                    ].filter(Boolean).join(', ')}</span>
                                </div>
                            {/if}
                            <div
                                class="flex items-center gap-2 text-sm opacity-70">
                                <a href={`mailto:${$lq__lead_obj.event_badge_email}`}
                                    class="flex items-center gap-1 underline">
                                <Mail size="1em" class="flex-none" />
                                <span class="truncate font-mono"
                                    >{$lq__lead_obj.event_badge_email ||
                                        'No email on file'}</span>
                                </a>
                            </div>
                            <div
                                class="flex items-center gap-2 text-sm opacity-60">
                                <CalendarDays size="1em" class="flex-none" />
                                <span
                                    >Captured {ae_util.iso_datetime_formatter(
                                        $lq__lead_obj.created_on, 'datetime_12_long'
                                    )}</span>
                            {#if $lq__lead_obj.updated_on}
                                <span
                                    >Updated {ae_util.iso_datetime_formatter(
                                        $lq__lead_obj.updated_on, 'datetime_12_long'
                                    )}</span>
                            {/if}
                            </div>
                            <div
                                class="flex items-center gap-2 text-sm opacity-60">
                                <UserCheck size="1em" class="flex-none" />
                                <span>Captured by {format_captured_by($lq__lead_obj.external_person_id)}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Custom Responses Section -->
                    <div class="card space-y-4 p-6 shadow-md">
                        <div
                            class="border-surface-500/10 flex items-center gap-2 border-b pb-3">
                            <ListTodo size="1.2em" class="text-primary-500" />
                            <h3
                                class="text-lg font-bold tracking-wider uppercase">
                                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 ?? ''}
                                event_id={page.params.event_id ?? ''}
                                custom_questions_json={$lq__exhibit_obj?.leads_custom_questions_json ??
                                    '[]'}
                                current_responses_json={$lq__lead_obj.responses_json ??
                                    '{}'}
                                bind:is_dirty={form_is_dirty} />
                        {: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="animate-in fade-in grid grid-cols-1 gap-4 sm:grid-cols-2">
                                    {#each Object.entries(responses) as [question, answer] (question)}
                                        {@const display_value =
                                            answer !== null &&
                                            typeof answer === 'object'
                                                ? ((answer as any).response ??
                                                  '')
                                                : String(answer ?? '')}
                                        <div
                                            class="bg-surface-500/5 border-surface-500/10 rounded-lg border p-3">
                                            <div
                                                class="mb-1 text-[10px] leading-tight font-black tracking-widest uppercase opacity-40">
                                                {question}
                                            </div>
                                            <div class="text-sm font-semibold">
                                                {display_value || '—'}
                                            </div>
                                        </div>
                                    {/each}
                                </div>
                            {:else}
                                <p class="py-4 text-center italic opacity-30">
                                    No responses captured for this lead.
                                </p>
                            {/if}
                        {:else}
                            <p class="py-4 text-center italic opacity-30">
                                No responses captured for this lead.
                            </p>
                        {/if}
                    </div>

                    <!-- Notes Section -->
                    <div class="card space-y-4 p-6 shadow-md">
                        <div
                            class="border-surface-500/10 flex items-center gap-2 border-b pb-3">
                            <FileText size="1.2em" class="text-secondary-500" />
                            <h3
                                class="text-lg font-bold tracking-wider uppercase">
                                Exhibitor Notes
                            </h3>
                        </div>
                        {#if is_edit_mode}
                            <AE_Comp_Editor_TipTap
                                bind:content={draft_notes}
                                placeholder="Add notes about this lead..." />
                            <div class="flex items-center justify-end gap-3">
                                {#if notes_status === 'success'}
                                    <span
                                        class="text-success-500 flex items-center gap-1 text-sm">
                                        <Check size="1em" /> Saved
                                    </span>
                                {:else if notes_status === 'error'}
                                    <span class="text-error-500 text-sm"
                                        >Save failed — try again</span>
                                {/if}
                                <button
                                    type="button"
                                    class="btn btn-sm preset-filled-primary"
                                    disabled={notes_status === 'saving' ||
                                        draft_notes ===
                                            ($lq__lead_obj?.exhibitor_notes ??
                                                '')}
                                    onclick={save_notes}>
                                    {#if notes_status === 'saving'}
                                        <LoaderCircle
                                            size="1em"
                                            class="animate-spin" />
                                    {:else}
                                        <Save size="1em" />
                                    {/if}
                                    Save Notes
                                </button>
                            </div>
                        {:else if $lq__lead_obj.exhibitor_notes}
                            <div
                                class="bg-surface-500/5 border-surface-500/10 rounded-xl border p-5">
                                <div
                                    class="prose dark:prose-invert max-w-none leading-relaxed">
                                    {@html $lq__lead_obj.exhibitor_notes}
                                </div>
                            </div>
                        {:else}
                            <div
                                class="bg-surface-500/5 border-surface-500/10 flex min-h-30 items-center justify-center rounded-xl border">
                                <button
                                    type="button"
                                    class="btn btn-sm preset-outlined-surface"
                                    onclick={() => {
                                        is_edit_mode = true;
                                        remove_status = 'idle';
                                    }}>
                                    <SquarePen size="1.2em" class="mr-1" /> Add Notes
                                </button>
                            </div>
                        {/if}
                    </div>
                </div>

                <!-- Right: Metadata & Stats -->
                <div class="space-y-6">
                    <!-- System Audit — staff/admin only; end users don't need raw IDs. -->
                    {#if $ae_loc.manager_access}
                        <div
                            class="card bg-surface-500/5 space-y-4 p-5 font-mono text-[10px] opacity-60 shadow-inner">
                            <div
                                class="border-surface-500/10 mb-2 border-b pb-2 font-black tracking-[0.2em] uppercase">
                                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">EXHIBIT:</span>
                                    {$lq__lead_obj.event_exhibit_name || '—'}
                                </div>
                                <div>
                                    <span class="opacity-50">MODIFIED:</span>
                                    {format_date($lq__lead_obj.updated_on)}
                                </div>
                            </div>
                        </div>
                    {/if}

                    <!-- Restore Lead card — only shown when lead has been removed (enable=false/0).
                         Removing sets enable=false rather than deleting so notes/responses are preserved. -->
                    {#if !$lq__lead_obj.enable}
                        <div
                            class="card preset-tonal-error border-error-500/50 space-y-3 border p-4 shadow-sm">
                            <div class="flex items-center gap-2">
                                <ShieldCheck
                                    size="1.4em"
                                    class="text-error-500 shrink-0" />
                                <div>
                                    <div class="text-sm font-bold">
                                        Lead Removed
                                    </div>
                                    <div
                                        class="text-[10px] font-black uppercase opacity-60">
                                        Not visible in leads list
                                    </div>
                                </div>
                            </div>
                            <button
                                type="button"
                                class="btn btn-sm preset-filled-success w-full font-bold"
                                disabled={remove_status === 'restoring'}
                                onclick={restore_lead}>
                                {#if remove_status === 'restoring'}
                                    <LoaderCircle
                                        size="1em"
                                        class="animate-spin" />
                                    Restoring...
                                {:else}
                                    <RotateCcw size="1em" />
                                    Restore Lead
                                {/if}
                            </button>
                        </div>
                    {/if}
                </div>
            </div>
        {/if}
    </div>
</section>

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