<script lang="ts">
interface Props {
    container_class_li?: string | Array<string>;
    lq__event_badge_obj_li: any;
    search_status?: string | null;
    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,
    search_status = null,
    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_MODULE_TITLE } from '$lib/stores/ae_events_stores';
import { badges_loc } from '$lib/stores/ae_events_stores__badges.svelte';
import { ae_util } from '$lib/ae_utils/ae_utils';
import {
    Check,
    Eye,
    EyeOff,
    Link,
    LoaderCircle,
    Mail,
    MapPin,
    Printer,
    Tags,
    User,
    UserCheck,
    UserSearch
} from '@lucide/svelte';
// Track per-badge copy state for the "Review Link" clipboard button
let copy_status: Record<string, 'idle' | 'copied'> = $state({});

// Track which badge has a pending email confirmation (null = none pending)
let email_confirm_badge_id: string | null = $state(null);

// Access level shortcuts
let is_trusted = $derived($ae_loc.trusted_access === true);
let is_admin = $derived($ae_loc.administrator_access === true);
let is_manager = $derived($ae_loc.manager_access === true);
let is_public = $derived($ae_loc.public_access === true); // public passcode or higher — may print first prints
let is_edit_mode = $derived($ae_loc.edit_mode === true);


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 with actual email API call when available
function confirm_send_review_email(event_badge_obj: any) {
    email_confirm_badge_id = event_badge_obj.event_badge_id;
}

function do_send_review_email(event_badge_obj: any) {
    email_confirm_badge_id = null;
    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)')
        : ae_util.obscure_email(event_badge_obj?.email);
    const event_name = EVENTS_MODULE_TITLE;
    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 vf = badges_loc.current.visibility_filter;
        // visibility_filter requires trusted + edit_mode — it's an admin override, not a
        // persistent search filter. Turning off edit mode reverts to hiding hidden badges.
        const show_hidden_badges = vf !== 'default' && is_trusted && is_edit_mode;
        const show_disabled_badges = vf === 'show_all' && is_trusted && is_edit_mode;

        const filtered = list.filter((item: any) => {
            if (!item) return false;
            if (is_trusted) {
                // Trusted staff and above: qry_printed_status is the authoritative control.
                // Filter state persists across edit mode toggles — intentional. Staff set
                // their filter and it stays regardless of whether edit mode is on or off.
                const hide_ok = show_hidden_badges || !item.hide;
                if (!show_disabled_badges && item.enable === false) return false;
                const ps = badges_loc.current.qry_printed_status;
                if (ps === 'printed') return (item.print_count ?? 0) >= 1 && hide_ok;
                if (ps === 'not_printed') return (item.print_count ?? 0) < 1 && hide_ok;
                return hide_ok; // 'all'
            }
            // Public/Attendee (public_access, not trusted): show all non-hidden.
            // Printed badges appear read-only so attendees can see their check-in status.
            if (is_public) return !item.hide;
            // Below public (anonymous, authenticated): only unprinted, never hidden.
            return (item.print_count ?? 0) < 1 && !item.hide;
        });

        // For public (attendee) kiosk: sort unprinted first so attendees find their
        // own badge at the top; already-checked-in records fall to the bottom.
        if (is_public && !is_trusted && filtered.length > 1) {
            filtered.sort((a: any, b: any) => {
                const a_p = (a.print_count ?? 0) > 0;
                const b_p = (b.print_count ?? 0) > 0;
                if (a_p !== b_p) return a_p ? 1 : -1;
                return 0; // preserve existing name order within each group
            });
        }

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

