<script lang="ts">
	import { onMount } from 'svelte';
	import { browser } from '$app/environment';
	
	interface Ort {
		id: number;
		name: string;
		lat: number;
		lon: number;
		vorlage_count: number;
	}
	
	interface Vorlage {
		id: number;
		aktenzeichen: string;
		typ: string;
		betreff: string;
		datum_eingang: string;
		kontext: string;
	}
	
	let orte = $state<Ort[]>([]);
	let selectedOrt = $state<Ort | null>(null);
	let selectedVorlagen = $state<Vorlage[]>([]);
	let loading = $state(true);
	let map: any = null;
	
	const API_BASE = typeof window !== 'undefined' 
		? (window.location.port === '5173' 
			? `http://${window.location.hostname}:8099/api`
			: '/api')
		: '/api';
	
	// Hagen Zentrum
	const HAGEN_CENTER: [number, number] = [51.361, 7.476];
	const HAGEN_ZOOM = 12;
	
	async function loadOrte() {
		try {
			const res = await fetch(`${API_BASE}/orte`);
			if (res.ok) {
				orte = await res.json();
			}
		} catch (e) {
			console.error('Fehler beim Laden der Orte:', e);
		} finally {
			loading = false;
		}
	}
	
	async function selectOrt(ort: Ort) {
		selectedOrt = ort;
		try {
			const res = await fetch(`${API_BASE}/orte/${ort.id}/vorlagen`);
			if (res.ok) {
				selectedVorlagen = await res.json();
			}
		} catch (e) {
			console.error('Fehler:', e);
		}
	}
	
	onMount(async () => {
		if (!browser) return;
		
		await loadOrte();
		
		// Leaflet dynamisch laden
		const L = await import('leaflet');
		await import('leaflet/dist/leaflet.css');
		
		// Map initialisieren
		map = L.map('map').setView(HAGEN_CENTER, HAGEN_ZOOM);
		
		L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
			attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
		}).addTo(map);
		
		// Marker hinzufügen
		for (const ort of orte) {
			const marker = L.circleMarker([ort.lat, ort.lon], {
				radius: Math.min(8 + ort.vorlage_count * 2, 20),
				fillColor: '#16a34a',
				color: '#166534',
				weight: 2,
				opacity: 1,
				fillOpacity: 0.7
			}).addTo(map);
			
			marker.bindPopup(`
				<strong>${ort.name}</strong><br>
				${ort.vorlage_count} Vorlage(n)
			`);
			
			marker.on('click', () => selectOrt(ort));
		}
	});
</script>

<svelte:head>
	<title>Karte - Antragstracker Hagen</title>
	<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
</svelte:head>

<div class="mb-6">
	<h1 class="text-2xl font-bold text-gray-900">📍 Anträge auf der Karte</h1>
	<p class="text-gray-500 text-sm mt-1">Orte aus Anträgen und Anfragen in Hagen</p>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
	<!-- Karte -->
	<div class="lg:col-span-2">
		<div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
			{#if loading}
				<div class="h-[500px] flex items-center justify-center">
					<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"></div>
				</div>
			{:else}
				<div id="map" class="h-[500px]"></div>
			{/if}
		</div>
		
		<div class="mt-4 text-sm text-gray-500">
			{orte.length} Orte geocodiert • Marker-Größe = Anzahl Vorlagen
		</div>
	</div>
	
	<!-- Sidebar -->
	<div class="space-y-6">
		<!-- Ausgewählter Ort -->
		{#if selectedOrt}
			<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
				<h2 class="text-lg font-semibold text-gray-900 mb-2">{selectedOrt.name}</h2>
				<p class="text-sm text-gray-500 mb-4">
					{selectedOrt.vorlage_count} Vorlage(n) betreffen diesen Ort
				</p>
				
				{#if selectedVorlagen.length > 0}
					<ul class="space-y-2">
						{#each selectedVorlagen as v}
							<li>
								<a href="/vorlagen/{v.id}" class="block p-2 rounded-lg border border-gray-100 hover:bg-gray-50 transition-colors">
									<div class="flex items-center gap-2">
										<span class="font-mono text-xs font-medium text-green-700">{v.aktenzeichen}</span>
										<span class="text-xs px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">{v.typ}</span>
									</div>
									<p class="text-xs text-gray-600 mt-1 line-clamp-2">{v.betreff}</p>
								</a>
							</li>
						{/each}
					</ul>
				{/if}
			</div>
		{:else}
			<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
				<p class="text-gray-500 text-sm">Klicke auf einen Marker um die zugehörigen Vorlagen zu sehen.</p>
			</div>
		{/if}
		
		<!-- Orte-Liste -->
		<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
			<h2 class="text-lg font-semibold text-gray-900 mb-4">🗺️ Alle Orte</h2>
			<ul class="space-y-1 max-h-80 overflow-y-auto">
				{#each orte as ort}
					<li>
						<button 
							onclick={() => selectOrt(ort)}
							class="w-full text-left px-3 py-2 rounded-lg hover:bg-gray-50 transition-colors text-sm
								   {selectedOrt?.id === ort.id ? 'bg-green-50 text-green-700' : 'text-gray-700'}">
							<span class="font-medium">{ort.name}</span>
							<span class="text-gray-400 ml-2">({ort.vorlage_count})</span>
						</button>
					</li>
				{/each}
			</ul>
		</div>
	</div>
</div>
