<script lang="ts">
	let {
		lat = null,
		lng = null,
		name = '',
		address = '',
		placeId = ''
	}: {
		lat?: number | null;
		lng?: number | null;
		name?: string;
		address?: string;
		placeId?: string;
	} = $props();

	let showPicker = $state(false);

	function openGoogle(e: Event) {
		e.stopPropagation();
		let url;
		if (lat && lng) {
			url = `https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`;
		} else if (address) {
			url = `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(address)}`;
		} else if (placeId) {
			url = `https://www.google.com/maps/dir/?api=1&destination=place_id:${placeId}`;
		} else {
			url = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(name)}`;
		}
		window.open(url, '_blank');
		showPicker = false;
	}

	function openApple(e: Event) {
		e.stopPropagation();
		let url;
		if (address) {
			url = `https://maps.apple.com/?daddr=${encodeURIComponent(address)}&dirflg=d`;
		} else if (lat && lng) {
			url = `https://maps.apple.com/?daddr=${lat},${lng}&dirflg=d`;
		} else {
			url = `https://maps.apple.com/?q=${encodeURIComponent(name)}`;
		}
		window.open(url, '_blank');
		showPicker = false;
	}

	function toggle(e: Event) {
		e.stopPropagation();
		showPicker = !showPicker;
	}
</script>

<div class="relative">
	<button
		type="button"
		class="btn btn-ghost btn-xs gap-1 text-base-content/40 hover:text-primary"
		onclick={toggle}
	>
		<svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" 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>
		Maps
	</button>

	{#if showPicker}
		<div class="absolute bottom-full right-0 mb-1 bg-base-200 border border-base-300 rounded-lg shadow-xl z-50 overflow-hidden">
			<button class="w-full flex items-center gap-2 px-4 py-2.5 hover:bg-base-300 transition-colors text-sm whitespace-nowrap" onclick={openGoogle}>
				<span class="text-base">G</span> Google Maps
			</button>
			<button class="w-full flex items-center gap-2 px-4 py-2.5 hover:bg-base-300 transition-colors text-sm whitespace-nowrap" onclick={openApple}>
				<span class="text-base">A</span> Apple Maps
			</button>
		</div>
	{/if}
</div>

{#if showPicker}
	<div class="fixed inset-0 z-40" onclick={(e) => { e.stopPropagation(); showPicker = false; }}></div>
{/if}
