<!doctype html>
<html lang="nl">
<head>
  <meta charset="utf-8">
  <title>BirdNET-Pi Setup Wizard – EasyComp Zeeland</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="{{ url_for('static', filename='assets/style.css') }}?v={{ BUILD_TS }}">
</head>
<body>
  <!-- debug: step = {{ step }} -->
  <div id="cookieNotice" style="display:block; position:fixed; bottom:30px; left:0; right:0; margin:auto; max-width:420px; background:#e6f8ff; color:#1E73BE; border-radius:10px; box-shadow:0 2px 12px #0001; text-align:center; padding:1.2em 2em; z-index:2000;">
    Deze website gebruikt cookies voor de beste ervaring.
    <button id="acceptCookies" class="btn btn--ghost" style="margin-left:1.2em;">Oké!</button>
  </div>

  <audio id="intro-audio" src="/static/media/intro.mp3" preload="auto"></audio>

  <div class="wizard-container">
    <!-- Sidebar with steps -->
    <div class="wizard-sidebar">
      <img src="{{ logo }}" alt="EasyComp Zeeland logo" class="logo">

      <!-- AUDIO CONTROLS -->
      <div class="audio-controls">
        <button id="audioPlayPause" class="audio-btn" title="Afspelen / Pauzeren"><span id="audioPlayIcon">⏵</span></button>
        <button id="audioVolume" class="audio-btn" title="Volume wijzigen"><span id="audioVolumeIcon">🔊</span></button>
      </div>

      <ul class="wizard-steps" data-url="{{ url_for('setup') }}">
        <li data-step="1" {% if step|int == 1 %}class="active"{% endif %}>1. Netwerkgegevens</li>
        <li data-step="2" {% if step|int == 2 %}class="active"{% endif %}>2. Apparaat & Locatie</li>
        <li data-step="3" {% if step|int == 3 %}class="active"{% endif %}>3. Extra Opties</li>
        <li data-step="4" {% if step|int == 4 %}class="active"{% endif %}>4. Bevestigen</li>
      </ul>

      <div class="sidebar-buttons">
        <button id="openManual" class="btn sidebar-btn" title="Alleen voor mensen met een BirdNET Pi Watchhouse">Handleiding</button>
        <button id="openSupport" class="btn sidebar-btn" title="Alleen voor mensen met een BirdNET Pi Watchhouse">Support via EasyComp Zeeland</button>
        <a href="https://github.com/nachtzuster/birdnetpi" class="btn sidebar-btn" title="GitHub-repo van nacht zuster" target="_blank">GitHub</a>
      </div>
    </div>

    <!-- Main content -->
    <div class="wizard-main">

      {% if step|int == 0 %}
      <!-- Intro -->
      <div class="wizard-intro-full">
        <img src="/static/media/images/ECZ-LOGO-WHITE.png" alt="EasyComp Zeeland Logo" class="intro-logo-main">
        <img src="/static/media/images/BirdNET-pi-logo.png" alt="Vogel" class="intro-bird-main">
        <h2>Welkom bij de BirdNET-Pi WatchHouse Setup Wizard!</h2>
        <p>
          Met deze installatiehulp maak je jouw BirdNET-Pi binnen een paar minuten klaar voor gebruik.<br>
          <span style="color:#fff;">Klik op de knop hieronder om te starten!</span>
        </p>
        <button id="startWizard" class="btn btn--ghost">Start installatie</button>
      </div>

      {% elif step|int == 1 %}
      <!-- Stap 1: Netwerk -->
      <div class="wizard-header">
        <h1>Netwerkgegevens</h1>
        <div class="wizard-progress"><div class="wizard-progress-bar" style="width:25%;"></div></div>
      </div>

      <div class="wizard-content">
        {% with messages = get_flashed_messages() %}
          {% if messages %}<div class="flash">{{ messages[0] }}</div>{% endif %}
        {% endwith %}

        <div class="form-note" id="netHelp">
          Kies hoe je BirdNET-Pi WatchHouse verbinding maakt met internet.
          <br><small>
            Tip: Zie je BirdNET-Pi als een <b>vogelhuisje</b> met een <b>huisnummer</b> in je netwerk. 
            Dat huisnummer (de naam) stellen we later in. 🐦🏠
          </small>
        </div>

        <form method="post" autocomplete="off" aria-describedby="netHelp">
          <input type="hidden" name="step" value="1">

          <!-- Keuze: Wi‑Fi of Ethernet -->
          <label for="connection_type">Hoe wil je verbinden? <span style="color:#b4000b">*</span></label>
          <div role="radiogroup" aria-label="Verbindingsmethode" class="choice-group">
            <label>
              <input type="radio" name="connection_type" value="wifi" {% if data.get('connection_type','wifi') == 'wifi' %}checked{% endif %}> Wi‑Fi
            </label>
            <label>
              <input type="radio" name="connection_type" value="ethernet" {% if data.get('connection_type') == 'ethernet' %}checked{% endif %}> Kabel (Ethernet)
            </label>
          </div>

          <!-- Blok: Wi‑Fi -->
          <div id="wifiBlock" style="margin-top:1em;">
            <label for="ssid">
              Wi‑Fi naam (SSID) <span style="color:#b4000b">*</span>
              <span class="help-tip" tabindex="0" aria-label="Hulp bij Wi‑Fi naam">?
                <span class="tip-content" role="tooltip">
                  <b>Waar vind ik de Wi‑Fi‑naam en het wachtwoord?</b>
                  <ul>
                    <li>Sticker onder/achter je modem of router.</li>
                    <li>Iemand thuis die al verbonden is met het Wi‑Fi.</li>
                    <li>Op je telefoon bij Wi‑Fi‑instellingen.</li>
                  </ul>
                  Tip: het wachtwoord is <b>hoofdlettergevoelig</b>.
                </span>
              </span>
            </label>
            <input id="ssid" type="text" name="ssid" placeholder="Bijv. Mijn Netwerk 5 GHz of EasyVoice Telecom 4G" value="{{ data.get('ssid', '') }}" inputmode="latin">

            <label for="wifi_password">Wi‑Fi wachtwoord <span style="color:#b4000b">*</span></label>
            <input id="wifi_password" type="password" name="wifi_password" minlength="8" autocomplete="off" placeholder="Minimaal 8 tekens, hoofdlettergevoelig" value="{{ data.get('wifi_password', '') }}" aria-describedby="pwHint pwCaps">
            <div style="display:flex;align-items:center;gap:.5em;margin-top:-.5em;">
              <input id="pw_toggle" type="checkbox" style="width:auto;">
              <label for="pw_toggle" style="margin:0; font-weight:400;">Toon wachtwoord</label>
            </div>
            <div id="pwHint" style="font-size:.95em;color:#464F7A; margin:.4em 0 0 0;">
              Voorbeeld: <code>MijnSterkWachtwoord12</code> (let op <b>hoofdletters</b>).
            </div>
            <div id="pwCaps" style="display:none;font-size:.95em;color:#B4000B; margin:.3em 0 0 0;">
              Caps‑Lock staat aan. Je wachtwoord kan daardoor fout gaan.
            </div>

            <label>IP‑instelling (Wi‑Fi)</label>
            <div role="radiogroup" aria-label="Wi‑Fi IP instelling" class="choice-group">
              <label>
                <input type="radio" name="wifi_ip_mode" value="dhcp" {% if data.get('wifi_ip_mode','dhcp') == 'dhcp' %}checked{% endif %}>
                DHCP (automatisch)
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>DHCP:</b> je modem/router geeft automatisch een adres. Meestal is dit wat je wilt.
                  </span>
                </span>
              </label>
              <label>
                <input type="radio" name="wifi_ip_mode" value="static" {% if data.get('wifi_ip_mode') == 'static' %}checked{% endif %}>
                Vast IP (statisch)
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>Vast IP:</b> zelf een vast adres kiezen voor dit vogelhuisje, zodat het altijd op hetzelfde adres te vinden is.
                  </span>
                </span>
              </label>
            </div>

            <div id="wifiStaticFields" style="margin-top:.5em;">
              <div class="row">
                <input type="text" name="wifi_ip" placeholder="IP‑adres (bijv. 192.168.1.123)" value="{{ data.get('wifi_ip','') }}">
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>IP‑adres (Wi‑Fi):</b> het vaste adres van dit vogelhuisje. Kies een vrij adres in je netwerk.
                  </span>
                </span>

                <input type="text" name="wifi_gw" placeholder="Gateway (bijv. 192.168.1.1)" value="{{ data.get('wifi_gw','') }}">
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>Gateway:</b> het adres van je modem/router. De “deur” naar het internet.
                  </span>
                </span>
              </div>
              <div class="row">
                <input type="text" name="wifi_dns" placeholder="DNS (bijv. 1.1.1.1, 8.8.8.8)" value="{{ data.get('wifi_dns','') }}">
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>DNS:</b> het telefoonboek van het internet. Weet je het niet? <code>1.1.1.1</code> of <code>8.8.8.8</code> is prima.
                  </span>
                </span>
              </div>
            </div>
          </div>

          <!-- Blok: Ethernet -->
          <div id="ethBlock" style="margin-top:1em;">
            <label>IP‑instelling (Ethernet)</label>
            <div role="radiogroup" aria-label="Ethernet IP instelling" class="choice-group">
              <label>
                <input type="radio" name="eth_ip_mode" value="dhcp" {% if data.get('eth_ip_mode','dhcp') == 'dhcp' %}checked{% endif %}>
                DHCP (automatisch)
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>DHCP:</b> automatisch een adres via je modem/router. Aanbevolen.
                  </span>
                </span>
              </label>
              <label>
                <input type="radio" name="eth_ip_mode" value="static" {% if data.get('eth_ip_mode') == 'static' %}checked{% endif %}>
                Vast IP (statisch)
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>Vast IP:</b> kies zelf één vast adres voor dit apparaat.
                  </span>
                </span>
              </label>
            </div>

            <div id="ethStaticFields" style="margin-top:1em;">
              <div class="row">
                <input type="text" name="eth_ip" placeholder="IP‑adres (bijv. 192.168.1.123)" value="{{ data.get('eth_ip','') }}">
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>IP‑adres (Ethernet):</b> het vaste adres voor de kabelverbinding.
                  </span>
                </span>

                <input type="text" name="eth_gw" placeholder="Gateway (bijv. 192.168.1.1)" value="{{ data.get('eth_gw','') }}">
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>Gateway:</b> je modem/router‑adres.
                  </span>
                </span>
              </div>
              <div class="row">
                <input type="text" name="eth_dns" placeholder="DNS (bijv. 1.1.1.1, 8.8.8.8)" value="{{ data.get('eth_dns','') }}">
                <span class="help-tip" tabindex="0">?<span class="tip-content" role="tooltip">
                    <b>DNS:</b> telefoonboek van het internet. <code>1.1.1.1</code> of <code>8.8.8.8</code> werkt goed.
                  </span>
                </span>
              </div>
            </div>
          </div>

          <div class="wizard-buttons">
            <button type="submit" class="btn">Volgende</button>
          </div>
        </form>
      </div>

      <script>
      (function(){
        const byId = (id) => document.getElementById(id);

        // Toggle wachtwoord
        const pw = byId('wifi_password');
        const toggle = byId('pw_toggle');
        const caps = byId('pwCaps');
        if (pw && toggle) {
          toggle.addEventListener('change', () => { pw.type = toggle.checked ? 'text' : 'password'; });
          const updCaps = (e) => { if ('getModifierState' in e) caps.style.display = e.getModifierState('CapsLock') ? 'block' : 'none'; };
          pw.addEventListener('keydown', updCaps);
          pw.addEventListener('keyup',   updCaps);
        }

        function syncBlocks(){
          const type = (document.querySelector('input[name="connection_type"]:checked')||{}).value || 'wifi';
          const wifi = byId('wifiBlock');
          const eth  = byId('ethBlock');
          if (wifi && eth){
            wifi.style.display = (type === 'wifi') ? 'block' : 'none';
            eth.style.display  = (type === 'ethernet') ? 'block' : 'none';
          }
          const wifiMode = (document.querySelector('input[name="wifi_ip_mode"]:checked')||{}).value || 'dhcp';
          byId('wifiStaticFields').style.display = (wifiMode === 'static') ? 'block' : 'none';
          const ethMode  = (document.querySelector('input[name="eth_ip_mode"]:checked')||{}).value || 'dhcp';
          byId('ethStaticFields').style.display  = (ethMode  === 'static') ? 'block' : 'none';
        }
        document.querySelectorAll('input[name="connection_type"],input[name="wifi_ip_mode"],input[name="eth_ip_mode"]')
          .forEach(el => el.addEventListener('change', syncBlocks));
        syncBlocks();

        // Tooltips: klik toggelt open/close, Esc sluit
        document.addEventListener('click', (e) => {
          const tip = e.target.closest('.help-tip');
          document.querySelectorAll('.help-tip.open').forEach(el => { if (el !== tip) el.classList.remove('open'); });
          if (tip) { e.preventDefault(); tip.classList.toggle('open'); }
        });
        document.addEventListener('keydown', (e) => {
          if (e.key === 'Escape') document.querySelectorAll('.help-tip.open').forEach(el => el.classList.remove('open'));
        });
      })();
      </script>

      {% elif step|int == 2 %}
      <!-- Stap 2: Apparaat & Locatie -->
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
        integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="">
      <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
        integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

      <div class="wizard-header">
        <h1>BirdNET-Pi Setup Wizard</h1>
        <div class="wizard-progress"><div class="wizard-progress-bar" style="width:50%;"></div></div>
      </div>

      <div class="wizard-content">
        {% with messages = get_flashed_messages() %}{% if messages %}<div class="flash">{{ messages[0] }}</div>{% endif %}{% endwith %}
        <div class="form-note">
          Stel hier de gegevens van dit BirdNET-Pi WatchHouse in.<br>
          Kies het unieke WatchHouse-nummer voor dit station.<br>
          De naam en locatie worden automatisch ingevuld zodat dit station herkenbaar is in je netwerk en op BirdWeather.
        </div>

        <form method="post" autocomplete="off">
          <input type="hidden" name="step" value="2">

          <!-- Hostnaam (suffix) -->
          <label for="hostname">
            BirdNET PI Watchhouse nummer <span style="color:#b4000b">*</span>
            <span class="help-tip" tabindex="0">?
              <span class="tip-content" role="tooltip">
                Dit is het <b>laatste stukje</b> van je hostnaam (bijv. huisnummer of korte code).<br>
                De uiteindelijke hostnaam wordt <code>ECZ-BIRDNET-PI-&lt;suffix&gt;</code>.
              </span>
            </span>
          </label>
          <input id="hostname" type="text" name="hostname" pattern="^[A-Za-z0-9\-]+$" required
                 placeholder="Bijv. 01 of 02 als u een tweede huis installeert enzovoort." value="{{ data.get('hostname', '') }}">

          <!-- Adres zoeken -->
          <label for="addressSearch">
            Adres zoeken (NL)
            <span class="help-tip" tabindex="0">?
              <span class="tip-content" role="tooltip">
                Begin te typen (straat, plaats). Kies een suggestie of druk op Enter.<br>
                We vullen automatisch de kaart, coördinaten, plaats en provincie in.
              </span>
            </span>
          </label>
          <div class="search-wrap">
            <input id="addressSearch" type="text" placeholder="Bijv. Markt 1, Middelburg" inputmode="search">
            <div id="searchResults" class="search-results" role="listbox" aria-label="Adres suggesties"></div>
          </div>

          <!-- Kaart -->
          <label>
            Locatie op de kaart
            <span class="help-tip" tabindex="0">?
              <span class="tip-content" role="tooltip">
                Versleep de pin of klik op de kaart om je locatie te kiezen. We vullen automatisch de velden in.
              </span>
            </span>
          </label>
          <div id="map" aria-label="Kaart voor locatiekeuze"></div>

          <!-- Adres details (optioneel, auto gevuld) -->
          <div class="row" style="margin-top:.8em;">
            <input id="street"   type="text" name="street"   placeholder="Straat"   value="{{ data.get('street','') }}">
            <input id="houseno"  type="text" name="houseno"  placeholder="Huisnr."  value="{{ data.get('houseno','') }}">
          </div>
          <div class="row">
            <input id="postcode" type="text" name="postcode" placeholder="Postcode"  value="{{ data.get('postcode','') }}">
            <input id="city"     type="text" name="city"     placeholder="Plaatsnaam" value="{{ data.get('city','') }}">
            <input id="province" type="text" name="province" placeholder="Provincie"  value="{{ data.get('province','') }}">
          </div>

          <!-- Apparaatnaam (readonly, wordt gegenereerd) -->
          <label for="site_name">
            Apparaatnaam (readonly) <span style="color:#b4000b">*</span>
            <span class="help-tip" tabindex="0">?
              <span class="tip-content" role="tooltip">
                Wordt automatisch opgebouwd als:<br>
                <code>ECZ-BirdNET-PI-WatchHouse-<b>Locatienaam</b>-<b>Suffix</b></code><br>
                Suffix = hostnaam‑suffix hierboven. Locatienaam komt uit het adres / de kaart.
              </span>
            </span>
          </label>
          <input id="site_name" type="text" name="site_name" readonly
                 value="{{ data.get('site_name','') }}" placeholder="Wordt automatisch ingevuld…">

          <!-- Locatienaam (readonly, samengesteld uit plaats + provincie) -->
          <input id="location_name" type="hidden" name="location_name" readonly
                 value="{{ data.get('location_name','') }}">

          <!-- Coördinaten -->
          <label>Coördinaten <span style="color:#b4000b">*</span></label>
          <div class="row">
            <input id="latitude"  type="text" name="latitude"  required placeholder="Breedtegraad"
                   value="{{ data.get('latitude', '') }}">
            <input id="longitude" type="text" name="longitude" required placeholder="Lengtegraad"
                   value="{{ data.get('longitude', '') }}">
          </div>

          <div class="wizard-buttons">
            <button type="submit" class="btn-nav btn--secondary back" name="back" value="2" formaction="{{ url_for('setup') }}">Terug</button>
            <button type="submit" class="btn">Volgende</button>
          </div>
        </form>
      </div>

      <script>
      (function(){
        // ---------- Helpers ----------
        const byId = (id) => document.getElementById(id);
        const prefix = 'ECZ-BirdNET-PI-WatchHouse';

        function slugify(str) {
          return (str || '')
            .normalize('NFKD').replace(/[\u0300-\u036f]/g,'')
            .replace(/[^A-Za-z0-9\- ]+/g, '')
            .trim().replace(/\s+/g, '-');
        }
        function buildSiteName() {
          const loc = byId('location_name').value.trim();
          const suffix = byId('hostname').value.trim();
          const parts = [prefix];
          if (loc) parts.push(slugify(loc));
          if (suffix) parts.push(slugify(suffix));
          byId('site_name').value = parts.join('-');
        }
        function composeLocationName(addr){
          const city = addr.city || addr.town || addr.village || addr.hamlet || '';
          const prov = addr.state || addr.county || '';
          return [city, prov].filter(Boolean).join('-');
        }
        function setMarker(lat, lon, label){
          marker.setLatLng([lat, lon]);
          map.setView([lat, lon], 15);
          if (label) marker.bindPopup(label, { autoClose: true });
        }
        function fillFromAddress(addr, lat, lon, display_name){
          byId('street').value   = (addr.road || addr.pedestrian || addr.cycleway || addr.footway || addr.path || '') || '';
          byId('houseno').value  = addr.house_number || '';
          byId('postcode').value = addr.postcode || '';
          byId('city').value     = addr.city || addr.town || addr.village || addr.hamlet || '';
          byId('province').value = addr.state || addr.county || '';
          byId('latitude').value  = (+lat).toFixed(6);
          byId('longitude').value = (+lon).toFixed(6);
          byId('location_name').value = composeLocationName(addr);
          buildSiteName();
          setMarker(+lat, +lon, display_name || '');
        }
        function reverseGeocode(lat, lon){
          fetch(`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lon}&accept-language=nl&addressdetails=1`)
            .then(r => r.json())
            .then(data => { if (data && data.address) fillFromAddress(data.address, lat, lon, data.display_name); })
            .catch(console.warn);
        }

        // ---------- Leaflet Kaart ----------
        const lat0 = parseFloat(byId('latitude').value)  || 52.1326;
        const lon0 = parseFloat(byId('longitude').value) || 5.2913;
        const map = L.map('map').setView([lat0, lon0], (byId('latitude').value && byId('longitude').value) ? 13 : 7);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          maxZoom: 19, attribution: '&copy; OpenStreetMap'
        }).addTo(map);

        let marker = L.marker([lat0, lon0], { draggable: true }).addTo(map);

        marker.on('dragend', () => {
          const {lat, lng} = marker.getLatLng();
          byId('latitude').value = lat.toFixed(6);
          byId('longitude').value = lng.toFixed(6);
          reverseGeocode(lat, lng);
        });

        map.on('click', (e) => {
          const lat = e.latlng.lat, lon = e.latlng.lng;
          setMarker(lat, lon);
          byId('latitude').value = lat.toFixed(6);
          byId('longitude').value = lon.toFixed(6);
          reverseGeocode(lat, lon);
        });

        // ---------- Adres zoeken (autocomplete) ----------
        const searchInput = byId('addressSearch');
        const resultsBox  = byId('searchResults');
        let debounceTimer;

        function showResults(items){
          resultsBox.innerHTML = '';
          if (!items || !items.length) { resultsBox.classList.remove('show'); return; }
          items.forEach((it, idx) => {
            const b = document.createElement('button');
            b.type = 'button';
            b.setAttribute('role','option');
            b.setAttribute('aria-posinset', String(idx+1));
            b.textContent = it.display_name;
            b.addEventListener('click', () => {
              resultsBox.classList.remove('show');
              searchInput.value = it.display_name;
              fillFromAddress(it.address || {}, it.lat, it.lon, it.display_name);
            });
            resultsBox.appendChild(b);
          });
          resultsBox.classList.add('show');
        }

        function searchAddress(q){
          if (!q || q.trim().length < 3) { showResults([]); return; }
          const url = `https://nominatim.openstreetmap.org/search?format=jsonv2&q=${encodeURIComponent(q)}&countrycodes=nl&addressdetails=1&accept-language=nl&limit=8`;
          fetch(url).then(r => r.json()).then(showResults).catch(_ => showResults([]));
        }

        searchInput.addEventListener('input', () => {
          clearTimeout(debounceTimer);
          debounceTimer = setTimeout(() => searchAddress(searchInput.value), 350);
        });

        document.addEventListener('click', (e) => {
          if (!resultsBox.contains(e.target) && e.target !== searchInput) {
            resultsBox.classList.remove('show');
          }
        });

        // Live afleiding van site_name
        ['hostname','location_name'].forEach(id => byId(id).addEventListener('input', buildSiteName));

        // Init: als coords al bekend zijn, reverse geocode; anders zachte geo-probe
        if (byId('latitude').value && byId('longitude').value) {
          reverseGeocode(byId('latitude').value, byId('longitude').value);
        } else if ('geolocation' in navigator) {
          navigator.geolocation.getCurrentPosition((pos) => {
            const lat = pos.coords.latitude, lon = pos.coords.longitude;
            byId('latitude').value = lat.toFixed(6);
            byId('longitude').value = lon.toFixed(6);
            reverseGeocode(lat, lon);
          }, () => {/* stil */}, { enableHighAccuracy: true, timeout: 5000 });
        }

        // Eerste build
        buildSiteName();
      })();
      </script>

    {% elif step|int == 3 %}
