<section class="info-section py-3" id="vergunningscheck">
  <div class="container overflow-hidden">
    <div class="row">
      <div class="mb-4 col-md-11 mx-auto">
        <h6 class="text-primary">Doe een vooronderzoek</h6>
        <h2 class="display-5 fw-bold">Toets uw kavel</h2>
        <p>U kunt geheel vrijblijvend een vooronderzoek doen naar uw mogelijkheden.</p>
        <p>Liever <a href="/contact">persoonlijk advies?</a> Dat kunt uiteraard ook.</p>
      </div>
    </div>
    
    <div class="row flex-nowrap g-5 h-100" style="min-height: 300px;" data-aos="zoom-in" data-aos-offset="200" data-aos-delay="100"> 
      
      <div id="col-map" class="col-12 mb-3" style="transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1); flex-shrink: 0;">
        <div class="panel overflow-hidden shadow" style="height: 600px; position: relative;border:2px solid #fff;">
          <div id="panel" class="bg-white p-4" style="position: absolute; left: 20px; top: 20px; z-index: 1000; width: 300px; border-radius: 20px; max-height: 90%;">
            <div class="">
              <input type="text" id="pc-input" class="form-control mb-2 rounded-pill" placeholder="Postcode">
              <input type="number" id="hn-input" class="form-control mb-2 rounded-pill" placeholder="Huisnummer">
              <button id="btnSearch" class="btn btn-cta">Analyseer Kavel</button>
            </div>
          </div>
          <div id="map" style="width: 100%; height: 100%; background: #eee;;"></div>
        </div>
      </div>

      <div id="col-results" class="col-md-5" style="display: none; opacity: 0; transform: translateX(50px); transition: all 0.6s ease-out; flex-shrink: 0;">
        <div class="bg-light panel px-5 py-4 pt-5">
          <div class="d-flex justify-content-between mb-2"><span>Kavelnummer:</span><strong id="res-kavelnummer"></strong></div>
          <div class="d-flex justify-content-between mb-2"><span>Bouwjaar hoofdgebouw:</span><strong id="res-bouwjaar"></strong></div>
          <hr>
          <div class="d-flex justify-content-between mb-2"><span>Formaat kavel:</span><strong id="res-kavelformaat"></strong></div>
          <div class="d-flex justify-content-between mb-2"><span>Vrije meters:</span><strong id="res-kavelvrij"></strong></div>
          <div class="d-flex justify-content-between mb-2"><span class="text-primary h5">Max. Mantelzorgwoning</span><strong class="text-primary h5" style="filter: blur(7px);" id="res-max"></strong></div>
        </div>
        <div class="p-4">
          <p>Ontvang een volledig rapport over alle  mogelijkheden binnen 5 minuten in uw email.</p>
          <form id="lead-form">
            
            <div class="row g-2">
              <div class="mb-2 col-md-4">
                <select class="form-select form-control form-select rounded-pill" id="f-aanhef" required>
                  <option value="" selected disabled>Aanhef</option>
                  <option value="Dhr.">Dhr.</option>
                  <option value="Mevr.">Mevr.</option>
                </select>
              </div>
              <div class="mb-2 col-md-8">
                <input type="text" id="f-achternaam" class="form-control rounded-pill" placeholder="Achternaam" required>
              </div>
              <div class="mb-2">
                <input type="email" id="f-email" class="form-control rounded-pill" placeholder="E-mailadres" required>
              </div>
              <div class="mb-3">
                <input type="tel" id="f-telefoon" class="form-control rounded-pill" placeholder="Telefoonnummer" required>
              </div>
              <div class="col-12">
                <button type="submit" class="btn btn-cta">Rapport Aanvragen</button>
              </div>
              
            </div>
            
          </form>
          <div id="form-success" class="mt-3 text-center d-none">
              <p class="fw-bold mb-0">✓ Je rapport is onderweg!</p>
          </div>
          
        </div>
      </div>
    </div>
  </div>
</section>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@9.2.4/ol.css">
<script src="https://cdn.jsdelivr.net/npm/ol@9.2.4/dist/ol.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const perceelSource = new ol.source.Vector();
    const gebouwSource = new ol.source.Vector();

    const map = new ol.Map({
        target: 'map',
        controls: [
            new ol.control.Zoom({
                className: 'custom-zoom'
            }),
            new ol.control.Attribution({
                collapsible: true
            })
        ],
        layers: [
            new ol.layer.Tile({ 
                source: new ol.source.OSM() 
            }),
            new ol.layer.Vector({
                source: perceelSource,
                style: new ol.style.Style({
                    stroke: new ol.style.Stroke({ color: '#B95913', width: 4 }),
                    fill: new ol.style.Fill({ color: 'rgba(185, 89, 19, 0.2)' })
                })
            }),
            new ol.layer.Vector({
                source: gebouwSource,
                style: new ol.style.Style({
                    stroke: new ol.style.Stroke({ color: '#ffffff', width: 2 }),
                    fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.4)' })
                })
            })
        ],
        view: new ol.View({ 
            center: ol.proj.fromLonLat([5.5846253, 52.2690304]), 
            zoom: 11 
        })
    });

    document.getElementById('btnSearch').addEventListener('click', async function() {
        const pc = document.getElementById('pc-input').value.replace(/\s+/g, "").toUpperCase();
        const hn = document.getElementById('hn-input').value;

        if (!pc || !hn) return alert("Vul postcode en huisnummer in.");

        try {
            const response = await fetch(`https://maps.start-it.nl/api/analyse?postcode=${pc}&huisnummer=${hn}`);
            const data = await response.json();
            
            if (data.results && data.results.length > 0) {
                const r = data.results[0];

                // document.getElementById('res-adres').innerText = r.adres || '—';
                document.getElementById('res-bouwjaar').innerText = r.hoofdgebouw_bouwjaar || '—';
                document.getElementById('res-max').innerText = (r.max_mantelzorgwoning_m2 || 0) + ' m²';
                document.getElementById("res-kavelnummer").innerText = r.kavelnummer || "—";
                document.getElementById("res-kavelformaat").innerText = (r.kavel_m2 || 0) + ' m²';
                document.getElementById("res-kavelvrij").innerText = (r.vrije_m2 || 0) + ' m²';

                const colMap = document.getElementById('col-map');
                const colRes = document.getElementById('col-results');

                colMap.classList.remove('col-12');
                colMap.classList.add('col-md-7');

                setTimeout(() => {
                    colRes.style.display = "block";
                    setTimeout(() => {
                        colRes.style.opacity = "1";
                        colRes.style.transform = "translateX(0)";
                    }, 50);
                }, 100);

                setTimeout(() => {
                    map.updateSize();
                    perceelSource.clear();
                    gebouwSource.clear();

                    const format = new ol.format.GeoJSON();
                    if (r.perceel_geojson) {
                        perceelSource.addFeatures(format.readFeatures(JSON.parse(r.perceel_geojson), {
                            dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857'
                        }));
                    }
                    if (r.gebouw_geojson) {
                        gebouwSource.addFeatures(format.readFeatures(JSON.parse(r.gebouw_geojson), {
                            dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857'
                        }));
                    }

                    if (perceelSource.getFeatures().length > 0) {
                        map.getView().fit(perceelSource.getExtent(), { 
                            padding: [50, 50, 50, 50], duration: 1000 
                        });
                    }
                }, 400);
            }
        } catch (e) { console.error(e); }
    });
});
</script>