<script lang="ts">
	import { fmtInt, fmtPct, fmtDateShort } from '$lib/format';
	import type { ToolErrors } from '$lib/server/stats/toolErrors';

	interface Props {
		toolErrors: ToolErrors;
	}

	let { toolErrors }: Props = $props();

	const daily = $derived(toolErrors.daily);
	const byTool = $derived(toolErrors.byTool);

	// --- errors-over-time chart geometry (hand-rolled inline SVG) -----------
	const W = 720;
	const H = 150;
	const PAD_TOP = 8;
	const PAD_BOTTOM = 26;
	const chartH = $derived(H - PAD_TOP - PAD_BOTTOM);

	const errorValues = $derived(daily.map((d) => d.errorCount));
	const hasErrors = $derived(errorValues.some((v) => v > 0));
	const maxError = $derived(Math.max(1, ...errorValues));
	const barW = $derived(W / Math.max(1, daily.length));

	// sparse x-axis ticks: first, middle, last day
	const tickIdx = $derived.by(() => {
		const n = daily.length;
		if (n === 0) return [];
		if (n === 1) return [0];
		if (n === 2) return [0, 1];
		return [0, Math.floor((n - 1) / 2), n - 1];
	});

	// error-rate list is scaled against the worst rate so the widest bar is full.
	const maxRate = $derived(Math.max(0.0001, ...byTool.map((t) => t.errorRate)));
</script>

<div class="te-wrap">
	<div class="te-head">
		<div>
			<span class="te-total mono">{fmtInt(toolErrors.totalErrors)}</span>
			<span class="te-total-lbl">tool errors</span>
		</div>
		<span class="te-rate mono">{fmtPct(toolErrors.overallErrorRate)} of {fmtInt(toolErrors.totalCalls)} calls</span>
	</div>

	<!-- (a) errors over time -->
	{#if !hasErrors}
		<p class="empty">No tool errors in this window.</p>
	{:else}
		<svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Tool errors per day (UTC)" class="chart">
			<defs>
				<linearGradient id="te-grad-danger" x1="0" y1="0" x2="0" y2="1">
					<stop offset="0" stop-color="var(--danger)" stop-opacity="1" />
					<stop offset="1" stop-color="var(--danger)" stop-opacity="0.5" />
				</linearGradient>
			</defs>
			{#each [0.25, 0.5, 0.75, 1] as frac (frac)}
				<line
					class="gridline"
					x1="0"
					x2={W}
					y1={PAD_TOP + chartH * (1 - frac)}
					y2={PAD_TOP + chartH * (1 - frac)}
				/>
			{/each}
			<line class="baseline" x1="0" x2={W} y1={PAD_TOP + chartH} y2={PAD_TOP + chartH} />

			{#each daily as d, i (d.day)}
				{@const h = maxError > 0 ? (d.errorCount / maxError) * chartH : 0}
				{#if h > 0.4}
					<rect
						class="bar"
						x={i * barW + barW * 0.15}
						y={PAD_TOP + chartH - h}
						width={barW * 0.7}
						height={h}
						rx="2.5"
					>
						<title
							>{fmtDateShort(d.day)} · {fmtInt(d.errorCount)} errors / {fmtInt(d.callCount)} calls</title
						>
					</rect>
				{/if}
			{/each}

			{#each tickIdx as i (i)}
				<text class="tick" x={i * barW + barW / 2} y={H - 6} text-anchor="middle"
					>{fmtDateShort(daily[i].day)}</text
				>
			{/each}
		</svg>
		<div class="chart-axis">
			<span>Errors per day</span>
			<span class="utc-note">UTC</span>
		</div>
	{/if}

	<!-- (b) per-tool error rate for the top offenders -->
	{#if byTool.length > 0}
		<ul class="te-list">
			{#each byTool as t (t.toolName)}
				<li class="te-item">
					<span class="te-name mono" title={t.toolName}>{t.toolName}</span>
					<span class="te-track" aria-hidden="true">
						<span class="te-fill" style={`width:${Math.max(2, (t.errorRate / maxRate) * 100)}%`}></span>
					</span>
					<span class="te-count mono">{fmtInt(t.errorCount)}/{fmtInt(t.callCount)}</span>
					<span class="te-pct mono">{fmtPct(t.errorRate)}</span>
				</li>
			{/each}
		</ul>
	{/if}
</div>

<style>
	.te-wrap {
		display: flex;
		flex-direction: column;
	}
	.te-head {
		display: flex;
		align-items: baseline;
		justify-content: space-between;
		gap: 0.75rem;
		margin-bottom: 0.6rem;
	}
	.te-total {
		font-size: 1.5rem;
		font-weight: 700;
		color: var(--danger);
		line-height: 1;
	}
	.te-total-lbl {
		font-size: 0.72rem;
		text-transform: uppercase;
		letter-spacing: 0.05em;
		color: var(--text-faint);
		margin-left: 0.35rem;
	}
	.te-rate {
		font-size: 0.78rem;
		color: var(--text-dim);
		white-space: nowrap;
	}

	.chart {
		width: 100%;
		height: 150px;
		overflow: visible;
	}
	.gridline {
		stroke: var(--grid-line);
		stroke-width: 1;
	}
	.baseline {
		stroke: var(--border);
		stroke-width: 1;
	}
	.bar {
		fill: url(#te-grad-danger);
		transition: opacity 0.15s ease;
	}
	.bar:hover {
		opacity: 0.85;
	}
	.tick {
		fill: var(--text-faint);
		font-family: var(--font-mono);
		font-size: 9px;
	}
	.chart-axis {
		display: flex;
		justify-content: space-between;
		align-items: baseline;
		margin-top: 4px;
		font-size: 11px;
		color: var(--text-faint);
	}
	.utc-note {
		font-family: var(--font-mono);
		text-transform: uppercase;
		letter-spacing: 0.05em;
	}

	.te-list {
		list-style: none;
		margin: 1rem 0 0;
		padding: 0;
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
	}
	.te-item {
		display: grid;
		grid-template-columns: minmax(80px, 1.4fr) 3fr auto auto;
		align-items: center;
		gap: 0.6rem;
		font-size: 0.8rem;
	}
	.te-name {
		color: var(--text);
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.te-track {
		position: relative;
		height: 7px;
		border-radius: 4px;
		background: var(--bg-raised);
		overflow: hidden;
	}
	.te-fill {
		position: absolute;
		inset: 0 auto 0 0;
		border-radius: 4px;
		background: linear-gradient(90deg, var(--amber), var(--danger));
	}
	.te-count {
		color: var(--text-dim);
		font-size: 0.75rem;
		text-align: right;
		white-space: nowrap;
	}
	.te-pct {
		color: var(--danger);
		font-weight: 600;
		text-align: right;
		min-width: 3.2rem;
		white-space: nowrap;
	}
	.empty {
		color: var(--text-dim);
		font-size: 13px;
		padding: 24px 0;
		text-align: center;
	}
</style>
