fetch('./back/generate.php')
  .then(() => fetch('./back/media_list.json'))
  .then(res => res.json())
  .then(data => {
    const container = document.getElementById('audio-list');
    container.innerHTML = '';

    Object.entries(data).forEach(([category, files]) => {
      const section = document.createElement('section');

      if (data[category].length !== 0) {
        const button = document.createElement('button');
        button.setAttribute("id", category);
        const title = document.createElement('h3');
        title.textContent = category === 'racine' ? 'Fichiers sans dossier' : category;
        button.appendChild(title);
        button.addEventListener("click", function() {
          elements = document.querySelectorAll(`div#${this.id}`);
          for (const el of elements) {
            if (el.className.includes("audio-item")) {
              if (el.className.includes("hidden")) {
                el.classList.remove("hidden");
              } else {
                el.classList.add("hidden");
              }
            }
          }
        });
        section.appendChild(button);
      }

      files.forEach(file => {
        const path = category === 'racine' ? file : `${category}/${file}`;
        const item = document.createElement('div');
        item.className = 'audio-item hidden';
        item.id = category;
        item.innerHTML = `
          <p><strong>${file}</strong></p>
          <audio controls src="./media/${path}"></audio>
          <p><a href="./media/${path}" download>Télécharger</a></p>
        `;
        section.appendChild(item);
      });

      container.appendChild(section);
    });
  });