
const DEFAULT_TAMPON = 100;
const BUFFER_MIN_ZOOM = 13;
const pageSize = 100;

// ====== Poziție și zoom din localStorage ======
let mapCenter = [47.1, 28.85], mapZoom = 8;
try {
  let saved = JSON.parse(localStorage.getItem('mapView'));
  if (saved && Array.isArray(saved.center) && typeof saved.zoom === 'number') {
    mapCenter = saved.center;
    mapZoom = saved.zoom;
  }
} catch(e){}

var map = L.map('map').setView(mapCenter, mapZoom);
var sitLayer = L.featureGroup().addTo(map);
var bufferLayer = L.featureGroup().addTo(map);
var bigLayer = L.featureGroup().addTo(map);

let baseLayers = {
  hybrid: L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', { attribution: 'Google Hybrid' }),
  osm: L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'),
  google: L.tileLayer('https://mt1.google.com/vt/lyrs=r&x={x}&y={y}&z={z}', { attribution: 'Google Road' })
};
let savedBase = localStorage.getItem('baseLayer') || 'hybrid';
let currentBaseLayer = baseLayers[savedBase].addTo(map);
document.getElementById('basemapSwitcher').value = savedBase;
document.getElementById('basemapSwitcher').addEventListener('change', function() {
  if (currentBaseLayer) map.removeLayer(currentBaseLayer);
  currentBaseLayer = baseLayers[this.value];
  map.addLayer(currentBaseLayer);
  localStorage.setItem('baseLayer', this.value);
});

let loggedIn = false, drawControl = null, currentPage = 1, currentSearchResults = null, sitEditat = null;
let sitFeaturesRaw = [], lazyLayerRefs = [];

// ====== UTILITARE ======
function simplificaGeojson(geojson, metri) {
  return turf.simplify(geojson, { tolerance: metri/111320, highQuality: false });
}

// ====== POPUP cu date publice + detalii doar pentru logați ======
function getPopupHTML(props, geometry) {
  // Colectează coordonatele pentru afișare
  let coordList = '';
  if (geometry) {
    let coords = [];
    if (geometry.type === "Point") {
      coords = [geometry.coordinates];
    } else if (geometry.type === "Polygon") {
      coords = geometry.coordinates[0];
    } else if (geometry.type === "MultiPolygon") {
      coords = geometry.coordinates[0][0];
    }
    coordList = coords.map((c, i) => `[${c[1].toFixed(6)}, ${c[0].toFixed(6)}]`).join('<br>');
  }

  // === Dimensiuni și centru, calculate automat ===
  let suprafata = '', centru = '', bbox = '', dimensiuni = '';
  if (geometry && (geometry.type === "Polygon" || geometry.type === "MultiPolygon")) {
    let turfArea = turf.area({type:'Feature', geometry: geometry});
    suprafata = (turfArea/10000).toFixed(2) + " ha";
    let turfCentroid = turf.centroid({type:'Feature', geometry: geometry});
    centru = turfCentroid.geometry.coordinates;
    bbox = turf.bbox({type:'Feature', geometry: geometry});
    let latMin = bbox[1].toFixed(6), latMax = bbox[3].toFixed(6),
        lngMin = bbox[0].toFixed(6), lngMax = bbox[2].toFixed(6);
    dimensiuni = `Lungime: ${(turf.distance([lngMin,latMin],[lngMax,latMin])*1000).toFixed(0)} m, 
                  Lățime: ${(turf.distance([lngMin,latMin],[lngMin,latMax])*1000).toFixed(0)} m`;
  }

  // === Public: doar datele din tabel ===
  let html = `
    <b>${props.denumire || props.name || "Situl importat"}</b><br>
    Nr. crt.: ${props.nrcrt || ""}<br>
    Cod RAN: ${props.codran || ""}<br>
    Localizare: ${props.localizare || ""}<br>
    Tip: ${props.tip || ""}<br>
    Datare: ${props.datare || ""}<br>
    <span style='color:red'>Zona tampon: ${props.tampon || DEFAULT_TAMPON} m</span>
    <div style="margin-top:10px;">
      <button class="popup-more-btn" onclick="document.getElementById('popupDetails${props.nrcrt}').style.display='block';this.style.display='none';">Continuare &darr;</button>
    </div>
    <div id="popupDetails${props.nrcrt}" style="display:none; margin-top:10px;">
      <b>Coordonate noduri:</b><br>${coordList || '-'}<br>
  `;

  // === Suplimentar doar pentru logați ===
  if (loggedIn) {
    html += `
      <hr>
      <b>Categoria clasării:</b> ${props.categoria_clasare || ""}<br>
      <b>Data clasării:</b> ${props.data_clasare || ""}<br>
      <b>Ref. document:</b> ${props.ref_doc_clasare || ""}<br>
      <b>Numere Cadastrale:</b> ${props.numere_cadastrale || ""}<br>
      <b>Centru GPS:</b> ${centru ? `[${centru[1].toFixed(6)}, ${centru[0].toFixed(6)}]` : ""}<br>
      <b>Dimensiuni:</b> ${dimensiuni}<br>
      <b>Suprafață:</b> ${suprafata}<br>
      <b>Caracteristici suprafață:</b> ${props.caracteristici_suprafata || ""}<br>
      <b>Grad de conservare:</b> ${props.grad_conservare || ""}<br>
      <b>An descoperire, autor:</b> ${props.an_descoperire || ""}<br>
      <b>Cercetare arheologică:</b> ${props.cercetare_arheologica || ""}<br>
      <b>Bibliografie:</b> ${props.bibliografie || ""}<br>
      <b>Data fișei / autor fișă:</b> ${props.data_fisa || ""} / ${props.autor_fisa || ""}<br>
      <button class="download-pdf-btn" data-nrcrt="${props.nrcrt}" style="margin-top:10px;">Descarcă PDF fișă</button>
      <div style="margin-bottom:8px;">
        <button type="button" class="editBtn" data-nrcrt="${props.nrcrt}">Editează</button>
        <button type="button" class="moveBtn" data-nrcrt="${props.nrcrt}">Mută situl</button>
      </div>
    `;
  }
  html += `</div>`;
  return `<div class="popup-truncated" id="popupContent">${html}</div>`;
}

