(() => {
  const $ = (id) => document.getElementById(id);

  // === API (relativo a /pages/configuracion.html) ===
  const API = {
    kpis: "../php/config/kpis.php",
    sz: {
      list: "../php/config/sectorizacion/list.php",
      save: "../php/config/sectorizacion/save.php",
      del: "../php/config/sectorizacion/delete.php",
    },
    sec: {
      list: "../php/config/sectores/list.php",
      save: "../php/config/sectores/save.php",
      del: "../php/config/sectores/delete.php",
    },
    fun: {
      list: "../php/config/funcionarios/list.php",
      save: "../php/config/funcionarios/save.php",
      del: "../php/config/funcionarios/delete.php",
    },
    sectorMap: {
      list: "../php/config/sectores_mapa/list.php",
      save: "../php/config/sectores_mapa/save.php",
    },
  };

  // User (para headers DEV fallback)
  const userRaw = sessionStorage.getItem("fp_user");
  const user = userRaw ? JSON.parse(userRaw) : null;
  const rolActual = String(user?.rol || user?.rol_funcionario || "").toLowerCase().trim();
  const isAdmin = ["admin", "administrador"].includes(rolActual);

  if (!isAdmin) return;

  function normalizaRolFuncionario(rol) {
    rol = String(rol || "").toLowerCase().trim().replaceAll("_", " ").replace(/\s+/g, "-");
    if (["admin", "administrador"].includes(rol)) return "administrador";
    if (rol === "digitador") return "digitador";
    if (["digitador-terreno", "terreno"].includes(rol)) return "digitador-terreno";
    if (["monitor", "lectura", "solo-lectura", "readonly", "read-only"].includes(rol)) return "monitor";
    if (rol === "supervisor") return "digitador";
    return "digitador";
  }

  const authHeaders = () => ({
    ...(user?.rut ? { "X-FP-RUT": String(user.rut) } : {}),
    ...(user?.rol ? { "X-FP-ROL": String(user.rol) } : {}),
    ...(user?.rol_funcionario ? { "X-FP-ROL": String(user.rol_funcionario) } : {}),
  });

  async function fetchJSON(url, opts = {}) {
    const headers = {
      Accept: "application/json",
      ...authHeaders(),
      ...(opts.headers || {}),
    };

    const res = await fetch(url, {
      credentials: "same-origin",
      cache: "no-store",
      ...opts,
      headers,
    });

    const data = await res.json().catch(() => null);
    if (!res.ok || !data || data.ok === false) {
      const msg = data?.message || "Error de servidor.";
      throw new Error(msg);
    }
    return data;
  }

  // ===== Elementos =====
  const kpiSectorizaciones = $("kpiSectorizaciones");
  const kpiSectores = $("kpiSectores");
  const kpiFuncionarios = $("kpiFuncionarios");

  const formSz = $("formSectorizacion");
  const szNombre = $("szNombre");
  const szColor = $("szColor");
  const szColorTxt = $("szColorTxt");
  const tblSz = $("tblSectorizaciones");
  const btnSzLimpiar = $("btnSzLimpiar");

  const formSec = $("formSector");
  const secNombre = $("secNombre");
  const secSectorizacion = $("secSectorizacion");
  const tblSec = $("tblSectores");
  const btnSecLimpiar = $("btnSecLimpiar");

  const formF = $("formFuncionario");
  const fRut = $("fRut");
  const fApPat = $("fApPat");
  const fApMat = $("fApMat");
  const fNombre = $("fNombre");
  const fCorreo = $("fCorreo");
  const fCelular = $("fCelular");
  const fRol = $("fRol");
  const fClave = $("fClave");
  const tblF = $("tblFuncionarios");
  const btnFLimpiar = $("btnFLimpiar");

  const mapSectorSelect = $("mapSectorSelect");
  const mapSectorLabel = $("mapSectorLabel");
  const mapSectorRadius = $("mapSectorRadius");
  const mapSectorStatus = $("mapSectorStatus");
  const btnMapSectorPick = $("btnMapSectorPick");
  const btnMapSectorSave = $("btnMapSectorSave");
  const btnMapSectorDelete = $("btnMapSectorDelete");
  const btnMapSectorExport = $("btnMapSectorExport");
  const btnMapSectorRecenter = $("btnMapSectorRecenter");

  // ===== Estado =====
  let SZ = [];
  let SEC = [];
  let FUN = [];
  let sectorMapConfig = {};
  let sectorMapDraft = null;
  let sectorMapPickMode = false;

  const PANQUEHUE_BOUNDS = [[-32.804165, -70.948224],[-32.755789, -70.739231]];
  const PANQUEHUE_CENTER = [-32.7800, -70.8450];

  // ===== Color sync =====
  if (szColor && szColorTxt) {
    szColorTxt.value = szColor.value;
    szColor.addEventListener("input", () => (szColorTxt.value = szColor.value));
    szColorTxt.addEventListener("input", () => {
      const v = szColorTxt.value.trim();
      if (/^#([0-9a-fA-F]{6})$/.test(v)) szColor.value = v;
    });
  }

  // ===== Render =====
  function renderKPIs(k) {
    kpiSectorizaciones.textContent = String(k.sectorizaciones ?? "—");
    kpiSectores.textContent = String(k.sectores ?? "—");
    kpiFuncionarios.textContent = String(k.funcionarios ?? "—");
  }

  function renderSectorizacionSelect() {
    const current = secSectorizacion.value;
    const options = ['<option value="">Seleccione…</option>']
      .concat(
        SZ.map(
          (z) => `<option value="${z.id}">${escapeHtml(z.nombre_sectorizacion)}</option>`
        )
      )
      .join("");
    secSectorizacion.innerHTML = options;
    if ([...secSectorizacion.options].some(o => o.value === String(current))) {
      secSectorizacion.value = current;
    }
  }

  function renderSectorizaciones() {
    if (!SZ.length) {
      tblSz.innerHTML = `<tr class="text-muted"><td colspan="3">Sin datos.</td></tr>`;
      return;
    }

    tblSz.innerHTML = SZ.map(z => `
      <tr>
        <td>${escapeHtml(z.nombre_sectorizacion || "")}</td>
        <td>
          ${z.color_sector ? `<span class="badge" style="background:${z.color_sector};color:#fff">${escapeHtml(z.color_sector)}</span>` : `<span class="text-muted">—</span>`}
        </td>
        <td class="text-end">
          <button class="btn btn-sm btn-outline-primary me-1" data-act="edit-sz" data-id="${z.id}">
            <i class="bi bi-pencil"></i>
          </button>
          <button class="btn btn-sm btn-outline-danger" data-act="del-sz" data-id="${z.id}">
            <i class="bi bi-trash"></i>
          </button>
        </td>
      </tr>
    `).join("");
  }

  function renderSectores() {
    if (!SEC.length) {
      tblSec.innerHTML = `<tr class="text-muted"><td colspan="3">Sin datos.</td></tr>`;
      return;
    }

    tblSec.innerHTML = SEC.map(s => `
      <tr>
        <td>${escapeHtml(s.nombre_sector || "")}</td>
        <td>
          ${escapeHtml(s.nombre_sectorizacion || "—")}
        </td>
        <td class="text-end">
          <button class="btn btn-sm btn-outline-primary me-1" data-act="edit-sec" data-id="${s.id}">
            <i class="bi bi-pencil"></i>
          </button>
          <button class="btn btn-sm btn-outline-danger" data-act="del-sec" data-id="${s.id}">
            <i class="bi bi-trash"></i>
          </button>
        </td>
      </tr>
    `).join("");
  }

  function renderFuncionarios() {
    if (!FUN.length) {
      tblF.innerHTML = `<tr class="text-muted"><td colspan="4">Sin datos.</td></tr>`;
      return;
    }

    tblF.innerHTML = FUN.map(f => {
      const nombre = `${f.nombre || ""} ${f.apellido_paterno || ""} ${f.apellido_materno || ""}`.trim();
      return `
        <tr>
          <td>${escapeHtml(f.rut || "")}</td>
          <td>${escapeHtml(nombre || "—")}</td>
          <td>${escapeHtml(normalizaRolFuncionario(f.rol_funcionario) || "—")}</td>
          <td class="text-end">
            <button class="btn btn-sm btn-outline-primary me-1" data-act="edit-f" data-rut="${escapeHtml(f.rut)}">
              <i class="bi bi-pencil"></i>
            </button>
            <button class="btn btn-sm btn-outline-danger" data-act="del-f" data-rut="${escapeHtml(f.rut)}">
              <i class="bi bi-trash"></i>
            </button>
          </td>
        </tr>
      `;
    }).join("");
  }

  // ===== Load =====
  async function loadAll(showToast = false) {
    try {
      const [k, sz, sec, fun] = await Promise.all([
        fetchJSON(API.kpis),
        fetchJSON(API.sz.list),
        fetchJSON(API.sec.list),
        fetchJSON(API.fun.list),
      ]);

      renderKPIs(k.data);
      SZ = sz.data || [];
      SEC = sec.data || [];
      FUN = fun.data || [];

      renderSectorizacionSelect();
      renderSectorizaciones();
      renderSectores();
      renderFuncionarios();
      renderSectorMapEditor();
      renderSectorMapPreview();

      if (showToast) {
        Swal.fire({ icon: "success", title: "Sincronizado", timer: 900, showConfirmButton: false });
      }
    } catch (e) {
      Swal.fire({ icon: "error", title: "Error", text: e.message || "No se pudo cargar configuración." });
    }
  }

  // ===== Botones superiores =====
  $("btnSync")?.addEventListener("click", async () => { await loadAll(true); await loadSectorMapConfig().catch(()=>{}); });

  $("btnAyuda")?.addEventListener("click", () => {
    Swal.fire({
      icon: "info",
      title: "¿Qué se configura aquí?",
      html: `
        <div style="text-align:left">
          <ul class="mb-0">
            <li><b>Sectorización</b>: nombre y color.</li>
            <li><b>Sectores</b>: sectores asociados a una sectorización.</li>
            <li><b>Funcionarios</b>: usuarios del sistema y roles.</li>
          </ul>
        </div>
      `
    });
  });

  // ===== CRUD Sectorización =====
  formSz?.addEventListener("submit", async (e) => {
    e.preventDefault();
    const nombre = (szNombre.value || "").trim();
    const color = (szColorTxt.value || "").trim();

    if (!nombre) {
      Swal.fire({ icon: "warning", title: "Faltan datos", text: "Ingresa nombre de sectorización." });
      return;
    }

    try {
      await fetchJSON(API.sz.save, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: formSz.dataset.id ? Number(formSz.dataset.id) : undefined,
          nombre_sectorizacion: nombre,
          color_sector: color,
        }),
      });

      Swal.fire({ icon: "success", title: "Guardado", timer: 900, showConfirmButton: false });
      clearSz();
      await loadAll(false);
    } catch (e2) {
      Swal.fire({ icon: "error", title: "Error", text: e2.message });
    }
  });

  function clearSz() {
    formSz?.reset();
    delete formSz.dataset.id;
    if (szColor && szColorTxt) szColorTxt.value = szColor.value;
  }
  btnSzLimpiar?.addEventListener("click", clearSz);

  tblSz?.addEventListener("click", async (e) => {
    const btn = e.target.closest("button[data-act]");
    if (!btn) return;
    const act = btn.dataset.act;
    const id = Number(btn.dataset.id || 0);
    const item = SZ.find(z => Number(z.id) === id);
    if (!item) return;

    if (act === "edit-sz") {
      formSz.dataset.id = String(id);
      szNombre.value = item.nombre_sectorizacion || "";
      const c = item.color_sector || "#2fb7ff";
      szColor.value = c;
      szColorTxt.value = c;
      return;
    }

    if (act === "del-sz") {
      const ok = await Swal.fire({
        icon: "warning",
        title: "¿Eliminar sectorización?",
        text: "Si está en uso, el sistema no permitirá eliminarla.",
        showCancelButton: true,
        confirmButtonText: "Sí, eliminar",
        cancelButtonText: "Cancelar",
      });

      if (!ok.isConfirmed) return;

      try {
        await fetchJSON(API.sz.del, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id }),
        });
        Swal.fire({ icon: "success", title: "Eliminado", timer: 900, showConfirmButton: false });
        await loadAll(false);
      } catch (e3) {
        Swal.fire({ icon: "error", title: "No se pudo eliminar", text: e3.message });
      }
    }
  });

  // ===== CRUD Sectores =====
  formSec?.addEventListener("submit", async (e) => {
    e.preventDefault();
    const nombre = (secNombre.value || "").trim();
    const sectorizacion = Number(secSectorizacion.value || 0);

    if (!nombre || !sectorizacion) {
      Swal.fire({ icon: "warning", title: "Faltan datos", text: "Ingresa nombre y selecciona sectorización." });
      return;
    }

    try {
      await fetchJSON(API.sec.save, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: formSec.dataset.id ? Number(formSec.dataset.id) : undefined,
          nombre_sector: nombre,
          sectorizacion,
        }),
      });

      Swal.fire({ icon: "success", title: "Guardado", timer: 900, showConfirmButton: false });
      clearSec();
      await loadAll(false);
    } catch (e2) {
      Swal.fire({ icon: "error", title: "Error", text: e2.message });
    }
  });

  function clearSec() {
    formSec?.reset();
    delete formSec.dataset.id;
  }
  btnSecLimpiar?.addEventListener("click", clearSec);

  tblSec?.addEventListener("click", async (e) => {
    const btn = e.target.closest("button[data-act]");
    if (!btn) return;
    const act = btn.dataset.act;
    const id = Number(btn.dataset.id || 0);
    const item = SEC.find(s => Number(s.id) === id);
    if (!item) return;

    if (act === "edit-sec") {
      formSec.dataset.id = String(id);
      secNombre.value = item.nombre_sector || "";
      secSectorizacion.value = String(item.sectorizacion || "");
      return;
    }

    if (act === "del-sec") {
      const ok = await Swal.fire({
        icon: "warning",
        title: "¿Eliminar sector?",
        text: "Si está en uso, el sistema no permitirá eliminarlo.",
        showCancelButton: true,
        confirmButtonText: "Sí, eliminar",
        cancelButtonText: "Cancelar",
      });

      if (!ok.isConfirmed) return;

      try {
        await fetchJSON(API.sec.del, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id }),
        });
        Swal.fire({ icon: "success", title: "Eliminado", timer: 900, showConfirmButton: false });
        await loadAll(false);
      } catch (e3) {
        Swal.fire({ icon: "error", title: "No se pudo eliminar", text: e3.message });
      }
    }
  });

  // ===== CRUD Funcionarios =====
  const normalizeRut = (s) =>
    (s || "").toUpperCase().replace(/\./g, "").replace(/-/g, "").replace(/\s+/g, "");

  formF?.addEventListener("submit", async (e) => {
    e.preventDefault();

    const rut = normalizeRut(fRut.value);
    const payload = {
      rut,
      apellido_paterno: (fApPat.value || "").trim(),
      apellido_materno: (fApMat.value || "").trim(),
      nombre: (fNombre.value || "").trim(),
      correo_electronico: (fCorreo.value || "").trim(),
      celular: (fCelular.value || "").trim(),
      rol_funcionario: normalizaRolFuncionario(fRol.value),
      clave: (fClave.value || ""), // si viene vacío y es update, backend lo ignora
    };

    if (!payload.rut || !payload.nombre || !payload.rol_funcionario) {
      Swal.fire({ icon: "warning", title: "Faltan datos", text: "RUT, Nombre y Rol son obligatorios." });
      return;
    }

    try {
      await fetchJSON(API.fun.save, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      Swal.fire({ icon: "success", title: "Guardado", timer: 900, showConfirmButton: false });
      clearF();
      await loadAll(false);
    } catch (e2) {
      Swal.fire({ icon: "error", title: "Error", text: e2.message });
    }
  });

  function clearF() {
    formF?.reset();
  }
  btnFLimpiar?.addEventListener("click", clearF);

  tblF?.addEventListener("click", async (e) => {
    const btn = e.target.closest("button[data-act]");
    if (!btn) return;
    const act = btn.dataset.act;
    const rut = btn.dataset.rut || "";
    const item = FUN.find(f => String(f.rut) === String(rut));
    if (!item) return;

    if (act === "edit-f") {
      fRut.value = item.rut || "";
      fApPat.value = item.apellido_paterno || "";
      fApMat.value = item.apellido_materno || "";
      fNombre.value = item.nombre || "";
      fCorreo.value = item.correo_electronico || "";
      fCelular.value = item.celular || "";
      fRol.value = normalizaRolFuncionario(item.rol_funcionario);
      fClave.value = ""; // no mostramos hash, si quieres cambiarla -> escribir nueva
      return;
    }

    if (act === "del-f") {
      const ok = await Swal.fire({
        icon: "warning",
        title: "¿Eliminar funcionario?",
        text: "Si tiene registros asociados, el sistema no permitirá eliminarlo.",
        showCancelButton: true,
        confirmButtonText: "Sí, eliminar",
        cancelButtonText: "Cancelar",
      });

      if (!ok.isConfirmed) return;

      try {
        await fetchJSON(API.fun.del, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ rut }),
        });
        Swal.fire({ icon: "success", title: "Eliminado", timer: 900, showConfirmButton: false });
        await loadAll(false);
      } catch (e3) {
        Swal.fire({ icon: "error", title: "No se pudo eliminar", text: e3.message });
      }
    }
  });

  function escapeHtml(str) {
    return String(str ?? "")
      .replaceAll("&", "&amp;")
      .replaceAll("<", "&lt;")
      .replaceAll(">", "&gt;")
      .replaceAll('"', "&quot;")
      .replaceAll("'", "&#039;");
  }


  async function loadSectorMapConfig() {
    try {
      const r = await fetchJSON(API.sectorMap.list);
      sectorMapConfig = (r.data && typeof r.data === "object") ? r.data : {};
    } catch {
      sectorMapConfig = {};
    }
    renderSectorMapEditor();
    renderSectorMapPreview();
  }

  function renderSectorMapEditor() {
    if (!mapSectorSelect) return;
    const current = mapSectorSelect.value || "";
    mapSectorSelect.innerHTML = '<option value="">Seleccione…</option>' + SEC.map(s => `<option value="${s.id}">${escapeHtml(s.nombre_sector || `Sector ${s.id}`)}</option>`).join('');
    if (current && SEC.some(s => String(s.id) === current)) mapSectorSelect.value = current;
    updateSectorMapStatus();
  }

  function getSectorNameById(id) {
    const sel = SEC.find(s => String(s.id) === String(id));
    return sel?.nombre_sector || `Sector ${id}`;
  }

  function layerTooltipText(key) {
    const item = sectorMapConfig[String(key)] || {};
    return item.label || item.name || getSectorNameById(key);
  }

  function updateSectorMapStatus() {
    if (!mapSectorStatus || !mapSectorSelect) return;
    const key = String(mapSectorSelect.value || '');
    const saved = key ? sectorMapConfig[key] : null;
    if (saved?.type === 'polygon' && Array.isArray(saved.coordinates) && saved.coordinates.length >= 3) {
      mapSectorStatus.textContent = `${saved.label || saved.name || 'Sector'} guardado como polígono.`;
      if (mapSectorLabel) mapSectorLabel.value = saved.label || saved.name || '';
      return;
    }
    if (sectorMapDraft && sectorMapDraft.key === key) {
      mapSectorStatus.textContent = `Polígono temporal listo. Pulsa Guardar.`;
      return;
    }
    mapSectorStatus.textContent = key ? 'Selecciona “Marcar área” y dibuja el polígono en el mapa.' : 'Selecciona un sector y pulsa “Marcar área”.';
  }

  let sectorMap, sectorMapLayer, sectorMapDrawHandler, sectorMapEditControl;
  function ensureSectorMap() {
    if (sectorMap || !window.L || !document.getElementById('configSectorMap')) return;
    sectorMap = L.map('configSectorMap', { preferCanvas:true }).setView(PANQUEHUE_CENTER, 13);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19, attribution:'&copy; OpenStreetMap'}).addTo(sectorMap);
    sectorMapLayer = new L.FeatureGroup().addTo(sectorMap);

    if (L.Control?.Draw) {
      sectorMapEditControl = new L.Control.Draw({
        position: 'topleft',
        draw: false,
        edit: {
          featureGroup: sectorMapLayer,
          edit: true,
          remove: false
        }
      });
      sectorMap.addControl(sectorMapEditControl);
    }

    sectorMap.on(L.Draw.Event.CREATED, (e) => {
      const key = String(mapSectorSelect?.value || '');
      if (!key) {
        Swal.fire({icon:'warning', title:'Selecciona sector', text:'Debes seleccionar un sector antes de dibujar.'});
        return;
      }
      const layer = e.layer;
      const existing = getLayerByKey(key);
      if (existing) sectorMapLayer.removeLayer(existing);
      bindSectorLayer(layer, key, (mapSectorLabel?.value || getSectorNameById(key)).trim());
      sectorMapLayer.addLayer(layer);
      sectorMapDraft = { key };
      sectorMapPickMode = false;
      updateSectorMapStatus();
    });

    sectorMap.on(L.Draw.Event.EDITED, () => {
      sectorMapDraft = { key: String(mapSectorSelect?.value || '') };
      updateSectorMapStatus();
    });

    setTimeout(()=>sectorMap.invalidateSize(true), 180);
  }

  function polygonStyle(selected = false) {
    return {
      color: selected ? '#0d6efd' : '#2563eb',
      weight: selected ? 3 : 2,
      fillColor: selected ? '#60a5fa' : '#93c5fd',
      fillOpacity: selected ? 0.18 : 0.10
    };
  }

  function getLayerByKey(key) {
    let found = null;
    sectorMapLayer?.eachLayer(layer => {
      if (!found && String(layer._sectorKey || '') === String(key)) found = layer;
    });
    return found;
  }

  function resetLayerStyles() {
    sectorMapLayer?.eachLayer(layer => {
      if (layer.setStyle) layer.setStyle(polygonStyle(false));
    });
  }

  function bindSectorLayer(layer, key, labelOverride = null) {
    const storedLabel = sectorMapConfig[String(key)]?.label || sectorMapConfig[String(key)]?.name || layerTooltipText(key) || getSectorNameById(key);
    const label = String(labelOverride || storedLabel || '').trim() || getSectorNameById(key);
    layer._sectorKey = String(key);
    layer._sectorLabel = label;
    if (layer.setStyle) layer.setStyle(polygonStyle(false));
    if (layer.unbindTooltip) layer.unbindTooltip();
    layer.bindTooltip(escapeHtml(label), {sticky:true, direction:'top', opacity:0.95, className:'config-sector-hover-tooltip'});
    layer.on('mouseover', () => { if (layer.setStyle) layer.setStyle(polygonStyle(true)); });
    layer.on('mouseout', () => { if (layer.setStyle) layer.setStyle(polygonStyle(false)); });
    layer.on('click', () => {
      if (mapSectorSelect) mapSectorSelect.value = String(key);
      if (mapSectorLabel) mapSectorLabel.value = sectorMapConfig[String(key)]?.label || layer._sectorLabel || getSectorNameById(key);
      resetLayerStyles();
      if (layer.setStyle) layer.setStyle(polygonStyle(true));
      updateSectorMapStatus();
    });
  }

  function renderSectorMapPreview() {
    ensureSectorMap();
    if (!sectorMapLayer) return;
    sectorMapLayer.clearLayers();
    Object.entries(sectorMapConfig).forEach(([key, area]) => {
      if (area?.type !== 'polygon' || !Array.isArray(area.coordinates) || area.coordinates.length < 3) return;
      const layer = L.polygon(area.coordinates, polygonStyle(false));
      bindSectorLayer(layer, key);
      sectorMapLayer.addLayer(layer);
    });
  }

  function extractCoords(layer) {
    const latlngs = layer.getLatLngs?.();
    if (!Array.isArray(latlngs) || !Array.isArray(latlngs[0])) return [];
    return latlngs[0].map(p => [Number(Number(p.lat).toFixed(6)), Number(Number(p.lng).toFixed(6))]);
  }

  async function saveSectorMapConfig() {
    await fetchJSON(API.sectorMap.save, {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ data: sectorMapConfig })
    });
  }

  mapSectorSelect?.addEventListener('change', () => {
    const key = String(mapSectorSelect.value || '');
    const saved = key ? sectorMapConfig[key] : null;
    const name = getSectorNameById(key);
    if (mapSectorLabel) mapSectorLabel.value = saved?.label || saved?.name || name || '';
    updateSectorMapStatus();
    const layer = key ? getLayerByKey(key) : null;
    resetLayerStyles();
    if (layer) {
      if (layer.setStyle) layer.setStyle(polygonStyle(true));
      sectorMap.fitBounds(layer.getBounds(), {padding:[30,30], maxZoom:16});
    }
  });

  mapSectorLabel?.addEventListener('input', () => {
    const key = String(mapSectorSelect?.value || '');
    const layer = key ? getLayerByKey(key) : null;
    if (layer) {
      const liveLabel = (mapSectorLabel.value.trim() || getSectorNameById(key));
      layer._sectorLabel = liveLabel;
      layer.unbindTooltip();
      layer.bindTooltip(escapeHtml(liveLabel), {sticky:true, direction:'top', opacity:0.95, className:'config-sector-hover-tooltip'});
    }
  });

  btnMapSectorPick?.addEventListener('click', () => {
    ensureSectorMap();
    if (!mapSectorSelect?.value) return Swal.fire({icon:'warning', title:'Selecciona sector', text:'Debes seleccionar un sector antes de dibujar.'});
    if (!L.Draw?.Polygon) return Swal.fire({icon:'error', title:'Falta librería', text:'Leaflet Draw no está cargado.'});
    if (sectorMapDrawHandler) sectorMapDrawHandler.disable();
    sectorMapPickMode = true;
    sectorMapDraft = null;
    sectorMapDrawHandler = new L.Draw.Polygon(sectorMap, {
      allowIntersection:false,
      showArea:true,
      repeatMode:false,
      shapeOptions: polygonStyle(true)
    });
    sectorMapDrawHandler.enable();
    updateSectorMapStatus();
  });

  btnMapSectorSave?.addEventListener('click', async () => {
    const key = String(mapSectorSelect?.value || '');
    if (!key) return Swal.fire({icon:'warning', title:'Selecciona sector', text:'Debes seleccionar un sector antes de guardar.'});
    const layer = getLayerByKey(key);
    if (!layer) return Swal.fire({icon:'warning', title:'Dibuja primero', text:'Debes dibujar el polígono del sector antes de guardar.'});
    const coordinates = extractCoords(layer);
    if (coordinates.length < 3) return Swal.fire({icon:'warning', title:'Polígono inválido', text:'El sector debe tener al menos 3 puntos.'});
    sectorMapConfig[key] = {
      id: key,
      name: getSectorNameById(key),
      label: (mapSectorLabel?.value || getSectorNameById(key)).trim(),
      type: 'polygon',
      coordinates,
      updated_at: new Date().toISOString()
    };
    sectorMapDraft = null;
    await saveSectorMapConfig();
    renderSectorMapPreview();
    updateSectorMapStatus();
    Swal.fire({icon:'success', title:'Sector guardado', timer:900, showConfirmButton:false});
  });

  btnMapSectorDelete?.addEventListener('click', async () => {
    const key = String(mapSectorSelect?.value || '');
    if (!key || !sectorMapConfig[key]) return;
    delete sectorMapConfig[key];
    const layer = getLayerByKey(key);
    if (layer) sectorMapLayer.removeLayer(layer);
    await saveSectorMapConfig();
    renderSectorMapPreview();
    updateSectorMapStatus();
    Swal.fire({icon:'success', title:'Sector eliminado', timer:900, showConfirmButton:false});
  });

  btnMapSectorExport?.addEventListener('click', () => {
    const blob = new Blob([JSON.stringify(sectorMapConfig, null, 2)], {type:'application/json'});
    const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'sectores_comuna.json'; a.click(); setTimeout(()=>URL.revokeObjectURL(a.href),500);
  });

  btnMapSectorRecenter?.addEventListener('click', () => {
    if (sectorMap) {
      sectorMap.setView(PANQUEHUE_CENTER, 13);
      setTimeout(()=>sectorMap.invalidateSize(true),120);
    }
  });

  document.getElementById('cMapaSectores')?.addEventListener('shown.bs.collapse', () => {
    ensureSectorMap();
    setTimeout(()=>{ sectorMap?.invalidateSize(true); sectorMap?.setView(PANQUEHUE_CENTER,13); }, 180);
  });
  // === Init ===
  loadAll(false).then(() => loadSectorMapConfig().catch(()=>{}));
})();
