<script lang="ts">
	import { page } from '$app/state';

	interface ShareTrip {
		name: string;
		description: string;
		start_date: string;
		end_date: string;
		transportations: any[];
		lodging: any[];
		locations: any[];
		notes: any[];
		hero_images: any[];
	}

	let trip = $state<ShareTrip | null>(null);
	let loading = $state(true);
	let error = $state('');
	let currentSlide = $state(0);

	let token = $derived(page.params.token);

	$effect(() => {
		if (token) loadShareTrip(token);
	});

	async function loadShareTrip(t: string) {
		loading = true;
		try {
			const res = await fetch(`/api/share/trip/${t}`);
			if (res.ok) {
				trip = await res.json();
			} else {
				error = 'Trip not found or link expired';
			}
		} catch {
			error = 'Failed to load trip';
		} finally {
			loading = false;
		}
	}

	// Auto-rotate carousel
	let autoplayTimer: ReturnType<typeof setInterval>;
	$effect(() => {
		if ((trip?.hero_images?.length || 0) > 1) {
			autoplayTimer = setInterval(() => {
				currentSlide = (currentSlide + 1) % (trip?.hero_images?.length || 1);
			}, 5000);
		}
		return () => clearInterval(autoplayTimer);
	});

	function formatDateShort(d: string): string {
		if (!d) return '';
		return new Date(d + 'T00:00:00').toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
	}

	function formatTime(dateStr: string): string {
		if (!dateStr || !dateStr.includes('T')) return '';
		const timePart = dateStr.split('T')[1]?.split('|')[0];
		if (!timePart) return '';
		const [h, m] = timePart.split(':');
		const hour = parseInt(h);
		const ampm = hour >= 12 ? 'PM' : 'AM';
		const h12 = hour % 12 || 12;
		return `${h12}:${m} ${ampm}`;
	}

	function extractDate(d: string | undefined): string {
		if (!d) return '';
		return d.split('T')[0];
	}

	function categoryBadgeClass(cat: string): string {
		switch (cat) {
			case 'restaurant': case 'cafe': case 'bar': return 'badge-warning';
			case 'hike': return 'badge-success';
			case 'attraction': return 'badge-info';
			default: return 'badge-ghost';
		}
	}

	// Build day groups
	let days = $derived.by(() => {
		if (!trip?.start_date || !trip?.end_date) return [];
		const start = new Date(trip.start_date + 'T00:00:00');
		const end = new Date(trip.end_date + 'T00:00:00');
		const dayMap = new Map<string, { date: string; label: string; num: number; items: any[] }>();

		let num = 1;
		for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
			const ds = d.toISOString().split('T')[0];
			dayMap.set(ds, {
				date: ds,
				label: d.toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' }),
				num: num++,
				items: []
			});
		}

		for (const t of trip.transportations || []) {
			const d = extractDate(t.date);
			if (d && dayMap.has(d)) dayMap.get(d)!.items.push({ type: 'transport', data: t });
		}
		for (const loc of trip.locations || []) {
			const d = loc.visit_date || extractDate(loc.start_time);
			if (d && dayMap.has(d)) dayMap.get(d)!.items.push({ type: 'location', data: loc });
		}
		for (const n of trip.notes || []) {
			if (n.date && dayMap.has(n.date)) dayMap.get(n.date)!.items.push({ type: 'note', data: n });
		}

		return Array.from(dayMap.values());
	});

	// Overnight lodging
	let overnightByDate = $derived.by(() => {
		const map = new Map<string, any>();
		if (!trip) return map;
		for (const l of trip.lodging || []) {
			const checkIn = extractDate(l.check_in);
			const checkOut = extractDate(l.check_out);
			if (!checkIn) continue;
			const start = new Date(checkIn + 'T00:00:00');
			const end = checkOut ? new Date(checkOut + 'T00:00:00') : start;
			for (let d = new Date(start); d < end; d.setDate(d.getDate() + 1)) {
				map.set(d.toISOString().split('T')[0], l);
			}
		}
		return map;
	});
</script>

<svelte:head>
	<title>{trip?.name || 'Shared Trip'}</title>
</svelte:head>