function getStyleSitul(selected = false) {
  return {
    color: "#e74c3c",
    weight: selected ? 5 : 3,
    dashArray: selected ? "6,2" : "2,2",
    fill: true,
    fillColor: "yellow",
    fillOpacity: selected ? 0.6 : 0.3
  };
}

// ====== INIȚIALIZARE & LAZY RENDER ======
window.onload = function() {
  if (localStorage.getItem('loggedIn') === 'true') {
    loggedIn = true;
    setTimeout(() => {
      activateDrawing();
      let importExportPanel = document.getElementById('importExportPanel');
      if(importExportPanel) importExportPanel.style.display = 'block';
    }, 10);
  }
  fetch('save_geojson.php')
    .then(response => response.json())
    .then(geojson => {
      sitFeaturesRaw = (geojson.features || []).map(function(feature){
        let simplified = simplificaGeojson(feature, 2);
        if (!simplified.properties) simplified.properties = {};
        if (!simplified.properties.tampon || isNaN(simplified.properties.tampon) || parseFloat(simplified.properties.tampon) <= 0) {
          simplified.properties.tampon = DEFAULT_TAMPON;
        }
        return simplified;
      });
      updateTable();
      renderLayersByZoom();
    });
};

map.on("zoomend moveend", function() {
  let center = map.getCenter();
  let zoom = map.getZoom();
  localStorage.setItem('mapView', JSON.stringify({center: [center.lat, center.lng], zoom: zoom}));
  renderLayersByZoom();
});

function renderBigPoints() {
  bigLayer.clearLayers();
  sitFeaturesRaw.forEach(feature => {
    let centroid = turf.centroid(feature).geometry.coordinates;
    let area = (feature.geometry && (feature.geometry.type === 'Polygon' || feature.geometry.type === 'MultiPolygon')) ? turf.area(feature) : 1;
    let radius = Math.max(2, Math.min(7, Math.log10(area+1)));
    let marker = L.circleMarker([centroid[1], centroid[0]], {
      radius: radius,
      color: "yellow",
      fillColor: "yellow",
      fillOpacity: 0.7,
      weight: 0.7
    });
    bigLayer.addLayer(marker);
  });
}

function renderAllPolygonsInView() {
  sitLayer.clearLayers();
  lazyLayerRefs = [];
  let bounds = map.getBounds();
  sitFeaturesRaw.forEach(feature => {
    let geojsonLayer = L.geoJSON(feature);
    let layer = geojsonLayer.getLayers()[0];
    if (layer && bounds.intersects(layer.getBounds())) {
      layer.setStyle(getStyleSitul(false));
      layer.feature = feature;
      layer.bindPopup(getPopupHTML(feature.properties, feature.geometry), {autoPan: false, closeButton: true});
      layer.on('click', function(e) {
        highlightFeature(layer);
        setTimeout(()=>{ layer.openPopup(); }, 200);
      });
      sitLayer.addLayer(layer);
      lazyLayerRefs.push(layer);
    }
  });
}
function renderLayersByZoom() {
  if (map.getZoom() < BUFFER_MIN_ZOOM) {
    renderBigPoints();
    sitLayer.clearLayers();
    bufferLayer.clearLayers();
  } else {
    bigLayer.clearLayers();
    renderAllPolygonsInView();
    renderBuffersIfZoom();
  }
}
function renderBuffersIfZoom() {
  bufferLayer.clearLayers();
  if (map.getZoom() < BUFFER_MIN_ZOOM) return;
  let bufferFeatures = [];
  let names = [];
  lazyLayerRefs.forEach(layer => {
    let props = layer.feature.properties;
    let dist = parseFloat(props.tampon || DEFAULT_TAMPON);
    if (!isNaN(dist) && dist > 0) {
      let buffered = turf.buffer(layer.toGeoJSON(), dist, {units: 'meters'});
      bufferFeatures.push(buffered);
      if(props.denumire) names.push(props.denumire);
    }
  });
  if (bufferFeatures.length === 0) return;
  let unioned = bufferFeatures[0];
  for (let i = 1; i < bufferFeatures.length; i++) {
    try {
      unioned = turf.union(unioned, bufferFeatures[i]);
    } catch (e) { }
  }
  if (unioned) {
    let bufLayer = L.geoJSON(unioned, {
      style: {
        color: "#e74c3c",
        weight: 2,
        dashArray: "6, 4",
        fill: false,
        fillOpacity: 0
      }
    });
    let den = (names.length>1) ? names.join(", ") : (names[0]||"");
    bufLayer.eachLayer(buf => buf.bindPopup(`<b>Zonă tampon combinată</b><br>Siturile: ${den}`));
    bufferLayer.addLayer(bufLayer);
  } else {
    bufferFeatures.forEach(buf => {
      L.geoJSON(buf, {
        style: {
          color: "#e74c3c",
          weight: 2,
          dashArray: "6, 4",
          fill: false,
          fillOpacity: 0
        }
      }).addTo(bufferLayer);
    });
  }
}
function highlightFeature(layer) {
  lazyLayerRefs.forEach(l => l.setStyle(getStyleSitul(false)));
  if (layer) layer.setStyle(getStyleSitul(true));
}

