<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import { get } from 'svelte/store';
	import { trackEnded, onPlaybackControl, onSeek, onVolume, reportPlaybackState, type SponsorSegment } from '$lib/socket';
	import { currentVolume } from '$lib/stores/content';

	interface Props {
		src: string;
		type: 'video' | 'audio';
		autoplay?: boolean;
		mimeType?: string;
		sponsorSegments?: SponsorSegment[];
		onmeta?: (width: number, height: number) => void;
		ontimeupdate?: (currentTime: number, duration: number) => void;
	}

	let { src, type, autoplay = true, mimeType, sponsorSegments = [], onmeta, ontimeupdate }: Props = $props();
	let mediaElement: HTMLVideoElement | HTMLAudioElement | null = $state(null);
	let error = $state<string | null>(null);
	let hls: any = null;
	let skippedSegment = $state<string | null>(null);
	let showSponsorBanner = $state(false);
	let needsUserInteraction = $state(true); // Always start true, user must click to confirm sound works
	let unsubPlayback: (() => void) | null = null;
	let unsubSeek: (() => void) | null = null;
	let unsubVolume: (() => void) | null = null;

	const isHLS = mimeType === 'application/x-mpegURL' || src.includes('.m3u8');

	// Category labels for skip notification
	const categoryLabels: Record<string, string> = {
		sponsor: 'Sponsor',
		selfpromo: 'Self-promo',
		intro: 'Intro',
		outro: 'Outro',
		interaction: 'Reminder',
		music_offtopic: 'Off-topic'
	};

	function handleAudioEnabled() {
		console.log('[MediaPlayer] droppyAudioEnabled received');
		if (mediaElement) {
			// User has interacted, unmute and try to play
			mediaElement.muted = false;
			mediaElement.volume = get(currentVolume);
			needsUserInteraction = false;

			if (mediaElement.paused) {
				mediaElement.play().then(() => {
					console.log('[MediaPlayer] Play succeeded after user interaction');
				}).catch((err) => {
					console.log('[MediaPlayer] Play still failed:', err.message);
				});
			}
		}
	}

	onMount(async () => {
		// Listen for audio enable event (user clicked "Click to Start")
		window.addEventListener('droppyAudioEnabled', handleAudioEnabled);

		if (isHLS && type === 'video' && mediaElement) {
			try {
				const Hls = (await import('hls.js')).default;

				if (Hls.isSupported()) {
					hls = new Hls({
						enableWorker: true,
						lowLatencyMode: true,
					});
					hls.loadSource(src);
					hls.attachMedia(mediaElement);
					hls.on(Hls.Events.MANIFEST_PARSED, () => {
						if (autoplay) {
							mediaElement?.play().catch(() => {});
						}
					});
					hls.on(Hls.Events.ERROR, (_: any, data: any) => {
						if (data.fatal) {
							error = 'Failed to load video stream';
						}
					});
				} else if (mediaElement.canPlayType('application/vnd.apple.mpegurl')) {
					mediaElement.src = src;
					if (autoplay) {
						mediaElement.play().catch(() => {});
					}
				} else {
					error = 'HLS not supported in this browser';
				}
			} catch (e) {
				console.error('Failed to load HLS.js:', e);
				error = 'Failed to initialize video player';
			}
		}

		// Set up time update handler for playback state reporting
		if (mediaElement) {
			// Apply initial volume from store
			const initialVolume = get(currentVolume);
			mediaElement.volume = initialVolume;
			console.log('[MediaPlayer] Initial volume set:', initialVolume);

			// Also apply volume when metadata is loaded (ensures it's set before playback)
			mediaElement.addEventListener('loadedmetadata', () => {
				const vol = get(currentVolume);
				if (mediaElement) {
					mediaElement.volume = vol;
					console.log('[MediaPlayer] Volume set on loadedmetadata:', vol);

					// Report video dimensions for vertical video detection
					if (type === 'video' && onmeta) {
						const video = mediaElement as HTMLVideoElement;
						onmeta(video.videoWidth, video.videoHeight);
					}
				}
			});

			mediaElement.addEventListener('timeupdate', handleTimeUpdate);
			mediaElement.addEventListener('play', handlePlayPause);
			mediaElement.addEventListener('pause', handlePlayPause);

			// Show brief "SponsorBlock active" banner when video starts
			if (sponsorSegments.length > 0) {
				mediaElement.addEventListener('playing', handlePlaying, { once: true });
			}
		}

		// Subscribe to remote playback controls
		unsubPlayback = onPlaybackControl((action) => {
			if (!mediaElement) return;
			if (action === 'play') {
				mediaElement.play().catch(() => {});
			} else if (action === 'pause') {
				mediaElement.pause();
			} else if (action === 'toggle') {
				if (mediaElement.paused) {
					mediaElement.play().catch(() => {});
				} else {
					mediaElement.pause();
				}
			}
		});

		// Subscribe to remote seek
		unsubSeek = onSeek((time) => {
			if (mediaElement) {
				mediaElement.currentTime = time;
			}
		});

		// Subscribe to volume changes
		unsubVolume = onVolume((volume) => {
			console.log('[MediaPlayer] Volume change received:', volume, 'mediaElement:', !!mediaElement);
			if (mediaElement) {
				mediaElement.volume = volume;
			}
		});
	});

	function handlePlaying() {
		if (sponsorSegments.length > 0) {
			showSponsorBanner = true;
			setTimeout(() => {
				showSponsorBanner = false;
			}, 3000);
		}
	}

	onDestroy(() => {
		if (hls) {
			hls.destroy();
			hls = null;
		}
		if (mediaElement) {
			mediaElement.removeEventListener('timeupdate', handleTimeUpdate);
			mediaElement.removeEventListener('play', handlePlayPause);
			mediaElement.removeEventListener('pause', handlePlayPause);
		}
		window.removeEventListener('droppyAudioEnabled', handleAudioEnabled);
		unsubPlayback?.();
		unsubSeek?.();
		unsubVolume?.();
	});

	function handleTimeUpdate() {
		if (!mediaElement) return;

		// Report playback state to uploader
		reportPlaybackState({
			playing: !mediaElement.paused,
			currentTime: mediaElement.currentTime,
			duration: mediaElement.duration || 0
		});

		// Report time to parent for progress bar
		if (ontimeupdate) {
			ontimeupdate(mediaElement.currentTime, mediaElement.duration || 0);
		}

		// SponsorBlock skip logic
		if (sponsorSegments.length === 0) return;

		const currentTime = mediaElement.currentTime;

		for (const segment of sponsorSegments) {
			// Check if we're inside a sponsor segment (with small buffer to prevent re-triggering)
			if (currentTime >= segment.start && currentTime < segment.end - 0.5) {
				console.log(`[SponsorBlock] Skipping ${segment.category}: ${segment.start}s -> ${segment.end}s`);
				mediaElement.currentTime = segment.end;

				// Show skip notification
				skippedSegment = categoryLabels[segment.category] || segment.category;
				setTimeout(() => {
					skippedSegment = null;
				}, 2000);
				break;
			}
		}
	}

	function handlePlayPause() {
		if (!mediaElement) return;
		reportPlaybackState({
			playing: !mediaElement.paused,
			currentTime: mediaElement.currentTime,
			duration: mediaElement.duration || 0
		});
	}

	function handleError() {
		if (!isHLS) {
			error = 'Failed to load media. The URL may have expired or be restricted.';
		}
	}

	function handleLoadStart() {
		error = null;
	}

	$effect(() => {
		// Handle autoplay - try unmuted first (works after user clicked "Click to Start")
		// Fall back to muted if browser blocks unmuted autoplay
		if (mediaElement && autoplay && src) {
			const playAttempt = setTimeout(() => {
				if (!mediaElement) return;

				// Set volume and try unmuted autoplay first
				mediaElement.volume = get(currentVolume);
				mediaElement.muted = false;

				mediaElement.play().then(() => {
					console.log('[MediaPlayer] Autoplay succeeded with sound');
					needsUserInteraction = false;
				}).catch(() => {
					// Unmuted autoplay blocked, fall back to muted
					console.log('[MediaPlayer] Unmuted autoplay blocked, trying muted...');
					mediaElement.muted = true;
					mediaElement.play().then(() => {
						console.log('[MediaPlayer] Autoplay started (muted), waiting for user to unmute');
						needsUserInteraction = true;
					}).catch((err) => {
						console.log('[MediaPlayer] Autoplay failed even muted:', err);
					});
				});
			}, 100);

			return () => clearTimeout(playAttempt);
		}
	});

	function handleUnmute() {
		if (mediaElement) {
			mediaElement.muted = false;
			needsUserInteraction = false;
			// Apply stored volume
			const vol = get(currentVolume);
			mediaElement.volume = vol;
			console.log('[MediaPlayer] User unmuted, volume set to:', vol);
		}
	}