<section
    class="mx-auto flex w-full max-w-7xl flex-col items-center justify-center gap-1 space-y-1 px-1">
    {#if visible_badge_obj_li === null}
        <div class="flex flex-col items-center justify-center p-10 opacity-50">
            <LoaderCircle size="2em" class="mb-2 animate-spin" />
            <p>Loading badges...</p>
        </div>
    {:else if visible_badge_obj_li.length > 0}
        <header
            class="mb-2 flex w-full flex-row items-center justify-start gap-2 px-2">
            <h2 class="text-sm font-normal text-gray-500">Results:</h2>
            <span
                class="badge preset-tonal-success px-3 py-1 text-lg font-bold">
                {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()}
                    {@const is_attendee_view = is_public && !is_trusted}
                    {@const is_attendee_printed = is_attendee_view && is_printed}
                    {@const can_print = is_trusted && (!is_printed || is_edit_mode)}
                    {@const row_clickable = can_print || (is_attendee_view && !is_printed)}
                    {@const print_href = `/events/${event_badge_obj?.event_id}/badges/${event_badge_obj?.event_badge_id}/print`}
                    {@const review_href = build_review_url(event_badge_obj)}
                    {@const row_href = is_trusted ? print_href : review_href}

                <li
                    class="
                    border-surface-200 dark:border-surface-700 bg-surface-50 dark:bg-surface-900/50 hover:border-primary-500
                    flex w-full
                    flex-col gap-1 rounded-lg border
                    p-2 transition-colors
                    ">
                    <div
                        class="flex w-full flex-row flex-wrap items-center justify-between gap-2">
                        <!-- Left cluster: main action (name + email + affiliations) -->
                        <div class="flex min-w-0 grow flex-row flex-wrap items-center gap-x-3 gap-y-1">
                            {#if row_clickable}
                                <a
                                    href={row_href}
                                    class="hover:text-primary-800-200 hover:bg-primary-200-800 active:bg-surface-200-800 flex items-center gap-3 justify-start px-3 py-2 text-left text-lg font-bold flex-1
                                    transition-all duration-1000 hover:duration-300 min-w-0 preset-tonal-primary rounded-lg
                                    max-w-4xl
                                    "
                                    title={is_trusted
                                        ? `Print badge for ${display_name} · ${event_badge_obj?.affiliations_override ?? event_badge_obj?.affiliations ?? ''} · ${event_badge_obj?.badge_type ?? ''} · id: ${event_badge_obj.event_badge_id}`
                                        : `Review your badge info`}
                                    >
                                    {#if event_badge_obj?.hide}
                                        <EyeOff size="1.1em" class="text-gray-400" />
                                    {:else if is_printed}
                                        <UserCheck size="1.1em" class="text-success-600 dark:text-success-400" />
                                    {:else}
                                        <User size="1.1em" class="text-primary-500" />
                                    {/if}

                                    <div class="
                                        flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-3 min-w-0
                                        hover:scale-115
                                        ease-in-out
                                        transition-all duration-1000 hover:duration-500
                                        hover:bg-primary-200-800 active:bg-primary-200-800
                                        ">
                                        <span class="truncate font-semibold min-w-44 max-w-64 ">{display_name}</span>

                                        {#if show_sensitive_fields && event_badge_obj?.email}

                                            <span class="
                                                text-surface-600-400
                                                bg-surface-100-900 rounded
                                                px-1.5 py-0.5
                                                font-mono text-sm
                                                select-all hover:bg-surface-100-900
                                                hover:text-surface-900-100
                                                truncate min-w-52 max-w-64
                                                transition-all duration-1000 hover:duration-100
                                                "
                                                >
                                                {is_trusted
                                                    ? event_badge_obj.email
                                                    : ae_util.obscure_email(event_badge_obj.email)}
                                            </span>
                                        {/if}

                                        {#if !hide_affiliations && (event_badge_obj?.affiliations_override ?? event_badge_obj?.affiliations)}

                                            <span class="
                                                text-surface-600-400 bg-surface-100-900 rounded
                                                px-1.5 py-0.5
                                                font-mono italic text-sm
                                                select-all hover:bg-surface-100-900
                                                hover:text-surface-900-100
                                                truncate min-w-52 max-w-64
                                                transition-all duration-1000 hover:duration-100
                                                ">
                                                {event_badge_obj.affiliations_override ?? event_badge_obj.affiliations}
                                            </span>
                                        {/if}
                                    </div>
                                </a>
                            {:else if is_attendee_printed}
                                <!-- Public attendee, badge already printed: show check-in status, no action -->
                                <div class="
                                    flex items-center gap-3 justify-start px-3 py-2 flex-1 min-w-0 rounded-lg bg-success-500/10
                                    ">
                                    <Check size="1.1em" class="text-success-600 dark:text-success-400 shrink-0" />
                                    <div class="flex flex-col min-w-0">
                                        <span class="truncate font-semibold">{display_name}</span>
                                        <span class="text-sm text-success-700 dark:text-success-300 opacity-80">
                                            Checked in &middot; {print_count}&times;
                                            {#if event_badge_obj.print_first_datetime}
                                                &middot;
                                                {ae_util.iso_datetime_formatter(event_badge_obj.print_first_datetime, 'date_full_no_year', null, true)}
                                                {ae_util.iso_datetime_formatter(event_badge_obj.print_first_datetime, 'time_12_long', null, true)}
                                            {/if}
                                            {#if event_badge_obj.print_last_datetime && event_badge_obj.print_last_datetime !== event_badge_obj.print_first_datetime}
                                                &middot; last print:
                                                {ae_util.iso_datetime_formatter(event_badge_obj.print_last_datetime, 'date_full_no_year', null, true)}
                                                {ae_util.iso_datetime_formatter(event_badge_obj.print_last_datetime, 'time_12_long', null, true)}
                                            {/if}
                                        </span>
                                    </div>
                                </div>
                            {:else}
                                <div
                                    class="hover:text-primary-800-200 hover:bg-primary-200-800 active:bg-surface-200-700 flex items-center gap-3 justify-start px-3 py-2 text-left text-lg font-bold flex-1 transition-colors duration-1000 hover:duration-300 min-w-0 preset-tonal-primary rounded-lg cursor-not-allowed
                                    max-w-4xl
                                    "
                                    title="Printing not permitted">
                                    {#if event_badge_obj?.hide}
                                        <EyeOff size="1.1em" class="text-gray-400" />
                                    {:else if is_printed}
                                        <UserCheck size="1.1em" class="text-success-600 dark:text-success-400" />
                                    {:else}
                                        <User size="1.1em" class="text-surface-400" />
                                    {/if}

                                    <div class="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-3 min-w-0">
                                        <span class="truncate font-semibold min-w-44">{display_name}</span>

                                        {#if show_sensitive_fields && event_badge_obj?.email}
                                            <span class="
                                                text-surface-600-400 bg-surface-100-900 rounded
                                                px-1.5 py-0.5
                                                font-mono italic text-sm
                                                select-all hover:bg-surface-100-900
                                                hover:text-surface-900-100
                                                truncate min-w-52 max-w-64
                                                transition-all duration-1000 hover:duration-100
                                                ">
                                                {is_trusted
                                                    ? event_badge_obj.email
                                                    : ae_util.obscure_email(event_badge_obj.email)}
                                            </span>
                                        {/if}

                                        {#if !hide_affiliations && (event_badge_obj?.affiliations_override ?? event_badge_obj?.affiliations)}
                                            <span class="
                                                text-surface-600-400 bg-surface-100-900 rounded
                                                px-1.5 py-0.5
                                                font-mono italic text-sm
                                                select-all hover:bg-surface-100-900
                                                hover:text-surface-900-100
                                                truncate min-w-52 max-w-64
                                                transition-all duration-1000 hover:duration-100
                                                ">
                                                {event_badge_obj.affiliations_override ?? event_badge_obj.affiliations}
                                            </span>
                                        {/if}
                                    </div>
                                </div>
                            {/if}

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

                        <!-- Right: up to 4 action buttons -->
                        <div class="flex shrink-0 flex-row items-center gap-1">
                            <!-- 1. Print Badge: Trusted — first print anytime, reprint in Edit Mode or Manager+ -->
                            {#if is_trusted && (!is_printed || is_edit_mode || is_manager)}
                                <a
                                    href={`/events/${event_badge_obj?.event_id}/badges/${event_badge_obj?.event_badge_id}/print`}
                                    class="hover:text-primary-800-200 hover:bg-primary-200-800 active:bg-surface-200-700 flex items-center gap-1 px-3 py-2 text-base font-bold transition-colors duration-1000 hover:duration-300 min-w-0 preset-tonal-primary rounded-lg border border-primary-200-800
                                    "
                                    title={is_printed
                                        ? `Reprint badge (printed ${print_count}×)`
                                        : `Print badge for ${display_name}`}>
                                    <Printer size="1em" />
                                    {#if is_printed}
                                        <span class="text-xs font-bold"
                                            >{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: Administrator + Edit Mode only
                                 Temporarily restricted — TODO: restore broader access after Axonius 2026 -->
                            {#if is_admin && 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: Manager+ always; Administrator + Edit Mode otherwise -->
                            {#if is_admin && (is_edit_mode || is_manager)}
                                {#if email_confirm_badge_id === event_badge_obj.event_badge_id}
                                    <!-- Inline confirmation: shown after clicking Email Link -->
                                    <div class="flex items-center gap-2 px-2 py-1 rounded-lg bg-warning-100 dark:bg-warning-900/30 border border-warning-300 dark:border-warning-700 text-sm">
                                        <span class="text-warning-800 dark:text-warning-200 font-medium">Send link to {display_name}?</span>
                                        <button
                                            type="button"
                                            class="flex items-center gap-1 px-2 py-1 rounded font-bold preset-filled-warning-500 text-sm"
                                            onclick={() => do_send_review_email(event_badge_obj)}>
                                            <Mail size="0.9em" />
                                            Send
                                        </button>
                                        <button
                                            type="button"
                                            class="flex items-center gap-1 px-2 py-1 rounded font-bold preset-tonal-surface text-sm"
                                            onclick={() => { email_confirm_badge_id = null; }}>
                                            Cancel
                                        </button>
                                    </div>
                                {:else}
                                    <button
                                        type="button"
                                        class="hover:text-primary-800-200 hover:bg-primary-200-800 active:bg-surface-200-700 flex items-center gap-1 px-3 py-2 text-base font-bold transition-colors duration-1000 hover:duration-300 min-w-0 preset-tonal-primary rounded-lg border border-primary-200-800"
                                        onclick={() => confirm_send_review_email(event_badge_obj)}
                                        title="Email a review link to {display_name}">
                                        <Mail size="1em" />
                                        <span class="hidden sm:inline">Email Link</span>
                                    </button>
                                {/if}
                            {/if}
                        </div>
                    </div>

                    <!-- Print status strip — Trusted staff, not in Edit Mode (debug row covers it there) -->
                    {#if is_trusted && is_printed && !is_edit_mode}
                        <div class="flex flex-row flex-wrap items-center gap-x-1.5 gap-y-0.5 px-2 text-base text-success-700 dark:text-success-300 opacity-70">
                            <Check size="0.85em" class="shrink-0" />
                            <span>Printed {print_count}&times;</span>
                            {#if event_badge_obj.print_first_datetime}
                                <span class="opacity-50">&middot;</span>
                                <span>{ae_util.iso_datetime_formatter(event_badge_obj.print_first_datetime, 'date_full_no_year', null, true)} {ae_util.iso_datetime_formatter(event_badge_obj.print_first_datetime, 'time_12_long', null, true)}</span>
                            {/if}
                            {#if event_badge_obj.print_last_datetime && event_badge_obj.print_last_datetime !== event_badge_obj.print_first_datetime}
                                <span class="opacity-50">&middot;</span>
                                <span>last print: {ae_util.iso_datetime_formatter(event_badge_obj.print_last_datetime, 'date_full_no_year', null, true)} {ae_util.iso_datetime_formatter(event_badge_obj.print_last_datetime, 'time_12_long', null, true)}</span>
                            {/if}
                        </div>
                    {/if}

                    <!-- Debug/metadata row — Edit Mode staff only -->
                    {#if is_edit_mode && is_trusted}
                        <div
                            class="bg-surface-200/50 dark:bg-surface-800/50 border-surface-300 dark:border-surface-700 mt-1 flex w-full flex-row flex-wrap items-center justify-start gap-x-4 gap-y-1 rounded border p-1.5 font-mono text-[10px] 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',
                                    null,
                                    true
                                )}
                            </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',
                                    null,
                                    true
                                )}
                            </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',
                                          null,
                                          true
                                      )
                                    : '—'}
                            </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',
                                          null,
                                          true
                                      )
                                    : '—'}
                            </span>
                        </div>
                    {/if}
                </li>
            {/each}
        </ul>
    {:else}
        <div
            class="flex w-full flex-col items-center justify-center p-16 text-center opacity-50">
            {#if search_status === 'loading'}
                <LoaderCircle size="3em" class="mx-auto mb-2 animate-spin" />
                <p class="text-xl">Searching...</p>
            {:else if !is_trusted && !(badges_loc.current.fulltext_search_qry_str ?? '').trim()}
                <UserSearch size="3em" class="mx-auto mb-2 opacity-20" />
                <p class="text-xl">Search by name, email, or organization above to find your badge.</p>
            {:else}
                <UserSearch size="3em" class="mx-auto mb-2 opacity-20" />
                <p class="text-xl">No badges found matching your criteria.</p>
            {/if}
        </div>
    {/if}
</section>