// ==== EVENT - Edit/Move/Download PDF ====
// Handler pentru butoanele globale (edit/move)
document.body.addEventListener('click', function(e){
  if (e.target.classList && e.target.classList.contains('editBtn')) {
    let nrcrt = e.target.getAttribute('data-nrcrt');
    let layer = lazyLayerRefs.find(l => l.feature && l.feature.properties.nrcrt == nrcrt);
    if (layer) showEditForm(layer);
  }
  if (e.target.classList && e.target.classList.contains('moveBtn')) {
    let nrcrt = e.target.getAttribute('data-nrcrt');
    let layer = lazyLayerRefs.find(l => l.feature && l.feature.properties.nrcrt == nrcrt);
    if (layer) enableMoveMode(layer);
  }
});

// Handler doar pentru popupul deschis (pentru PDF)
map.on('popupopen', function(e) {
  const btn = e.popup._contentNode.querySelector('.download-pdf-btn');
  if (btn) {
    btn.onclick = function() {
      const nrcrt = btn.getAttribute('data-nrcrt');
      const found = sitLayer.getLayers().find(f =>
        f.feature && f.feature.properties && String(f.feature.properties.nrcrt) === String(nrcrt)
      );
      if (found) downloadSitulPDF(found.feature);
      else alert('Eroare: nu s-a găsit situl.');
    };
  }
});


function enableMoveMode(layer) {
  map.closePopup();
  highlightFeature(layer);
  let moveInProgress = false;
  let startLatLng = null;
  let originalGeometry = null;
  function onMouseDown(e) {
    moveInProgress = true;
    startLatLng = e.latlng;
    originalGeometry = layer.toGeoJSON().geometry;
    map.on('mousemove', onMouseMove);
    map.on('mouseup', onMouseUp);
    map.dragging.disable();
    layer.setStyle({fillColor: "#00aaff", color: "#00aaff"});
  }
  function onMouseMove(e) {
    if (!moveInProgress || !startLatLng || !originalGeometry) return;
    let dLat = e.latlng.lat - startLatLng.lat;
    let dLng = e.latlng.lng - startLatLng.lng;
    let newGeometry = JSON.parse(JSON.stringify(originalGeometry));
    function translateCoords(coords) {
      if (Array.isArray(coords[0])) {
        return coords.map(translateCoords);
      } else {
        return [coords[0] + dLng, coords[1] + dLat];
      }
    }
    if (originalGeometry.type === "Polygon" || originalGeometry.type === "MultiPolygon") {
      newGeometry.coordinates = translateCoords(originalGeometry.coordinates);
      layer.setLatLngs(L.GeoJSON.coordsToLatLngs(newGeometry.coordinates, originalGeometry.type === "Polygon" ? 1 : 2));
    } else if (originalGeometry.type === "Point") {
      newGeometry.coordinates = [originalGeometry.coordinates[0] + dLng, originalGeometry.coordinates[1] + dLat];
      layer.setLatLng([newGeometry.coordinates[1], newGeometry.coordinates[0]]);
    }
  }
  function onMouseUp(e) {
    map.off('mousemove', onMouseMove);
    map.off('mouseup', onMouseUp);
    map.dragging.enable();
    moveInProgress = false;
    startLatLng = null;
    originalGeometry = null;
    let newGeo = layer.toGeoJSON();
    let idx = sitFeaturesRaw.findIndex(f => f.properties.nrcrt == layer.feature.properties.nrcrt);
    if (idx > -1) {
      let simplified = simplificaGeojson(newGeo, 2);
      simplified.properties = layer.feature.properties;
      sitFeaturesRaw[idx] = simplified;
    }
    saveAllGeojsonToServer();
    renderLayersByZoom();
    alert('Situl a fost mutat!');
  }
  layer.on('mousedown', onMouseDown);
  alert('Trage cu mouse-ul situl pentru a-l muta. Poziția nouă se salvează automat când dai drumul mouse-ului.');
  function cleanup() {
    layer.off('mousedown', onMouseDown);
    layer.setStyle(getStyleSitul(true));
  }
  map.once('zoomstart', cleanup);
  map.once('moveend', cleanup);
}

