{% extends "base.html" %}

{% block title %}Padel Opportunity Map — {{ config.APP_NAME }}{% endblock %}

{% block head %}
<meta name="description" content="Explore padel investment opportunities by location. Find underserved markets with high population, strong sports culture, and no existing padel courts.">
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/leaflet/leaflet.min.css') }}">
<style>
  #opportunity-map { width: 100%; height: 600px; border-radius: 12px; }
  .opp-legend {
    background: white; padding: 10px 14px; border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0,0,0,.15); font-size: 0.8125rem; line-height: 1.8;
  }
  .opp-legend span { display: inline-block; width: 12px; height: 12px; border-radius: 50%; margin-right: 6px; vertical-align: middle; }
</style>
{% endblock %}

{% block content %}
<main class="container-page py-12">
  <header class="mb-6">
    <h1 class="text-3xl mb-2">Padel Opportunity Map</h1>
    <p class="text-slate">Locations ranked by investment potential — population, supply gap, sports culture, and catchment reach.</p>
  </header>

  <div class="card mb-4" style="padding: 1rem 1.25rem;">
    <label class="form-label" for="opp-country-select" style="margin-bottom: 0.5rem; display:block;">Select a country</label>
    <select id="opp-country-select" name="country" class="form-input" style="max-width:280px;"
            hx-get="{{ url_for('public.opportunity_map_data') }}"
            hx-target="#map-data"
            hx-trigger="change">
      <option value="">— choose country —</option>
      {% for c in countries %}
      <option value="{{ c.country_slug }}" {% if c.country_slug == selected_slug %}selected{% endif %}>{{ c.country_name }}</option>
      {% endfor %}
    </select>
  </div>

  <div id="opportunity-map"></div>
  <div id="map-data" style="display:none;"></div>

  <div class="mt-4 text-sm text-slate" style="display:flex; flex-wrap:wrap; gap:0.5rem 1.5rem; align-items:center;">
    <span style="display:flex; align-items:center; gap:0.3rem;">
      <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#15803D;"></span>≥60
      <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#D97706;margin-left:4px;"></span>≥30
      <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#DC2626;margin-left:4px;"></span>&lt;30
    </span>
    <span><strong>Size:</strong> population</span>
  </div>
</main>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='vendor/leaflet/leaflet.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/map-markers.js') }}"></script>
<script>
window.__MAP_T = {score_label:"{{ t.map_score_label }}",venues:"{{ t.map_venues }}",pop:"{{ t.map_pop }}",existing_venues:"{{ t.map_existing_venues }}",km_nearest:"{{ t.map_km_nearest }}",no_nearby:"{{ t.map_no_nearby }}"};
(function() {
  var sc = PNMarkers.scoreColor;
  var T = window.__MAP_T;
  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 map = L.map('opportunity-map', {scrollWheelZoom: false}).setView([48.5, 10], 4);
  L.tileLayer(TILES, { attribution: TILES_ATTR, maxZoom: 18 }).addTo(map);

  var oppLayer = L.layerGroup().addTo(map);
  var refLayer = L.layerGroup().addTo(map);

  var REF_ICON = L.divIcon({
    className: '',
    html: '<div class="pn-venue" style="background:#94A3B8;border-color:white;opacity:0.7;"></div>',
    iconSize: [10, 10],
    iconAnchor: [5, 5],
  });

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

  function renderMap() {
    oppLayer.clearLayers();
    refLayer.clearLayers();
    var oppEl = document.getElementById('opp-data');
    var refEl = document.getElementById('ref-data');
    if (!oppEl) return;
    var oppData = JSON.parse(oppEl.textContent);
    var refData = JSON.parse(refEl.textContent);

    refData.forEach(function(c) {
      if (!c.lat || !c.lon || !c.padel_venue_count) return;
      L.marker([c.lat, c.lon], { icon: REF_ICON })
        .bindTooltip(c.city_name + ' — ' + c.padel_venue_count + ' ' + T.existing_venues,
          { className: 'map-tooltip', direction: 'top', offset: [0, -7] })
        .addTo(refLayer);
    });

    if (!oppData.length) return;
    var maxPop = Math.max.apply(null, oppData.map(function(d) { return d.population || 1; }));
    var bounds = [];
    oppData.forEach(function(loc) {
      if (!loc.lat || !loc.lon) return;
      var size = 8 + 40 * Math.sqrt((loc.population || 1) / maxPop);
      var score = loc.opportunity_score;
      var hex = sc(score);
      var dist = loc.nearest_padel_court_km != null
        ? loc.nearest_padel_court_km.toFixed(1) + ' ' + T.km_nearest
        : T.no_nearby;
      var tip = '<strong>' + loc.location_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 + ': ' + score + '/100</span><br>'
        + '<span style="color:#94A3B8;font-size:0.75rem;">' + dist + ' · ' + T.pop + ' ' + fmtPop(loc.population) + '</span>';
      var icon = PNMarkers.makeIcon({
        size: size,
        color: hex,
        pulse: score >= 60,
      });
      L.marker([loc.lat, loc.lon], { icon: icon })
        .bindTooltip(tip, { className: 'map-tooltip', direction: 'top', offset: [0, -Math.round(size / 2)] })
        .addTo(oppLayer);
      bounds.push([loc.lat, loc.lon]);
    });
    if (bounds.length) map.fitBounds(bounds, { padding: [30, 30] });
  }

  document.body.addEventListener('htmx:afterSwap', function(e) {
    if (e.detail.target.id === 'map-data') renderMap();
  });

  // Auto-load if country pre-selected via geo header
  var sel = document.getElementById('opp-country-select');
  if (sel.value) htmx.trigger(sel, 'change');
})();
</script>
{% endblock %}