<!-- Stap 3: Extra opties -->
<div class="wizard-header">
  <h1>Extra opties</h1>
  <div class="wizard-progress"><div class="wizard-progress-bar" style="width:75%;"></div></div>
</div>

<div class="wizard-content">
  {% with messages = get_flashed_messages() %}{% if messages %}<div class="flash">{{ messages[0] }}</div>{% endif %}{% endwith %}

  <div class="form-note">
    Deze instellingen zijn <b>niet verplicht</b>. Je kunt ze later altijd nog aanpassen.
  </div>

  <form method="post" autocomplete="off" novalidate>
    <input type="hidden" name="step" value="3">

    <!-- BirdWeather -->
    <label for="birdweather_id">
      BirdWeather code (optioneel)
      <span class="help-tip" tabindex="0">?
        <span class="tip-content" role="tooltip">
          Heb je een BirdWeather‑account? Vul hier je code in zodat je waarnemingen online gedeeld worden.
          Geen account? Laat dit veld leeg – dat is prima.
        </span>
      </span>
    </label>
    <input
      id="birdweather_id"
      type="text"
      name="birdweather_id"
      placeholder="Bijv. BW-1234-ABCD"
      value="{{ data.get('birdweather_id', '') }}"
      inputmode="latin"
      spellcheck="false"
      {% if data.get('lock_birdweather') %}readonly aria-readonly="true" class="readonly"{% endif %}
    >

    <!-- Wachtwoord webpagina -->
    <label for="caddy_pwd">
      Wachtwoord voor je vogelpagina
      <span class="help-tip" tabindex="0">?
        <span class="tip-content" role="tooltip">
          Hiermee log je in op de BirdNET‑Pi webpagina. Kies iets dat je onthoudt.
        </span>
      </span>
    </label>
    <input
      id="caddy_pwd"
      type="password"
      name="caddy_pwd"
      placeholder="Kies een wachtwoord (min. 6 tekens)"
      value="{{ data.get('caddy_pwd', '') }}"
      autocomplete="new-password"
    >
    <div style="display:flex;align-items:center;gap:.5em;margin:.3em 0 1em;">
      <input id="caddy_toggle" type="checkbox" style="width:auto;">
      <label for="caddy_toggle" style="margin:0; font-weight:400;">Toon wachtwoord</label>
    </div>

    <!-- Live luisteren (audio) -->
    <label for="ice_pwd">
      Wachtwoord voor live luisteren (optioneel)
      <span class="help-tip" tabindex="0">?
        <span class="tip-content" role="tooltip">
          Alleen nodig als je live audio (luisteren) aanzet via Icecast/ezstream.
          Gebruik je dat niet? Laat leeg.
        </span>
      </span>
    </label>
    <input
      id="ice_pwd"
      type="text"
      name="ice_pwd"
      placeholder="Alleen invullen als je live audio gebruikt"
      value="{{ data.get('ice_pwd', '') }}"
      spellcheck="false"
      autocomplete="off"
    >

    <!-- Webadres van je vogelpagina -->
    <label for="birdnetpi_url">
      Webadres van je vogelpagina (optioneel)
      <span class="help-tip" tabindex="0">?
        <span class="tip-content" role="tooltip">
          Het internet‑adres waarop jouw WatchHouse te zien is.
          Voorbeeld: <code>https://mijn-vogelpagina.domein.nl</code>
        </span>
      </span>
    </label>
    <input
      id="birdnetpi_url"
      type="url"
      name="birdnetpi_url"
      placeholder="https://jouw-watchhouse.domein.nl"
      value="{{ data.get('birdnetpi_url', '') }}"
      pattern="https?://.+"
      inputmode="url"
      spellcheck="false"
    >

    <!-- Camera (RTSP) -->
    <label for="rtsp_stream">
      Adres van je camera (optioneel)
      <span class="help-tip" tabindex="0">?
        <span class="tip-content" role="tooltip">
          Gebruik je een IP‑camera of microfoon met RTSP? Vul hier het adres in.
          Voorbeeld: <code>rtsp://gebruiker:wachtwoord@192.168.1.10:554/stream</code>
        </span>
      </span>
    </label>
    <input
      id="rtsp_stream"
      type="text"
      name="rtsp_stream"
      placeholder="rtsp://user:pass@ip-adres:poort/stream"
      value="{{ data.get('rtsp_stream', '') }}"
      inputmode="text"
      spellcheck="false"
    >

    <!-- Foto’s bij soorten (Flickr) -->
    <label for="flickr_api_key">
      Foto’s bij vogelsoorten (aanbevolen)
      <span class="help-tip" tabindex="0">?
        <span class="tip-content" role="tooltip">
          Hiermee kan je BirdNET‑Pi voorbeeldfoto’s tonen van soorten. Dit staat al goed voor je ingevuld.
        </span>
      </span>
    </label>
    <input
      id="flickr_api_key"
      type="text"
      name="flickr_api_key"
      placeholder="Wordt automatisch ingevuld"
      value="{{ data.get('flickr_api_key', '8427550a6678894dfe644455025bcf3a') or '8427550a6678894dfe644455025bcf3a' }}"
      inputmode="latin"
      spellcheck="false"
    >

    <div class="wizard-buttons">
      <button type="submit" class="btn-nav btn--secondary back" name="back" value="3" formaction="{{ url_for('setup') }}">Terug</button>
      <button type="submit" class="btn">Volgende</button>
    </div>
  </form>
