(function () {
  const cfgEl = document.getElementById("mb-cpt-pins-config");

  if (!cfgEl) {
    console.error("Missing #mb-cpt-pins-config JSON config element.");
    return;
  }

  let MB_CPT_PINS = null;

  try {
    MB_CPT_PINS = JSON.parse(cfgEl.textContent || "{}");
  } catch (e) {
    console.error("Failed to parse MB config JSON.", e);
    return;
  }

  let map;
  let markers = [];

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

  function clearMarkers() {
    markers.forEach((m) => m.remove());
    markers = [];
  }

  function renderList(pins) {
    const list = document.getElementById("mb-pins-list");
    if (!list) return;

    if (!pins.length) {
      list.innerHTML = `<div class="mb-empty">No results.</div>`;
      return;
    }

    list.innerHTML = pins
      .map((p) => {
        const cats = p.categories?.length ? p.categories.join(", ") : "";
        return `
          <div class="mb-pin-card" data-pin-id="${p.id}">
            <div class="mb-pin-title"><a href="${p.permalink}">${escapeHtml(
          p.title
        )}</a></div>
            ${cats ? `<div class="mb-pin-cats">${escapeHtml(cats)}</div>` : ""}
            ${
              p.excerpt
                ? `<div class="mb-pin-excerpt">${escapeHtml(p.excerpt)}</div>`
                : ""
            }
            <button class="mb-pin-zoom" data-lat="${p.lat}" data-lng="${p.lng}">Zoom</button>
          </div>
        `;
      })
      .join("");

    list.querySelectorAll(".mb-pin-zoom").forEach((btn) => {
      btn.addEventListener("click", () => {
        const lat = parseFloat(btn.dataset.lat);
        const lng = parseFloat(btn.dataset.lng);
        map.flyTo({ center: [lng, lat], zoom: Math.max(map.getZoom(), 13) });
      });
    });
  }

  async function fetchPins(catId) {
    const url = new URL(MB_CPT_PINS.ajax_url);
    url.searchParams.set("action", "mapbox_cpt_pins_get");
    url.searchParams.set("nonce", MB_CPT_PINS.nonce);
    if (catId) url.searchParams.set("cat_id", String(catId));

    const res = await fetch(url.toString(), { credentials: "same-origin" });
    const data = await res.json();

    if (!data.success) return [];
    return data.data.pins || [];
  }

  function fitToPins(pins) {
    if (!pins.length) return;

    if (pins.length === 1) {
      map.flyTo({ center: [pins[0].lng, pins[0].lat], zoom: 13 });
      return;
    }

    const bounds = new mapboxgl.LngLatBounds();
    pins.forEach((p) => bounds.extend([p.lng, p.lat]));
    map.fitBounds(bounds, { padding: 60, duration: 700 });
  }

  function renderMarkers(pins) {
      clearMarkers();
    
      pins.forEach((p) => {
    
        const lat = parseFloat(p.lat);
        const lng = parseFloat(p.lng);
    
        if (isNaN(lat) || isNaN(lng)) {
          console.warn("Invalid coordinates:", p);
          return;
        }
    
        const el = document.createElement("div");
        el.className = "mb-marker";
        el.style.background = MB_CPT_PINS.marker_color || "#e11d48";
    
        const popupHtml = `
          <div class="mb-popup">
            <div class="mb-popup-title">${escapeHtml(p.title)}</div>
            ${
              p.excerpt
                ? `<div class="mb-popup-excerpt">${escapeHtml(p.excerpt)}</div>`
                : ""
            }
            <a class="mb-popup-link" href="${p.permalink}">Open</a>
          </div>
        `;
    
        const popup = new mapboxgl.Popup({ offset: 18 }).setHTML(popupHtml);
    
        const marker = new mapboxgl.Marker(el)
          .setLngLat([lng, lat])
          .setPopup(popup)
          .addTo(map);
    
        markers.push(marker);
      });
    }

  async function loadPins(catId) {
      
      console.log("Loading pins");
    const pins = await fetchPins(catId);
    renderMarkers(pins);
    renderList(pins);
    fitToPins(pins);
  }

  function init() {
    const mapEl = document.getElementById("mb-pins-map");
    if (!mapEl) return;

    if (!MB_CPT_PINS.access_token || !MB_CPT_PINS.style_url) {
      mapEl.innerHTML =
        '<div class="mb-error">Mapbox token or style URL missing. Set it in Settings → Mapbox CPT Pins.</div>';
      return;
    }

    mapboxgl.accessToken = MB_CPT_PINS.access_token;

    map = new mapboxgl.Map({
      container: mapEl,
      style: MB_CPT_PINS.style_url,
      center: [MB_CPT_PINS.default_lng, MB_CPT_PINS.default_lat],
      zoom: MB_CPT_PINS.default_zoom || 10,
    });

    map.addControl(new mapboxgl.NavigationControl());

    map.on("load", () => {
      loadPins("");
    });

    const select = document.getElementById("mb-pins-category");
    if (select) {
      select.addEventListener("change", () => {
        loadPins(select.value);
      });
    }
  }

  document.addEventListener("DOMContentLoaded", init);
})();