// ====== Formular editare/adăugare cu toate câmpurile ======
function showEditForm(layer) {
  sitEditat = layer;
  highlightFeature(layer);
  renderBuffersIfZoom();
  let props = layer.feature.properties;
  let geometry = layer.feature.geometry;
  let suprafata = '', centru = '', bbox = '', dimensiuni = '';
  if (geometry && (geometry.type === "Polygon" || geometry.type === "MultiPolygon")) {
    let turfArea = turf.area({type:'Feature', geometry: geometry});
    suprafata = (turfArea/10000).toFixed(2);
    let turfCentroid = turf.centroid({type:'Feature', geometry: geometry});
    centru = turfCentroid.geometry.coordinates;
    bbox = turf.bbox({type:'Feature', geometry: geometry});
    let latMin = bbox[1].toFixed(6), latMax = bbox[3].toFixed(6),
        lngMin = bbox[0].toFixed(6), lngMax = bbox[2].toFixed(6);
    dimensiuni = `Lungime: ${(turf.distance([lngMin,latMin],[lngMax,latMin])*1000).toFixed(0)} m, 
                  Lățime: ${(turf.distance([lngMin,latMin],[lngMin,latMax])*1000).toFixed(0)} m`;
  }
  let form = document.createElement('form');
  form.innerHTML = `
    <label>Nr. crt.: <input type="number" id="nrcrt" value="${props.nrcrt||""}" required></label><br>
    <label>Cod RAN: <input type="text" id="codran" value="${props.codran||""}"></label><br>
    <label>Localizare: <input type="text" id="localizare" value="${props.localizare||""}"></label><br>
    <label>Denumire: <input type="text" id="denumire" value="${props.denumire||""}"></label><br>
    <label>Tip: <input type="text" id="tip" value="${props.tip||""}"></label><br>
    <label>Datare: <input type="text" id="datare" value="${props.datare||""}"></label><br>
    <label>Zonă tampon (m): <input type="number" id="tampon" min="0" value="${props.tampon||DEFAULT_TAMPON}"></label><br>
    <label>Categoria clasării: <input type="text" id="categoria_clasare" value="${props.categoria_clasare||""}"></label><br>
    <label>Data clasării: <input type="text" id="data_clasare" value="${props.data_clasare||""}"></label><br>
    <label>Ref. document clasare: <input type="text" id="ref_doc_clasare" value="${props.ref_doc_clasare||""}"></label><br>
<label>Numere Cadastrale: <input type="text" id="numere_cadastrale" value="${props.numere_cadastrale||""}"></label><br>
    <label>Caracteristici suprafață: <input type="text" id="caracteristici_suprafata" value="${props.caracteristici_suprafata||""}"></label><br>
    <label>Grad conservare: <input type="text" id="grad_conservare" value="${props.grad_conservare||""}"></label><br>
    <label>An descoperire/autor: <input type="text" id="an_descoperire" value="${props.an_descoperire||""}"></label><br>
    <label>Cercetare arheologică: <input type="text" id="cercetare_arheologica" value="${props.cercetare_arheologica||""}"></label><br>
    <label>Bibliografie: <input type="text" id="bibliografie" value="${props.bibliografie||""}"></label><br>
    <label>Data fișei: <input type="text" id="data_fisa" value="${props.data_fisa||""}"></label><br>
    <label>Autor fișă: <input type="text" id="autor_fisa" value="${props.autor_fisa||""}"></label><br>
    <div style="margin:7px 0; font-size:90%;">
      <b>Centru GPS:</b> ${centru ? `[${centru[1].toFixed(6)}, ${centru[0].toFixed(6)}]` : ""}<br>
      <b>Dimensiuni:</b> ${dimensiuni}<br>
      <b>Suprafață estimată:</b> ${suprafata} ha
    </div>
    <button type="submit">Salvează</button>
    <button type="button" id="anuleaza">Anulează</button>
    <button type="button" id="sterge" style="background:#e74c3c;color:#fff;float:right;">Șterge</button>
  `;
  let popup = L.popup({autoPan: false}).setContent(form);
  layer.bindPopup(popup).openPopup();
  L.DomEvent.disableClickPropagation(form);

  form.querySelector("#anuleaza").onclick = function() {
    layer.closePopup();
    highlightFeature();
    sitEditat = null; renderBuffersIfZoom();
  };
  form.querySelector("#sterge").onclick = function() {
    if (confirm("Sigur vrei să ștergi acest poligon/cerc?")) {
      let idx = sitFeaturesRaw.findIndex(f => f.properties.nrcrt == props.nrcrt);
      if (idx > -1) sitFeaturesRaw.splice(idx, 1);
      updateTable();
      saveAllGeojsonToServer();
      sitEditat = null;
      highlightFeature();
      renderLayersByZoom();
    }
  };
  form.addEventListener('submit', function(ev) {
    ev.preventDefault();
    let tamponVal = form.tampon.value && parseFloat(form.tampon.value) > 0 ? form.tampon.value : DEFAULT_TAMPON;
    let propsNew = {
      nrcrt: form.nrcrt.value, codran: form.codran.value, localizare: form.localizare.value,
      denumire: form.denumire.value, tip: form.tip.value, datare: form.datare.value, tampon: tamponVal,
      categoria_clasare: form.categoria_clasare.value, data_clasare: form.data_clasare.value,
      ref_doc_clasare: form.ref_doc_clasare.value, 
      numere_cadastrale: form.numere_cadastrale.value,
      caracteristici_suprafata: form.caracteristici_suprafata.value, grad_conservare: form.grad_conservare.value,
      an_descoperire: form.an_descoperire.value, cercetare_arheologica: form.cercetare_arheologica.value,
      bibliografie: form.bibliografie.value, data_fisa: form.data_fisa.value, autor_fisa: form.autor_fisa.value,
      color: 'orange', fillColor: 'yellow'
    };
    let simplified = simplificaGeojson(layer.toGeoJSON(), 2);
    layer.feature = simplified;
    layer.feature.properties = propsNew;
    let idx = sitFeaturesRaw.findIndex(f => f.properties.nrcrt == props.nrcrt);
    if (idx > -1) sitFeaturesRaw[idx] = simplified;
    layer.setStyle(getStyleSitul(true));
    layer.bindPopup(getPopupHTML(propsNew, simplified.geometry), {autoPan: false});
    layer.openPopup();
    sitEditat = null;
    updateTable();
    saveAllGeojsonToServer();
    renderLayersByZoom();
  });
}

