<script lang="ts">
import { onMount } from 'svelte';
import { PUBLIC_AE_BOOTSTRAP_KEY } from '$env/static/public';

// import { api } from '$lib/ae_api/api';
import { ae_loc, ae_api, ae_sess } from '$lib/stores/ae_stores';
// import { get_object } from '$lib/ae_api/api_get_object';
import { post_object } from '$lib/ae_api/api_post_object';
import { patch_object } from '$lib/ae_api/api_patch_object';
import {
    ArrowRightLeft,
    Bug,
    Building2,
    CircleCheck,
    Code,
    Contact,
    Database,
    Eye,
    EyeOff,
    FlaskConical,
    Globe,
    Info,
    Key,
    MapPin,
    RefreshCcw,
    Satellite,
    Server,
    Settings2,
    ShieldAlert,
    ShieldCheck,
    Trash2,
    Unlock,
    User,
    UserCheck,
    Users,
    Zap
} from '@lucide/svelte';
// Core Module Imports
import { load_ae_obj_li__account } from '$lib/ae_core/ae_core__account';
import { lookup_site_domain } from '$lib/ae_core/ae_core__site';
import { load_ae_obj_id__user } from '$lib/ae_core/ae_core__user';
import { db_core } from '$lib/ae_core/db_core';
import { launcher_loc } from '$lib/stores/ae_events_stores__launcher.svelte';

// State Variables
let test_result: any = $state(null);
let trace_details: any = $state(null);
let test_fqdn = $state('');
let db_counts: Record<string, number> = $state({});
let show_raw_keys = $state(false);

// Trace Controls
let trace_use_jwt = $state(true);
let trace_jwt_method = $state('header'); // 'header' or 'url'
let trace_use_bypass = $state(false);
let trace_agent_key = PUBLIC_AE_BOOTSTRAP_KEY;
let trace_use_agent_key = $state(false);

onMount(async () => {
    console.log('Testing Dashboard: +page.svelte mounted');
    await update_db_counts();
});

async function update_db_counts() {
    try {
        db_counts = {
            user: await db_core.user.count(),
            person: await db_core.person.count(),
            account: await db_core.account.count(),
            address: await db_core.address.count(),
            contact: await db_core.contact.count(),
            site: await db_core.site.count()
        };
    } catch (e) {
        console.error('Failed to get DB counts:', e);
    }
}

async function run_test(name: string, test_fn: () => Promise<any>) {
    test_result = 'loading...';
    trace_details = null;
    try {
        const result = await test_fn();
        test_result = {
            test: name,
            timestamp: new Date().toISOString(),
            result
        };
        await update_db_counts();
    } catch (error: any) {
        test_result = { test: name, error: error.message, details: error };
    }
}

async function run_trace_test() {
    test_result = 'loading...';
    const endpoint = '/v3/crud/journal/';
    const params: Record<string, any> = { limit: 1 };

    const custom_headers: Record<string, string> = {};
    const active_key = trace_use_agent_key
        ? trace_agent_key
        : $ae_api.api_secret_key;
    custom_headers['x-aether-api-key'] = active_key;

    if (trace_use_bypass) {
        custom_headers['x-no-account-id'] = 'bypass';
    } else {
        custom_headers['x-account-id'] = $ae_loc.account_id || 'nqOzejLCDXM';
    }

    if (trace_use_jwt && $ae_loc.jwt) {
        if (trace_jwt_method === 'header') {
            custom_headers['Authorization'] = `Bearer ${$ae_loc.jwt}`;
        } else {
            params['jwt'] = $ae_loc.jwt;
        }
    }

    trace_details = {
        request: {
            method: 'GET',
            url: `${$ae_api.base_url}${endpoint}`,
            params,
            headers: custom_headers
        }
    };

    try {
        const url = new URL(endpoint, $ae_api.base_url);
        Object.keys(params).forEach((k) =>
            url.searchParams.append(k, String(params[k]))
        );

        const response = await fetch(url.toString(), {
            method: 'GET',
            headers: custom_headers
        });

        const status = response.status;
        const statusText = response.statusText;
        let body;
        try {
            body = await response.json();
        } catch (e) {
            body = await response.text();
        }

        trace_details.response = { status, statusText, body };
        test_result = {
            test: 'V3 Journal Trace',
            status,
            success: response.ok
        };
    } catch (error: any) {
        test_result = { test: 'V3 Journal Trace', error: error.message };
        trace_details.response_error = error;
    }
}

