/**
 * Leaflet map initialisation for article pages (country + city maps).
 *
 * Looks for #country-map and #city-map elements. If neither exists, does nothing.
 * Country maps read inline JSON from #country-map-data (no network fetch).
 * City maps still fetch venue data from the JSON API.
 *
 * Depends on map-markers.js (window.PNMarkers) being loaded first.
 */
(function() {
  var countryMapEl = document.getElementById('country-map');
  var cityMapEl = document.getElementById('city-map');
  if (!countryMapEl && !cityMapEl) return;

  var TILES = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png';
  var TILES_ATTR = '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> &copy; <a href="https://carto.com/">CARTO</a>';
  var sc = PNMarkers.scoreColor;
  var T = window.__MAP_T || {};

  function fmtPop(p) {
    return p >= 1000000 ? (p / 1000000).toFixed(1) + 'M'
         : p >= 1000   ? Math.round(p / 1000) + 'K'
         : (p || '');
  }

  function initCountryMap(el) {
    var dataEl = document.getElementById('country-map-data');
    if (!dataEl) return;
    var data = JSON.parse(dataEl.textContent);
    var slug = el.dataset.countrySlug;
    var map = L.map(el, {scrollWheelZoom: false});
    L.tileLayer(TILES, { attribution: TILES_ATTR, maxZoom: 18 }).addTo(map);
    var lang = document.documentElement.lang || 'en';

    if (!data.length) return;
    var maxPop = Math.max.apply(null, data.map(function(d) { return d.population || 1; }));
    var bounds = [];
    data.forEach(function(c) {
      if (!c.lat || !c.lon) return;
      var size = 8 + 36 * Math.sqrt((c.population || 1) / maxPop);
      var hasArticle = c.has_article === true;
      var score = c.opportunity_score || 0;
      var hex = sc(score);
      var pop = fmtPop(c.population);
      var venueInfo = (c.padel_venue_count || 0) > 0
        ? (c.padel_venue_count + ' ' + (T.venues || 'venues'))
        : (c.nearest_padel_court_km
          ? Math.round(c.nearest_padel_court_km) + ' ' + (T.km_nearest || 'km to nearest court')
          : (T.no_nearby || 'No courts nearby'));
      var tip = '<strong>' + c.city_name + '</strong><br>'
        + '<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:' + hex + ';vertical-align:middle;margin-right:4px;"></span>'
        + '<span style="color:' + hex + ';font-weight:600;">' + (T.score_label || 'Padelnomics Score') + ': ' + Math.round(score) + '/100</span><br>'
        + '<span style="color:#94A3B8;font-size:0.75rem;">'
        + venueInfo
        + (pop ? ' · ' + pop + ' ' + (T.pop || 'pop') : '') + '</span>';
      if (hasArticle) {
        tip += '<br><span style="color:#94A3B8;font-size:0.75rem;">' + (T.click_explore || 'Click to explore →') + '</span>';
      } else {
        tip += '<br><span style="color:#94A3B8;font-size:0.75rem;">' + (T.coming_soon || 'Coming soon') + '</span>';
      }
      var icon = PNMarkers.makeIcon({
        size: size,
        color: hex,
        muted: !hasArticle,
      });
      var marker = L.marker([c.lat, c.lon], { icon: icon })
        .bindTooltip(tip, { className: 'map-tooltip', direction: 'top', offset: [0, -Math.round(size / 2)] })
        .addTo(map);
      if (hasArticle) {
        marker.on('click', function() { window.location = '/' + lang + '/markets/' + slug + '/' + c.city_slug; });
      }
      bounds.push([c.lat, c.lon]);
    });
    if (bounds.length) map.fitBounds(bounds, { padding: [24, 24] });

    // Highlight user's city (best-effort name match via CF-IPCity)
    var uc = (window.__GEO || {}).city || '';
    if (uc) {
      var match = data.find(function(c) {
        return c.city_name && c.city_name.toLowerCase() === uc.toLowerCase();
      });
      if (match && match.lat && match.lon) {
        var hSize = 8 + 36 * Math.sqrt((match.population || 1) / maxPop);
        var hIcon = PNMarkers.makeIcon({
          size: hSize,
          color: sc(match.opportunity_score || 0),
          highlight: true,
        });
        L.marker([match.lat, match.lon], { icon: hIcon }).addTo(map);
      }
    }
  }

  function initCityMap(el, venueIcon) {
    var countrySlug = el.dataset.countrySlug;
    var citySlug = el.dataset.citySlug;
    var lat = parseFloat(el.dataset.lat);
    var lon = parseFloat(el.dataset.lon);
    var map = L.map(el, {scrollWheelZoom: false}).setView([lat, lon], 13);
    L.tileLayer(TILES, { attribution: TILES_ATTR, maxZoom: 18 }).addTo(map);
    fetch('/api/markets/' + countrySlug + '/' + citySlug + '/venues.json')
      .then(function(r) { return r.json(); })
      .then(function(data) {
        data.forEach(function(v) {
          if (!v.lat || !v.lon) return;
          var indoor = v.indoor_court_count || 0;
          var outdoor = v.outdoor_court_count || 0;
          var total = v.court_count || (indoor + outdoor);
          var courtLine = total
            ? total + ' ' + (T.courts || 'court' + (total > 1 ? 's' : ''))
              + (indoor || outdoor
                ? ' (' + [indoor ? indoor + ' ' + (T.indoor || 'indoor') : '', outdoor ? outdoor + ' ' + (T.outdoor || 'outdoor') : ''].filter(Boolean).join(', ') + ')'
                : '')
            : '';
          var tip = '<strong>' + v.name + '</strong>' + (courtLine ? '<br>' + courtLine : '');
          L.marker([v.lat, v.lon], { icon: venueIcon })
            .bindTooltip(tip, { className: 'map-tooltip', direction: 'top', offset: [0, -7] })
            .addTo(map);
        });
      })
      .catch(function(err) { console.error('City map fetch failed:', err); });
  }

  /* Dynamically load Leaflet JS then init maps */
  var script = document.createElement('script');
  script.src = window.LEAFLET_JS_URL || '/static/vendor/leaflet/leaflet.min.js';
  script.onload = function() {
    if (countryMapEl) initCountryMap(countryMapEl);
    if (cityMapEl) {
      var venueIcon = L.divIcon({
        className: '',
        html: '<div class="pn-venue"></div>',
        iconSize: [10, 10],
        iconAnchor: [5, 5],
      });
      initCityMap(cityMapEl, venueIcon);
    }
  };
  document.head.appendChild(script);
})();