</div>

<script>
  // Toggle voor "toon wachtwoord" bij caddy_pwd
  (function(){
    const pw = document.getElementById('caddy_pwd');
    const t = document.getElementById('caddy_toggle');
    if (pw && t) t.addEventListener('change', () => { pw.type = t.checked ? 'text' : 'password'; });
  })();
</script>

{% elif step|int == 4 %}
      <!-- Stap 4: Bevestigen -->
      <div class="wizard-header">
        <h1>BirdNET-Pi Setup Wizard</h1>
        <div class="wizard-progress"><div class="wizard-progress-bar" style="width:100%;"></div></div>
      </div>
      <div class="wizard-content">
        {% with messages = get_flashed_messages() %}{% if messages %}<div class="flash">{{ messages[0] }}</div>{% endif %}{% endwith %}
        <div class="form-note">Controleer je instellingen hieronder. Klik op 'Afronden' om de installatie te starten.</div>
        <form method="post" autocomplete="off">
          <input type="hidden" name="step" value="4">
        <ul style="font-size:1.05em; line-height:1.6; color:#1E73BE; list-style: none; padding:0; margin:0;">
  <!-- Netwerk -->
  <li style="margin:.25em 0;"><b>Verbinding:</b> {{ 'Wi‑Fi' if data.get('connection_type')=='wifi' else 'Kabel (Ethernet)' }}</li>
  <li style="margin:.25em 0;"><b>Wi‑Fi netwerk (SSID):</b> {{ data.get('ssid','') or '—' }}</li>

  {% if data.get('connection_type') == 'wifi' %}
    <li style="margin:.25em 0;"><b>IP‑instelling (Wi‑Fi):</b> {{ 'DHCP (automatisch)' if data.get('wifi_ip_mode')=='dhcp' else 'Vast IP (statisch)' }}</li>
    {% if data.get('wifi_ip_mode') == 'static' %}
      <li style="margin:.25em 0;"><b>Wi‑Fi IP‑adres:</b> {{ data.get('wifi_ip','') or '—' }}</li>
      <li style="margin:.25em 0;"><b>Wi‑Fi Gateway:</b> {{ data.get('wifi_gw','') or '—' }}</li>
      <li style="margin:.25em 0;"><b>Wi‑Fi DNS:</b> {{ data.get('wifi_dns','') or '—' }}</li>
    {% endif %}
  {% else %}
    <li style="margin:.25em 0;"><b>IP‑instelling (Ethernet):</b> {{ 'DHCP (automatisch)' if data.get('eth_ip_mode')=='dhcp' else 'Vast IP (statisch)' }}</li>
    {% if data.get('eth_ip_mode') == 'static' %}
      <li style="margin:.25em 0;"><b>Ethernet IP‑adres:</b> {{ data.get('eth_ip','') or '—' }}</li>
      <li style="margin:.25em 0;"><b>Ethernet Gateway:</b> {{ data.get('eth_gw','') or '—' }}</li>
      <li style="margin:.25em 0;"><b>Ethernet DNS:</b> {{ data.get('eth_dns','') or '—' }}</li>
    {% endif %}
  {% endif %}

  <!-- Apparaat & locatie -->
  <li style="margin:.25em 0;"><b>Hostnaam:</b> ECZ-BIRDNET-PI-{{ data.get('hostname','') or '—' }}</li>
  <li style="margin:.25em 0;"><b>Apparaatnaam:</b> {{ data.get('site_name','') or '—' }}</li>
  <li style="margin:.25em 0;"><b>Coördinaten (lat,lon):</b> {{ data.get('latitude','') or '—' }}, {{ data.get('longitude','') or '—' }}</li>
  <li style="margin:.25em 0;"><b>Adres:</b>
    {% set straat = data.get('street','') %}
    {% set nr = data.get('houseno','') %}
    {% set pc = data.get('postcode','') %}
    {% set plaats = data.get('city','') %}
    {% set prov = data.get('province','') %}
    {% if straat or nr or pc or plaats or prov %}
      {{ (straat ~ (' ' ~ nr if nr else '')) ~ (', ' ~ pc if pc else '') ~ (', ' ~ plaats if plaats else '') ~ (', ' ~ prov if prov else '') }}
    {% else %}
      —
    {% endif %}
  </li>

  <!-- Extra opties -->
  <li style="margin:.25em 0;"><b>BirdWeather code:</b> {{ data.get('birdweather_id','') or '—' }}</li>
  <li style="margin:.25em 0;"><b>Webadres (vogelpagina):</b> {{ data.get('birdnetpi_url','') or '—' }}</li>
  <li style="margin:.25em 0;"><b>Wi‑Fi wachtwoord:</b> {{ 'ingevuld' if data.get('wifi_password') else '—' }}</li>
  <li style="margin:.25em 0;"><b>Wachtwoord vogelpagina:</b> {{ 'ingevuld' if data.get('caddy_pwd') else '—' }}</li>
  <li style="margin:.25em 0;"><b>Live luisteren (ICE):</b> {{ 'aan (wachtwoord ingesteld)' if data.get('ice_pwd') else 'uit' }}</li>
  <li style="margin:.25em 0;"><b>Camera (RTSP):</b> {{ data.get('rtsp_stream') and 'ingesteld' or 'geen' }}</li>
  <li style="margin:.25em 0;"><b>Foto’s bij soorten (Flickr):</b> {{ (data.get('flickr_api_key') and 'aan') or 'uit' }}</li>
