<script lang="ts">
    import { onMount } from 'svelte';
    import { fmtDuration } from '$lib/format';
    import TrendChart from '$lib/components/charts/TrendChart.svelte';
    import { buildSeries, type TrendSeries } from '$lib/admin/series';
    import {
        getAnalysisMetrics,
        getAnalysisMetricsSeries,
        type AnalysisMetrics
    } from '$lib/api/admin';

    let days = $state(7);
    let metrics = $state<AnalysisMetrics | null>(null);
    let loading = $state(true);
    let error = $state<string | null>(null);
    let series = $state<TrendSeries | null>(null);
    let seriesCtrl: AbortController | null = null;

    const successPct = $derived(
        metrics && metrics.n > 0 ? Math.round((metrics.ok / metrics.n) * 100) : null
    );

    async function load() {
        loading = true;
        error = null;
        try {
            metrics = await getAnalysisMetrics(days);
        } catch (e) {
            error = e instanceof Error ? e.message : 'Failed to load metrics.';
        } finally {
            loading = false;
        }
        loadSeries();
    }

    async function loadSeries() {
        seriesCtrl?.abort();
        const ctrl = new AbortController();
        seriesCtrl = ctrl;
        try {
            const resp = await getAnalysisMetricsSeries(days, { signal: ctrl.signal });
            series = buildSeries(resp.buckets, days);
        } catch (e) {
            if ((e as Error)?.name === 'AbortError') return;
            // Chart failure is non-fatal — keep the tiles/table usable.
        }
    }

    onMount(load);
</script>

<section data-testid="analysis-metrics">
    <div class="winrow">
        <label>
            Window
            <select bind:value={days} onchange={load} data-testid="analysis-metrics-window">
                <option value={1}>24 hours</option>
                <option value={7}>7 days</option>
                <option value={30}>30 days</option>
                <option value={0}>All time</option>
            </select>
        </label>
    </div>

    {#if error}
        <p class="error" role="alert">{error}</p>
    {:else if loading}
        <p class="muted">Loading…</p>
    {:else if metrics}
        {#if series}
            <div class="charts" data-testid="analysis-metrics-charts">
                <TrendChart points={series.throughput} label="Pages analyzed (per bucket)" />
                <TrendChart
                    points={series.success}
                    label="Success rate"
                    format={(v) => `${v.toFixed(0)}%`}
                    accent="var(--success, #16a34a)"
                />
                <TrendChart
                    points={series.duration}
                    label="Avg duration"
                    format={(v) => fmtDuration(v)}
                    accent="var(--warning, #d97706)"
                />
            </div>
        {/if}

        <div class="tiles">
            <div class="tile">
                <span class="label">Pages analyzed</span>
                <span class="value" data-testid="analysis-metrics-n">{metrics.n}</span>
            </div>
            <div class="tile">
                <span class="label">Avg duration</span>
                <span class="value" data-testid="analysis-metrics-avg"
                    >{fmtDuration(metrics.avg_ms)}</span
                >
            </div>
            <div class="tile">
                <span class="label">Success</span>
                <span class="value">{successPct == null ? '—' : `${successPct}%`}</span>
            </div>
            <div class="tile">
                <span class="label">Failed</span>
                <span class="value">{metrics.failed}</span>
            </div>
        </div>
    {/if}
</section>

<style>
    .winrow {
        display: flex;
        justify-content: flex-end;
        margin-bottom: var(--space-3);
    }
    label {
        font-size: var(--font-sm);
        color: var(--text-muted);
    }
    select {
        height: 32px;
        margin-left: var(--space-1);
        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);
    }
    .charts {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
        gap: var(--space-3) var(--space-4);
        margin-bottom: var(--space-4);
        max-width: 60rem;
    }
    .tiles {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));
        gap: var(--space-3);
        max-width: 44rem;
        margin-bottom: var(--space-4);
    }
    .tile {
        display: flex;
        flex-direction: column;
        gap: 2px;
        padding: var(--space-3);
        border: 1px solid var(--border);
        border-radius: var(--radius-md);
        background: var(--surface);
    }
    .tile .label {
        font-size: var(--font-xs);
        color: var(--text-muted);
        text-transform: uppercase;
        letter-spacing: 0.04em;
    }
    .tile .value {
        font-size: var(--font-lg);
        font-weight: var(--weight-semibold);
        font-variant-numeric: tabular-nums;
    }
    .muted {
        color: var(--text-muted);
    }
    .error {
        color: var(--danger);
    }
</style>
