<script lang="ts">
import AE_Obj_Field_Editor from '$lib/elements/element_ae_obj_field_editor.svelte';
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import { liveQuery } from 'dexie';
import { db_journals } from '$lib/ae_journals/db_journals';
import { load_ae_obj_id__journal } from '$lib/ae_journals/ae_journals__journal';
import { load_ae_obj_id__journal_entry } from '$lib/ae_journals/ae_journals__journal_entry';
import { FileText, LoaderCircle, RefreshCw, Zap } from '@lucide/svelte';
import { onMount } from 'svelte';

let log_lvl = $state(1);

// Provided Test IDs
let test_journal_id = $state('SWFK-48-89-90'); 
let test_journal_entry_id = $state('xRx-Y4-h3-fU');

// Fetch objects from API on mount to ensure local DB is populated
onMount(async () => {
    if (log_lvl) console.log('Test Page: Initializing data from server...');
    try {
        await Promise.all([
            load_ae_obj_id__journal({
                api_cfg: $ae_api,
                journal_id: test_journal_id,
                log_lvl
            }),
            load_ae_obj_id__journal_entry({
                api_cfg: $ae_api,
                journal_entry_id: test_journal_entry_id,
                log_lvl
            })
        ]);
    } catch (e) {
        console.error('Test Page: Error loading initial data', e);
    }
});

// Dexie LiveQueries
let lq__test_journal = $derived(
    liveQuery(async () => {
        return await db_journals.journal.get(test_journal_id);
    })
);

let lq__test_journal_entry = $derived(
    liveQuery(async () => {
        return await db_journals.journal_entry.get(test_journal_entry_id);
    })
);

function handle_success(data: any) {
    console.log('Test Page: Patch Success!', data);
}
</script>

<div class="mx-auto h-full max-w-4xl space-y-8 overflow-y-auto p-8">
    <header
        class="border-surface-500/30 flex items-center justify-between border-b pb-4">
        <div>
            <h1 class="text-3xl font-bold">Field Editor</h1>
            <p class="font-mono text-xs opacity-70">
                Aether V3 Inline Editor (Tailwind v4)
            </p>
        </div>
        <div class="flex items-center gap-4">
            <label
                class="bg-surface-200 dark:bg-surface-800 flex cursor-pointer items-center gap-2 rounded-full px-3 py-1.5 shadow-inner">
                <span class="text-xs font-bold uppercase opacity-70"
                    >Edit Mode</span>
                <input
                    type="checkbox"
                    bind:checked={$ae_loc.edit_mode}
                    class="checkbox" />
            </label>
            <button
                class="btn preset-filled-primary-500"
                onclick={() => window.location.reload()}>
                <RefreshCw size="1em" class="mr-2" /> Reload Page
            </button>
        </div>
    </header>

    <div class="space-y-8">
        <h2 class="text-xl font-bold flex items-center gap-2 text-primary-500">
            <Zap /> Interactive Tests
        </h2>

        {#if $lq__test_journal && $lq__test_journal_entry}
            <section class="border-surface-200-800 bg-surface-50-950 space-y-6 rounded-xl border p-6 shadow-xl">
                <div class="field_group">
                    <label for="j_name" class="text-surface-500 mb-1 block text-xs font-bold uppercase">Name (Text + Generic T)</label>
                    <AE_Obj_Field_Editor
                        id="j_name"
                        object_type="journal"
                        object_id={test_journal_id}
                        field_name="name"
                        current_value={$lq__test_journal.name}
                        field_type="text"
                        {log_lvl}
                        on_success={handle_success} />
                </div>

                <div class="field_group">
                    <label for="j_type" class="text-surface-500 mb-1 block text-xs font-bold uppercase">Type (Select + Coercion)</label>
                    <AE_Obj_Field_Editor
                        id="j_type"
                        object_type="journal"
                        object_id={test_journal_id}
                        field_name="type_code"
                        current_value={$lq__test_journal.type_code}
                        field_type="select"
                        select_options={{ personal: 'Personal', work: 'Work' }}
                        {log_lvl} />
                </div>

                <div class="field_group">
                    <label for="e_start" class="text-surface-500 mb-1 block text-xs font-bold uppercase">Start (Datetime + Conversion)</label>
                    <AE_Obj_Field_Editor
                        id="e_start"
                        object_type="journal_entry"
                        object_id={test_journal_entry_id}
                        field_name="start_datetime"
                        current_value={$lq__test_journal_entry.start_datetime}
                        field_type="datetime"
                        edit_label="Event Start"
                        {log_lvl} />
                </div>

                <div class="field_group">
                    <label for="j_summary" class="text-surface-500 mb-1 block text-xs font-bold uppercase">Summary (CodeMirror)</label>
                    <AE_Obj_Field_Editor
                        id="j_summary"
                        object_type="journal"
                        object_id={test_journal_id}
                        field_name="summary"
                        current_value={$lq__test_journal.summary}
                        field_type="codemirror"
                        display_block={true}
                        {log_lvl} />
                </div>

                <div class="field_group">
                    <label for="j_code" class="text-surface-500 mb-1 block text-xs font-bold uppercase">Code (New: Email/URL/Tel)</label>
                    <AE_Obj_Field_Editor
                        id="j_code"
                        object_type="journal"
                        object_id={test_journal_id}
                        field_name="code"
                        current_value={$lq__test_journal.code}
                        field_type="email"
                        placeholder="test@example.com"
                        {log_lvl} />
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div class="field_group">
                        <label for="e_priority" class="text-surface-500 mb-1 block text-xs font-bold uppercase">Priority</label>
                        <AE_Obj_Field_Editor
                            id="e_priority"
                            object_type="journal_entry"
                            object_id={test_journal_entry_id}
                            field_name="priority"
                            current_value={$lq__test_journal_entry.priority}
                            field_type="checkbox"
                            {log_lvl} />
                    </div>
                    <div class="field_group">
                        <label for="e_enable" class="text-surface-500 mb-1 block text-xs font-bold uppercase">Enable</label>
                        <AE_Obj_Field_Editor
                            id="e_enable"
                            object_type="journal_entry"
                            object_id={test_journal_entry_id}
                            field_name="enable"
                            current_value={$lq__test_journal_entry.enable}
                            field_type="checkbox"
                            {log_lvl} />
                    </div>
                </div>
            </section>
        {:else}
            <div class="card variant-soft-surface flex flex-col items-center justify-center gap-4 p-10 opacity-50">
                <LoaderCircle size="32" class="animate-spin" />
                <p class="text-sm font-bold">Loading Test Objects...</p>
            </div>
        {/if}
    </div>

    <!-- DEBUG FOOTER -->
    <section class="border-surface-200-800 bg-surface-100-900 rounded-lg border p-4">
        <h2 class="mb-3 font-bold">Debug Context</h2>
        <div class="grid grid-cols-2 gap-4 font-mono text-xs lg:grid-cols-4">
            <div class="bg-surface-950 text-success-500 rounded p-2">
                <strong>Edit Mode:</strong> {$ae_loc.edit_mode}
            </div>
            <div class="bg-surface-950 text-success-500 rounded p-2">
                <strong>Journal:</strong> {$lq__test_journal ? 'OK' : '...'}
            </div>
            <div class="bg-surface-950 text-success-500 rounded p-2">
                <strong>Entry:</strong> {$lq__test_journal_entry ? 'OK' : '...'}
            </div>
            <div class="bg-surface-950 text-primary-500 rounded p-2">
                <strong>JS:</strong> Svelte 5 Runes
            </div>
        </div>
    </section>
</div>
