<script lang="ts">
	import { onMount } from 'svelte';
	
	interface FraktionStats {
		fraktion: string;
		ja: number;
		nein: number;
		enthaltung: number;
		gesamt: number;
		ja_quote: number;
	}
	
	interface Uebereinstimmung {
		quote: number;
		gleich: number;
		gesamt: number;
	}
	
	interface KoalitionsRow {
		fraktion: string;
		uebereinstimmung: Record<string, Uebereinstimmung>;
	}
	
	let fraktionen = $state<FraktionStats[]>([]);
	let koalitionsmatrix = $state<KoalitionsRow[]>([]);
	let loading = $state(true);
	let error = $state('');
	
	const API_BASE = typeof window !== 'undefined' 
		? (window.location.port === '5173' 
			? `http://${window.location.hostname}:8099/api`
			: '/api')
		: '/api';
	
	onMount(async () => {
		try {
			const [frakRes, koalRes] = await Promise.all([
				fetch(`${API_BASE}/abstimmungen/fraktionen`),
				fetch(`${API_BASE}/abstimmungen/koalitionsmatrix`)
			]);
			
			if (frakRes.ok) fraktionen = await frakRes.json();
			if (koalRes.ok) koalitionsmatrix = await koalRes.json();
		} catch (e) {
			error = `Fehler: ${e}`;
		} finally {
			loading = false;
		}
	});
	
	function getColor(quote: number): string {
		if (quote >= 90) return 'bg-green-500';
		if (quote >= 70) return 'bg-green-400';
		if (quote >= 50) return 'bg-yellow-400';
		if (quote >= 30) return 'bg-orange-400';
		return 'bg-red-400';
	}
	
	function getTextColor(quote: number): string {
		return quote >= 50 ? 'text-white' : 'text-gray-900';
	}
</script>

<svelte:head>
	<title>Abstimmungen - Antragstracker Hagen</title>
</svelte:head>

<div class="mb-6">
	<h1 class="text-2xl font-bold text-gray-900">Abstimmungsverhalten</h1>
	<p class="text-gray-500 text-sm mt-1">Analyse des Stimmverhaltens der Ratsfraktionen</p>
</div>

{#if error}
	<div class="bg-red-50 text-red-700 p-4 rounded-lg mb-6">{error}</div>
{/if}

{#if loading}
	<div class="flex justify-center py-20">
		<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"></div>
	</div>
{:else}
	<!-- Fraktionen Übersicht -->
	<section class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-8">
		<h2 class="text-lg font-semibold text-gray-900 mb-4">📊 Stimmverhalten nach Fraktion</h2>
		
		<div class="overflow-x-auto">
			<table class="w-full">
				<thead class="bg-gray-50">
					<tr>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Fraktion</th>
						<th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Ja</th>
						<th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Nein</th>
						<th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Enthaltung</th>
						<th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Gesamt</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Zustimmungsquote</th>
					</tr>
				</thead>
				<tbody class="divide-y divide-gray-100">
					{#each fraktionen as f}
						<tr class="hover:bg-gray-50">
							<td class="px-4 py-3 font-medium text-gray-900">{f.fraktion}</td>
							<td class="px-4 py-3 text-center text-green-600 font-medium">{f.ja}</td>
							<td class="px-4 py-3 text-center text-red-600 font-medium">{f.nein}</td>
							<td class="px-4 py-3 text-center text-yellow-600 font-medium">{f.enthaltung}</td>
							<td class="px-4 py-3 text-center text-gray-600">{f.gesamt}</td>
							<td class="px-4 py-3">
								<div class="flex items-center gap-2">
									<div class="flex-1 bg-gray-200 rounded-full h-2 max-w-24">
										<div class="bg-green-500 h-2 rounded-full" style="width: {f.ja_quote}%"></div>
									</div>
									<span class="text-sm text-gray-600">{f.ja_quote}%</span>
								</div>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>
	</section>

	<!-- Koalitionsmatrix -->
	<section class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
		<h2 class="text-lg font-semibold text-gray-900 mb-4">🤝 Koalitionsmatrix</h2>
		<p class="text-sm text-gray-500 mb-4">Wie oft stimmen Fraktionen gleich ab? (nur Ja/Nein-Stimmen)</p>
		
		{#if koalitionsmatrix.length > 0}
			{@const allFraktionen = koalitionsmatrix.map(r => r.fraktion).sort()}
			<div class="overflow-x-auto">
				<table class="text-xs">
					<thead>
						<tr>
							<th class="p-2 text-left"></th>
							{#each allFraktionen as f}
								<th class="p-2 text-center writing-mode-vertical" style="writing-mode: vertical-lr; transform: rotate(180deg); height: 100px;">
									{f}
								</th>
							{/each}
						</tr>
					</thead>
					<tbody>
						{#each koalitionsmatrix as row}
							<tr>
								<td class="p-2 font-medium text-right pr-3 whitespace-nowrap">{row.fraktion}</td>
								{#each allFraktionen as f2}
									{#if row.fraktion === f2}
										<td class="p-1">
											<div class="w-10 h-10 bg-gray-300 rounded flex items-center justify-center text-gray-500">
												—
											</div>
										</td>
									{:else if row.uebereinstimmung[f2]}
										{@const data = row.uebereinstimmung[f2]}
										<td class="p-1">
											<div class="w-10 h-10 {getColor(data.quote)} {getTextColor(data.quote)} rounded flex items-center justify-center font-medium"
												 title="{row.fraktion} & {f2}: {data.gleich}/{data.gesamt} ({data.quote}%)">
												{Math.round(data.quote)}
											</div>
										</td>
									{:else}
										<td class="p-1">
											<div class="w-10 h-10 bg-gray-100 rounded flex items-center justify-center text-gray-400">
												-
											</div>
										</td>
									{/if}
								{/each}
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
			
			<div class="mt-4 flex items-center gap-4 text-xs text-gray-500">
				<span>Legende:</span>
				<span class="flex items-center gap-1"><span class="w-4 h-4 bg-green-500 rounded"></span> 90-100%</span>
				<span class="flex items-center gap-1"><span class="w-4 h-4 bg-green-400 rounded"></span> 70-90%</span>
				<span class="flex items-center gap-1"><span class="w-4 h-4 bg-yellow-400 rounded"></span> 50-70%</span>
				<span class="flex items-center gap-1"><span class="w-4 h-4 bg-orange-400 rounded"></span> 30-50%</span>
				<span class="flex items-center gap-1"><span class="w-4 h-4 bg-red-400 rounded"></span> &lt;30%</span>
			</div>
		{:else}
			<p class="text-gray-500">Noch keine Koalitionsdaten verfügbar.</p>
		{/if}
	</section>
{/if}
