<script lang="ts">
	import { createEventDispatcher } from "svelte";
	import type { Prediction } from "$lib/types";
	import "bootstrap-icons/font/bootstrap-icons.css";

	let { prediction }: { prediction: Prediction | null } = $props();

	const dispatch = createEventDispatcher<{
		timeUpdate: { index: number; lat: number; lng: number; alt: number; datetime: Date };
	}>();

	let isPlaying = $state(false);
	let currentIndex = $state(0);
	let playbackSpeed = $state(1);
	let isCollapsed = $state(false);
	let animationFrame: number | null = null;
	let lastUpdateTime = 0;

	$effect(() => {
		if (prediction && currentIndex >= flightPathLength) {
			currentIndex = 0;
		}
	});

	const flightPathLength = $derived(prediction?.flight_path?.length || 0);
	const progress = $derived(flightPathLength > 0 ? (currentIndex / flightPathLength) * 100 : 0);

	const currentPosition = $derived.by(() => {
		if (!prediction || !prediction.flight_path[currentIndex]) return null;

		const point = prediction.flight_path[currentIndex];
		let lat: number, lng: number, alt: number;

		if (Array.isArray(point)) {
			lat = point[0];
			lng = point[1];
			alt = point[2] || 0;
		} else {
			lat = point.lat;
			lng = point.lng;
			alt = point.alt || 0;
		}

		const totalTime = prediction.flight_time;
		const timeProgress = (currentIndex / flightPathLength) * totalTime;
		const launchTime = prediction.launch.datetime instanceof Date
			? prediction.launch.datetime.getTime()
			: new Date(prediction.launch.datetime).getTime();
		const datetime = new Date(launchTime + timeProgress * 1000);

		return { lat, lng, alt, datetime };
	});

	const timeElapsed = $derived.by(() => {
		if (!prediction || !currentPosition) return "00:00:00";
		const launchTime = prediction.launch.datetime instanceof Date
			? prediction.launch.datetime.getTime()
			: new Date(prediction.launch.datetime).getTime();
		const totalSeconds = Math.floor(
			(currentPosition.datetime.getTime() - launchTime) / 1000,
		);
		const hours = Math.floor(totalSeconds / 3600);
		const minutes = Math.floor((totalSeconds % 3600) / 60);
		const seconds = totalSeconds % 60;
		return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
	});

	function animate(timestamp: number) {
		if (!isPlaying) return;

		if (!lastUpdateTime) lastUpdateTime = timestamp;
		const deltaTime = timestamp - lastUpdateTime;

		if (deltaTime >= 50 / playbackSpeed) {
			if (currentIndex < flightPathLength - 1) {
				currentIndex++;
				if (currentPosition) {
					dispatch("timeUpdate", { ...currentPosition, index: currentIndex });
				}
			} else {
				stop();
			}
			lastUpdateTime = timestamp;
		}

		animationFrame = requestAnimationFrame(animate);
	}

	function play() {
		if (!prediction) return;
		if (currentIndex >= flightPathLength - 1) {
			currentIndex = 0;
		}
		isPlaying = true;
		lastUpdateTime = 0;
		animationFrame = requestAnimationFrame(animate);
	}

	function pause() {
		isPlaying = false;
		if (animationFrame !== null) {
			cancelAnimationFrame(animationFrame);
			animationFrame = null;
		}
	}

	function stop() {
		pause();
		currentIndex = 0;
		if (currentPosition) {
			dispatch("timeUpdate", { ...currentPosition, index: currentIndex });
		}
	}

	function handleSliderChange(event: Event) {
		const target = event.target as HTMLInputElement;
		currentIndex = parseInt(target.value);
		if (currentPosition) {
			dispatch("timeUpdate", { ...currentPosition, index: currentIndex });
		}
	}

	function changeSpeed() {
		const speeds = [1, 2, 5, 0.5];
		const currentSpeedIndex = speeds.indexOf(playbackSpeed);
		playbackSpeed = speeds[(currentSpeedIndex + 1) % speeds.length];
	}

	function handleToggleCollapse() {
		isCollapsed = !isCollapsed;
	}

	$effect(() => {
		return () => {
			if (animationFrame !== null) {
				cancelAnimationFrame(animationFrame);
			}
		};
	});
