<script lang="ts">
	import { onMount, onDestroy } from 'svelte';

	interface MusicTrack {
		id: string; name: string; artists: { name: string }[];
		album: { name: string; images: { url: string }[] };
		duration_ms: number; type: string;
		images?: { url: string }[]; owner?: { display_name: string };
		tracks?: { total: number }; total_tracks?: number; release_date?: string; genres?: string[];
	}
	interface MusicTask {
		task_id: string; status: string; download_type: string;
		name?: string; artist?: string; progress?: number;
		total_items?: number; completed_items?: number; speed?: string; eta?: string; error_message?: string;
	}

	let query = $state('');
	let searchType = $state<'track' | 'album' | 'artist' | 'playlist'>('track');
	let results = $state<MusicTrack[]>([]);
	let tasks = $state<MusicTask[]>([]);
	let searching = $state(false);
	let searched = $state(false);
	let downloading = $state<Set<string>>(new Set());
	let activeView = $state<'search' | 'downloads'>('search');
	let playingId = $state<string | null>(null);
	let playingEmbed = $state<string | null>(null);
	let poll: ReturnType<typeof setInterval> | null = null;

	const activeTasks = $derived(tasks.filter(t => ['downloading', 'queued'].includes(t.status)));

	function artistNames(t: MusicTrack): string { return t.artists?.map(a => a.name).join(', ') || ''; }
	function albumArt(t: MusicTrack): string | null { return t.album?.images?.[0]?.url || t.images?.[0]?.url || null; }
	function fmtDuration(ms: number): string { const m = Math.floor(ms / 60000); const s = Math.floor((ms % 60000) / 1000); return `${m}:${s.toString().padStart(2, '0')}`; }

	async function search() {
		if (!query.trim()) return;
		searching = true; searched = true; results = [];
		try {
			const res = await fetch(`/api/music/api/search?q=${encodeURIComponent(query.trim())}&search_type=${searchType}&limit=30`, { credentials: 'include' });
			if (res.ok) { const data = await res.json(); results = data.items || []; }
		} catch { /* silent */ }
		searching = false;
	}

	async function downloadItem(id: string, type: string) {
		downloading = new Set([...downloading, id]);
		try {
			await fetch(`/api/music/api/${type}/download/${id}`, { credentials: 'include' });
			fetchTasks();
		} catch { /* silent */ }
	}

	async function fetchTasks() {
		try {
			const res = await fetch('/api/music/api/prgs/list', { credentials: 'include' });
			if (res.ok) { const data = await res.json(); tasks = Array.isArray(data) ? data : (data.tasks || []); }
		} catch { /* silent */ }
	}

	async function cancelTask(taskId: string) {
		try { await fetch(`/api/music/api/prgs/cancel/${taskId}`, { method: 'POST', credentials: 'include' }); fetchTasks(); } catch { /* silent */ }
	}

	function togglePlay(id: string) {
		if (playingId === id) { playingId = null; playingEmbed = null; }
		else { playingId = id; playingEmbed = `https://open.spotify.com/embed/track/${id}?utm_source=generator&theme=0`; }
	}

	onMount(() => { fetchTasks(); poll = setInterval(fetchTasks, 3000); });
	onDestroy(() => { if (poll) clearInterval(poll); });
</script>

