let pins = [];

function loadConfig() {
  return fetch('/get_config')
    .then(r => r.json())
    .then(cfg => pins = cfg.pins);
}

function updateButtons() {
  fetch('/states')
    .then(r => r.json())
    .then(states => {
      let html = '';
      for (let p of pins) {
        const state = states[p.pin] == 1;
        html += `
          <button class="button ${state ? 'on':'off'}"
                  onclick="toggle(${p.pin})">
            <span class="icon">${p.icon}</span>
            ${p.name}<br>
            <span class="label">GPIO ${p.pin}</span><br>
            ${state ? 'AN':'AUS'}
          </button>`;
      }
      document.getElementById('buttons').innerHTML = html;
    });
}

function toggle(pin) {
  fetch('/toggle?pin=' + pin)
    .then(() => updateButtons());
}

function allOn() {
  fetch('/all_on')
    .then(() => updateButtons());
}

function allOff() {
  fetch('/all_off')
    .then(() => updateButtons());
}

// Version in Titel + Header einfügen
function injectVersion() {
  fetch('/html_version')
    .then(r => r.text())
    .then(v => {
      document.getElementById("title").innerText = "AdventureControl v" + v;
      document.getElementById("header").innerText = "AdventureControl v" + v;
    });
}



function updateWifiSignal() {
  fetch('/wifi_rssi')
    .then(r => r.json())
    .then(data => {
      const div = document.getElementById("wifi_signal");
      if (!div) return;

      const rssi = data.rssi;

      if (rssi <= -90) {
        div.innerHTML = "";
        return;
      }

      let arcs = 0;
      if (rssi > -50) arcs = 4;
      else if (rssi > -60) arcs = 3;
      else if (rssi > -70) arcs = 2;
      else arcs = 1;

      let colorClass = "wifi-red";
      if (arcs >= 3) colorClass = "wifi-green";
      else if (arcs == 2) colorClass = "wifi-yellow";

      div.className = colorClass;

	div.innerHTML = `
	  <div class="wifi-arc arc4 ${arcs >= 4 ? "active" : ""}"></div>
	  <div class="wifi-arc arc3 ${arcs >= 3 ? "active" : ""}"></div>
	  <div class="wifi-arc arc2 ${arcs >= 2 ? "active" : ""}"></div>
	  <div class="wifi-arc arc1 ${arcs >= 1 ? "active" : ""}"></div>
	`;


    });
}




document.addEventListener("DOMContentLoaded", () => {
  loadConfig().then(updateButtons);
  setInterval(updateButtons, 1000);
  injectVersion();
  
  updateWifiSignal();
  setInterval(updateWifiSignal, 3000);
});

// Service Worker
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register("/service-worker.js");
}
