<script lang="ts">
	import type { Repository } from '$lib/types';

	let {
		repo,
		onReindex,
		onDelete
	}: {
		repo: Repository;
		onReindex: (id: string) => void;
		onDelete: (id: string) => void;
	} = $props();

	const stateColors: Record<string, string> = {
		pending: 'bg-gray-100 text-gray-600',
		indexing: 'bg-blue-100 text-blue-700',
		indexed: 'bg-green-100 text-green-700',
		error: 'bg-red-100 text-red-700'
	};

	const stateLabels: Record<string, string> = {
		pending: 'Pending',
		indexing: 'Indexing...',
		indexed: 'Indexed',
		error: 'Error'
	};

	const totalSnippets = $derived(repo.totalSnippets ?? 0);
	const trustScore = $derived(repo.trustScore ?? 0);
</script>

<div class="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
	<div class="flex items-start justify-between">
		<div class="min-w-0 flex-1">
			<h3 class="truncate font-semibold text-gray-900">{repo.title}</h3>
			<p class="mt-0.5 truncate font-mono text-sm text-gray-500">{repo.id}</p>
		</div>
		<span
			class="ml-3 shrink-0 rounded-full px-2.5 py-0.5 text-xs font-medium {stateColors[repo.state] ??
				'bg-gray-100 text-gray-600'}"
		>
			{stateLabels[repo.state] ?? repo.state}
		</span>
	</div>

	{#if repo.description}
		<p class="mt-2 line-clamp-2 text-sm text-gray-600">{repo.description}</p>
	{/if}

	<div class="mt-4 flex flex-wrap gap-x-4 gap-y-1 text-sm text-gray-500">
		<span>{totalSnippets.toLocaleString()} snippets</span>
		<span>·</span>
		<span>Trust: {trustScore.toFixed(1)}/10</span>
		{#if repo.stars}
			<span>·</span>
			<span>★ {repo.stars.toLocaleString()}</span>
		{/if}
		{#if repo.lastIndexedAt}
			<span>·</span>
			<span>Last indexed {new Date(repo.lastIndexedAt).toLocaleDateString()}</span>
		{/if}
	</div>

	{#if repo.state === 'error'}
		<p class="mt-2 text-xs text-red-600">Indexing failed. Check jobs for details.</p>
	{/if}

	<div class="mt-4 flex flex-wrap gap-2">
		<button
			type="button"
			onclick={() => onReindex(repo.id)}
			class="rounded-lg bg-blue-600 px-3 py-1.5 text-sm text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
			disabled={repo.state === 'indexing'}
		>
			{repo.state === 'indexing' ? 'Indexing...' : 'Re-index'}
		</button>
		<a
			href="/repos/{encodeURIComponent(repo.id)}"
			class="rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-50"
		>
			Details
		</a>
		<button
			type="button"
			onclick={() => onDelete(repo.id)}
			class="ml-auto rounded-lg px-3 py-1.5 text-sm text-red-600 hover:bg-red-50"
		>
			Delete
		</button>
	</div>
</div>
