document.addEventListener('DOMContentLoaded', () => {
  const audio = document.getElementById('myAudio');
  const playPauseBtn = document.getElementById('playPauseBtn');
  const seekSlider = document.getElementById('seekSlider');
  const progressOverlay = document.getElementById('progressOverlay');
  const title = document.getElementById('title');
  const secondTitle = document.getElementById('second-title');

  let isDragging = false;
  let animationFrameId = null;

  const isMobile = /Mobi|Android/i.test(navigator.userAgent);
  playPauseBtn.textContent = isMobile ? '▶' : 'Lecture';

  // Met à jour la barre de progression
  function updateProgress() {
    if (!isDragging && !isNaN(audio.duration)) {
      seekSlider.value = audio.currentTime;
      const percent = (audio.currentTime / audio.duration) * 100;
      progressOverlay.style.width = percent + "%";
    }
    animationFrameId = requestAnimationFrame(updateProgress);
  }

  // Play / Pause
  playPauseBtn.addEventListener('click', () => {
    if (audio.paused) {
      audio.play();
      playPauseBtn.textContent = isMobile ? '⏸' : 'Pause';
      updateProgress();
    } else {
      audio.pause();
      playPauseBtn.textContent = isMobile ? '▶' : 'Lecture';
      cancelAnimationFrame(animationFrameId);
    }
  });

  // Drag de la barre
  seekSlider.addEventListener('input', () => {
    isDragging = true;
    const percent = (seekSlider.value / audio.duration) * 100;
    progressOverlay.style.width = percent + "%";
  });

  seekSlider.addEventListener('change', () => {
    isDragging = false;
    audio.currentTime = parseFloat(seekSlider.value);
  });

  // Quand l'audio change (durée chargée)
  audio.addEventListener('loadedmetadata', () => {
    seekSlider.max = audio.duration;
  });

  // Quand un bouton "Écouter" est cliqué
  document.querySelectorAll('.listen-button').forEach(button => {
    button.addEventListener('click', () => {
      const newSrc = button.getAttribute('data-src');
      const newTitle = button.getAttribute('data-title');
      const newSecondTitle = button.getAttribute('data-second-title');

      if (audio.src !== location.href + newSrc) {
        audio.src = newSrc;
        title.textContent = newTitle || '';
        secondTitle.textContent = newSecondTitle || '';

        audio.load();
        audio.play();
        playPauseBtn.textContent = isMobile ? '⏸' : 'Pause';
        updateProgress();
      } else {
        // Si on reclique sur le même, on relance la lecture
        audio.currentTime = 0;
        audio.play();
        playPauseBtn.textContent = isMobile ? '⏸' : 'Pause';
      }
    });
  });
});