</script>

{#if error}
	<div class="error">
		<p>{error}</p>
		<a href={src} target="_blank" rel="noopener noreferrer">Open in new tab</a>
	</div>
{:else if type === 'video'}
	<div class="video-wrapper">
		<video
			bind:this={mediaElement}
			src={isHLS ? undefined : src}
			controls
			playsinline
			class="media-player"
			onerror={handleError}
			onloadstart={handleLoadStart}
			onended={trackEnded}
		>
			Your browser does not support video playback.
		</video>

		{#if skippedSegment}
			<div class="skip-notification">
				<svg viewBox="0 0 24 24"><polygon points="5 4 15 12 5 20 5 4"/><line x1="19" y1="5" x2="19" y2="19"/></svg>
				Skipped {skippedSegment}
			</div>
		{/if}

		{#if showSponsorBanner}
			<div class="sponsor-banner">
				<svg viewBox="0 0 24 24"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
				SponsorBlock active
			</div>
		{/if}

		{#if needsUserInteraction}
			<button class="unmute-overlay" onclick={handleUnmute}>
				<svg viewBox="0 0 24 24">
					<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>
					<path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"/>
				</svg>
				<span>Click for sound</span>
			</button>
		{/if}
	</div>
{:else}
	<div class="audio-container">
		<div class="audio-visual">
			<div class="audio-icon">
				<svg viewBox="0 0 24 24">
					<path d="M9 18V5l12-2v13"/>
					<circle cx="6" cy="18" r="3"/>
					<circle cx="18" cy="16" r="3"/>
				</svg>
			</div>
		</div>
		<audio
			bind:this={mediaElement}
			{src}
			controls
			class="audio-player"
			onerror={handleError}
			onloadstart={handleLoadStart}
			onended={trackEnded}
		>
			Your browser does not support audio playback.
		</audio>
	</div>
{/if}

<style>
	.video-wrapper {
		position: relative;
		width: 100%;
		height: 100%;
	}

	.media-player {
		width: 100%;
		height: 100%;
		max-height: 100vh;
		object-fit: contain;
		background: #000;
	}

	.skip-notification {
		position: absolute;
		bottom: 80px;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		align-items: center;
		gap: 0.5rem;
		padding: 0.75rem 1.25rem;
		background: rgba(0, 0, 0, 0.85);
		backdrop-filter: blur(10px);
		border-radius: 8px;
		color: #4ade80;
		font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
		font-size: 0.9rem;
		font-weight: 500;
		animation: slideUp 0.3s ease-out;
		z-index: 10;
	}

	.skip-notification svg {
		width: 18px;
		height: 18px;
		fill: currentColor;
	}

	@keyframes slideUp {
		from {
			opacity: 0;
			transform: translateX(-50%) translateY(10px);
		}
		to {
			opacity: 1;
			transform: translateX(-50%) translateY(0);
		}
	}

	.sponsor-banner {
		position: absolute;
		top: 1rem;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		align-items: center;
		gap: 0.5rem;
		padding: 0.5rem 1rem;
		background: rgba(0, 0, 0, 0.75);
		backdrop-filter: blur(10px);
		border-radius: 8px;
		color: #4ade80;
		font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
		font-size: 0.85rem;
		font-weight: 500;
		z-index: 10;
		animation: fadeInOut 3s ease-in-out forwards;
	}

	@keyframes fadeInOut {
		0% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
		15% { opacity: 1; transform: translateX(-50%) translateY(0); }
		85% { opacity: 1; transform: translateX(-50%) translateY(0); }
		100% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
	}

	.sponsor-banner svg {
		width: 16px;
		height: 16px;
		fill: none;
		stroke: #4ade80;
		stroke-width: 2;
	}

	.unmute-overlay {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 1rem;
		padding: 2rem 3.5rem;
		background: rgba(0, 0, 0, 0.9);
		backdrop-filter: blur(12px);
		border: 2px solid #FF6B35;
		border-radius: 20px;
		color: #FAFAFA;
		font-family: 'Outfit', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
		font-size: clamp(1.1rem, 2.5vmin, 1.5rem);
		font-weight: 600;
		cursor: pointer;
		z-index: 20;
		transition: all 0.2s ease;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
	}

	.unmute-overlay:hover {
		background: rgba(255, 107, 53, 0.12);
		transform: translate(-50%, -50%) scale(1.03);
	}

	.unmute-overlay svg {
		width: clamp(48px, 7vmin, 64px);
		height: clamp(48px, 7vmin, 64px);
		fill: none;
		stroke: #FF6B35;
		stroke-width: 2;
		stroke-linecap: round;
		stroke-linejoin: round;
	}

	.unmute-overlay span {
		color: rgba(255, 255, 255, 0.6);
		font-size: clamp(0.9rem, 1.8vmin, 1.1rem);
		font-weight: 400;
	}

	.audio-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100%;
		background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
		padding: 2rem;
	}

	.audio-visual {
		margin-bottom: 2rem;
	}

	.audio-icon {
		width: 120px;
		height: 120px;
		animation: pulse 2s ease-in-out infinite;
	}

	.audio-icon svg {
		width: 100%;
		height: 100%;
		stroke: #FF6B35;
		fill: none;
		stroke-width: 1.5;
	}

	@keyframes pulse {
		0%, 100% { transform: scale(1); opacity: 1; }
		50% { transform: scale(1.1); opacity: 0.8; }
	}

	.audio-player {
		width: 100%;
		max-width: 500px;
	}

	.error {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100%;
		color: #ff6b6b;
		text-align: center;
		padding: 2rem;
		font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}

	.error p {
		margin-bottom: 1rem;
		font-size: 1.1rem;
	}

	.error a {
		color: #FF6B35;
		text-decoration: none;
	}

	.error a:hover {
		text-decoration: underline;
	}
</style>