const test_site_domain_lookup = () =>
    run_test('Site Domain Lookup', async () => {
        const fqdn = test_fqdn || window.location.host;
        return await lookup_site_domain({ api_cfg: $ae_api, fqdn, log_lvl: 1 });
    });

const test_load_accounts = () =>
    run_test('Load Accounts', async () => {
        return await load_ae_obj_li__account({
            api_cfg: $ae_api,
            enabled: 'all',
            log_lvl: 1
        });
    });

const test_whoami = () =>
    run_test('Who Am I? (JWT Test)', async () => {
        if (!$ae_loc.user_id) throw new Error('No user_id found in session.');
        return await load_ae_obj_id__user({
            api_cfg: $ae_api,
            user_id: $ae_loc.user_id,
            try_cache: false,
            log_lvl: 1
        });
    });

const clear_local_cache = () =>
    run_test('Clear Local Cache', async () => {
        await Promise.all([
            db_core.user.clear(),
            db_core.person.clear(),
            db_core.account.clear(),
            db_core.address.clear(),
            db_core.contact.clear(),
            db_core.site.clear()
        ]);
        return 'Local cache cleared successfully';
    });

const test_manifest = () =>
    run_test('PWA Manifest Lookup', async () => {
        const response = await fetch('/manifest.webmanifest');
        if (!response.ok)
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        return await response.json();
    });

// V3 Schema & Error Validation
const test_permissive_mode = () =>
    run_test('Permissive Mode Test', async () => {
        // Capture current state at test time
        const current_ae_api = $ae_api;
        const current_ae_loc = $ae_loc;

        const endpoint = `/v3/crud/account/${current_ae_loc.account_id || 'ghost'}`;
        const data = {
            name: current_ae_loc.account_name,
            _non_existent_field: 'This should be ignored by the API'
        };

        console.log('Permissive Mode: Starting PATCH test...', {
            endpoint,
            headers: current_ae_api.headers
        });

        const result = await patch_object({
            api_cfg: current_ae_api,
            endpoint,
            data,
            log_lvl: 1
        });

        if (!result)
            throw new Error(
                'API returned false. Check console for 401/403/500 errors.'
            );

        return {
            message:
                'SUCCESS: API accepted request with unknown field (Permissive Mode Active)',
            account_id: result.account_id,
            id_vision:
                typeof result.account_id === 'string'
                    ? 'V3 (String)'
                    : 'LEGACY (Integer)',
            returned_data: result
        };
    });

const test_structured_error = () =>
    run_test('Structured Error Validation (Deliberate 400)', async () => {
        const current_ae_api = $ae_api;

        // Use the exact Recovery Meetings search pattern to verify why it's throwing 403
        const endpoint = `/v3/crud/event/search`;
        const search_query = {
            and: [
                { field: 'conference', op: 'eq', value: 0 },
                {
                    field: 'trigger_schema_violation_400',
                    op: 'eq',
                    value: 'fail'
                }
            ]
        };

        console.log(
            'Structured Error: Starting deliberate 400 test with Recovery filters...',
            { endpoint }
        );

        const result = await post_object({
            api_cfg: current_ae_api,
            endpoint,
            data: search_query,
            log_lvl: 1
        });

        // In Structured Error Mode, the helper returns the JSON object if it contains meta.details
        if (result?.meta?.details) {
            return {
                success: true,
                message: 'PASS: Successfully extracted rich error metadata',
                source:
                    result.meta.details.category === 'validation'
                        ? 'FastAPI Detail (Wrapped)'
                        : 'V3 Meta Envelope',
                details: result.meta.details
            };
        }

        return {
            success: false,
            message:
                'FAIL: API returned an error but the helper could not extract metadata.',
            raw_result: result
        };
    });

// Environment Diagnostics
let is_native = $derived(
    typeof window !== 'undefined' && !!(window as any).native_app
);
let app_mode = $derived(launcher_loc.current.app_mode || 'web');