{#if loading}
	<div class="flex justify-center py-20">
		<span class="loading loading-spinner loading-lg text-primary"></span>
	</div>
{:else if error || !trip}
	<div class="container mx-auto px-4 py-20 text-center">
		<svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 mx-auto text-base-content/20 mb-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><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>
		<h2 class="text-xl font-bold text-base-content/60">{error || 'Trip not found'}</h2>
	</div>
{:else}
	<!-- Hero carousel -->
	{#if trip.hero_images && trip.hero_images.length > 0}
		<div class="relative w-full h-64 md:h-80 overflow-hidden bg-base-300">
			{#each trip.hero_images as img, i}
				<div class="absolute inset-0 transition-opacity duration-500" class:opacity-100={i === currentSlide} class:opacity-0={i !== currentSlide}>
					<img src={img.url} alt="" class="w-full h-full object-cover" />
				</div>
			{/each}
			<div class="absolute inset-0 bg-gradient-to-t from-base-100 via-base-100/10 to-black/30"></div>
			<div class="absolute inset-0 flex flex-col items-center justify-center text-center px-6">
				<h1 class="text-5xl md:text-6xl font-extrabold text-white drop-shadow-[0_2px_8px_rgba(0,0,0,0.7)]">{trip.name}</h1>
				{#if trip.start_date}
					<span class="badge badge-lg bg-primary border-0 text-white gap-1.5 px-4 py-3 mt-4">
						{formatDateShort(trip.start_date)} - {formatDateShort(trip.end_date)}
					</span>
				{/if}
			</div>
			{#if trip.hero_images.length > 1}
				<div class="absolute bottom-4 right-4 badge bg-black/40 border-0 text-white text-xs">
					{currentSlide + 1} / {trip.hero_images.length}
				</div>
			{/if}
		</div>
	{/if}

	<div class="container mx-auto px-4 py-6 max-w-4xl">
		<!-- Shared badge -->
		<div class="flex justify-center mb-6">
			<span class="badge badge-outline gap-1 text-base-content/40">
				<svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>
				Shared Trip
			</span>
		</div>

		{#if !trip.start_date}
			<h1 class="text-3xl font-bold text-base-content text-center mb-6">{trip.name}</h1>
		{/if}

		<!-- Itinerary -->
		<div class="space-y-3">
			{#each days as day}
				{#if day.items.length > 0}
					<section>
						<div class="flex items-center gap-3 p-3">
							<div class="w-10 h-10 rounded-full bg-primary/15 flex items-center justify-center shrink-0">
								<span class="text-sm font-bold text-primary">{day.num}</span>
							</div>
							<div>
								<div class="font-semibold text-base-content">{day.label}</div>
								<div class="text-xs text-base-content/40">Day {day.num} · {day.items.length} items</div>
							</div>
						</div>

						<div class="ml-5 border-l-2 border-base-300 pl-6 space-y-3">
							{#each day.items as item}
								{#if item.type === 'transport'}
									{@const t = item.data}
									<div class="card bg-base-200 border border-base-300 shadow-sm">
										<div class="card-body p-3">
											<div class="flex items-center gap-3">
												<div class="w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
													<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 16.21v-1.895L14 8.42V4a2 2 0 1 0-4 0v4.42L2 14.315v1.895l8-2.526V18l-2 1.5V21l4-1 4 1v-1.5L16 18v-4.316z"/></svg>
												</div>
												<div class="flex-1 min-w-0">
													<div class="font-semibold text-sm">{t.name || t.flight_number || `${t.from_location} → ${t.to_location}`}</div>
													<div class="text-xs text-base-content/50">{t.from_location} → {t.to_location}</div>
												</div>
												{#if t.date}<div class="text-xs font-medium shrink-0">{formatTime(t.date)}</div>{/if}
											</div>
										</div>
									</div>
								{:else if item.type === 'location'}
									{@const loc = item.data}
									<div class="card bg-base-200 border border-base-300 shadow-sm">
										{#if loc.images?.length > 0}
											<figure class="h-32"><img src={loc.images[0].url} alt="" class="w-full h-full object-cover" /></figure>
										{/if}
										<div class="card-body p-3">
											<div class="flex items-center gap-2">
												<span class="font-semibold text-sm">{loc.name}</span>
												{#if loc.category}<span class="badge badge-xs {categoryBadgeClass(loc.category)}">{loc.category}</span>{/if}
											</div>
											{#if loc.address}<div class="text-xs text-base-content/40">{loc.address}</div>{/if}
											{#if loc.description}<div class="text-xs text-base-content/50 mt-1 line-clamp-2">{@html loc.description}</div>{/if}
										</div>
									</div>
								{:else if item.type === 'note'}
									{@const n = item.data}
									<div class="card bg-base-200 border border-base-300 shadow-sm border-l-4 border-l-warning">
										<div class="card-body p-3">
											<div class="font-semibold text-sm">{n.name}</div>
											{#if n.content}<div class="text-xs text-base-content/60 mt-1">{@html n.content}</div>{/if}
										</div>
									</div>
								{/if}
							{/each}
						</div>

						{#if overnightByDate.has(day.date)}
							{@const hotel = overnightByDate.get(day.date)}
							<div class="mt-3 ml-5 pl-6 border-l-2 border-dashed border-secondary/30">
								<div class="text-sm text-base-content/60 font-medium mb-1.5 flex items-center gap-1.5">
									<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"><path d="M3 14h18v7H3z"/><path d="M3 7v7"/><path d="M21 7v7"/><path d="M3 7l9-4 9 4"/></svg>
									Staying overnight
								</div>
								<div class="flex items-center gap-3 py-2 px-3 rounded-lg bg-secondary/5 border border-secondary/10">
									<span class="text-sm text-base-content/70">{hotel.name}</span>
								</div>
							</div>
						{/if}
					</section>
				{/if}
			{/each}
		</div>
	</div>
{/if}
