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

	let {
		trip,
		onClose
	}: {
		trip: TripDetail;
		onClose: () => void;
	} = $props();

	let modal = $state<HTMLDialogElement | null>(null);

	interface Marker {
		lat: number;
		lng: number;
		label: string;
		type: string;
	}

	let markers = $derived.by(() => {
		const m: Marker[] = [];
		for (const loc of trip.locations || []) {
			if (loc.latitude && loc.longitude) {
				m.push({ lat: loc.latitude, lng: loc.longitude, label: loc.name, type: 'activity' });
			}
		}
		for (const l of trip.lodging || []) {
			if ((l as any).latitude && (l as any).longitude) {
				m.push({ lat: (l as any).latitude, lng: (l as any).longitude, label: l.name, type: 'hotel' });
			}
		}
		for (const t of trip.transportations || []) {
			if (t.from_lat && t.from_lng) {
				m.push({ lat: t.from_lat, lng: t.from_lng, label: t.from_location, type: 'transport' });
			}
			if (t.to_lat && t.to_lng) {
				m.push({ lat: t.to_lat, lng: t.to_lng, label: t.to_location, type: 'transport' });
			}
		}
		return m;
	});

	// Open in Google Maps with all locations
	function openInGoogleMaps() {
		if (markers.length === 0) return;
		if (markers.length === 1) {
			window.open(`https://www.google.com/maps/search/?api=1&query=${markers[0].lat},${markers[0].lng}`, '_blank');
		} else {
			const origin = `${markers[0].lat},${markers[0].lng}`;
			const dest = `${markers[markers.length - 1].lat},${markers[markers.length - 1].lng}`;
			const waypoints = markers.slice(1, -1).map(m => `${m.lat},${m.lng}`).join('|');
			window.open(`https://www.google.com/maps/dir/?api=1&origin=${origin}&destination=${dest}${waypoints ? '&waypoints=' + waypoints : ''}`, '_blank');
		}
	}

	function typeBadge(type: string): string {
		switch (type) {
			case 'activity': return 'badge-accent';
			case 'hotel': return 'badge-secondary';
			case 'transport': return 'badge-info';
			default: return 'badge-ghost';
		}
	}

	$effect(() => { modal?.showModal(); });
</script>

<dialog bind:this={modal} class="modal modal-bottom sm:modal-middle" onclose={onClose}>
	<div class="modal-box max-w-2xl max-h-[85vh] overflow-y-auto">
		<form method="dialog">
			<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">&#x2715;</button>
		</form>

		<h3 class="font-bold text-lg flex items-center gap-2 mb-4">
			<div class="p-2 rounded-xl bg-primary/15">
				<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/>
				</svg>
			</div>
			Map
			<span class="badge badge-primary badge-sm">{markers.length} pins</span>
		</h3>

		{#if markers.length === 0}
			<div class="text-center py-12 text-base-content/40">No locations with coordinates</div>
		{:else}
			<!-- Open in Google Maps -->
			<button type="button" class="btn btn-primary btn-sm gap-2 mb-4 w-full" onclick={openInGoogleMaps}>
				<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>
				</svg>
				Open in Google Maps
			</button>

			<!-- Location list -->
			<div class="space-y-1">
				{#each markers as marker, i}
					<a
						href="https://www.google.com/maps/search/?api=1&query={marker.lat},{marker.lng}"
						target="_blank"
						class="flex items-center gap-3 p-2 rounded-lg hover:bg-base-200 transition-colors"
					>
						<span class="w-6 h-6 rounded-full bg-base-300 flex items-center justify-center text-xs font-bold text-base-content/50 shrink-0">{i + 1}</span>
						<div class="flex-1 min-w-0">
							<div class="text-sm font-medium truncate">{marker.label}</div>
							<div class="text-xs text-base-content/30">{marker.lat.toFixed(4)}, {marker.lng.toFixed(4)}</div>
						</div>
						<span class="badge badge-sm {typeBadge(marker.type)}">{marker.type}</span>
					</a>
				{/each}
			</div>
		{/if}
	</div>
	<form method="dialog" class="modal-backdrop"><button>close</button></form>
</dialog>