</script>

<div class="timeline-container card shadow-sm">
	<div
		class="card-header bg-primary text-white d-flex justify-content-between align-items-center p-1 px-3"
		style="cursor:pointer;"
		onclick={handleToggleCollapse}
		role="button"
		tabindex="0"
		onkeydown={(e) => e.key === 'Enter' && handleToggleCollapse()}
	>
		<span class="fw-bold mb-0">Flight Timeline</span>
		<button
			type="button"
			class="btn btn-sm btn-primary p-0"
			aria-label="Toggle timeline visibility"
		>
			<i class="bi {isCollapsed ? 'bi-caret-left-fill' : 'bi-caret-down-fill'}"></i>
		</button>
	</div>

	{#if !isCollapsed}
		<div class="card-body p-3">
			<div class="timeline-info mb-2">
				<div class="info-section">
					<span class="form-label mb-1">Time:</span>
					<span class="fw-bold font-monospace">{timeElapsed}</span>
				</div>
				{#if currentPosition}
					<div class="info-section">
						<span class="form-label mb-1">Altitude:</span>
						<span class="fw-bold font-monospace">{Math.round(currentPosition.alt)} m</span>
					</div>
					<div class="info-section">
						<span class="form-label mb-1">Position:</span>
						<span class="fw-bold font-monospace"
							>{currentPosition.lat.toFixed(4)}, {currentPosition.lng.toFixed(4)}</span
						>
					</div>
				{/if}
			</div>

			<div class="timeline-controls">
				<div class="btn-group me-2" role="group">
					<button
						type="button"
						class="btn btn-sm btn-outline-primary"
						onclick={stop}
						disabled={!prediction || currentIndex === 0}
						title="Reset to start"
						aria-label="Reset to start"
					>
						<i class="bi bi-skip-start-fill"></i>
					</button>

					{#if !isPlaying}
						<button
							type="button"
							class="btn btn-sm btn-success"
							onclick={play}
							disabled={!prediction}
							title="Play animation"
							aria-label="Play animation"
						>
							<i class="bi bi-play-fill"></i>
						</button>
					{:else}
						<button
							type="button"
							class="btn btn-sm btn-warning"
							onclick={pause}
							title="Pause animation"
							aria-label="Pause animation"
						>
							<i class="bi bi-pause-fill"></i>
						</button>
					{/if}

					<button
						type="button"
						class="btn btn-sm btn-outline-secondary"
						onclick={changeSpeed}
						disabled={!prediction}
						title="Change playback speed"
						aria-label="Change playback speed"
					>
						{playbackSpeed}x
					</button>
				</div>

				<div class="flex-grow-1 position-relative">
					<input
						type="range"
						min="0"
						max={flightPathLength - 1}
						value={currentIndex}
						oninput={handleSliderChange}
						disabled={!prediction}
						class="form-range timeline-slider"
					/>
				</div>
			</div>
		</div>
	{/if}
</div>

<style>
	.timeline-container {
		position: absolute;
		bottom: 20px;
		left: 50%;
		transform: translateX(-50%);
		min-width: 500px;
		max-width: 700px;
		z-index: 1000;
		background: var(--bs-body-bg, #fff);
		backdrop-filter: blur(10px);
	}

	.timeline-info {
		display: flex;
		justify-content: space-around;
		gap: 0.5rem;
	}

	.info-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 0.001rem;
		flex: 1;
	}

	.timeline-controls {
		display: flex;
		align-items: center;
		gap: 0.5rem;
	}

	/* Custom range slider styling to match Bootstrap theme */
	.timeline-slider::-webkit-slider-thumb {
		background: var(--bs-primary, #007bff);
	}

	.timeline-slider::-moz-range-thumb {
		background: var(--bs-primary, #007bff);
	}

	/* Responsive design */
	@media (max-width: 767.98px) {
		.timeline-container {
			min-width: calc(100vw - 40px);
			max-width: calc(100vw - 40px);
			bottom: 10px;
		}

		.timeline-info {
			flex-direction: column;
			gap: 0.5rem;
		}

		.info-section {
			flex-direction: row;
			justify-content: space-between;
		}

		.btn-group {
			flex-wrap: nowrap;
		}
	}
</style>