// ====== Generare PDF completă ======
// === DESCĂRCARE PDF cu PDFMake ===

// Atașează handlerul la popup la deschidere (nu modifica dacă ai deja!)
map.on('popupopen', function(e) {
  const btn = e.popup._contentNode.querySelector('.download-pdf-btn');
  if (btn) {
    btn.onclick = function() {
      const nrcrt = btn.getAttribute('data-nrcrt');
      const found = sitLayer.getLayers().find(f =>
        f.feature && f.feature.properties && String(f.feature.properties.nrcrt) === String(nrcrt)
      );
      if (found) downloadSitulPDF(found.feature);
      else alert('Eroare: nu s-a găsit situl.');
    };
  }
}); // <- Aici trebuie să se termine handlerul de popupopen


// Funcția principală pentru generare și descărcare PDF
function downloadSitulPDF(feature) {
  if (!feature) {
    alert("Eroare: date lipsă pentru generare PDF!");
    return;
  }
  const props = feature.properties || {};
  const geometry = feature.geometry || {};

  // Calcule suplimentare pentru Centru, Dimensiuni, Suprafață
  let coordText = "-";
  let centru = "-";
  let dimensiuni = "-";
  let suprafata = "-";
  if (geometry && geometry.type) {
    let coords = [];
    if (geometry.type === "Point") {
      coords = [geometry.coordinates];
    } else if (geometry.type === "Polygon") {
      coords = geometry.coordinates[0];
    } else if (geometry.type === "MultiPolygon") {
      coords = geometry.coordinates[0][0];
    }
    if (coords && coords.length > 0) {
      coordText = coords.map(c => `[${c[1].toFixed(6)}, ${c[0].toFixed(6)}]`).join('\n');
    }
    // Centru și dimensiuni pentru poligon
    if (geometry.type === "Polygon" || geometry.type === "MultiPolygon") {
      try {
        let turfCentroid = turf.centroid({type:'Feature', geometry: geometry});
        if (turfCentroid && turfCentroid.geometry) {
          centru = `[${turfCentroid.geometry.coordinates[1].toFixed(6)}, ${turfCentroid.geometry.coordinates[0].toFixed(6)}]`;
        }
        let turfArea = turf.area({type:'Feature', geometry: geometry});
        suprafata = (turfArea/10000).toFixed(2) + " ha";
        let bbox = turf.bbox({type:'Feature', geometry: geometry});
        let latMin = bbox[1], latMax = bbox[3], lngMin = bbox[0], lngMax = bbox[2];
        dimensiuni = `Lungime: ${(turf.distance([lngMin,latMin],[lngMax,latMin])*1000).toFixed(0)} m, Lățime: ${(turf.distance([lngMin,latMin],[lngMin,latMax])*1000).toFixed(0)} m`;
      } catch(e){}
    }
  }

  // Construiește datele sub formă de tabel
  var docDefinition = {
    content: [
      { text: 'Fișă sit arheologic', style: 'header' },
      {
        table: {
          widths: [180, '*'],
          body: [
            ['Nr. crt.', props.nrcrt || '-'],
            ['Cod RAN', props.codran || '-'],
            ['Denumire', props.denumire || '-'],
            ['Localizare', props.localizare || '-'],
            ['Tip', props.tip || '-'],
            ['Datare', props.datare || '-'],
            ['Zonă tampon', props.tampon || '-'],
            ['Categoria clasării', props.categoria_clasare || '-'],
            ['Data clasării', props.data_clasare || '-'],
            ['Ref. document clasare', props.ref_doc_clasare || '-'],
            ['Numere Cadastrale', props.numere_cadastrale || '-'],
            ['Caracteristici suprafață', props.caracteristici_suprafata || '-'],
            ['Grad de conservare', props.grad_conservare || '-'],
            ['An descoperire, autor', props.an_descoperire || '-'],
            ['Cercetare arheologică', props.cercetare_arheologica || '-'],
            ['Bibliografie', props.bibliografie || '-'],
            ['Data fișei', props.data_fisa || '-'],
            ['Autor fișă', props.autor_fisa || '-'],
            [{ text: 'Coordonate noduri', bold: true }, { text: coordText, fontSize: 9 }],
            ['Centru GPS', centru],
            ['Dimensiuni', dimensiuni],
            ['Suprafață estimată', suprafata]
          ]
        }
      }
    ],
    styles: {
      header: { fontSize: 18, bold: true, margin: [0,0,0,12] }
    },
    defaultStyle: {
      font: 'Roboto'
    }
  };

  pdfMake.createPdf(docDefinition).download(
    `Fisa_sit_${(props.codran || 'necunoscut').replace(/[^\w-]/g,'_')}.pdf`
  );
}