</ul>

          <div class="wizard-buttons">
            <button type="submit" class="btn-nav btn--secondary back" name="back" value="4" formaction="{{ url_for('setup') }}">Terug</button>
            <button type="submit" class="btn">Afronden</button>
          </div>
        </form>
      </div>
      <div class="wizard-footer">
        &copy; {{ 2025 }} EasyComp Zeeland &mdash; Ondersteuning via
        <a href="https://easycompzeeland.nl/contact/" target="_blank" style="color:#1E73BE;text-decoration:none;">EasyComp Zeeland</a>
      </div>

      {% endif %}
    </div>
  </div>

  <!-- Lightbox voor Handleiding -->
  <div id="manualModal" class="modal" aria-hidden="true">
    <div class="modal-content">
      <button id="closeManual" class="modal-close" aria-label="Sluiten">&times;</button>
      <iframe src="/static/assets/handleiding.html" frameborder="0"></iframe>
    </div>
  </div>

  <script>
  document.addEventListener('DOMContentLoaded', () => {
    // Stap-navigatie
    const stepsEl = document.querySelector('.wizard-steps');
    if (stepsEl) {
      const url = stepsEl.dataset.url;
      document.querySelectorAll('.wizard-steps li').forEach(el => {
        el.style.cursor = 'pointer';
        el.addEventListener('click', () => {
          const step = el.dataset.step;
          window.location.href = `${url}?step=${step}`;
        });
      });
    }

    // Handleiding modal
    const modal = document.getElementById('manualModal');
    document.getElementById('openManual').addEventListener('click', e => {
      e.preventDefault();
      modal.style.display = 'flex';
    });
    document.getElementById('closeManual').addEventListener('click', () => modal.style.display = 'none');
    modal.addEventListener('click', e => { if (e.target === modal) modal.style.display = 'none'; });

    // Support-knop
    document.getElementById('openSupport').addEventListener('click', () => {
      window.open('https://easycompzeeland.nl/contact', '_blank');
    });

    // Audio controls logica
    const audio = document.getElementById('intro-audio');
    const playBtn = document.getElementById('audioPlayPause');
    const playIcon = document.getElementById('audioPlayIcon');
    const volBtn = document.getElementById('audioVolume');
    const volIcon = document.getElementById('audioVolumeIcon');
    const volLevels = [
      {vol: 1, icon: "🔊"},
      {vol: 0.65, icon: "🔉"},
      {vol: 0.3, icon: "🔈"},
      {vol: 0, icon: "🔇"}
    ];
    let volIdx = 0;

    function updateAudioIcons() {
      playIcon.textContent = audio.paused ? "⏵" : "⏸";
      let closest = 0, smallest = 999;
      for (let i = 0; i < volLevels.length; i++) {
        const diff = Math.abs(audio.volume - volLevels[i].vol);
        if (diff < smallest) { smallest = diff; closest = i; }
      }
      volIdx = closest;
      volIcon.textContent = volLevels[volIdx].icon;
    }

    playBtn.addEventListener('click', () => {
      if (audio.paused) {
        audio.play().catch(err => console.warn("Audio play error:", err));
      } else {
        audio.pause();
      }
      updateAudioIcons();
    });

    volBtn.addEventListener('click', () => {
      volIdx = (volIdx + 1) % volLevels.length;
      audio.volume = volLevels[volIdx].vol;
      updateAudioIcons();
    });

    audio.addEventListener('play', updateAudioIcons);
    audio.addEventListener('pause', updateAudioIcons);
    audio.addEventListener('volumechange', updateAudioIcons);
    updateAudioIcons();

    // Startknop wizard
    document.getElementById('startWizard')?.addEventListener('click', function(e) {
      e.preventDefault();
      audio.currentTime = 0;
      audio.volume = 1.0;
      audio.play().catch(err => console.warn("Audio play error:", err));
      document.cookie = "introplay=1; path=/";
      window.location.href = "{{ url_for('setup') }}?step=1";
    });

    // Cookie popup
    if (document.cookie.includes("introplay=1")) {
      document.getElementById('cookieNotice').style.display = 'none';
    }
    document.getElementById('acceptCookies').addEventListener('click', function() {
      document.getElementById('cookieNotice').style.display = 'none';
      audio.currentTime = 0;
      audio.play().catch(err => console.warn("Audio play error:", err));
      document.cookie = "introplay=1; path=/";
    });
  });
  </script>
</body>
</html>