<!-- Sub-tabs -->
<div class="sub-tabs">
	<button class="sub-tab" class:active={activeView === 'search'} onclick={() => activeView = 'search'}>Search</button>
	<button class="sub-tab" class:active={activeView === 'downloads'} onclick={() => activeView = 'downloads'}>
		Downloads
		{#if activeTasks.length > 0}<span class="sub-badge">{activeTasks.length}</span>{/if}
	</button>
</div>

{#if activeView === 'search'}
	<div class="search-bar">
		<select class="type-select" bind:value={searchType}>
			<option value="track">Tracks</option>
			<option value="album">Albums</option>
			<option value="artist">Artists</option>
			<option value="playlist">Playlists</option>
		</select>
		<div class="search-wrap">
			<svg class="s-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
			<input class="s-input" type="text" placeholder="Search songs, albums, artists..." bind:value={query} onkeydown={(e) => { if (e.key === 'Enter') search(); }} />
		</div>
		<button class="s-btn" onclick={search} disabled={searching || !query.trim()}>
			{#if searching}<span class="spinner"></span>{:else}Search{/if}
		</button>
	</div>

	{#if searching}
		<div class="empty">Searching Spotify...</div>
	{:else if searched && results.length === 0}
		<div class="empty">No results for "{query}"</div>
	{:else if results.length > 0}
		{#if searchType === 'track'}
			{#if playingEmbed}
				<div class="player-wrap">
					<iframe src={playingEmbed} width="100%" height="80" frameborder="0" allow="autoplay; clipboard-write; encrypted-media" title="Spotify player"></iframe>
				</div>
			{/if}
			<div class="track-list">
				{#each results as track (track.id)}
					{@const art = albumArt(track)}
					<div class="track-row">
						<button class="play-btn" onclick={() => togglePlay(track.id)}>
							{#if playingId === track.id}
								<svg viewBox="0 0 24 24" fill="currentColor"><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" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>
							{/if}
						</button>
						{#if art}<img class="track-art" src={art} alt="" loading="lazy" />{/if}
						<div class="track-info">
							<div class="track-name">{track.name}</div>
							<div class="track-artist">{artistNames(track)}{track.album?.name ? ` · ${track.album.name}` : ''}</div>
						</div>
						<span class="track-dur">{track.duration_ms ? fmtDuration(track.duration_ms) : ''}</span>
						{#if downloading.has(track.id)}
							<span class="dl-badge accent">Queued</span>
						{:else}
							<button class="dl-sm-btn" onclick={() => downloadItem(track.id, 'track')}>
								<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
							</button>
						{/if}
					</div>
				{/each}
			</div>
		{:else}
			<div class="card-grid">
				{#each results as item (item.id)}
					{@const art = albumArt(item)}
					<div class="m-card">
						<div class="m-card-img" class:round={searchType === 'artist'}>
							{#if art}<img src={art} alt="" loading="lazy" />{:else}<div class="m-card-placeholder">♪</div>{/if}
						</div>
						<div class="m-card-name">{item.name}</div>
						<div class="m-card-sub">
							{#if searchType === 'playlist'}{item.owner?.display_name || ''}{item.tracks?.total ? ` · ${item.tracks.total} tracks` : ''}
							{:else if searchType === 'album'}{artistNames(item)}{item.release_date ? ` · ${item.release_date.slice(0, 4)}` : ''}
							{:else}{item.genres?.slice(0, 2).join(', ') || 'Artist'}{/if}
						</div>
						<button class="dl-card-btn" onclick={() => downloadItem(item.id, searchType)} disabled={downloading.has(item.id)}>
							{downloading.has(item.id) ? 'Queued' : 'Download'}
						</button>
					</div>
				{/each}
			</div>
		{/if}
	{:else}
		<div class="empty">
			<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" style="width:64px;height:64px;opacity:0.2"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
			<div>Search for music</div>
			<div class="empty-sub">Spotify tracks, albums, playlists</div>
		</div>
	{/if}
{:else}
	<!-- Download Tasks -->
	{#if tasks.length === 0}
		<div class="empty">No music downloads</div>
	{:else}
		<div class="task-list">
			{#each tasks as task (task.task_id)}
				<div class="task-row">
					<div class="task-info">
						<div class="task-name">{task.name || task.task_id}</div>
						{#if task.artist}<div class="task-artist">{task.artist}</div>{/if}
						<div class="task-meta">
							<span class="dl-badge {task.status === 'downloading' ? 'accent' : task.status === 'completed' ? 'success' : task.status === 'error' ? 'error' : 'muted'}">{task.status}</span>
							{#if task.completed_items != null && task.total_items}<span class="task-progress-text">{task.completed_items}/{task.total_items} tracks</span>{/if}
							{#if task.speed}<span class="task-speed">{task.speed}</span>{/if}
							{#if task.eta}<span class="task-eta">ETA {task.eta}</span>{/if}
							{#if task.error_message}<span class="task-error">{task.error_message}</span>{/if}
						</div>
						{#if task.progress != null && task.progress > 0}
							<div class="dl-bar full"><div class="dl-fill" style="width:{task.progress}%"></div></div>
						{/if}
					</div>
					{#if ['downloading', 'queued'].includes(task.status)}
						<button class="action-btn danger" onclick={() => cancelTask(task.task_id)}>Cancel</button>
					{/if}
				</div>
			{/each}
		</div>
	{/if}
{/if}

<style>
	.sub-tabs { display: flex; gap: var(--sp-1); margin-bottom: var(--sp-4); }
	.sub-tab { padding: var(--sp-2) 14px; border-radius: var(--radius-md); font-size: var(--text-base); font-weight: 500; color: var(--text-3); background: none; border: none; cursor: pointer; font-family: var(--font); transition: all var(--transition); display: flex; align-items: center; gap: var(--sp-1.5); }
	.sub-tab:hover { color: var(--text-1); background: var(--card-hover); }
	.sub-tab.active { color: var(--text-1); background: var(--card); box-shadow: var(--shadow-xs); }
	.sub-badge { font-size: var(--text-xs); font-family: var(--mono); background: var(--accent); color: white; padding: 1px 6px; border-radius: var(--radius-xs); }

	.search-bar { display: flex; gap: var(--sp-2); margin-bottom: var(--sp-5); align-items: stretch; }
	.type-select { height: 42px; padding: 0 var(--sp-3); border-radius: var(--radius-md); border: 1px solid var(--border); background: var(--card); color: var(--text-1); font-size: var(--text-sm); font-weight: 500; font-family: var(--font); cursor: pointer; -webkit-appearance: none; appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b6b76' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 10px center; padding-right: 30px; }
	.type-select:focus { outline: none; border-color: var(--accent); }
	.search-wrap { flex: 1; position: relative; }
	.s-icon { position: absolute; left: 14px; top: 50%; transform: translateY(-50%); width: 16px; height: 16px; color: var(--text-4); pointer-events: none; }
	.s-input { width: 100%; height: 42px; padding: 0 14px 0 40px; border-radius: var(--radius-md); border: 1px solid var(--border); background: var(--card); color: var(--text-1); font-size: var(--text-base); font-family: var(--font); box-sizing: border-box; }
	.s-input:focus { outline: none; border-color: var(--accent); }
	.s-input::placeholder { color: var(--text-4); }
	.s-btn { height: 42px; padding: 0 var(--sp-5); border-radius: var(--radius-md); background: var(--accent); color: white; border: none; font-size: var(--text-sm); font-weight: 600; cursor: pointer; font-family: var(--font); white-space: nowrap; }
	.s-btn:disabled { opacity: 0.4; cursor: default; }
	.spinner { width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.3); border-top-color: white; border-radius: 50%; animation: spin 0.6s linear infinite; display: inline-block; }
	@keyframes spin { to { transform: rotate(360deg); } }

	.empty { padding: var(--sp-12); text-align: center; color: var(--text-3); font-size: var(--text-base); display: flex; flex-direction: column; align-items: center; gap: var(--sp-2); }
	.empty-sub { font-size: var(--text-sm); color: var(--text-4); }

	.player-wrap { margin-bottom: var(--sp-3); border-radius: var(--radius); overflow: hidden; }

	.track-list { background: var(--card); border-radius: var(--radius); border: 1px solid var(--border); box-shadow: var(--shadow-sm); overflow: hidden; }
	.track-row { display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-2) var(--sp-3); border-bottom: 1px solid var(--border); transition: background var(--transition); }
	.track-row:last-child { border-bottom: none; }
	.track-row:hover { background: var(--card-hover); }
	.play-btn { width: 32px; height: 32px; border-radius: var(--radius-full); background: none; border: none; cursor: pointer; color: var(--text-3); display: flex; align-items: center; justify-content: center; flex-shrink: 0; transition: color var(--transition); }
	.play-btn:hover { color: var(--accent); }
	.play-btn svg { width: 16px; height: 16px; }
	.track-art { width: 40px; height: 40px; border-radius: var(--radius-xs); object-fit: cover; flex-shrink: 0; }
	.track-info { flex: 1; min-width: 0; }
	.track-name { font-size: var(--text-base); font-weight: 500; color: var(--text-1); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
	.track-artist { font-size: var(--text-sm); color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
	.track-dur { font-size: var(--text-sm); font-family: var(--mono); color: var(--text-4); flex-shrink: 0; }
	.dl-sm-btn { width: 32px; height: 32px; border-radius: var(--radius-md); background: none; border: 1px solid var(--border); cursor: pointer; color: var(--text-3); display: flex; align-items: center; justify-content: center; flex-shrink: 0; transition: all var(--transition); }
	.dl-sm-btn:hover { color: var(--accent); border-color: var(--accent); }
	.dl-sm-btn svg { width: 14px; height: 14px; }

	.card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: var(--sp-4); }
	.m-card { text-align: center; }
	.m-card-img { width: 100%; aspect-ratio: 1; border-radius: var(--radius); overflow: hidden; background: var(--surface-secondary); margin-bottom: var(--sp-2); }
	.m-card-img.round { border-radius: var(--radius-full); }
	.m-card-img img { width: 100%; height: 100%; object-fit: cover; }
	.m-card-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: var(--text-3xl); color: var(--text-4); }
	.m-card-name { font-size: var(--text-sm); font-weight: 600; color: var(--text-1); line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
	.m-card-sub { font-size: var(--text-xs); color: var(--text-3); margin-top: 2px; }
	.dl-card-btn { margin-top: var(--sp-2); padding: var(--sp-1) var(--sp-3); border-radius: var(--radius-md); background: var(--accent); color: white; border: none; font-size: var(--text-xs); font-weight: 600; cursor: pointer; font-family: var(--font); }
	.dl-card-btn:disabled { opacity: 0.4; }

	.dl-badge { font-size: var(--text-xs); font-weight: 600; padding: 2px var(--sp-2); border-radius: var(--radius-xs); text-transform: uppercase; }
	.dl-badge.success { background: var(--success-dim); color: var(--success); }
	.dl-badge.accent { background: var(--accent-dim); color: var(--accent); }
	.dl-badge.error { background: var(--error-dim); color: var(--error); }
	.dl-badge.muted { background: var(--card-hover); color: var(--text-4); }

	.task-list { background: var(--card); border-radius: var(--radius); border: 1px solid var(--border); box-shadow: var(--shadow-sm); overflow: hidden; }
	.task-row { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--sp-4); padding: var(--sp-4); border-bottom: 1px solid var(--border); }
	.task-row:last-child { border-bottom: none; }
	.task-info { flex: 1; min-width: 0; }
	.task-name { font-size: var(--text-base); font-weight: 500; color: var(--text-1); }
	.task-artist { font-size: var(--text-sm); color: var(--text-3); margin-top: 2px; }
	.task-meta { display: flex; align-items: center; gap: var(--sp-2); margin-top: var(--sp-2); flex-wrap: wrap; }
	.task-progress-text { font-size: var(--text-xs); font-family: var(--mono); color: var(--text-3); }
	.task-speed { font-size: var(--text-xs); color: var(--text-4); }
	.task-eta { font-size: var(--text-xs); color: var(--text-4); }
	.task-error { font-size: var(--text-xs); color: var(--error); }
	.dl-bar { width: 100%; height: 4px; background: var(--border); border-radius: 2px; overflow: hidden; margin-top: var(--sp-2); }
	.dl-bar.full { width: 100%; }
	.dl-fill { height: 100%; background: var(--accent); border-radius: 2px; transition: width 0.3s ease; }
	.action-btn { padding: var(--sp-1.5) var(--sp-3); border-radius: var(--radius-md); font-size: var(--text-sm); font-weight: 500; cursor: pointer; font-family: var(--font); flex-shrink: 0; }
	.action-btn.danger { background: none; border: 1px solid var(--error); color: var(--error); }

	@media (max-width: 768px) {
		.search-bar { flex-wrap: wrap; }
		.type-select { width: 100%; }
		.card-grid { grid-template-columns: repeat(2, 1fr); }
	}
</style>
