{% extends "base.html" %}

{% block title %}Soundboard – {{ config.name }}{% endblock %}

{% block content %}
<div class="container my-5">
  <h1>Soundboard – {{ config.name }}</h1>
  <p class="lead mb-4">Wähle einen Sound aus – wird direkt über den Raspberry Pi ausgegeben.</p>

  {% if sounds %}
    <div class="row g-3">
      {% for sound in sounds %}
        <div class="col-md-4 col-lg-3">
          <div class="card h-100 shadow-sm">
            <div class="card-body text-center">
              <h5 class="card-title">{{ sound.name }}</h5>
              {% if sound.description %}
                <p class="card-text text-muted small">{{ sound.description }}</p>
              {% endif %}
              <button class="btn btn-primary mt-3 play-sound-btn"
                      data-sound-id="{{ sound.id }}">
                <i class="bi bi-play-fill me-2"></i> Abspielen
              </button>
            </div>
          </div>
        </div>
      {% endfor %}
    </div>
  {% else %}
    <div class="alert alert-info">
      In dieser Konfiguration sind noch keine Sounds definiert.
    </div>
  {% endif %}

  <div class="mt-5 text-center">
    <a href="{{ url_for('main.control_page') }}" class="btn btn-secondary">Zurück zur Steuerung</a>
  </div>
</div>

{% endblock %}

{% block scripts %}
<script>
  document.querySelectorAll('.play-sound-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
      const soundId = btn.dataset.soundId;
      btn.disabled = true;
      btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Spielt...';

      try {
        const res = await fetch('/api/play_sound', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ sound_id: soundId })
        });

        const data = await res.json();

        if (data.success) {
          btn.classList.remove('btn-primary');
          btn.classList.add('btn-success');
          btn.innerHTML = '<i class="bi bi-check-lg me-2"></i> Gespielt';
          setTimeout(() => {
            btn.classList.remove('btn-success');
            btn.classList.add('btn-primary');
            btn.innerHTML = '<i class="bi bi-play-fill me-2"></i> Abspielen';
            btn.disabled = false;
          }, 2000);
        } else {
          alert('Fehler: ' + (data.message || 'Unbekannt'));
          btn.disabled = false;
          btn.innerHTML = '<i class="bi bi-play-fill me-2"></i> Abspielen';
        }
      } catch (err) {
        console.error('Sound-Play-Fehler:', err);
        alert('Netzwerkfehler beim Abspielen');
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-play-fill me-2"></i> Abspielen';
      }
    });
  });
</script>
{% endblock %}