import { Layout } from "./Layout";

export const IndexPage = () => (
  <Layout title="WiFi Setup">
    <h1>WiFi Configuration</h1>
    <form method="post" action="/save">
      <label>
        SSID (Network Name)
        <select name="ssid" id="ssid-select" required aria-busy="true">
          <option value="">Loading networks...</option>
        </select>
      </label>
      <label>
        Password
        <input type="password" name="password" placeholder="password123" required />
      </label>
      <button type="submit">Connect to Network</button>
    </form>

    <script dangerouslySetInnerHTML={{__html: `
      (async () => {
        const select = document.getElementById('ssid-select');
        try {
          const res = await fetch('/api/networks');
          const data = await res.json();

          select.setAttribute('aria-busy', 'false');

          if (data.networks && data.networks.length > 0) {
            select.innerHTML = '<option value="">Select a network...</option>';
            data.networks.forEach(ssid => {
              const option = document.createElement('option');
              option.value = ssid;
              option.textContent = ssid;
              select.appendChild(option);
            });
          } else {
            select.innerHTML = '<option value="">No networks found</option>';
          }
        } catch (error) {
          console.error('Error loading networks:', error);
          select.setAttribute('aria-busy', 'false');
          select.innerHTML = '<option value="">Error loading networks</option>';
        }
      })();
    `}} />
  </Layout>
);