// ========== Autentificare =============
function showLogin() { document.getElementById('loginScreen').style.display = 'block'; }
function login() {
  var user = document.getElementById('username').value, pass = document.getElementById('password').value;
  if (user === 'admin' && pass === 'admin') {
    document.getElementById('loginScreen').style.display = 'none';
    loggedIn = true;
    localStorage.setItem('loggedIn', 'true');
    activateDrawing();
    let importExportPanel = document.getElementById('importExportPanel');
    if(importExportPanel) importExportPanel.style.display = 'block';
    renderLayersByZoom();
  } else document.getElementById('loginMessage').innerText = 'Date incorecte';
}
window.logout = function() {
  loggedIn = false;
  localStorage.removeItem('loggedIn');
  window.location.reload();
}
function activateDrawing() {
  if (drawControl) return;
  drawControl = new L.Control.Draw({
    edit: { featureGroup: sitLayer },
    draw: {
      polygon: { shapeOptions: getStyleSitul() },
      circle: { shapeOptions: getStyleSitul() },
      polyline: false, rectangle: false, marker: false, circlemarker: false
    }
  });
  map.addControl(drawControl);
}
map.on(L.Draw.Event.CREATED, function (e) {
  if (!loggedIn) return;
  var layer = e.layer;
  let simplified = simplificaGeojson(layer.toGeoJSON(), 2);
  let simpLayer = L.geoJSON(simplified, { style: getStyleSitul(true) }).getLayers()[0];
  sitLayer.addLayer(simpLayer);
  let geometry = simplified.geometry;
  let suprafata = '', centru = '', bbox = '', dimensiuni = '';
  if (geometry && (geometry.type === "Polygon" || geometry.type === "MultiPolygon")) {
    let turfArea = turf.area({type:'Feature', geometry: geometry});
    suprafata = (turfArea/10000).toFixed(2);
    let turfCentroid = turf.centroid({type:'Feature', geometry: geometry});
    centru = turfCentroid.geometry.coordinates;
    bbox = turf.bbox({type:'Feature', geometry: geometry});
    let latMin = bbox[1].toFixed(6), latMax = bbox[3].toFixed(6),
        lngMin = bbox[0].toFixed(6), lngMax = bbox[2].toFixed(6);
    dimensiuni = `Lungime: ${(turf.distance([lngMin,latMin],[lngMax,latMin])*1000).toFixed(0)} m, 
                  Lățime: ${(turf.distance([lngMin,latMin],[lngMin,latMax])*1000).toFixed(0)} m`;
  }
  var form = document.createElement('form');
  form.innerHTML = `
    <label>Nr. crt.: <input type="number" id="nrcrt" required></label><br>
    <label>Cod RAN: <input type="text" id="codran"></label><br>
    <label>Localizare: <input type="text" id="localizare"></label><br>
    <label>Denumire: <input type="text" id="denumire"></label><br>
    <label>Tip: <input type="text" id="tip"></label><br>
    <label>Datare: <input type="text" id="datare"></label><br>
    <label>Zonă tampon (m): <input type="number" id="tampon" min="0" value="${DEFAULT_TAMPON}"></label><br>
    <label>Categoria clasării: <input type="text" id="categoria_clasare"></label><br>
    <label>Data clasării: <input type="text" id="data_clasare"></label><br>
    <label>Ref. document clasare: <input type="text" id="ref_doc_clasare"></label><br>
    <label>Numere Cadastrale: <input type="text" id="numere_cadastrale"></label><br>
    <label>Caracteristici suprafață: <input type="text" id="caracteristici_suprafata"></label><br>
    <label>Grad conservare: <input type="text" id="grad_conservare"></label><br>
    <label>An descoperire/autor: <input type="text" id="an_descoperire"></label><br>
    <label>Cercetare arheologică: <input type="text" id="cercetare_arheologica"></label><br>
    <label>Bibliografie: <input type="text" id="bibliografie"></label><br>
    <label>Data fișei: <input type="text" id="data_fisa"></label><br>
    <label>Autor fișă: <input type="text" id="autor_fisa"></label><br>
    <div style="margin:7px 0; font-size:90%;">
      <b>Centru GPS:</b> ${centru ? `[${centru[1].toFixed(6)}, ${centru[0].toFixed(6)}]` : ""}<br>
      <b>Dimensiuni:</b> ${dimensiuni}<br>
      <b>Suprafață estimată:</b> ${suprafata} ha
    </div>
    <button type="submit">Salvează</button>
    <button type="button" id="anuleaza">Anulează</button>
  `;
  var popup = L.popup({autoPan: false}).setContent(form);
  simpLayer.bindPopup(popup).openPopup();
  L.DomEvent.disableClickPropagation(form);
  form.querySelector("#anuleaza").onclick = function() {
    sitLayer.removeLayer(simpLayer);
  };
  form.addEventListener('submit', function(ev) {
    ev.preventDefault();
    let tamponVal = form.tampon.value && parseFloat(form.tampon.value) > 0 ? form.tampon.value : DEFAULT_TAMPON;
    let props = {
      nrcrt: form.nrcrt.value, codran: form.codran.value, localizare: form.localizare.value,
      denumire: form.denumire.value, tip: form.tip.value, datare: form.datare.value, tampon: tamponVal,
      categoria_clasare: form.categoria_clasare.value, data_clasare: form.data_clasare.value,
      ref_doc_clasare: form.ref_doc_clasare.value,
      numere_cadastrale: form.numere_cadastrale.value,
      caracteristici_suprafata: form.caracteristici_suprafata.value, grad_conservare: form.grad_conservare.value,
      an_descoperire: form.an_descoperire.value, cercetare_arheologica: form.cercetare_arheologica.value,
      bibliografie: form.bibliografie.value, data_fisa: form.data_fisa.value, autor_fisa: form.autor_fisa.value,
      color: 'orange', fillColor: 'yellow'
    };
    simpLayer.feature = simpLayer.toGeoJSON();
    simpLayer.feature.properties = props;
    sitFeaturesRaw.push(simpLayer.feature);
    updateTable();
    saveAllGeojsonToServer();
    renderLayersByZoom();
    map.closePopup();
  });
});
map.on(L.Draw.Event.EDITED, function (e) {
  e.layers.eachLayer(function(layer) { showEditForm(layer); });
});

