<script lang="ts">
interface Props {
    badge_li: any[];
    event_id: string;
    log_lvl?: number;
}
let { badge_li, event_id, log_lvl = 0 }: Props = $props();

import { UserRoundPen } from '@lucide/svelte';

type NameField = 'given' | 'family' | 'full';
let name_field: NameField = $state('full');
let threshold: number = $state(20);

const MAX_DISPLAY = 500;

function get_display_name(badge: any): string {
    switch (name_field) {
        case 'given':
            return badge.given_name ?? '';
        case 'family':
            return badge.family_name ?? '';
        case 'full':
        default:
            return (
                badge.full_name_override ??
                badge.full_name ??
                `${badge.given_name ?? ''} ${badge.family_name ?? ''}`.trim()
            );
    }
}

function get_field_label(field: NameField): string {
    return field === 'given' ? 'Given' : field === 'family' ? 'Family' : 'Full Name';
}

interface BadgeRow {
    event_badge_id: string;
    display_name: string;
    name_len: number;
    badge_type: string | null;
    affiliations: string | null;
    has_override: boolean;
}

let all_results: BadgeRow[] = $derived.by(() => {
    if (!badge_li?.length) return [];
    return badge_li
        .map((b) => {
            const display_name = get_display_name(b);
            return {
                event_badge_id: b.event_badge_id,
                display_name,
                name_len: display_name.length,
                badge_type: b.badge_type_override ?? b.badge_type ?? null,
                affiliations: b.affiliations_override ?? b.affiliations ?? null,
                has_override: name_field === 'full' ? !!b.full_name_override : false
            };
        })
        .filter((r) => r.name_len >= threshold)
        .sort((a, b) => b.name_len - a.name_len);
});

let results = $derived(all_results.slice(0, MAX_DISPLAY));
let is_truncated = $derived(all_results.length > MAX_DISPLAY);
</script>

<div class="space-y-3">
    <!-- Controls -->
    <div class="flex flex-row flex-wrap items-center gap-3">
        <!-- Field selector -->
        <div class="flex flex-row items-center gap-1">
            <span class="text-sm text-surface-600-400">Field:</span>
            {#each (['full', 'given', 'family'] as NameField[]) as field}
                <button
                    type="button"
                    onclick={() => (name_field = field)}
                    class="btn btn-sm border transition-all"
                    class:preset-filled-primary={name_field === field}
                    class:border-primary-600={name_field === field}
                    class:preset-tonal-surface={name_field !== field}
                    class:border-surface-300-700={name_field !== field}>
                    {get_field_label(field)}
                </button>
            {/each}
        </div>

        <!-- Threshold stepper -->
        <div class="flex flex-row items-center gap-1">
            <span class="text-sm text-surface-600-400">Min length:</span>
            <button
                type="button"
                onclick={() => (threshold = Math.max(5, threshold - 1))}
                class="btn btn-sm preset-tonal-surface border border-surface-300-700 w-8"
                aria-label="Decrease threshold">−</button>
            <span class="w-7 text-center font-mono font-semibold">{threshold}</span>
            <button
                type="button"
                onclick={() => (threshold = Math.min(60, threshold + 1))}
                class="btn btn-sm preset-tonal-surface border border-surface-300-700 w-8"
                aria-label="Increase threshold">+</button>
        </div>

        <!-- Result count -->
        <span class="text-sm text-surface-600-400">
            {all_results.length} badge{all_results.length !== 1 ? 's' : ''} with {get_field_label(name_field).toLowerCase()} ≥ {threshold} chars
            {#if is_truncated}
                <span class="text-warning-600 dark:text-warning-400">(showing first {MAX_DISPLAY})</span>
            {/if}
        </span>
    </div>

    <!-- Results table -->
    {#if results.length === 0}
        <p class="py-4 text-sm text-surface-600-400">
            No badges found with a {get_field_label(name_field).toLowerCase()} of {threshold} or more characters.
        </p>
    {:else}
        <div class="overflow-x-auto rounded-md border border-surface-200 dark:border-surface-700">
            <table class="w-full text-sm">
                <thead>
                    <tr class="border-b border-surface-200 dark:border-surface-700 bg-surface-100 dark:bg-surface-800 text-left text-xs uppercase tracking-wide text-surface-600-400">
                        <th class="px-3 py-2">Name ({get_field_label(name_field)})</th>
                        <th class="px-3 py-2 text-right">Len</th>
                        <th class="px-3 py-2">Badge Type</th>
                        <th class="px-3 py-2">Affiliations</th>
                        <th class="px-3 py-2"></th>
                    </tr>
                </thead>
                <tbody>
                    {#each results as row (row.event_badge_id)}
                        <tr class="border-b border-surface-100 dark:border-surface-800 hover:bg-surface-50 dark:hover:bg-surface-900/50 transition-colors">
                            <td class="px-3 py-2 font-medium">
                                {row.display_name}
                                {#if row.has_override}
                                    <span class="ml-1 rounded bg-warning-100 dark:bg-warning-900/30 px-1 text-xs text-warning-700 dark:text-warning-300" title="Staff override value">override</span>
                                {/if}
                            </td>
                            <td class="px-3 py-2 text-right font-mono">
                                <span
                                    class="rounded px-1 font-semibold"
                                    class:text-error-600={row.name_len >= 30}
                                    class:dark:text-error-400={row.name_len >= 30}
                                    class:bg-error-100={row.name_len >= 30}
                                    class:dark:bg-error-900={row.name_len >= 30}
                                    class:text-warning-700={row.name_len >= 25 && row.name_len < 30}
                                    class:dark:text-warning-400={row.name_len >= 25 && row.name_len < 30}
                                    class:bg-warning-100={row.name_len >= 25 && row.name_len < 30}
                                    class:dark:bg-warning-900={row.name_len >= 25 && row.name_len < 30}
                                    class:text-surface-600-400={row.name_len < 25}>
                                    {row.name_len}
                                </span>
                            </td>
                            <td class="px-3 py-2 text-surface-600-400">{row.badge_type ?? '—'}</td>
                            <td class="max-w-48 truncate px-3 py-2 text-surface-600-400" title={row.affiliations ?? ''}>
                                {row.affiliations ?? '—'}
                            </td>
                            <td class="px-3 py-2">
                                <a
                                    href={`/events/${event_id}/badges/${row.event_badge_id}/print`}
                                    class="btn btn-sm preset-tonal-primary border border-primary-300-700 flex items-center gap-1"
                                    title={`Edit badge · ${row.event_badge_id} · ${row.display_name}`}>
                                    <UserRoundPen size="0.9em" />
                                    Edit
                                </a>
                            </td>
                        </tr>
                    {/each}
                </tbody>
            </table>
        </div>
    {/if}
</div>
