// static/js/ui-connect.js – Connect- & Reconnect-Logik

function initConnect() {
  const connectBtn = document.getElementById('connect-btn');
  const reconnectBtn = document.getElementById('reconnect-btn');

  if (connectBtn) {
    connectBtn.addEventListener('click', async () => {
      connectBtn.disabled = true;
      connectBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Verbinde...';

      try {
        console.log("→ Sende /api/connect ...");
        const res = await fetch('/api/connect', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
        const data = await res.json();

        if (data.success) {
          document.getElementById('connect-section').style.display = 'none';
          document.getElementById('control-section').style.display = 'block';
          document.getElementById('reconnect-section').style.display = 'none';

          updateStatus(true);
          startConnectionCheck();
          renderChannels();

          console.log("→ Verbunden");
        } else {
          alert('Verbindungsfehler: ' + (data.message || 'Unbekannt'));
          updateStatus(false);
        }
      } catch (err) {
        console.error("Connect-Fehler:", err);
        alert('Netzwerkfehler');
        updateStatus(false);
      } finally {
        connectBtn.disabled = false;
        connectBtn.innerHTML = '<i class="bi bi-bluetooth me-2"></i> Mit Hub verbinden';
      }
    });
  }

  if (reconnectBtn) {
    reconnectBtn.addEventListener('click', async () => {
      reconnectBtn.disabled = true;
      reconnectBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Verbinde...';

      try {
        const res = await fetch('/api/reconnect', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
        const data = await res.json();

        if (data.success) {
          document.getElementById('reconnect-section').style.display = 'none';
          document.getElementById('control-section').style.display = 'block';

          updateStatus(true);
          startConnectionCheck();
          alert('Verbindung wiederhergestellt!');
        } else {
          alert('Re-Connect fehlgeschlagen: ' + (data.message || 'Unbekannt'));
        }
      } catch (err) {
        console.error("Reconnect-Fehler:", err);
        alert('Netzwerkfehler');
      } finally {
        reconnectBtn.disabled = false;
        reconnectBtn.innerHTML = '<i class="bi bi-arrow-repeat me-2"></i> Erneut verbinden';
      }
    });
  }
}

window.initConnect = initConnect;