// === Import/Export KML, salvare, tabel etc (restul codului tău rămâne neschimbat) ===
function uploadKML() {
  let input = document.getElementById('importKML');
  let file = input.files[0];
  let importStatus = document.getElementById('importStatus');
  importStatus.innerText = "";
  if (!file) { alert("Selectează un fișier KML sau KMZ."); return; }
  let ext = file.name.split('.').pop().toLowerCase();
  if (ext === "kmz") {
    JSZip.loadAsync(file).then(function(zip) {
      let kmlFile = Object.keys(zip.files).find(name => name.endsWith('.kml'));
      if (!kmlFile) { alert("Fișierul KMZ nu conține KML valid."); return; }
      zip.files[kmlFile].async("string").then(function(kmlText) { importKMLText(kmlText, importStatus); });
    });
  } else if (ext === "kml") {
    let reader = new FileReader();
    reader.onload = function(e) { importKMLText(e.target.result, importStatus); };
    reader.readAsText(file);
  } else { alert("Doar fișiere KML/KMZ suportate!"); }
}
function importKMLText(kmlText, importStatus) {
  let parser = new DOMParser();
  let kml = parser.parseFromString(kmlText, 'text/xml');
  let geojson = toGeoJSON.kml(kml);
  let features = geojson.features || [];
  let total = features.length, imported = 0;
  if (total === 0) { importStatus.innerText = "Fișierul nu conține date importabile!"; return; }
  function processNext(i) {
    if (i >= total) {
      updateTable();
      saveAllGeojsonToServer();
      renderLayersByZoom();
      importStatus.innerText = `Import finalizat: ${imported} situri importate!`;
      document.getElementById('importKML').value = '';
      setTimeout(()=>importStatus.innerText="",4000);
      return;
    }
    let feature = features[i];
    let simplified = simplificaGeojson(feature, 2);
    if (!simplified.properties) simplified.properties = {};
    if (!simplified.properties.tampon || isNaN(simplified.properties.tampon) || parseFloat(simplified.properties.tampon) <= 0) {
      simplified.properties.tampon = DEFAULT_TAMPON;
    }
    sitFeaturesRaw.push(simplified);
    imported++;
    importStatus.innerText = `Se importă ${imported} / ${total} ...`;
    setTimeout(()=>processNext(i+1), 2);
  }
  importStatus.innerText = `Se importă 0 / ${total} ...`;
  processNext(0);
}
function exportKML() {
  let geojson = {type: "FeatureCollection", features: sitFeaturesRaw};
  let kml = tokml(geojson, {name: 'denumire'});
  let blob = new Blob([kml], {type: "application/vnd.google-earth.kml+xml"});
  let a = document.createElement('a');
  a.href = URL.createObjectURL(blob); a.download = "siturile_mele.kml";
  document.body.appendChild(a); a.click(); document.body.removeChild(a);
}
function saveAllGeojsonToServer() {
  let geojson = { type: "FeatureCollection", features: sitFeaturesRaw };
  fetch('save_geojson.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(geojson)
  })
  .then(r=>r.text())
  .then(resp => { if(resp.trim() === "success") console.log("Date salvate cu succes!"); else alert("Eroare la salvare!"); });
}
function searchSitul() {
  const val = document.getElementById('searchInput').value.trim().toLowerCase();
  let results = [];
  sitFeaturesRaw.forEach(function(feature) {
    let props = feature.properties;
    let rowText = [
      props.nrcrt,
      props.codran,
      props.localizare,
      props.denumire,
      props.tip,
      props.datare
    ].join(' ').toLowerCase();
    if (rowText.indexOf(val) !== -1) {
      results.push(feature);
    }
  });
  currentSearchResults = results;
  currentPage = 1;
  updateTable();
  renderLayersByZoom();
}
function clearSearch() {
  document.getElementById('searchInput').value = "";
  currentSearchResults = null;
  currentPage = 1;
  updateTable();
  renderLayersByZoom();
}
function updateTable() {
  let tbody = document.getElementById("situlTable").getElementsByTagName('tbody')[0];
  tbody.innerHTML = "";
  let features = [];
  if (currentSearchResults) {
    features = currentSearchResults.slice();
  } else {
    features = sitFeaturesRaw.slice();
  }
  features.sort((a, b) => (parseInt(a.properties.nrcrt || 0) - parseInt(b.properties.nrcrt || 0)));
  let total = features.length;
  let totalPages = Math.max(1, Math.ceil(total / pageSize));
  if (currentPage > totalPages) currentPage = totalPages;
  let start = (currentPage - 1) * pageSize;
  let end = Math.min(start + pageSize, total);
  for (let i = start; i < end; i++) {
    let feature = features[i];
    let props = feature.properties || {};
    let row = tbody.insertRow();
    row.insertCell(0).innerText = props.nrcrt || "";
    row.insertCell(1).innerText = props.codran || "";
    row.insertCell(2).innerText = props.localizare || "";
    row.insertCell(3).innerText = props.denumire || props.name || "";
    row.insertCell(4).innerText = props.tip || "";
    row.insertCell(5).innerText = props.datare || "";
    let btn = document.createElement('button');
    btn.innerText = "Afișează";
    btn.onclick = function() {
      let doShow = function() {
        let l = lazyLayerRefs.find(l => l.feature && l.feature.properties.nrcrt == props.nrcrt);
        if (l) {
          map.fitBounds(l.getBounds(), {maxZoom: BUFFER_MIN_ZOOM + 1});
          l.openPopup();
          highlightFeature(l);
        }
      };
      if (map.getZoom() < BUFFER_MIN_ZOOM) {
        let centroid = null;
        if (feature.geometry) {
          centroid = turf.centroid(feature).geometry.coordinates;
        }
        if (centroid) {
          map.setView([centroid[1], centroid[0]], BUFFER_MIN_ZOOM + 1);
        } else {
          map.setZoom(BUFFER_MIN_ZOOM + 1);
        }
        setTimeout(doShow, 500);
      } else {
        doShow();
      }
    };
    row.insertCell(6).appendChild(btn);
  }
  if (total === 0) {
    let row = tbody.insertRow();
    let cell = row.insertCell(0);
    cell.colSpan = 7;
    cell.innerText = "Niciun sit găsit!";
  }
  showPagination(total, currentPage, pageSize);
}
function showPagination(total, page, pageSize) {
  let pagDiv = document.getElementById("paginationDiv");
  if (!pagDiv) {
    pagDiv = document.createElement("div");
    pagDiv.id = "paginationDiv";
    pagDiv.style.margin = "10px 0";
    document.getElementById("attributeTable").appendChild(pagDiv);
  }
  pagDiv.innerHTML = '';
  let totalPages = Math.ceil(total / pageSize);
  if (totalPages <= 1) {
    pagDiv.style.display = "none";
    return;
  }
  pagDiv.style.display = "block";
  let prevBtn = document.createElement("button");
  prevBtn.innerText = "Pagina anterioară";
  prevBtn.disabled = page === 1;
  prevBtn.onclick = function() {
    if (page > 1) {
      currentPage--;
      updateTable();
      renderLayersByZoom();
    }
  };
  pagDiv.appendChild(prevBtn);
  let span = document.createElement("span");
  span.innerHTML = `&nbsp;Pagina ${page} / ${totalPages}&nbsp;`;
  pagDiv.appendChild(span);
  let nextBtn = document.createElement("button");
  nextBtn.innerText = "Pagina următoare";
  nextBtn.disabled = page === totalPages;
  nextBtn.onclick = function() {
    if (page < totalPages) {
      currentPage++;
      updateTable();
      renderLayersByZoom();
    }
  };
  pagDiv.appendChild(nextBtn);
}

  document.body.addEventListener('click', function(e) {
  if (e.target.classList && e.target.classList.contains('download-pdf-btn')) {
    var nrcrt = e.target.getAttribute('data-nrcrt');
    var found = sitLayer.getLayers().find(f =>
      f.feature && f.feature.properties && String(f.feature.properties.nrcrt) === String(nrcrt)
    );
    console.log('Delegare globală PDF, nrcrt:', nrcrt, found);
    if (found) downloadSitulPDF(found.feature);
    else alert('Eroare: nu s-a găsit situl.');
  }
  
});
