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

	interface Props {
		embedUrl?: string;
		audioUrl?: string;
		title: string;
		artistName?: string;
		thumbnail?: string;
	}

	let { embedUrl, audioUrl, title, artistName, thumbnail }: Props = $props();

	let audioElement: HTMLAudioElement | null = $state(null);
	let isPlaying = $state(false);
	let currentTime = $state(0);
	let duration = $state(0);
	let unsubVolume: (() => void) | null = null;
	let unsubPlayback: (() => void) | null = null;
	let unsubSeek: (() => void) | null = null;

	// Audio mode - when we have audioUrl from YouTube search
	const isAudioMode = !!audioUrl;

	function handleAudioEnabled() {
		console.log('[SpotifyPlayer] droppyAudioEnabled received, attempting play');
		if (audioElement && audioElement.paused) {
			audioElement.play().then(() => {
				console.log('[SpotifyPlayer] Play succeeded after user interaction');
			}).catch((err) => {
				console.log('[SpotifyPlayer] Play still failed:', err.message);
			});
		}
	}

	onMount(() => {
		if (isAudioMode) {
			// Subscribe to global volume
			unsubVolume = currentVolume.subscribe((vol) => {
				if (audioElement) {
					audioElement.volume = vol;
				}
			});

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

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

			// Listen for audio enable event (user clicked "Click to Start")
			window.addEventListener('droppyAudioEnabled', handleAudioEnabled);
		}
	});

	onDestroy(() => {
		unsubVolume?.();
		unsubPlayback?.();
		unsubSeek?.();
		if (isAudioMode) {
			window.removeEventListener('droppyAudioEnabled', handleAudioEnabled);
		}
	});

	function handleTimeUpdate() {
		if (audioElement) {
			currentTime = audioElement.currentTime;
			// Report playback state to uploader
			reportPlaybackState({
				playing: !audioElement.paused,
				currentTime: audioElement.currentTime,
				duration: audioElement.duration || 0
			});
		}
	}

	function handleLoadedMetadata() {
		if (audioElement) {
			duration = audioElement.duration;
			// Apply initial volume from store
			audioElement.volume = get(currentVolume);
			// Auto-play
			audioElement.play().catch(() => {});
		}
	}

	function handlePlay() {
		isPlaying = true;
		if (audioElement) {
			reportPlaybackState({
				playing: true,
				currentTime: audioElement.currentTime,
				duration: audioElement.duration || 0
			});
		}
	}

	function handlePause() {
		isPlaying = false;
		if (audioElement) {
			reportPlaybackState({
				playing: false,
				currentTime: audioElement.currentTime,
				duration: audioElement.duration || 0
			});
		}
	}

	function handleEnded() {
		isPlaying = false;
		trackEnded();
	}

	function togglePlayPause() {
		if (audioElement) {
			if (isPlaying) {
				audioElement.pause();
			} else {
				audioElement.play();
			}
		}
	}

	function seek(e: MouseEvent) {
		if (audioElement && duration) {
			const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
			const percent = (e.clientX - rect.left) / rect.width;
			audioElement.currentTime = percent * duration;
		}
	}

	function formatTime(seconds: number): string {
		if (!seconds || !isFinite(seconds)) return '0:00';
		const mins = Math.floor(seconds / 60);
		const secs = Math.floor(seconds % 60);
		return `${mins}:${secs.toString().padStart(2, '0')}`;
	}
</script>

