var map, googleHybrid, marker, polygon;

let evaluationElement = document.getElementById("evaluations");
let evaluation = JSON.parse(evaluationElement.dataset.evaluations);

document.addEventListener("DOMContentLoaded", function () {
    initMap();
    map.invalidateSize();
    setEvaluationToMap();
});

function initMap() {
    map = L.map("map", {
        attributionControl: false,
    }).setView([-8.159774548190976, 113.72305183874593], 10);

    googleHybrid = L.tileLayer(
        "http://{s}.google.com/vt?lyrs=y&x={x}&y={y}&z={z}",
        {
            maxZoom: 20,
            subdomains: ["mt0", "mt1", "mt2", "mt3"],
        }
    ).addTo(map);
}

function setEvaluationToMap() {
    evaluation.forEach((evaluation) => {
        let coordinates = evaluation.land.detail_lands.map((detail) => {
            return [detail.lat, detail.lng];
        });

        let cfValue = evaluation.cf_value * 100;

        polygon = L.polygon(coordinates, {
            color: "blue",
            fillColor: "blue",
            fillOpacity: 0.5,
        }).addTo(map);

        marker = L.marker(coordinates[0])
            .addTo(map)
            .bindPopup(
                `<div class="text-center font-semibold"><b> Hasil presentase CF pada lahan <br /> ${
                    evaluation.land.owner
                }</br>${cfValue.toFixed(2)} %</b></div>`
            );
    });
}
