document.addEventListener('DOMContentLoaded', () => {
  const configForm = document.getElementById('config-form');
  const testAudioBtn = document.getElementById('test-audio-btn');
  const audioPlayer = document.querySelector('.audio-player');

  const updateBotStatus = async () => {
    const statusBadge = document.getElementById('bot-status-badge');
    if (!statusBadge) return;

    try {
      const response = await fetch('api/bot_status.php');
      const result = await response.json();

      if (result.running) {
        statusBadge.textContent = 'Online (PID: ' + result.pid + ')';
        statusBadge.className = 'badge badge-connected';
      } else {
        statusBadge.textContent = 'Offline';
        statusBadge.className = 'badge badge-disconnected';
      }
    } catch (error) {
      statusBadge.textContent = 'Error';
      statusBadge.className = 'badge badge-disconnected';
    }
  };

  updateBotStatus();
  setInterval(updateBotStatus, 5000);

  if (configForm) {
    configForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      
      const formData = new FormData(configForm);
      const submitBtn = configForm.querySelector('button[type="submit"]');
      const originalBtnText = submitBtn.textContent;
      
      submitBtn.disabled = true;
      submitBtn.textContent = 'Saving...';

      try {
        const response = await fetch('api/save_settings.php', {
          method: 'POST',
          body: formData
        });

        const result = await response.json();

        if (result.success) {
          alert('Settings saved successfully!');
        } else {
          alert('Error: ' + result.error);
        }
      } catch (error) {
        alert('Network error while saving settings.');
      } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = originalBtnText;
      }
    });
  }

  const deployBtn = document.getElementById('deploy-commands-btn');

  if (deployBtn) {
    deployBtn.addEventListener('click', async () => {
      const originalText = deployBtn.textContent;
      deployBtn.disabled = true;
      deployBtn.textContent = 'Deploying...';

      try {
        const response = await fetch('api/deploy_commands.php');
        const result = await response.json();

        if (result.success) {
          alert('Slash Commands berhasil didaftarkan! Tunggu beberapa saat agar muncul di Discord.');
        } else {
          alert('Gagal: ' + result.error);
        }
      } catch (error) {
        alert('Network error.');
      } finally {
        deployBtn.disabled = false;
        deployBtn.textContent = originalText;
      }
    });
  }

  const startBotBtn = document.getElementById('start-bot-btn');

  if (startBotBtn) {
    startBotBtn.addEventListener('click', async () => {
      const originalText = startBotBtn.textContent;
      startBotBtn.disabled = true;
      startBotBtn.textContent = 'Starting...';

      try {
        const response = await fetch('api/start_bot.php');
        const result = await response.json();

        if (result.success) {
          alert('Bot berhasil dijalankan di background!');
        } else {
          alert('Gagal menjalankan bot: ' + result.error);
        }
      } catch (error) {
        alert('Network error.');
      } finally {
        startBotBtn.disabled = false;
        startBotBtn.textContent = originalText;
      }
    });
  }

  if (testAudioBtn && audioPlayer) {
    testAudioBtn.addEventListener('click', () => {
      if (audioPlayer.paused) {
        audioPlayer.play();
        testAudioBtn.textContent = 'Pause';
      } else {
        audioPlayer.pause();
        testAudioBtn.textContent = 'Test Play Locally';
      }
    });

    audioPlayer.addEventListener('ended', () => {
      testAudioBtn.textContent = 'Test Play Locally';
    });
  }

  // Sahur MP3 Upload Logic
  const sahurUpload = document.getElementById('sahur-upload');
  const uploadBtn = document.getElementById('upload-btn');
  const uploadStatus = document.getElementById('upload-status');

  if (sahurUpload && uploadBtn) {
    sahurUpload.addEventListener('change', () => {
      if (sahurUpload.files.length > 0) {
        uploadBtn.style.display = 'block';
        uploadStatus.textContent = `Selected: ${sahurUpload.files[0].name}`;
      } else {
        uploadBtn.style.display = 'none';
        uploadStatus.textContent = '';
      }
    });

    uploadBtn.addEventListener('click', async () => {
      if (sahurUpload.files.length === 0) return;

      const formData = new FormData();
      formData.append('sahur_file', sahurUpload.files[0]);

      uploadBtn.disabled = true;
      uploadBtn.textContent = 'Uploading...';
      uploadStatus.textContent = 'Processing your file...';

      try {
        const response = await fetch('api/upload_audio.php', {
          method: 'POST',
          body: formData
        });

        const result = await response.json();

        if (result.success) {
          uploadStatus.innerHTML = '<span style="color:var(--primary);">✓ Berhasil di-upload!</span>';
          // Reload page to refresh status and audio player
          setTimeout(() => {
            window.location.reload();
          }, 1500);
        } else {
          uploadStatus.innerHTML = `<span style="color:red;">Gagal: ${result.error}</span>`;
        }
      } catch (error) {
        uploadStatus.innerHTML = '<span style="color:red;">Network error.</span>';
      } finally {
        uploadBtn.disabled = false;
        uploadBtn.textContent = 'Upload Now';
        uploadBtn.style.display = 'none';
        sahurUpload.value = '';
      }
    });
  }
});
