const API_BASE = "https://maps.start-it.nl/api";
const TILE_BASE = "https://maps.start-it.nl";

const sources = {
    osm: new ol.source.OSM(),
    "pdok-luchtfoto": new ol.source.XYZ({
        url: "https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_ortho25/EPSG:3857/{z}/{x}/{y}.jpeg"
    }),
    "pdok-grijs": new ol.source.XYZ({
        url: "https://service.pdok.nl/brt/achtergrondkaart/wmts/v2_0/grijs/EPSG:3857/{z}/{x}/{y}.png"
    })
};

const baseLayer = new ol.layer.Tile({ source: sources.osm });

const kavelLayer = new ol.layer.VectorTile({
    source: new ol.source.VectorTile({
        format: new ol.format.MVT(),
        url: `${TILE_BASE}/public.perceel/{z}/{x}/{y}.pbf`
    }),
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({ color: 'rgba(185, 89, 19, 0.4)', width: 1 })
    })
});

const map = new ol.Map({
    target: 'map',
    layers: [baseLayer, kavelLayer],
    view: new ol.View({ center: ol.proj.fromLonLat([5.594, 52.285]), zoom: 16 })
});

document.getElementById('doSearch').addEventListener('click', async () => {
    const pc = document.getElementById('pc').value.replace(/\s+/g, '');
    const hn = document.getElementById('hn').value;
    
    try {
        const response = await fetch(`${API_BASE}/analyse?postcode=${pc}&huisnummer=${hn}`);
        const data = await response.json();
        if (data.results && data.results.length > 0) {
            updateUI(data.results[0]);
            zoomToResult(data.results[0]);
        }
    } catch (err) {
        console.error("Fout bij ophalen data", err);
    }
});

function updateUI(row) {
    document.getElementById('placeholder-text').style.display = 'none';
    document.getElementById('data-content').style.display = 'block';
    
    document.getElementById('res-adres').innerText = row.adres;
    document.getElementById('res-bouwjaar').innerText = row.hoofdgebouw_bouwjaar;
    document.getElementById('res-kavel').innerText = row.kavel_m2 + " m²";
    document.getElementById('res-bebouwd').innerText = row.bebouwd_m2 + " m²";
    document.getElementById('res-max').innerText = row.max_mantelzorgwoning_m2 + " m²";
    document.getElementById('res-omgevingswet').href = `https://omgevingswet.overheid.nl/regels-op-de-kaart/documenten?locatie=${encodeURIComponent(row.adres)}`;
}