<script lang="ts">
    interface Props {
        /** @type {import('./$types').PageData} */
        data: any;
        log_lvl?: number;
    }

    let { data, log_lvl = 0 }: Props = $props();

    import { untrack } from 'svelte';
    import { liveQuery } from 'dexie';

    import { ae_loc } from '$lib/stores/ae_stores';
    import { db_events } from '$lib/ae_events/db_events';
    import { events_loc } from '$lib/stores/ae_events_stores';
    import { page } from '$app/state';
    import { ArrowLeft, Eye, LoaderCircle, Mail, Printer } from 'lucide-svelte';

    import Comp_badge_obj_view from '../ae_comp__badge_obj_view.svelte';
    import Comp_badge_obj_view_v2 from '../ae_comp__badge_obj_view_v2.svelte';
    import Comp_badge_print_controls from '../ae_comp__badge_print_controls.svelte';

    // V2 toggle: temporary — lets staff compare auto-scaling text (v2) vs heuristic sizing (v1).
    // Remove once v2 is verified and v1 is retired.
    let use_v2 = $state(false);

    let event_badge_id = $derived(page.params.badge_id);
    let event_id = $derived(page.params.event_id);

    let is_loading_idb = $state(true);

    let lq__event_badge_obj = $derived(
        liveQuery(async () => {
            if (!event_badge_id) return null;
            return await db_events.badge.get(event_badge_id);
        })
    );

    $effect(() => {
        if ($lq__event_badge_obj !== undefined) {
            untrack(() => (is_loading_idb = false));
        }
    });

    let lq__event_badge_template_obj = $derived(
        liveQuery(async () => {
            return await db_events.badge_template.get(
                $lq__event_badge_obj?.event_badge_template_id ?? ''
            );
        })
    );

    // Access level shortcuts
    let is_trusted = $derived($ae_loc.trusted_access === true);
    let is_edit_mode = $derived($ae_loc.edit_mode === true);

    // Print state derived from badge
    let print_count = $derived($lq__event_badge_obj?.print_count ?? 0);
    let is_printed = $derived(print_count >= 1);

    function build_review_url(): string {
        // TODO: append ?passcode=... when person_passcode is added to the event_badge schema
        return `/events/${$lq__event_badge_obj?.event_id}/badges/${$lq__event_badge_obj?.event_badge_id}/review`;
    }

    function obscure_email(email: string | null | undefined): string {
        if (!email) return '';
        const at = email.indexOf('@');
        if (at < 0) return email;
        return `${email.slice(0, Math.min(3, at))}***${email.slice(at)}`;
    }

    // TODO: replace alert with actual email API call when available
    function send_review_email() {
        const badge = $lq__event_badge_obj;
        const name =
            badge?.full_name_override
            ?? badge?.full_name
            ?? `${badge?.given_name ?? ''} ${badge?.family_name ?? ''}`.trim();
        const email = is_trusted
            ? (badge?.email ?? '(no email on file)')
            : obscure_email(badge?.email);
        const event_name = $events_loc?.title ?? 'this event';
        alert(`PLACEHOLDER: An email will be sent to ${name} at ${email}. Use that link to review your ${event_name} badge.`);
    }

    // Print mode: display only — ae_comp__badge_obj_view handles print count + window.print()
    // The "Print Now" header button below only triggers window.print() for convenience;
    // print count is incremented by the print button inside ae_comp__badge_obj_view.

    // Font size overrides (px). null = auto-sizing from ae_comp__badge_obj_view.
    // Controls live in Comp_badge_print_controls (right panel) via $bindable().
    // Constants and adjust logic are defined there; only the state lives here so
    // the values can be forwarded to both the controls and the badge render.
    let font_size_name: number | null = $state(null);
    let font_size_title: number | null = $state(null);
    let font_size_affiliations: number | null = $state(null);
    let font_size_location: number | null = $state(null);
</script>

