function loadAudios(){
  const el=document.getElementById('page-audios');
  el.innerHTML=`<div class="page-header"><div><h2>🔊 Audio Manager</h2><p>Manage audio files by class name for your apps</p></div><div class="header-actions"><button class="btn btn-primary" onclick="openAudioModal()">➕ Add Audio</button></div></div><div id="audios-list"></div>`;
  fetchAudios();
}
function fetchAudios(){
  api('get_audios',{},'GET').then(r=>{
    if(r.status!=='success')return;
    const el=document.getElementById('audios-list');
    if(!r.data.length){el.innerHTML='<div class="empty-state"><div class="empty-icon">🔇</div><h3>No Audios</h3><p>Add audio files with class names for your apps</p></div>';return;}
    el.innerHTML='<div class="table-wrapper"><table><tr><th>Class Name</th><th>Title</th><th>App</th><th>Preview</th><th>Plays</th><th>Status</th><th>Actions</th></tr>'+
    r.data.map(a=>`<tr>
      <td><code style="background:rgba(255,165,0,0.1);color:#FFA500;padding:3px 8px;border-radius:4px">${a.class_name}</code></td>
      <td>${a.audio_title||'-'}</td>
      <td>${a.linked_app_name||'<span style="color:#666">Global</span>'}</td>
      <td><audio controls style="height:32px;max-width:200px"><source src="${a.audio_url}"></audio></td>
      <td>${a.play_count||0}</td>
      <td><span class="badge ${a.is_active==1?'badge-active':'badge-inactive'}">${a.is_active==1?'Active':'Inactive'}</span></td>
      <td style="white-space:nowrap">
        <button class="btn btn-secondary btn-sm" onclick="openAudioModal(${a.id})">✏️</button>
        <button class="btn btn-sm" style="background:rgba(255,165,0,0.1);color:#FFA500" onclick="toggleAudio(${a.id})">⏯️</button>
        <button class="btn btn-danger btn-sm" onclick="deleteAudio(${a.id})">🗑️</button>
      </td></tr>`).join('')+'</table></div>';
  });
}
function openAudioModal(id=0){
  const title=id?'Edit Audio':'Add Audio';
  // First get apps list for dropdown
  api('get_apps',{page:1},'GET').then(appsR=>{
    const apps=appsR.data||[];
    const appOpts='<option value="">Global (all apps)</option>'+apps.map(a=>`<option value="${a.id}">${a.app_name}</option>`).join('');
    const body=`<form id="audio-form" onsubmit="saveAudio(event)"><input type="hidden" name="id" value="${id}">
      <div class="form-group"><label>Class Name *</label><input name="class_name" required placeholder="e.g. login_audio, win_sound, click_sfx"><div class="hint">Your app will use this class name to request the audio</div></div>
      <div class="form-group"><label>Title</label><input name="audio_title" placeholder="Login Sound Effect"></div>
      <div class="form-group"><label>Link to App</label><select name="app_id">${appOpts}</select><div class="hint">Leave as Global to make available to all apps</div></div>
      <div class="form-group"><label>Audio File *</label>
        <div class="upload-zone" id="audio-zone"><div class="upload-icon">🎵</div><p>Click or drag audio file (mp3, wav, ogg, aac, m4a)</p>
        <input type="file" accept="audio/*" onchange="uploadAudioFile(this.files[0])">
        <div class="upload-progress" id="audio-progress" style="display:none"><div class="progress-bar"><div class="progress-fill" id="audio-progress-fill"></div></div><div class="progress-text" id="audio-progress-text">0%</div></div>
        <div id="audio-preview"></div></div>
        <input type="hidden" name="audio_file" id="audio-file-field">
      </div>
      <div class="form-group"><label class="checkbox"><input type="checkbox" name="is_active" value="1" checked> Active</label></div>
    </form>`;
    const footer=`<button class="btn btn-secondary" onclick="closeModal()">Cancel</button><button class="btn btn-primary" onclick="document.getElementById('audio-form').requestSubmit()">💾 Save Audio</button>`;
    openModal(title,body,footer);
    if(id)api('get_audios',{},'GET').then(r=>{
      const a=(r.data||[]).find(x=>x.id==id);
      if(a){
        const f=document.getElementById('audio-form');
        f.elements.class_name.value=a.class_name||'';
        f.elements.audio_title.value=a.audio_title||'';
        f.elements.app_id.value=a.app_id||'';
        f.elements.is_active.checked=a.is_active==1;
        document.getElementById('audio-file-field').value=a.audio_file||'';
        if(a.audio_url)document.getElementById('audio-preview').innerHTML=`<audio controls style="margin-top:10px;width:100%"><source src="${a.audio_url}"></audio>`;
      }
    });
  });
}
function uploadAudioFile(file){
  if(!file)return;
  const prog=document.getElementById('audio-progress');const fill=document.getElementById('audio-progress-fill');const txt=document.getElementById('audio-progress-text');
  prog.style.display='block';
  const xhr=new XMLHttpRequest();const fd=new FormData();fd.append('action','upload_audio');fd.append('audio',file);
  xhr.upload.onprogress=e=>{if(e.lengthComputable){const pct=Math.round(e.loaded/e.total*100);fill.style.width=pct+'%';txt.textContent=pct+'%';}};
  xhr.onload=()=>{const r=JSON.parse(xhr.responseText);if(r.status==='success'){document.getElementById('audio-file-field').value=r.filename;document.getElementById('audio-preview').innerHTML=`<audio controls style="margin-top:10px;width:100%"><source src="${r.url}"></audio>`;toast('Audio uploaded!');}else toast(r.message,'error');prog.style.display='none';};
  xhr.onerror=()=>{toast('Upload failed','error');prog.style.display='none';};
  xhr.open('POST',API);xhr.send(fd);
}
function saveAudio(e){
  e.preventDefault();const fd=new FormData(e.target);const data={};fd.forEach((v,k)=>data[k]=v);
  if(!data.is_active)data.is_active='0';
  api('save_audio',data).then(r=>{if(r.status==='success'){toast(r.message);closeModal();fetchAudios();}else toast(r.message,'error');});
}
function deleteAudio(id){api('delete_audio',{id}).then(r=>{toast(r.message,r.status==='success'?'success':'error');fetchAudios();});}
function toggleAudio(id){api('toggle_audio',{id}).then(r=>{toast(r.message);fetchAudios();});}