<div class="spotify-player">
	<!-- Background blur from artwork -->
	{#if thumbnail}
		<div class="player-backdrop" style="background-image: url({thumbnail})"></div>
	{/if}
	<div class="player-overlay"></div>

	<div class="player-content">
		<!-- Artwork -->
		<div class="artwork-section">
			{#if thumbnail}
				<div class="artwork-glow" style="background-image: url({thumbnail})"></div>
				<img src={thumbnail} alt="Album artwork" class="artwork" />
			{:else}
				<div class="artwork-placeholder">
					<svg viewBox="0 0 24 24">
						<circle cx="12" cy="12" r="10"/>
						<polygon points="10 8 16 12 10 16 10 8"/>
					</svg>
				</div>
			{/if}
		</div>

		<!-- Track info and player -->
		<div class="track-section">
			<div class="track-header">
				<div class="track-meta">
					<h1 class="track-title">{title}</h1>
					{#if artistName}
						<p class="track-artist">{artistName}</p>
					{/if}
				</div>
				<div class="spotify-badge">
					<svg viewBox="0 0 24 24">
						<path d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3z"/>
					</svg>
				</div>
			</div>

			{#if isAudioMode}
				<!-- Custom audio player for YouTube-sourced audio -->
				<audio
					bind:this={audioElement}
					src={audioUrl}
					ontimeupdate={handleTimeUpdate}
					onloadedmetadata={handleLoadedMetadata}
					onplay={handlePlay}
					onpause={handlePause}
					onended={handleEnded}
				></audio>

				<div class="audio-controls">
					<button class="play-button" onclick={togglePlayPause} aria-label={isPlaying ? 'Pause' : 'Play'}>
						{#if isPlaying}
							<svg viewBox="0 0 24 24">
								<rect x="6" y="4" width="4" height="16" rx="1"/>
								<rect x="14" y="4" width="4" height="16" rx="1"/>
							</svg>
						{:else}
							<svg viewBox="0 0 24 24">
								<polygon points="5 3 19 12 5 21 5 3"/>
							</svg>
						{/if}
					</button>

					<!-- svelte-ignore a11y_click_events_have_key_events -->
					<!-- svelte-ignore a11y_no_static_element_interactions -->
					<div class="progress-container" onclick={seek}>
						<div class="progress-bar">
							<div class="progress-fill" style="width: {duration ? (currentTime / duration) * 100 : 0}%"></div>
						</div>
						<div class="time-display">
							<span>{formatTime(currentTime)}</span>
							<span>{formatTime(duration)}</span>
						</div>
					</div>
				</div>
			{:else if embedUrl}
				<!-- Spotify embed player -->
				<div class="embed-container">
					<iframe
						src={embedUrl}
						title={title}
						allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
						loading="lazy"
					></iframe>
				</div>
			{:else}
				<!-- No playback available -->
				<div class="no-playback">
					<p>Unable to play this track</p>
					<p class="no-playback-hint">Audio extraction failed</p>
				</div>
			{/if}

			<!-- "Playing on Spotify" label -->
			<div class="playing-label">
				<span class="pulse-dot"></span>
				<span>{isAudioMode ? 'Playing via Spotify' : 'Playing on Spotify'}</span>
			</div>
		</div>
	</div>
</div>

<style>
	.spotify-player {
		position: relative;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
		font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}

	.player-backdrop {
		position: absolute;
		inset: -100px;
		background-size: cover;
		background-position: center;
		filter: blur(80px) saturate(1.5) brightness(0.25);
		transform: scale(1.3);
		animation: backdrop-breathe 8s ease-in-out infinite;
	}

	@keyframes backdrop-breathe {
		0%, 100% { transform: scale(1.3); }
		50% { transform: scale(1.35); }
	}

	.player-overlay {
		position: absolute;
		inset: 0;
		background: linear-gradient(135deg, rgba(30, 215, 96, 0.08) 0%, rgba(0, 0, 0, 0.7) 100%);
	}

	.player-content {
		position: relative;
		z-index: 1;
		display: flex;
		align-items: center;
		gap: clamp(2rem, 5vw, 4rem);
		padding: clamp(2rem, 5vw, 4rem);
		max-width: 1400px;
		width: 100%;
	}

	/* Artwork section */
	.artwork-section {
		position: relative;
		flex-shrink: 0;
	}

	.artwork-glow {
		position: absolute;
		inset: -20px;
		background-size: cover;
		background-position: center;
		filter: blur(40px) saturate(1.5);
		opacity: 0.6;
		border-radius: 20px;
	}

	.artwork {
		position: relative;
		width: clamp(200px, 30vmin, 400px);
		height: clamp(200px, 30vmin, 400px);
		border-radius: 8px;
		object-fit: cover;
		box-shadow:
			0 8px 60px rgba(0, 0, 0, 0.6),
			0 0 0 1px rgba(255, 255, 255, 0.1);
		animation: artwork-float 6s ease-in-out infinite;
	}

	@keyframes artwork-float {
		0%, 100% { transform: translateY(0); }
		50% { transform: translateY(-8px); }
	}

	.artwork-placeholder {
		width: clamp(200px, 30vmin, 400px);
		height: clamp(200px, 30vmin, 400px);
		border-radius: 8px;
		background: linear-gradient(135deg, #1DB954 0%, #191414 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow:
			0 8px 60px rgba(0, 0, 0, 0.6),
			0 0 0 1px rgba(255, 255, 255, 0.1);
	}

	.artwork-placeholder svg {
		width: 40%;
		height: 40%;
		stroke: rgba(255, 255, 255, 0.3);
		fill: none;
		stroke-width: 1.5;
	}

	/* Track section */
	.track-section {
		flex: 1;
		min-width: 0;
		display: flex;
		flex-direction: column;
		gap: 1.5rem;
	}

	.track-header {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 1rem;
	}

	.track-meta {
		min-width: 0;
	}

	.track-title {
		font-size: clamp(2rem, 5vmin, 3.5rem);
		font-weight: 700;
		color: #fff;
		margin: 0;
		line-height: 1.2;
		text-shadow: 0 2px 20px rgba(0, 0, 0, 0.5);
		word-wrap: break-word;
	}

	.track-artist {
		font-size: clamp(1.2rem, 3vmin, 2rem);
		font-weight: 400;
		color: rgba(255, 255, 255, 0.7);
		margin: 0.5rem 0 0;
	}

	.spotify-badge {
		flex-shrink: 0;
		width: 56px;
		height: 56px;
		background: #1DB954;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4px 24px rgba(30, 215, 96, 0.4);
	}

	.spotify-badge svg {
		width: 32px;
		height: 32px;
		fill: #fff;
	}

	/* Audio controls */
	.audio-controls {
		display: flex;
		align-items: center;
		gap: 1.5rem;
		padding: 1.5rem;
		background: rgba(0, 0, 0, 0.4);
		border-radius: 16px;
		box-shadow:
			0 4px 30px rgba(0, 0, 0, 0.3),
			inset 0 0 0 1px rgba(255, 255, 255, 0.1);
	}

	.play-button {
		width: 64px;
		height: 64px;
		border-radius: 50%;
		background: #1DB954;
		border: none;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: transform 0.15s ease, background 0.15s ease;
		flex-shrink: 0;
	}

	.play-button:hover {
		transform: scale(1.05);
		background: #1ed760;
	}

	.play-button:active {
		transform: scale(0.98);
	}

	.play-button svg {
		width: 28px;
		height: 28px;
		fill: #fff;
	}

	.progress-container {
		flex: 1;
		cursor: pointer;
	}

	.progress-bar {
		height: 8px;
		background: rgba(255, 255, 255, 0.2);
		border-radius: 4px;
		overflow: hidden;
	}

	.progress-fill {
		height: 100%;
		background: #1DB954;
		border-radius: 4px;
		transition: width 0.1s linear;
	}

	.time-display {
		display: flex;
		justify-content: space-between;
		margin-top: 0.5rem;
		font-size: clamp(0.9rem, 1.5vmin, 1.1rem);
		color: rgba(255, 255, 255, 0.6);
		font-variant-numeric: tabular-nums;
	}

	/* Spotify embed */
	.embed-container {
		width: 100%;
		height: 152px;
		border-radius: 12px;
		overflow: hidden;
		background: rgba(0, 0, 0, 0.3);
		box-shadow:
			0 4px 30px rgba(0, 0, 0, 0.3),
			inset 0 0 0 1px rgba(255, 255, 255, 0.1);
	}

	.embed-container iframe {
		width: 100%;
		height: 100%;
		border: none;
		border-radius: 12px;
	}

	/* No playback fallback */
	.no-playback {
		padding: 2rem;
		background: rgba(0, 0, 0, 0.4);
		border-radius: 12px;
		text-align: center;
		box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.1);
	}

	.no-playback p {
		margin: 0;
		color: rgba(255, 255, 255, 0.7);
		font-size: 1.2rem;
	}

	.no-playback-hint {
		margin-top: 0.5rem !important;
		font-size: 0.9rem !important;
		color: rgba(255, 255, 255, 0.4) !important;
	}

	/* Playing label */
	.playing-label {
		display: flex;
		align-items: center;
		gap: 0.75rem;
		font-size: clamp(0.9rem, 2vmin, 1.1rem);
		color: rgba(255, 255, 255, 0.5);
		text-transform: uppercase;
		letter-spacing: 0.1em;
	}

	.pulse-dot {
		width: 10px;
		height: 10px;
		background: #1DB954;
		border-radius: 50%;
		animation: pulse 2s ease-in-out infinite;
	}

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

	/* Responsive adjustments */
	@media (max-width: 900px) {
		.player-content {
			flex-direction: column;
			text-align: center;
		}

		.track-header {
			flex-direction: column;
			align-items: center;
		}

		.spotify-badge {
			order: -1;
		}

		.playing-label {
			justify-content: center;
		}

		.audio-controls {
			flex-direction: column;
			gap: 1rem;
		}

		.progress-container {
			width: 100%;
		}
	}
</style>