<svelte:head>
    <title>
        &AElig;: Print Badge —
        {$lq__event_badge_obj?.full_name_override ?? $lq__event_badge_obj?.full_name ?? '—'}
        {$events_loc?.title ? ` — ${$events_loc.title}` : ''}
    </title>

    <!--
        @page rule sets paper size for the browser print dialog.
        Scoped per layout code from the badge template.

        Epson 4×5 fanfold:  front (5") + back (5") = 10" strip, 4" wide.
        Zebra ZC10L PVC:    single card, 3.5" × 5.5", single-sided (duplex=0).
        Default (4×6):      front (6") + back (6") = 12" strip, 4" wide.

        @page cannot use selector scoping — it must be top-level CSS — so we inject
        it dynamically here based on the template's layout field rather than putting
        it in the compiled layout CSS files.
    -->
    {#if $lq__event_badge_template_obj?.layout === 'badge_3.5x5.5_pvc'}
        <style>
            @page { size: 3.5in 5.5in; margin: 0; }
            @media print { body { margin: 0; padding: 0; } .event_badge_wrapper { gap: 0 !important; padding: 0 !important; } }
        </style>
    {:else if $lq__event_badge_template_obj?.layout === 'badge_4x5_fanfold'}
        <style>
            @page { size: 4in 10in; margin: 0; }
            @media print { body { margin: 0; padding: 0; } .event_badge_wrapper { gap: 0 !important; padding: 0 !important; } }
        </style>
    {:else}
        <!-- Default: badge_4x6_fanfold or layout not yet set -->
        <style>
            @page { size: 4in 12in; margin: 0; }
            @media print { body { margin: 0; padding: 0; } .event_badge_wrapper { gap: 0 !important; padding: 0 !important; } }
        </style>
    {/if}

    <!-- External client CSS: brand colors, logo sizing, footer stripe colors per event.
         Set style_href on the badge template. Edit the file on the static server and
         refresh to update mid-event without any deployment. -->
    {#if $lq__event_badge_template_obj?.style_href}
        <link rel="stylesheet" href={$lq__event_badge_template_obj.style_href} />
    {/if}
</svelte:head>

{#if $lq__event_badge_obj && $lq__event_badge_obj.event_id && event_badge_id}

    <!-- Print chrome: hidden when browser prints (print:hidden) -->
    <header class="print:hidden w-full flex flex-row flex-wrap gap-2 items-center justify-between border-b border-gray-300 mb-3 pb-2">

        <!-- Left: Back to Search + name + already-printed warning -->
        <div class="flex flex-row gap-2 items-center min-w-0">
            <a
                href={`/events/${$lq__event_badge_obj.event_id}/badges`}
                class="btn btn-sm preset-tonal-surface flex items-center gap-1 shrink-0"
                title="Back to badge search"
            >
                <ArrowLeft size="1em" />
                <span class="hidden sm:inline">Search</span>
            </a>
            <div class="flex flex-col min-w-0">
                <h2 class="text-base font-bold truncate">
                    {$lq__event_badge_obj.full_name_override ?? $lq__event_badge_obj.full_name ?? '— no name —'}
                </h2>
                {#if is_printed}
                    <p class="text-xs text-amber-600 font-medium">
                        Printed {print_count}×
                        {#if $lq__event_badge_obj.print_last_datetime}
                            — last {new Date($lq__event_badge_obj.print_last_datetime).toLocaleString()}
                        {/if}
                    </p>
                {/if}
            </div>
        </div>

        <!-- Right: Action buttons -->
        <div class="flex flex-row gap-1 items-center shrink-0">

            <!-- V1/V2 toggle: temporary comparison tool — remove once v2 is verified -->
            <button
                type="button"
                class="btn btn-sm preset-tonal-surface flex items-center gap-1 font-mono"
                onclick={() => (use_v2 = !use_v2)}
                title={use_v2 ? 'Switch to v1 (heuristic sizing)' : 'Switch to v2 (auto-scaling text)'}
            >
                {use_v2 ? 'v2' : 'v1'}
            </button>

            <!-- 1. Print Now: Trusted+, not printed OR Edit Mode (reprint) -->
            {#if is_trusted && (!is_printed || is_edit_mode)}
                <button
                    type="button"
                    class="btn btn-sm preset-tonal-primary flex items-center gap-1"
                    onclick={() => window.print()}
                    title={is_printed ? `Reprint badge (printed ${print_count}×)` : 'Print badge now'}
                >
                    <Printer size="1em" />
                    {#if is_printed}
                        <span class="font-bold text-xs">{print_count}×</span>
                    {/if}
                    <span class="hidden sm:inline">Print Now</span>
                </button>
            {/if}

            <!-- 2. Direct Review link: Trusted + Edit Mode -->
            {#if is_trusted && is_edit_mode}
                <a
                    href={build_review_url()}
                    class="btn btn-sm preset-tonal-secondary flex items-center gap-1"
                    title="Open badge review page"
                >
                    <Eye size="1em" />
                    <span class="hidden sm:inline">Review</span>
                </a>
            {/if}

            <!-- 3. Email Review Link: all if not printed; Trusted+Edit if printed
                 TODO: replace alert with actual email API call -->
            {#if !is_printed || (is_trusted && is_edit_mode)}
                <button
                    type="button"
                    class="btn btn-sm preset-tonal-surface flex items-center gap-1"
                    onclick={() => send_review_email()}
                    title="Email a review link to this attendee"
                >
                    <Mail size="1em" />
                    <span class="hidden sm:inline">Email Link</span>
                </button>
            {/if}

        </div>
    </header>

    <!-- Badge render — controls panel is fixed to the right viewport edge (out of flow),
         so the badge gets the full available width on any screen size.
         pr-64 offsets the badge area so it's not hidden under the fixed controls panel.
         On print, pr-64 is cleared and the fixed controls panel is hidden. -->
    <div class="print:pr-0 pr-64">
        {#if use_v2}
            <!-- V2: pass null directly (not ?? undefined) so auto-scaling is active by default.
                 null → Element_fit_text auto-scales; a number → manual override from print controls. -->
            <Comp_badge_obj_view_v2
                event_id={$lq__event_badge_obj.event_id as string}
                event_badge_id={event_badge_id as string}
                {lq__event_badge_obj}
                {lq__event_badge_template_obj}
                is_review_mode={false}
                font_size_name={font_size_name}
                font_size_title={font_size_title}
                font_size_affiliations={font_size_affiliations}
                font_size_location={font_size_location}
            />
        {:else}
            <Comp_badge_obj_view
                event_id={$lq__event_badge_obj.event_id as string}
                event_badge_id={event_badge_id as string}
                {lq__event_badge_obj}
                {lq__event_badge_template_obj}
                is_review_mode={false}
                font_size_name={font_size_name ?? undefined}
                font_size_title={font_size_title ?? undefined}
                font_size_affiliations={font_size_affiliations ?? undefined}
                font_size_location={font_size_location ?? undefined}
            />
        {/if}
    </div>

    <!-- Controls panel: fixed to the right edge of the viewport — screen-only.
         w-64 (256px) matches pr-64 above. top-20 clears the page header (~80px).
         Independently scrollable. Always visible regardless of viewport width. -->
    <div class="print:hidden fixed right-0 top-20 bottom-0 w-64 overflow-y-auto z-30
                border-l border-gray-200 dark:border-gray-700
                bg-white dark:bg-zinc-900 p-2">
        <Comp_badge_print_controls
            event_id={$lq__event_badge_obj.event_id as string}
            event_badge_id={event_badge_id as string}
            {lq__event_badge_obj}
            {lq__event_badge_template_obj}
            bind:font_size_name
            bind:font_size_title
            bind:font_size_affiliations
            bind:font_size_location
        />
    </div>

{:else if is_loading_idb || !event_badge_id}
    <div class="flex flex-col items-center justify-center p-20 gap-4 opacity-50">
        <LoaderCircle size="3em" class="animate-spin" />
        <p class="text-xl font-bold text-center">Loading Badge...</p>
    </div>
{:else}
    <div class="card p-8 text-center space-y-4">
        <h2 class="text-2xl font-bold text-error-500">Badge Not Found</h2>
        <p class="opacity-70">No record found for ID: <span class="font-mono">{event_badge_id}</span></p>
        <div class="flex gap-2 justify-center">
            <button class="btn preset-filled-primary" onclick={() => window.location.reload()}>
                Retry
            </button>
            <a href={`/events/${event_id}/badges`} class="btn preset-tonal-surface">
                Back to Search
            </a>
        </div>
    </div>
{/if}
