<script lang="ts">
	import { onMount } from 'svelte';

	interface Issue {
		id: number;
		item: string;
		orderNumber: string;
	}

	let issues = $state<Issue[]>([]);
	let loading = $state(true);

	onMount(async () => {
		try {
			const res = await fetch('/api/inventory/summary', { credentials: 'include' });
			if (res.ok) {
				const data = await res.json();
				issues = (data.issues || []).slice(0, 5);
			}
		} catch { /* silent */ }
		loading = false;
	});
</script>

<div class="module">
	<div class="module-header">
		<div class="module-title">Issues</div>
		<a href="/inventory" class="module-action">View all &rarr;</a>
	</div>

	<div class="issue-rows">
		{#if loading}
			{#each [1, 2, 3] as _}
				<div class="issue-row">
					<div class="issue-info">
						<div class="skeleton" style="width:160px;height:14px"></div>
						<div class="skeleton" style="width:120px;height:12px;margin-top:var(--sp-1)"></div>
					</div>
				</div>
			{/each}
		{:else if issues.length === 0}
			<div class="issue-empty">No issues found</div>
		{:else}
			{#each issues as issue}
				<a href="/inventory?item={issue.id}" class="issue-row">
					<div class="issue-info">
						<div class="issue-name">{issue.item}</div>
						<div class="issue-meta">Order #{issue.orderNumber || '—'}</div>
					</div>
					<span class="badge error" style="text-transform:uppercase;letter-spacing:0.02em;font-weight:600">Issue</span>
				</a>
			{/each}
		{/if}
	</div>
</div>

<style>
	/* No .module/.module-header/.module-title/.module-action — using globals from app.css */

	.issue-rows {
		display: flex;
		flex-direction: column;
	}

	.issue-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: var(--sp-3) var(--sp-3) var(--sp-3) var(--sp-4);
		border-bottom: 1px solid var(--border);
		border-left: 3px solid var(--error);
		margin-left: calc(-1 * var(--sp-1));
		transition: background var(--transition);
		border-radius: 0 var(--radius-xs) var(--radius-xs) 0;
		text-decoration: none;
		color: inherit;
	}

	.issue-row:last-child {
		border-bottom: none;
	}

	.issue-row:hover {
		background: var(--card-hover);
	}

	.issue-info {
		min-width: 0;
		flex: 1;
	}

	.issue-name {
		font-size: var(--text-base);
		font-weight: 500;
		color: var(--text-1);
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.issue-meta {
		font-size: var(--text-sm);
		color: var(--text-3);
		margin-top: var(--sp-0.5);
	}

	.issue-empty {
		padding: var(--sp-5);
		text-align: center;
		font-size: var(--text-sm);
		color: var(--text-3);
	}
</style>
