<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Wake on LAN Service</title>
  <link rel="stylesheet" href="/static/styles.css" />
  <style>
    /* Optional small tweaks that play nice with your existing styles */
    .row { display: flex; gap: 1rem; flex-wrap: wrap; align-items: end; }
    .row .form-group { flex: 1 1 220px; }
    .muted { color: #6b7280; font-size: .95rem; }
    .inline-btns { display: flex; gap: .5rem; flex-wrap: wrap; }
    .section { margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid #e5e7eb; }
    .danger { background: #7f1d1d; border-color: #7f1d1d; }
  </style>
</head>
<body>
  <div class="container">
    <h1>Wake on LAN Service</h1>
    <p>Welcome to the Wake on LAN service. Use the form below to wake devices on your network.</p>

    <div class="device-form">
      <h2>Wake a device</h2>
      <form id="wakeForm" class="wake-form">
        <div class="row">
          <div class="form-group">
            <label for="mac_address">MAC address</label>
            <input id="mac_address" name="mac_address" placeholder="AA:BB:CC:DD:EE:FF" required>
          </div>
          <div class="form-group">
            <label for="ip_address">IP / Broadcast</label>
            <input id="ip_address" name="ip_address" placeholder="255.255.255.255" value="255.255.255.255" required>
          </div>
          <div class="form-group" style="max-width:120px">
            <label for="port_number">Port</label>
            <input id="port_number" name="port_number" type="number" value="9" required>
          </div>
        </div>
        <input type="hidden" name="csrf_token" id="csrf_token_field">
        <div class="inline-btns">
          <button type="submit" class="btn">Send magic packet</button>
        </div>
      </form>
    </div>

    <!-- Saved Hosts -->
    <div class="device-form">
      <h2>Saved hosts</h2>
      <p class="muted" id="hostsStatus">Loading saved hosts…</p>

      <form id="wakeSavedForm" class="wake-form">
        <div class="row">
          <div class="form-group" style="min-width:260px">
            <label for="hostSelect">Choose host:</label>
            <select id="hostSelect" name="name">
              <!-- options injected by JS -->
            </select>
          </div>
          <div class="inline-btns">
            <button type="submit" class="btn">Wake selected</button>
          </div>
        </div>
      </form>

      <div class="section">
        <h3>Add host</h3>
        <form id="addHostForm" class="wake-form">
          <div class="row">
            <div class="form-group">
              <label for="add_name">Name</label>
              <input id="add_name" name="name" placeholder="Gaming PC" required>
            </div>
            <div class="form-group">
              <label for="add_mac">MAC</label>
              <input id="add_mac" name="mac" placeholder="AA:BB:CC:DD:EE:FF" required>
            </div>
            <div class="form-group">
              <label for="add_ip">IP / Broadcast</label>
              <input id="add_ip" name="ip" placeholder="192.168.1.255" required>
            </div>
            <div class="form-group" style="max-width:120px">
              <label for="add_port">Port</label>
              <input id="add_port" name="port" type="number" value="9" required>
            </div>
          </div>
          <div class="inline-btns" style="margin-top:.5rem">
            <button type="submit" class="btn">Add host</button>
          </div>
        </form>
      </div>

      <div class="section">
        <h3>Delete host</h3>
        <form id="delHostForm" class="wake-form">
          <div class="row">
            <div class="form-group" style="min-width:260px">
              <label for="delHostSelect">Choose host to delete:</label>
              <select id="delHostSelect" name="name">
                <!-- options injected by JS -->
              </select>
            </div>
          </div>
          <div class="inline-btns" style="margin-top:.5rem">
            <button type="submit" class="btn danger">Delete</button>
          </div>
        </form>
      </div>
    </div>

    <div id="result" class="result"></div>

    <div class="logout-section">
      <a href="/logout" class="btn btn-secondary">Logout</a>
    </div>
  </div>

  <script>
    // ---- Helpers ----
    const $ = (sel) => document.querySelector(sel);

    function getCookie(name) {
      return document.cookie.split('; ').map(v => v.split('=')).reduce((acc, [k, v]) => {
        acc[k] = v; return acc;
      }, {})[name];
    }

    function getCsrfToken() {
      return getCookie('csrf_token') || '';
    }

    function attachCsrf(data) {
      const token = getCsrfToken();
      if (token) data.append('csrf_token', token);
    }

    function showResult(kind, message) {
      const el = $('#result');
      if (!el) return;
      el.className = `result ${kind}`;
      el.textContent = message;
    }

    async function api(url, opts={}) {
      const csrf = getCsrfToken();
      const headers = new Headers(opts.headers || {});
      const method = (opts.method || 'GET').toUpperCase();
      if (csrf && method !== 'GET') {
        headers.set('X-CSRF-Token', csrf);
      }
      const res = await fetch(url, { ...opts, headers });
      if (!res.ok) {
        const text = await res.text().catch(()=>'');
        throw new Error(text || (res.status + ' ' + res.statusText));
      }
      const ct = res.headers.get('content-type') || '';
      if (ct.includes('application/json')) return res.json();
      return res.text();
    }

    // ---- Saved hosts state ----
    let hosts = [];

    function renderHostSelect() {
      const sel = $('#hostSelect');
      const delSel = $('#delHostSelect');
      if (sel) sel.innerHTML = '';
      if (delSel) delSel.innerHTML = '';
      if (!hosts.length) {
        $('#hostsStatus').textContent = 'No saved hosts yet.';
        if (sel) {
          const opt = document.createElement('option');
          opt.value = ''; opt.textContent = '— none —';
          sel.appendChild(opt);
        }
        if (delSel) {
          const opt = document.createElement('option');
          opt.value = ''; opt.textContent = '— none —';
          delSel.appendChild(opt);
        }
        return;
      }
      $('#hostsStatus').textContent = `${hosts.length} saved host(s).`;
      for (const h of hosts) {
        if (sel) {
          const opt = document.createElement('option');
          opt.value = h.name;
          opt.textContent = `${h.name} (${h.mac} → ${h.ip}:${h.port ?? 9})`;
          sel.appendChild(opt);
        }
        if (delSel) {
          const opt = document.createElement('option');
          opt.value = h.name;
          opt.textContent = `${h.name} (${h.mac} → ${h.ip}:${h.port ?? 9})`;
          delSel.appendChild(opt);
        }
      }
    }

    async function loadHosts() {
      try {
        hosts = await api('/api/hosts');
        if (!Array.isArray(hosts)) hosts = [];
      } catch (e) {
        hosts = [];
        $('#hostsStatus').textContent = 'Saved hosts API not available (manual entry still works).';
      }
      renderHostSelect();
    }

    function findHostByName(name) {
      return hosts.find(h => h.name === name);
    }

    function hydrateCsrfFields() {
      const token = getCsrfToken();
      document.querySelectorAll('input[name=\"csrf_token\"]').forEach(el => {
        el.value = token || '';
      });
    }

    // ---- Wire up forms ----
    document.addEventListener('DOMContentLoaded', () => {
      hydrateCsrfFields();
      loadHosts();

      const wakeForm = $('#wakeForm');
      if (wakeForm) {
        wakeForm.addEventListener('submit', async (e) => {
          e.preventDefault();
          const data = new FormData(wakeForm);
          attachCsrf(data);
          try {
            const res = await api('/wake', { method: 'POST', body: data });
            showResult('success', res.message || 'Magic packet sent');
          } catch (err) {
            showResult('error', err.message);
          }
        });
      }

      // 1) Wake selected (uses existing /wake by filling fields then submitting)
      const wakeSavedForm = $('#wakeSavedForm');
      if (wakeSavedForm) {
        wakeSavedForm.addEventListener('submit', (e) => {
          e.preventDefault();
          const name = $('#hostSelect')?.value;
          const h = findHostByName(name);
          if (!h) return alert('Please choose a saved host.');
          $('#mac_address').value = h.mac || '';
          $('#ip_address').value = h.ip || '';
          $('#port_number').value = h.port ?? 9;
          $('#wakeForm').requestSubmit();
        });
      }

      // 2) Add host (POST /api/hosts as FormData)
      const addHostForm = $('#addHostForm');
      if (addHostForm) {
        addHostForm.addEventListener('submit', async (e) => {
          e.preventDefault();
          const data = new FormData(e.target);
          attachCsrf(data);
          try {
            await api('/api/hosts', { method: 'POST', body: data });
            e.target.reset();
            hydrateCsrfFields();
            await loadHosts();
            showResult('success', 'Host added.');
          } catch (err) {
            showResult('error', 'Add failed: ' + err.message);
          }
        });
      }

      // 3) Delete host (DELETE /api/hosts with FormData)
      const delHostForm = $('#delHostForm');
      if (delHostForm) {
        delHostForm.addEventListener('submit', async (e) => {
          e.preventDefault();
          const data = new FormData(e.target);
          attachCsrf(data);
          try {
            await api('/api/hosts', { method: 'DELETE', body: data });
            e.target.reset();
            hydrateCsrfFields();
            await loadHosts();
            showResult('success', 'Host deleted.');
          } catch (err) {
            showResult('error', 'Delete failed: ' + err.message);
          }
        });
      }
    });
  </script>
</body>
</html>
