document.addEventListener('DOMContentLoaded', () => {
  const list       = document.getElementById('service-list');
  const empty      = document.getElementById('empty-state');
  const dot        = document.getElementById('status-dot');
  const settingsBtn = document.getElementById('settings-btn');

  const icons = {
    online:  `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"></polyline></svg>`,
    offline: `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`,
    unknown: `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>`
  };

  function render() {
    // Lade alle Server und die spezielle Auswahl für das Popup
    chrome.storage.sync.get({services: [], popupServers: []}, (data) => {
      chrome.storage.local.get({serviceStatus: {}}, (local) => {
        const allServices = data.services;
        const popupSelection = data.popupServers;
        const statuses = local.serviceStatus;

        list.innerHTML = '';
        list.appendChild(empty);

        if (allServices.length === 0) {
          dot.className = 'status-dot red';
          empty.style.display = 'flex';
          list.classList.remove('few-servers'); // Klasse entfernen
          return;
        }

        let displayServers = [];

        // Logik zur Bestimmung der anzuzeigenden Server
        if (allServices.length <= 8) {
          // Weniger als 8 Server: Alle anzeigen, Layout anpassen
          displayServers = allServices;
          list.classList.add('few-servers');
        } else {
          // Mehr als 8 Server: Festes 2-Spalten-Layout
          list.classList.remove('few-servers');
          if (popupSelection.length > 0) {
            // Wenn eine Auswahl existiert, diese anzeigen
            displayServers = popupSelection;
          } else {
            // Ansonsten die ersten 8 als Fallback
            displayServers = allServices.slice(0, 8);
          }
        }
        
        const onlineCount = displayServers.filter(s => statuses[s.name]?.status === 'online').length;

        if (onlineCount === displayServers.length) dot.className = 'status-dot green pulse';
        else if (onlineCount === 0)         dot.className = 'status-dot red';
        else                                 dot.className = 'status-dot orange';

        empty.style.display = 'none';

        displayServers.forEach(s => {
          const st = statuses[s.name] || {status: 'unknown', responseTime: null};

          const card = document.createElement('div');
          card.className = 'service-card';

          card.innerHTML = `
            <div class="service-info">
              <h2>${s.name}</h2>
              <p>${s.adresse || ''}</p>
            </div>
            <div class="status-badge ${st.status}">
              ${
                st.status === 'online'
                  ? icons.online + 'Online' + (st.responseTime ? ` · ${st.responseTime} ms` : '')
                : st.status === 'offline'
                  ? icons.offline + 'Offline'
                : icons.unknown + 'Prüfung…'
              }
            </div>
          `;

          list.appendChild(card);
        });
      });
    });
  }

  // Event Listener für Zahnrad-Button
  if (settingsBtn) {
    settingsBtn.addEventListener('click', () => {
      chrome.runtime.openOptionsPage(() => {
        if (chrome.runtime.lastError) {
          console.error(chrome.runtime.lastError);
          window.open('options.html', '_blank'); // Fallback
        }
      });
    });
  }

  render();
  chrome.storage.onChanged.addListener(render);
});