<script lang="ts">
    interface Props {
        container_class_li?: string | Array<string>;
        lq__event_badge_obj_li: any;
        log_lvl?: number;
        show_sensitive_fields?: boolean;
        hide_affiliations?: boolean;
        hide_location?: boolean;
        hide_badge_type?: boolean;
    }

    let {
        container_class_li = [],
        lq__event_badge_obj_li,
        log_lvl = $bindable(0),
        show_sensitive_fields = true,
        hide_affiliations = false,
        hide_location = false,
        hide_badge_type = false
    }: Props = $props();

    import { ae_loc } from '$lib/stores/ae_stores';
    import { events_loc } from '$lib/stores/ae_events_stores';
    import { ae_util } from '$lib/ae_utils/ae_utils';
    import {
        LoaderCircle,
        Check,
        Eye,
        EyeOff,
        Mail,
        MapPin,
        Tags,
        FileSearch,
        Link,
        Printer,
        User
    } from 'lucide-svelte';

    // Track per-badge copy state for the "Review Link" clipboard button
    let copy_status: Record<string, 'idle' | 'copied'> = $state({});

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

    /**
     * Obscures an email address for display to non-trusted users.
     * e.g. john.doe@example.com → joh***@example.com
     */
    function obscure_email(email: string | null | undefined): string {
        if (!email) return '';
        const at = email.indexOf('@');
        if (at < 0) return email;
        const visible = email.slice(0, Math.min(3, at));
        return `${visible}***${email.slice(at)}`;
    }

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

    async function copy_review_link(event_badge_obj: any) {
        const url = build_review_url(event_badge_obj);
        const full_url = window.location.origin + url;
        try {
            await navigator.clipboard.writeText(full_url);
            copy_status[event_badge_obj.event_badge_id] = 'copied';
            setTimeout(() => {
                copy_status[event_badge_obj.event_badge_id] = 'idle';
            }, 2000);
        } catch {
            console.error('Clipboard write failed');
        }
    }

    // TODO: replace alert with actual email API call when available
    function send_review_email(event_badge_obj: any) {
        const name =
            event_badge_obj?.full_name_override
            ?? event_badge_obj?.full_name
            ?? `${event_badge_obj?.given_name ?? ''} ${event_badge_obj?.family_name ?? ''}`.trim();
        const email = is_trusted
            ? (event_badge_obj?.email ?? '(no email on file)')
            : obscure_email(event_badge_obj?.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.`);
    }

    let visible_badge_obj_li = $derived(
        (() => {
            const list = $lq__event_badge_obj_li;
            if (list === undefined || list === null) return null;
            if (!Array.isArray(list)) return [];

            const filtered = list.filter((item: any) => {
                if (!item) return false;
                if (is_trusted && is_edit_mode) {
                    // Edit Mode: show all non-hidden, including already-printed
                    return !item.hide;
                }
                // Everyone else (non-trusted or trusted not in edit mode):
                // Only show badges that have not been printed yet
                return (item.print_count ?? 0) < 1 && !item.hide;
            });

            if (log_lvl)
                console.log(`visible_badge_obj_li: Input=${list.length}, Output=${filtered.length}`);
            return filtered;
        })()
    );
</script>

<section
    class="px-1 flex flex-col gap-1 items-center justify-center space-y-1 w-full max-w-7xl mx-auto"
>
    {#if visible_badge_obj_li === null}
        <div class="flex flex-col items-center justify-center p-10 opacity-50">
            <LoaderCircle size="2em" class="animate-spin mb-2" />
            <p>Loading badges...</p>
        </div>
    {:else if visible_badge_obj_li.length > 0}
        <header class="w-full flex flex-row gap-2 items-center justify-start mb-2 px-2">
            <h2 class="text-sm text-gray-500 font-normal">Results:</h2>
            <span class="badge preset-tonal-success font-bold text-lg px-3 py-1">
                {visible_badge_obj_li.length}<span class="text-gray-400 dark:text-gray-600">&times;</span>
            </span>
        </header>

        <ul class="w-full space-y-1">
            {#each visible_badge_obj_li as event_badge_obj (event_badge_obj.event_badge_id)}
                {@const print_count = event_badge_obj.print_count ?? 0}
                {@const is_printed = print_count >= 1}
                {@const display_name =
                    event_badge_obj?.full_name_override
                    ?? event_badge_obj?.full_name
                    ?? `${event_badge_obj?.given_name ?? ''} ${event_badge_obj?.family_name ?? ''}`.trim()}

                <li
                    class="
                    border border-surface-200 dark:border-surface-700 rounded-lg p-2
                    bg-surface-50 dark:bg-surface-900/50
                    flex flex-col gap-1 w-full
                    hover:border-primary-500 transition-colors
                    "
                >
                    <div class="flex flex-row flex-wrap gap-2 items-center justify-between w-full">

                        <!-- Left cluster: name (display only) + info chips -->
                        <div class="flex flex-row flex-wrap gap-x-3 gap-y-1 items-center grow min-w-0">

                            <!-- Name: always plain display — print action is a separate button -->
                            <span class="flex flex-row gap-1.5 items-center font-bold text-lg shrink-0">
                                {#if event_badge_obj?.hide}
                                    <EyeOff size="1.1em" class="text-gray-400" />
                                {:else}
                                    <User size="1.1em" class="text-surface-400" />
                                {/if}
                                <span>{display_name}</span>
                            </span>

                            <!-- Email chip — obscured for non-trusted -->
                            {#if show_sensitive_fields && event_badge_obj?.email}
                                <span class="text-xs text-surface-400 flex items-center gap-1">
                                    <Mail size="1em" />
                                    {is_trusted
                                        ? event_badge_obj.email
                                        : obscure_email(event_badge_obj.email)}
                                </span>
                            {/if}

                            <!-- Affiliations chip (prefers override) -->
                            {#if !hide_affiliations && (event_badge_obj?.affiliations_override ?? event_badge_obj?.affiliations)}
                                <span class="text-xs text-surface-400 flex items-center gap-1">
                                    <MapPin size="1em" />
                                    {event_badge_obj.affiliations_override ?? event_badge_obj.affiliations}
                                </span>
                            {/if}

                            <!-- Badge type chip -->
                            {#if !hide_badge_type && event_badge_obj?.badge_type}
                                <span class="text-xs italic text-primary-500 bg-primary-500/10 px-2 rounded-token flex items-center gap-1">
                                    <Tags size="1em" />
                                    {event_badge_obj.badge_type}
                                </span>
                            {/if}
                        </div>

                        <!-- Right: up to 4 action buttons -->
                        <div class="flex flex-row gap-1 items-center shrink-0">

                            <!-- 1. Print Badge: Trusted+, not yet printed OR in Edit Mode (reprint) -->
                            {#if is_trusted && (!is_printed || is_edit_mode)}
                                <a
                                    href={`/events/${event_badge_obj?.event_id}/badges/${event_badge_obj?.event_badge_id}/print`}
                                    class="btn btn-sm preset-tonal-primary flex items-center gap-1"
                                    title={is_printed ? `Reprint badge (printed ${print_count}×)` : 'Print badge'}
                                >
                                    <Printer size="1em" />
                                    {#if is_printed}
                                        <span class="font-bold text-xs">{print_count}×</span>
                                    {/if}
                                    <span class="hidden sm:inline">Print</span>
                                </a>
                            {/if}

                            <!-- 2. Direct Review link: Trusted + Edit Mode (navigates to /review) -->
                            {#if is_trusted && is_edit_mode}
                                <a
                                    href={build_review_url(event_badge_obj)}
                                    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. Copy review link to clipboard: Trusted + Edit Mode -->
                            {#if is_trusted && is_edit_mode}
                                <button
                                    type="button"
                                    class="btn btn-sm flex items-center gap-1"
                                    class:preset-tonal-secondary={copy_status[event_badge_obj.event_badge_id] !== 'copied'}
                                    class:preset-filled-success-500={copy_status[event_badge_obj.event_badge_id] === 'copied'}
                                    onclick={() => copy_review_link(event_badge_obj)}
                                    title="Copy review link to clipboard"
                                >
                                    {#if copy_status[event_badge_obj.event_badge_id] === 'copied'}
                                        <Check size="1em" />
                                        <span class="hidden sm:inline">Copied!</span>
                                    {:else}
                                        <Link size="1em" />
                                        <span class="hidden sm:inline">Copy Link</span>
                                    {/if}
                                </button>
                            {/if}

                            <!-- 4. Email Review Link: all if not printed; Trusted + Edit Mode 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(event_badge_obj)}
                                    title="Email a review link to this attendee"
                                >
                                    <Mail size="1em" />
                                    <span class="hidden sm:inline">Email Link</span>
                                </button>
                            {/if}

                        </div>
                    </div>

                    <!-- Debug/metadata row — Edit Mode staff only -->
                    {#if is_edit_mode && is_trusted}
                        <div
                            class="flex flex-row flex-wrap gap-x-4 gap-y-1 items-center justify-start w-full mt-1 p-1.5 bg-surface-200/50 dark:bg-surface-800/50 rounded text-[10px] font-mono border border-surface-300 dark:border-surface-700 opacity-80"
                        >
                            <span class="flex items-center gap-1">
                                <span class="font-bold opacity-50">ID:</span>
                                {event_badge_obj?.event_badge_id}
                            </span>
                            <span class="flex items-center gap-1">
                                <span class="font-bold opacity-50">CR:</span>
                                {ae_util.iso_datetime_formatter(event_badge_obj.created_on, 'datetime_iso_12_no_seconds')}
                            </span>
                            <span class="flex items-center gap-1">
                                <span class="font-bold opacity-50">UP:</span>
                                {ae_util.iso_datetime_formatter(event_badge_obj.updated_on, 'datetime_iso_12_no_seconds')}
                            </span>
                            <span class="flex items-center gap-1">
                                <span class="font-bold opacity-50">PC:</span>
                                {print_count}
                            </span>
                            <span class="flex items-center gap-1">
                                <span class="font-bold opacity-50">FP:</span>
                                {event_badge_obj.print_first_datetime
                                    ? ae_util.iso_datetime_formatter(event_badge_obj.print_first_datetime, 'datetime_iso_12_no_seconds')
                                    : '—'}
                            </span>
                            <span class="flex items-center gap-1">
                                <span class="font-bold opacity-50">LP:</span>
                                {event_badge_obj.print_last_datetime
                                    ? ae_util.iso_datetime_formatter(event_badge_obj.print_last_datetime, 'datetime_iso_12_no_seconds')
                                    : '—'}
                            </span>
                        </div>
                    {/if}
                </li>
            {/each}
        </ul>
    {:else}
        <div class="flex flex-col items-center justify-center p-20 opacity-50 text-center">
            <FileSearch size="3em" class="mb-2 opacity-20 mx-auto" />
            <p>No badges found matching your criteria. Try adjusting your filters.</p>
        </div>
    {/if}
</section>
