<script lang="ts">
	import { onMount } from 'svelte';
	import { page } from '$app/stores';
	import { apiService, type Score, type Instrument } from '$lib/api';

	const INSTRUMENT_ICONS: Record<string, string> = {
		dir: '🎼', pic: '/icons/piccolo.png', flu: '/icons/flute.png', cla: '/icons/clarinette.png', clb: '/icons/clarinette_basse.png',
		sax: '/icons/sax-alto.png', sab: '/icons/sax-barython.png', sat: '/icons/sax-tenor.png', coa: '/icons/cor-anglais.jpg', cba: '/icons/contrebasse.png',
		cor: '/icons/cor.png', trp: '/icons/trumpet.png', trb: '/icons/tronbonne.png', tub: '/icons/tuba.png', htb: '/icons/hautbois.png',
		bas: '/icons/basson.png', per: '/icons/percussion.png', crn: '/icons/cornet.png', eup: '/icons/euphonium.png', har: '/icons/harpe.png',
		pia: '🎹', sup: '📄', par: '📄'
	};

	function getInstrumentIcon(code: string): string {
		return INSTRUMENT_ICONS[code] || '🎵';
	}

	let scoreId = '';
	let pieceId = '';
	let instruments: Instrument[] = $state([]);
	let loading = $state(true);
	let error = $state('');

	page.subscribe(($page) => {
		scoreId = $page.params.id || '';
		pieceId = $page.params.piece || '';
	});

	onMount(async () => {
		try {
			const score = await apiService.getScore(scoreId);
			// Filter instruments by piece
			instruments = (score.instruments || []).filter(i => i.piece === pieceId);
		} catch (err) {
			error = 'Erreur lors du chargement';
			console.error(err);
		} finally {
			loading = false;
		}
	});
</script>

<svelte:head>
	<title>Pièce {pieceId} - {scoreId} - OHMJ</title>
</svelte:head>

<div class="container mx-auto px-4 py-8">
	<a href="/scores/{scoreId}" class="inline-flex items-center text-ohmj-primary hover:underline mb-4">
		← Retour aux pièces
	</a>

	<h1 class="text-2xl font-bold text-ohmj-primary mb-6">Instruments - Pièce {pieceId}</h1>

	{#if loading}
		<div class="flex justify-center items-center py-20">
			<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-ohmj-primary"></div>
		</div>
	{:else if error}
		<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
			{error}
		</div>
	{:else}
		<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
			{#each instruments as instrument}
				{@const fileCount = instrument.parts?.[0]?.files?.length || 0}
				{@const icon = getInstrumentIcon(instrument.id)}
				<a
					href="/scores/{scoreId}/{pieceId}/{instrument.id}"
					class="bg-white p-6 rounded-lg shadow hover:shadow-lg transition-shadow border border-gray-200 hover:border-ohmj-primary"
				>
					<div class="text-center">
						<div class="text-4xl mb-2">
							{#if icon.startsWith('/')}
								<img src={icon} alt={instrument.title} class="w-12 h-12 mx-auto object-contain" />
							{:else}
								{icon}
							{/if}
						</div>
						<h3 class="font-semibold text-gray-800">{instrument.title}</h3>
						<p class="text-sm text-gray-500 mt-1">{fileCount} fichier{fileCount !== 1 ? 's' : ''}</p>
					</div>
				</a>
			{/each}
		</div>
	{/if}
</div>