// Derived state for Header Inspection - dynamically reconstruct standard request headers
let active_headers = $derived({
    ...($ae_api.headers || {}),
    'x-account-id': $ae_loc.account_id || '(missing)',
    Authorization: $ae_loc.jwt
        ? `Bearer ${$ae_loc.jwt.slice(0, 10)}...`
        : '(missing)'
});
</script>

<!-- Outer wrapper to enable scrolling if parent is overflow-hidden -->
<div class="h-full w-full overflow-x-hidden overflow-y-auto bg-transparent">
    <div class="container mx-auto space-y-8 p-4 pb-20">
        <header
            class="bg-surface-50-900-token rounded-container flex items-center justify-between border border-gray-500 p-6 shadow-xl">
            <div class="space-y-1">
                <h1 class="h1 flex items-center gap-3">
                    <Bug class="text-error-500" /> System Testing
                </h1>
                <p class="text-sm opacity-60">
                    Validation dashboard for Aether Platform V3
                </p>
            </div>
            <div class="flex gap-4">
                <div
                    class="card variant-soft-secondary flex items-center gap-4 p-3 shadow-inner">
                    <div class="flex flex-col items-center px-2">
                        <span class="font-bold">{db_counts.user ?? 0}</span>
                        <span class="text-[10px] uppercase opacity-60"
                            >Users</span>
                    </div>
                    <div class="divider-vertical h-8 border-l border-gray-500">
                    </div>
                    <div class="flex flex-col items-center px-2">
                        <span class="font-bold">{db_counts.person ?? 0}</span>
                        <span class="text-[10px] uppercase opacity-60"
                            >People</span>
                    </div>
                    <div class="divider-vertical h-8 border-l border-gray-500">
                    </div>
                    <button
                        class="btn-icon btn-icon-sm hover:variant-filled-secondary transition-all"
                        onclick={update_db_counts}
                        title="Refresh Row Counts">
                        <RefreshCcw size={14} />
                    </button>
                </div>
            </div>
        </header>

        <div class="grid grid-cols-1 gap-8 xl:grid-cols-[1fr_400px]">
            <main class="space-y-6">
                <!-- Environment & Bridge Card -->
                <div
                    class="card variant-soft-tertiary space-y-4 border border-gray-500 p-6 shadow-lg">
                    <header
                        class="flex items-center justify-between border-b border-gray-500 pb-3">
                        <div
                            class="text-tertiary-700 dark:text-tertiary-300 flex items-center gap-2">
                            <Satellite size={20} />
                            <h3 class="h3 font-bold">
                                Environment & Bridge Diagnostics
                            </h3>
                        </div>
                        <span
                            class="badge variant-filled-tertiary p-2 font-mono uppercase">
                            Runtime: {is_native ? 'Electron' : 'Web Browser'}
                        </span>
                    </header>
                    <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
                        <div
                            class="flex flex-col rounded bg-gray-500/10 p-3"
                            title="The current logic mode of the application (e.g. native, onsite, web).">
                            <span
                                class="text-[10px] font-bold uppercase opacity-50"
                                >App Mode</span>
                            <span
                                class="text-tertiary-600 dark:text-tertiary-400 text-sm font-bold tracking-widest uppercase"
                                >{app_mode}</span>
                        </div>
                        <div
                            class="flex flex-col rounded bg-gray-500/10 p-3"
                            title="Presence of window.native_app bridge object.">
                            <span
                                class="text-[10px] font-bold uppercase opacity-50"
                                >Bridge Detected</span>
                            <div class="flex items-center gap-2">
                                <div
                                    class="h-2 w-2 rounded-full {is_native
                                        ? 'bg-success-500 animate-pulse'
                                        : 'bg-surface-500'}">
                                </div>
                                <span class="text-sm font-semibold"
                                    >{is_native
                                        ? 'Active'
                                        : 'Missing / Inactive'}</span>
                            </div>
                        </div>
                        <div
                            class="flex flex-col rounded bg-gray-500/10 p-3"
                            title="The host string being used for bootstrap site resolution.">
                            <span
                                class="text-[10px] font-bold uppercase opacity-50"
                                >Bootstrap Host</span>
                            <span class="truncate font-mono text-xs"
                                >{$ae_loc.hostname || '--'}</span>
                        </div>
                    </div>
                </div>

                <!-- Header Inspection Card -->
                <div
                    class="card variant-soft-primary space-y-4 border border-gray-500 p-6 shadow-lg">
                    <header
                        class="flex items-center justify-between border-b border-gray-500 pb-3">
                        <div
                            class="text-primary-700 dark:text-primary-300 flex items-center gap-2">
                            <Settings2 size={20} />
                            <h3 class="h3 font-bold">
                                Live V3 Header Inspection
                            </h3>
                        </div>
                        <span
                            class="font-mono text-[10px] tracking-tighter uppercase opacity-50"
                            >Real-time API Store View</span>
                    </header>
                    <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                        {#each Object.entries(active_headers) as [key, value] (key)}
                            <div
                                class="flex items-center justify-between rounded border border-gray-500/20 bg-gray-500/10 p-3">
                                <span
                                    class="font-mono text-[10px] font-bold opacity-70"
                                    >{key}</span>
                                <span
                                    class="font-mono text-xs {key ===
                                    'x-ae-ignore-extra-fields'
                                        ? 'text-success-500 font-bold'
                                        : ''}">
                                    {key.includes('key') ||
                                    key.includes('token') ||
                                    key.includes('account')
                                        ? '********'
                                        : value}
                                </span>
                            </div>
                        {/each}
                    </div>
                </div>

                <!-- Session Context Card -->
                <div
                    class="card variant-soft-surface space-y-4 border border-gray-500 p-6 shadow-lg">
                    <header
                        class="flex items-center justify-between border-b border-gray-500 pb-3">
                        <div
                            class="text-surface-700 dark:text-surface-300 flex items-center gap-2">
                            <User size={20} />
                            <h3 class="h3 font-bold">Active Session Context</h3>
                        </div>
                        <span
                            class="badge variant-filled-primary p-2 font-mono"
                            title="Your current logical rank in the application (e.g. super, manager, trusted).">
                            Level: {$ae_loc.access_type || 'anonymous'}
                        </span>
                    </header>
                    <div class="grid grid-cols-2 gap-4 md:grid-cols-4">
                        <div
                            class="flex flex-col rounded bg-gray-500/10 p-3"
                            title="The Aether Username from the User object.">
                            <span
                                class="text-[10px] font-bold uppercase opacity-50"
                                >Username</span>
                            <span class="truncate font-mono text-sm"
                                >{$ae_loc.user?.username || '--'}</span>
                        </div>
                        <div
                            class="flex flex-col rounded bg-gray-500/10 p-3"
                            title="Full Name from the linked Person object.">
                            <span
                                class="text-[10px] font-bold uppercase opacity-50"
                                >Full Name</span>
                            <span class="truncate text-sm font-semibold"
                                >{$ae_loc.person?.full_name || '--'}</span>
                        </div>
                        <div
                            class="flex flex-col items-center rounded bg-gray-500/10 p-3"
                            title="TRUE if session has matched a 'Trusted' level site passcode.">
                            <span
                                class="text-[10px] font-bold uppercase opacity-50"
                                >Trusted</span>
                            <div class="mt-1 flex items-center gap-1">
                                {#if $ae_loc.trusted_access}
                                    <ShieldCheck
                                        size={18}
                                        class="text-success-500" />
                                    <span
                                        class="text-success-500 text-[10px] font-bold uppercase"
                                        >YES</span>
                                {:else}
                                    <Unlock size={18} class="opacity-30" />
                                    <span
                                        class="text-[10px] font-bold uppercase opacity-30"
                                        >NO</span>
                                {/if}
                            </div>
                        </div>
                        <div
                            class="flex flex-col items-center rounded bg-gray-500/10 p-3"
                            title="TRUE if user has signed in with credentials (Username/Email).">
                            <span
                                class="text-[10px] font-bold uppercase opacity-50"
                                >Authenticated</span>
                            <div class="mt-1 flex items-center gap-1">
                                {#if $ae_loc.authenticated_access}
                                    <ShieldCheck
                                        size={18}
                                        class="text-success-500" />
                                    <span
                                        class="text-success-500 text-[10px] font-bold uppercase"
                                        >YES</span>
                                {:else}
                                    <Unlock size={18} class="opacity-30" />
                                    <span
                                        class="text-[10px] font-bold uppercase opacity-30"
                                        >NO</span>
                                {/if}
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Security Dashboard -->
                <div
                    class="card variant-soft-warning border-warning-500 space-y-6 border p-6 shadow-lg">
                    <header
                        class="border-warning-500 flex items-center justify-between border-b pb-3">
                        <div
                            class="text-warning-700 dark:text-warning-500 flex items-center gap-2">
                            <Key size={20} />
                            <h3 class="h3 font-bold">API Security Controls</h3>
                        </div>
                        <button
                            class="btn btn-sm variant-filled-warning shadow-md transition-all hover:scale-105"
                            onclick={() => (show_raw_keys = !show_raw_keys)}
                            title="Toggle visibility of the raw secret keys for character verification.">
                            {#if show_raw_keys}
                                <EyeOff size={14} class="mr-2" /> Hide Raw
                            {:else}
                                <Eye size={14} class="mr-2" /> Inspect Raw
                            {/if}
                        </button>
                    </header>

                    <div class="grid grid-cols-1 gap-6 md:grid-cols-3">
                        <label class="label space-y-2">
                            <span
                                class="flex items-center gap-1 text-[10px] font-bold uppercase opacity-70"
                                title="Primary secret key identifying this application. Required for ALL V3 requests. Sent as 'x-aether-api-key'.">
                                Active API Key <span class="text-secondary-500"
                                    ><Info size={10} /></span>
                            </span>
                            <div
                                class="bg-surface-500/10 flex overflow-hidden rounded-lg border border-gray-500 shadow-sm">
                                <input
                                    type={show_raw_keys ? 'text' : 'password'}
                                    readonly
                                    value={$ae_api.api_secret_key || 'MISSING'}
                                    class="flex-1 border-none bg-transparent p-3 font-mono text-xs focus:ring-0" />
                                <div
                                    class="flex items-center bg-gray-500/20 p-3">
                                    {#if $ae_api.api_secret_key}<CircleCheck
                                            size="1em"
                                            class="text-success-500" />{:else}<CircleCheck
                                            size="1em"
                                            class="opacity-20" />{/if}
                                </div>
                            </div>
                        </label>
                        <label class="label space-y-2">
                            <span
                                class="flex items-center gap-1 text-[10px] font-bold uppercase opacity-70"
                                title="Token received after successful user login. Stored in localStorage ($ae_loc.jwt). Required for multi-tenant isolation.">
                                Local JWT Store <span class="text-secondary-500"
                                    ><Info size={10} /></span>
                            </span>
                            <div
                                class="bg-surface-500/10 flex overflow-hidden rounded-lg border border-gray-500 shadow-sm">
                                <input
                                    type={show_raw_keys ? 'text' : 'password'}
                                    readonly
                                    value={$ae_loc.jwt || 'No Token'}
                                    class="flex-1 border-none bg-transparent p-3 font-mono text-xs focus:ring-0" />
                                <div
                                    class="flex items-center bg-gray-500/20 p-3">
                                    {#if $ae_loc.jwt}<Key
                                            size="1em"
                                            class="text-warning-500" />{:else}<Key
                                            size="1em"
                                            class="opacity-20" />{/if}
                                </div>
                            </div>
                        </label>
                        <label class="label space-y-2">
                            <span
                                class="flex items-center gap-1 text-[10px] font-bold uppercase opacity-70"
                                title="Verifies if the Local JWT has been synced to the active API configuration ($ae_api.jwt).">
                                Sync Status <span class="text-secondary-500"
                                    ><Info size={10} /></span>
                            </span>
                            <div
                                class="card flex h-[46px] items-center justify-center border border-gray-500 bg-transparent p-2 text-center text-xs font-bold shadow-sm">
                                {#if $ae_api.jwt === $ae_loc.jwt}
                                    <span
                                        class="text-success-600 dark:text-success-400 flex items-center gap-1"
                                        ><ShieldCheck size={14} /> HANDSHAKE OK</span>
                                {:else}
                                    <span
                                        class="text-error-600 dark:text-error-400 flex items-center gap-1"
                                        ><ShieldAlert size={14} /> MISMATCH</span>
                                {/if}
                            </div>
                        </label>
                    </div>

                    {#if show_raw_keys}
                        <div
                            class="rounded-container space-y-2 border border-gray-500 bg-black/20 p-4 font-mono text-[10px] break-all shadow-inner">
                            <p
                                class="text-warning-500 flex items-center gap-2 border-b border-gray-500 pb-1 font-bold tracking-widest uppercase">
                                <Bug size={12} /> Raw Strings
                            </p>
                            <div
                                class="grid grid-cols-[80px_1fr] gap-x-2 gap-y-1">
                                <span class="opacity-50">CUR_KEY:</span>
                                <span>{$ae_api.api_secret_key}</span>
                                <span class="opacity-50">AGT_KEY:</span>
                                <span>{trace_agent_key}</span>
                                <span class="opacity-50">LOC_JWT:</span>
                                <span>{$ae_loc.jwt || 'NULL'}</span>
                            </div>
                        </div>
                    {/if}

                    <div class="space-y-4 border-t border-gray-500 pt-6">
                        <header class="flex items-center gap-2">
                            <FlaskConical
                                size={18}
                                class="text-secondary-500" />
                            <h4 class="h4 font-bold">V3 Trace Controls</h4>
                        </header>
                        <div
                            class="rounded-container space-y-4 border border-gray-500 bg-gray-500/5 p-4 shadow-inner">
                            <div class="flex flex-wrap gap-6 text-sm">
                                <label
                                    class="group flex cursor-pointer items-center gap-2"
                                    title="When checked, the request will include the JWT token. Mandatory for nearly all V3 CRUD calls.">
                                    <input
                                        type="checkbox"
                                        class="checkbox"
                                        bind:checked={trace_use_jwt} />
                                    <span
                                        class="group-hover:text-secondary-500 transition-colors"
                                        >Include JWT</span>
                                </label>
                                <label
                                    class="group flex cursor-pointer items-center gap-2"
                                    title="Sets 'x-no-account-id: bypass'. Combined with valid API Key, grants superuser access across all accounts.">
                                    <input
                                        type="checkbox"
                                        class="checkbox"
                                        bind:checked={trace_use_bypass} />
                                    <span
                                        class="group-hover:text-error-500 transition-colors"
                                        >Bypass Header</span>
                                </label>
                                <label
                                    class="group flex cursor-pointer items-center gap-2"
                                    title="Test using the dedicated Agent API Key (IDF68...).">
                                    <input
                                        type="checkbox"
                                        class="checkbox"
                                        bind:checked={trace_use_agent_key} />
                                    <span
                                        class="text-secondary-600 font-bold underline decoration-dotted"
                                        >Use Agent Key</span>
                                </label>
                            </div>

                            <div
                                class="mt-2 flex flex-wrap gap-6 border-t border-gray-500 pt-3"
                                title="Section 6: JWT can be sent via Header (standard) or URL Parameter (for direct links/downloads).">
                                <span
                                    class="flex items-center gap-1 text-[10px] font-bold uppercase opacity-50"
                                    >JWT Method <span class="text-secondary-500"
                                        ><Info size={10} /></span
                                    >:</span>
                                <label
                                    class="flex cursor-pointer items-center gap-3">
                                    <input
                                        type="radio"
                                        name="jwt_method"
                                        value="header"
                                        bind:group={trace_jwt_method}
                                        class="radio" />
                                    <span class="text-xs font-semibold"
                                        >Header (Bearer)</span>
                                </label>
                                <label
                                    class="flex cursor-pointer items-center gap-3">
                                    <input
                                        type="radio"
                                        name="jwt_method"
                                        value="url"
                                        bind:group={trace_jwt_method}
                                        class="radio" />
                                    <span class="text-xs font-semibold"
                                        >URL Param (?jwt=)</span>
                                </label>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <button
                                class="btn variant-filled-secondary flex items-center justify-center gap-2 p-4 font-bold shadow-lg transition-all hover:brightness-110 active:scale-95"
                                onclick={run_trace_test}
                                title="Initiate GET request to /v3/crud/journal/ and capture headers.">
                                <ArrowRightLeft size={16} /> RUN TRACE
                            </button>
                            <button
                                class="btn variant-filled-warning flex items-center justify-center gap-2 p-4 font-bold shadow-lg transition-all hover:brightness-110 active:scale-95"
                                disabled={!$ae_loc.jwt}
                                onclick={test_whoami}
                                title="Verify user authentication by loading your own profile.">
                                <UserCheck size={16} /> WHO AM I?
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Trace Visualizer -->
                {#if trace_details}
                    <div
                        class="card variant-soft-secondary space-y-4 border border-gray-500 p-6 shadow-xl">
                        <header
                            class="flex items-center gap-2 border-b border-gray-500 pb-3">
                            <Code size={20} class="text-secondary-500" />
                            <h3 class="h3 font-bold">
                                Request / Response Trace
                            </h3>
                        </header>
                        <div
                            class="grid grid-cols-1 gap-6 font-mono text-[10px] md:grid-cols-2">
                            <div class="space-y-2">
                                <p
                                    class="font-bold tracking-widest uppercase opacity-70">
                                    📤 Sent
                                </p>
                                <div
                                    class="overflow-auto rounded border border-black/10 bg-black/20 p-4 shadow-inner">
                                    <p
                                        class="text-secondary-500 mb-2 font-bold">
                                        URL: {trace_details.request.url}
                                    </p>
                                    <p
                                        class="text-secondary-500 mb-1 uppercase underline">
                                        Headers:
                                    </p>
                                    <pre>{JSON.stringify(
                                            trace_details.request.headers,
                                            null,
                                            2
                                        )}</pre>
                                </div>
                            </div>
                            <div class="space-y-2">
                                <p
                                    class="font-bold tracking-widest uppercase opacity-70">
                                    📥 Received
                                </p>
                                <div
                                    class="max-h-[400px] overflow-auto rounded border border-l-4 border-black/10 bg-black/20 p-4 shadow-inner"
                                    class:border-l-success-500={test_result?.success}
                                    class:border-l-error-500={!test_result?.success}>
                                    <pre>{JSON.stringify(
                                            trace_details.response ||
                                                trace_details.response_error,
                                            null,
                                            2
                                        )}</pre>
                                </div>
                            </div>
                        </div>
                    </div>
                {/if}

                <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
                    <div
                        class="card group hover:bg-surface-500/5 space-y-4 border border-gray-500 p-6 shadow-lg transition-all">
                        <header
                            class="text-primary-500 flex items-center gap-2 border-b border-gray-500 pb-2">
                            <Server size={20} />
                            <h4 class="h4 font-bold tracking-widest uppercase">
                                Infrastructure
                            </h4>
                        </header>
                        <button
                            class="btn variant-filled-primary flex w-full items-center justify-center gap-2 p-4 shadow-md transition-all hover:scale-[1.02]"
                            onclick={test_site_domain_lookup}
                            title="Test guest site domain lookup.">
                            <Globe size={16} /> Site Domain Lookup
                        </button>
                        <button
                            class="btn variant-filled-primary flex w-full items-center justify-center gap-2 p-4 shadow-md transition-all hover:scale-[1.02]"
                            onclick={test_manifest}
                            title="Verifies the dynamic PWA manifest returns correct branding for this domain.">
                            <Code size={16} /> PWA Manifest Lookup
                        </button>
                    </div>
                    <div
                        class="card group hover:bg-surface-500/5 space-y-4 border border-gray-500 p-6 shadow-lg transition-all">
                        <header
                            class="text-secondary-500 flex items-center gap-2 border-b border-gray-500 pb-2">
                            <Database size={20} />
                            <h4 class="h4 font-bold tracking-widest uppercase">
                                Core V3
                            </h4>
                        </header>
                        <button
                            class="btn variant-filled-secondary flex w-full items-center justify-center gap-2 p-4 shadow-md transition-all hover:scale-[1.02]"
                            onclick={test_load_accounts}
                            title="Test authenticated accounts load.">
                            <Building2 size={16} /> Load Accounts
                        </button>
                    </div>
                    <div
                        class="card group hover:bg-surface-500/5 space-y-4 border border-gray-500 p-6 shadow-lg transition-all">
                        <header
                            class="text-warning-500 flex items-center gap-2 border-b border-gray-500 pb-2">
                            <ShieldAlert size={20} />
                            <h4 class="h4 font-bold tracking-widest uppercase">
                                V3 Hardening
                            </h4>
                        </header>
                        <button
                            class="btn variant-filled-warning flex w-full items-center justify-center gap-2 p-4 shadow-md transition-all hover:scale-[1.02]"
                            onclick={test_permissive_mode}
                            title="Verifies the API ignores unknown fields (x-ae-ignore-extra-fields).">
                            <Zap size={16} /> Permissive Mode Test
                        </button>
                        <button
                            class="btn variant-filled-error flex w-full items-center justify-center gap-2 p-4 shadow-md transition-all hover:scale-[1.02]"
                            onclick={test_structured_error}
                            title="Deliberately triggers a 400 error to verify rich metadata extraction.">
                            <ShieldAlert size={16} /> Structured Error Test
                        </button>
                    </div>
                </div>

                <!-- Maintenance -->
                <div
                    class="card variant-soft-error border-error-500 flex items-center justify-between border p-6 shadow-lg">
                    <div
                        class="text-error-700 dark:text-error-400 flex items-center gap-4">
                        <Trash2 size={24} />
                        <div>
                            <p class="text-lg font-bold">Cache Management</p>
                            <p
                                class="font-mono text-xs tracking-tighter uppercase italic opacity-70">
                                Wipe IndexedDB (ae_core_db)
                            </p>
                        </div>
                    </div>
                    <button
                        class="btn variant-filled-error p-4 font-bold shadow-lg transition-all hover:scale-105"
                        onclick={clear_local_cache}>CLEAR LOCAL IDB</button>
                </div>
            </main>

            <aside class="space-y-4">
                <div
                    class="card bg-surface-100 dark:bg-surface-800 sticky top-4 flex h-full max-h-[calc(100vh-2rem)] flex-col overflow-hidden border border-gray-500 p-6 shadow-2xl">
                    <header
                        class="mb-4 flex items-center justify-between border-b border-gray-500 pb-3">
                        <h3
                            class="h3 font-bold tracking-widest uppercase opacity-70">
                            Audit Result
                        </h3>
                        {#if test_result === 'loading...'}
                            <span
                                class="badge variant-filled-warning animate-pulse"
                                >RUNNING</span>
                        {:else if test_result?.success}
                            <span
                                class="badge variant-filled-success font-bold uppercase"
                                >Passed</span>
                        {:else if test_result?.error || (test_result && !test_result.success)}
                            <span
                                class="badge variant-filled-error font-bold uppercase italic"
                                >Failed</span>
                        {:else}
                            <span
                                class="badge variant-soft-surface uppercase italic opacity-50"
                                >Idle</span>
                        {/if}
                    </header>
                    <div
                        class="flex-1 overflow-auto rounded border border-black/10 bg-black/20 p-4 font-mono text-xs shadow-inner">
                        {#if test_result === 'loading...'}
                            <div
                                class="flex h-full flex-col items-center justify-center gap-4 opacity-30">
                                <RefreshCcw size={32} class="animate-spin" />
                                <p class="uppercase italic">Auditing...</p>
                            </div>
                        {:else if test_result}
                            <pre
                                class="leading-relaxed whitespace-pre-wrap text-blue-600 dark:text-blue-400">{JSON.stringify(
                                    test_result,
                                    null,
                                    2
                                )}</pre>
                        {:else}
                            <div
                                class="flex h-full flex-col items-center justify-center py-20 text-center opacity-20">
                                <Zap size={64} class="mb-4" />
                                <p class="font-bold tracking-widest uppercase">
                                    Select test to begin
                                </p>
                            </div>
                        {/if}
                    </div>
                </div>
            </aside>
        </div>
    </div>
</div>

<style lang="postcss">
/* No @apply on Skeleton tokens to prevent Tailwind 4 errors */
.checkbox {
    width: 1.25rem;
    height: 1.25rem;
    cursor: pointer;
}
.radio {
    width: 1.15rem;
    height: 1.15rem;
    cursor: pointer;
}
.btn:disabled {
    opacity: 0.3;
    filter: saturate(0);
    cursor: not-allowed;
}
</style>
