<script lang="ts">
    import { onMount } from 'svelte';
    import Pager from '$lib/components/Pager.svelte';
    import { fmtDuration } from '$lib/format';
    import {
        listAnalysisHistory,
        type AnalysisHistoryRow
    } from '$lib/api/admin';

    // Row click opens the parent's existing page-detail modal — history
    // reuses the same drill-down inspector as the coverage grid.
    let {
        onOpenDetail
    }: {
        onOpenDetail: (pageId: string) => void;
    } = $props();

    const LIMIT = 25;

    let rows = $state<AnalysisHistoryRow[]>([]);
    let total = $state(0);
    let page = $state(1);
    let statusFilter = $state<'' | 'done' | 'failed'>('');
    let search = $state('');
    let loading = $state(true);
    let error = $state<string | null>(null);

    const totalPages = $derived(Math.max(1, Math.ceil(total / LIMIT)));

    async function load() {
        loading = true;
        error = null;
        try {
            const resp = await listAnalysisHistory({
                status: statusFilter || undefined,
                search: search.trim() || undefined,
                limit: LIMIT,
                offset: (page - 1) * LIMIT
            });
            rows = resp.items;
            total = resp.page.total ?? resp.items.length;
        } catch (e) {
            error = e instanceof Error ? e.message : 'Failed to load history.';
        } finally {
            loading = false;
        }
    }

    onMount(load);

    function applyFilters() {
        page = 1;
        load();
    }
    function onPageChange(p: number) {
        page = p;
        load();
    }
    function onSearchKey(e: KeyboardEvent) {
        if (e.key === 'Enter') applyFilters();
    }

    function fmtAgo(iso: string | null): string {
        if (!iso) return '—';
        const secs = Math.round((Date.now() - new Date(iso).getTime()) / 1000);
        if (secs < 45) return 'just now';
        const mins = Math.round(secs / 60);
        if (mins < 60) return `${mins}m ago`;
        const hrs = Math.round(mins / 60);
        if (hrs < 24) return `${hrs}h ago`;
        return new Date(iso).toLocaleDateString();
    }
</script>

<section class="history" data-testid="analysis-history">
    <div class="toolbar">
        <select
            bind:value={statusFilter}
            onchange={applyFilters}
            aria-label="Filter by status"
            data-testid="analysis-history-status"
        >
            <option value="">All statuses</option>
            <option value="done">done</option>
            <option value="failed">failed</option>
        </select>
        <input
            class="search"
            type="text"
            bind:value={search}
            placeholder="Search manga title…"
            onkeydown={onSearchKey}
            data-testid="analysis-history-search"
        />
        <button type="button" onclick={applyFilters}>Search</button>
    </div>

    {#if error}
        <p class="error" role="alert">{error}</p>
    {/if}

    {#if loading}
        <p class="muted" data-testid="analysis-history-loading">Loading…</p>
    {:else if rows.length === 0}
        <p class="muted" data-testid="analysis-history-empty">No analyses match.</p>
    {:else}
        <table>
            <thead>
                <tr>
                    <th>Status</th>
                    <th>Page</th>
                    <th>Model</th>
                    <th class="num">Dur</th>
                    <th>Analyzed</th>
                </tr>
            </thead>
            <tbody>
                {#each rows as r (r.page_id)}
                    <tr
                        class="clickable"
                        onclick={() => onOpenDetail(r.page_id)}
                        data-testid={`analysis-history-row-${r.page_id}`}
                        title={r.error ?? ''}
                    >
                        <td><span class="status-pill {r.status}">{r.status}</span></td>
                        <td>
                            {r.manga_title} · Ch {r.chapter_number} · p{r.page_number}
                        </td>
                        <td class="muted">{r.model ?? '—'}</td>
                        <td class="num">{fmtDuration(r.duration_ms)}</td>
                        <td title={r.analyzed_at ? new Date(r.analyzed_at).toLocaleString() : ''}
                            >{fmtAgo(r.analyzed_at)}</td
                        >
                    </tr>
                {/each}
            </tbody>
        </table>
        <Pager {page} {totalPages} onChange={onPageChange} testid="analysis-history-pager" />
    {/if}
</section>

<style>
    .toolbar {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: var(--space-2);
        margin-bottom: var(--space-3);
    }
    select,
    .search {
        height: 36px;
        padding: 0 var(--space-2);
        border: 1px solid var(--border);
        border-radius: var(--radius-md);
        background: var(--surface);
        color: var(--text);
        font-size: var(--font-sm);
    }
    .muted {
        color: var(--text-muted);
    }
    table {
        width: 100%;
        border-collapse: collapse;
        max-width: 52rem;
    }
    th,
    td {
        padding: var(--space-2);
        text-align: left;
        border-bottom: 1px solid var(--border);
        font-size: var(--font-sm);
    }
    .num {
        text-align: right;
        font-variant-numeric: tabular-nums;
    }
    tr.clickable {
        cursor: pointer;
    }
    tr.clickable:hover {
        background: var(--surface);
    }
    .status-pill {
        font-weight: var(--weight-semibold);
        font-size: var(--font-xs);
        padding: 1px var(--space-2);
        border-radius: var(--radius-pill);
        text-transform: uppercase;
        background: var(--surface-elevated);
        color: var(--text-muted);
    }
    .status-pill.done {
        background: color-mix(in srgb, #2e7d32 16%, transparent);
        color: #2e7d32;
    }
    .status-pill.failed {
        background: color-mix(in srgb, var(--danger) 16%, transparent);
        color: var(--danger);
    }
    .error {
        color: var(--danger);
    }
</style>
