{% load i18n %}
<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% trans "Visitor overview" %}</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="">
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
    <style>
      * { box-sizing: border-box; }
      :root, [data-theme="dark"] {
        --vo-bg: linear-gradient(180deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
        --vo-text: #e2e8f0; --vo-text-muted: #94a3b8; --vo-text-dim: #64748b;
        --vo-card-bg: rgba(30, 41, 59, 0.6); --vo-card-border: rgba(71, 85, 105, 0.5);
        --vo-btn-bg: rgba(30, 41, 59, 0.8); --vo-btn-hover: rgba(51, 65, 85, 0.8);
        --vo-btn-border: #475569; --vo-btn-text: #94a3b8; --vo-btn-text-hover: #e2e8f0;
        --vo-insight-bg: rgba(30, 41, 59, 0.5); --vo-insight-border: rgba(71, 85, 105, 0.4);
        --vo-table-border: rgba(71, 85, 105, 0.5); --vo-table-hover: rgba(51, 65, 85, 0.3);
        --vo-map-tiles: dark;
      }
      [data-theme="light"] {
        --vo-bg: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 50%, #e2e8f0 100%);
        --vo-text: #1e293b; --vo-text-muted: #475569; --vo-text-dim: #64748b;
        --vo-card-bg: rgba(255, 255, 255, 0.9); --vo-card-border: rgba(226, 232, 240, 0.8);
        --vo-btn-bg: #fff; --vo-btn-hover: #f1f5f9;
        --vo-btn-border: #cbd5e1; --vo-btn-text: #64748b; --vo-btn-text-hover: #334155;
        --vo-insight-bg: rgba(255, 255, 255, 0.8); --vo-insight-border: rgba(226, 232, 240, 0.9);
        --vo-table-border: rgba(226, 232, 240, 0.9); --vo-table-hover: rgba(241, 245, 249, 0.9);
        --vo-map-tiles: light;
      }
      body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; padding: 24px; background: var(--vo-bg); min-height: 100vh; color: var(--vo-text); transition: background 0.3s, color 0.3s; }
      .overview { max-width: 1100px; margin: 0 auto; }
      h1 { font-size: 1.5rem; margin: 0 0 8px; color: var(--vo-text); font-weight: 600; }
      .description { color: var(--vo-text-muted); font-size: 0.9rem; margin-bottom: 16px; line-height: 1.4; }
      .grid { display: grid; grid-template-columns: minmax(0, 50%) 1fr; gap: 24px; }
      @media (max-width: 640px) { .grid { grid-template-columns: 1fr; } }
      .card { background: var(--vo-card-bg); border: 1px solid var(--vo-card-border); border-radius: 16px; padding: 24px; backdrop-filter: blur(8px); }
      .card h2 { font-size: 0.9rem; margin: 0 0 16px; color: var(--vo-text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; }
      .summary-grid { display: flex; flex-direction: column; gap: 12px; flex: 1; }
      .summary-stat { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; padding: 16px 18px; border-radius: 12px; }
      .summary-stat.today { background: linear-gradient(135deg, rgba(59, 130, 246, 0.25), rgba(59, 130, 246, 0.08)); border: 1px solid rgba(59, 130, 246, 0.3); }
      .summary-stat.month { background: linear-gradient(135deg, rgba(34, 197, 94, 0.25), rgba(34, 197, 94, 0.08)); border: 1px solid rgba(34, 197, 94, 0.3); }
      .summary-stat.year { background: linear-gradient(135deg, rgba(234, 179, 8, 0.25), rgba(234, 179, 8, 0.08)); border: 1px solid rgba(234, 179, 8, 0.3); }
      .summary-value { font-size: 1.5rem; font-weight: 700; line-height: 1.2; }
      .summary-stat.today .summary-value { color: #60a5fa; }
      .summary-stat.month .summary-value { color: #4ade80; }
      .summary-stat.year .summary-value { color: #facc15; }
      .summary-stat.value-add { background: linear-gradient(135deg, rgba(168, 85, 247, 0.3), rgba(139, 92, 246, 0.1)); border: 1px solid rgba(168, 85, 247, 0.5); }
      .summary-stat.value-add .summary-value { color: #c084fc; }
      .summary-label { font-size: 0.7rem; color: var(--vo-text-dim); text-transform: uppercase; letter-spacing: 0.06em; font-weight: 600; }
      .hero { background: linear-gradient(135deg, rgba(168, 85, 247, 0.2) 0%, rgba(59, 130, 246, 0.15) 100%); border: 1px solid rgba(168, 85, 247, 0.4); border-radius: 20px; padding: 32px; margin-bottom: 24px; text-align: center; }
      .hero-value { font-size: 3rem; font-weight: 800; font-variant-numeric: tabular-nums; background: linear-gradient(135deg, #c084fc, #60a5fa); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; line-height: 1.1; }
      .hero-label { font-size: 1rem; color: var(--vo-text-muted); margin-top: 8px; font-weight: 500; }
      .hero-sub { font-size: 0.85rem; color: var(--vo-text-dim); margin-top: 4px; }
      .insight-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 12px; margin-bottom: 24px; }
      .insight-card { background: var(--vo-insight-bg); border-radius: 12px; padding: 16px; text-align: center; border: 1px solid var(--vo-insight-border); }
      .insight-value { font-size: 1.75rem; font-weight: 700; color: var(--vo-text); }
      .insight-label { font-size: 0.75rem; color: var(--vo-text-dim); margin-top: 4px; }
      .donut-container, .chart-container { position: relative; height: 280px; }
      .month-nav { display: flex; align-items: center; justify-content: center; gap: 16px; margin-bottom: 24px; }
      .month-nav-btn { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; border: 1px solid var(--vo-btn-border); border-radius: 8px; background: var(--vo-btn-bg); color: var(--vo-text); text-decoration: none; font-size: 1.5rem; transition: all 0.2s; }
      .month-nav-btn:hover { background: var(--vo-btn-hover); }
      .month-name { font-size: 1.1rem; font-weight: 600; color: var(--vo-text); min-width: 140px; text-align: center; }
      .overview-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 8px; }
      .header-btns { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
      .switch-btn { display: inline-flex; align-items: center; justify-content: center; padding: 0 12px; height: 36px; border: 1px solid var(--vo-btn-border); border-radius: 8px; background: var(--vo-btn-bg); color: var(--vo-btn-text); text-decoration: none; font-size: 0.875rem; transition: all 0.2s; }
      .switch-btn:hover { background: var(--vo-btn-hover); color: var(--vo-btn-text-hover); }
      .refresh-btn { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; padding: 0; border: 1px solid var(--vo-btn-border); border-radius: 8px; background: var(--vo-btn-bg); color: var(--vo-btn-text); cursor: pointer; transition: all 0.2s; }
      .refresh-btn:hover { background: var(--vo-btn-hover); color: var(--vo-btn-text-hover); }
      .refresh-btn:disabled { opacity: 0.5; cursor: not-allowed; }
      .map-container { height: 400px; border-radius: 12px; overflow: hidden; flex: 1; min-width: 0; }
      .map-card { grid-column: 1 / -1; }
      .map-and-stats { display: flex; gap: 20px; align-items: stretch; }
      @media (max-width: 640px) { .map-and-stats { flex-direction: column; } }
      .map-hover-stats { width: 220px; min-width: 200px; padding: 20px; border-radius: 12px; background: var(--vo-card-bg); border: 1px solid var(--vo-card-border); font-size: 0.95rem; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; }
      @media (max-width: 640px) { .map-hover-stats { width: auto; min-width: 0; min-height: 80px; } }
      .map-hover-stats.empty { color: var(--vo-text-dim); font-style: italic; }
      .map-hover-stats .country-flag { font-size: 3rem; line-height: 1; margin-bottom: 8px; }
      .map-hover-stats.empty .country-flag { display: none; }
      .map-hover-stats .country-name { font-weight: 600; color: var(--vo-text); font-size: 1.05rem; }
      .map-hover-stats .country-detail { margin-top: 6px; color: var(--vo-text-muted); }
      .map-legend { display: flex; align-items: center; gap: 24px; margin-top: 12px; font-size: 0.8rem; color: var(--vo-text-dim); flex-wrap: wrap; }
      .map-legend span { display: flex; align-items: center; gap: 6px; }
      .map-legend .swatch { width: 16px; height: 16px; border-radius: 4px; }
      .map-legend .swatch.unvisited { background: #e8e8e8; }
      .map-legend-gradient .bar { width: 80px; height: 12px; border-radius: 4px; background: linear-gradient(to right, #b8d4f0, #4169e1); }
      .country-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
      .country-table th, .country-table td { padding: 10px 12px; border-bottom: 1px solid var(--vo-table-border); }
      .country-table th { color: var(--vo-text-muted); font-weight: 600; }
      .country-table th:nth-child(1), .country-table td:nth-child(1) { text-align: center; width: 40px; }
      .country-table th:nth-child(2), .country-table td:nth-child(2) { text-align: left; }
      .country-table th:nth-child(3), .country-table td:nth-child(3), .country-table th:nth-child(4), .country-table td:nth-child(4) { text-align: center; font-variant-numeric: tabular-nums; }
      .country-table .rank { color: var(--vo-text-dim); font-size: 0.85rem; }
      .country-table tbody tr:hover { background: var(--vo-table-hover); }
      .country-table td { color: var(--vo-text); }
    </style>
  </head>
  <body>
    <div class="overview">
      <div class="overview-header">
        <h1>{% trans "Visitor overview" %}</h1>
        <div class="header-btns">
          <a href="{% url 'cookie_optin:overview' %}?year={{ year }}&month={{ month }}" class="switch-btn" title="{% trans 'Consent overview' %}">{% trans "Consent overview" %}</a>
          <button type="button" id="refreshBtn" class="refresh-btn" title="{% trans 'Refresh' %}" aria-label="{% trans 'Refresh' %}">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 4v6h-6"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
          </button>
        </div>
      </div>
      <p class="description">
        {% trans "Number of visitors who saw the cookie banner, by day, month and year." %}
      </p>
      <div class="month-nav">
        <a href="{{ prev_url }}" class="month-nav-btn" title="{% trans 'Previous month' %}">‹</a>
        <span class="month-name">{{ month_name|capfirst }}</span>
        <a href="{{ next_url }}" class="month-nav-btn" title="{% trans 'Next month' %}">›</a>
      </div>

      {% if month_total > 0 %}
        <div class="hero">
          <div class="hero-value">+{{ value_add_display }}</div>
          <div class="hero-label">{% trans "visitors invisible to GA" %}</div>
          <div class="hero-sub">{% trans "Your tracking advantage this month" %}</div>
        </div>
        <div class="insight-grid">
          <div class="insight-card">
            <div class="insight-value">{{ invisible_pct }}%</div>
            <div class="insight-label">{% trans "of traffic invisible to GA" %}</div>
          </div>
          <div class="insight-card">
            <div class="insight-value">{{ ga_coverage_pct }}%</div>
            <div class="insight-label">{% trans "GA coverage (acceptance rate)" %}</div>
          </div>
          {% if ga_month_total > 0 %}
            <div class="insight-card">
              <div class="insight-value">+{{ value_add_vs_ga_pct }}%</div>
              <div class="insight-label">{% trans "more than GA sees" %}</div>
            </div>
          {% endif %}
        </div>
      {% endif %}

      <div class="grid">
        <div class="card summary-card">
          <h2>{% trans "Summary" %}</h2>
          <div class="summary-grid">
            <div class="summary-stat today">
              <div class="summary-value">{{ today_count_display }}</div>
              <div class="summary-label">{% trans "Today" %}</div>
            </div>
            <div class="summary-stat month">
              <div class="summary-value">{{ month_total_display }}</div>
              <div class="summary-label">{% trans "This month" %}</div>
            </div>
            <div class="summary-stat year">
              <div class="summary-value">{{ year_total_display }}</div>
              <div class="summary-label">{% trans "This year" %} ({{ year }})</div>
            </div>
            {% if has_ga_data %}
              <div class="summary-stat value-add">
                <div class="summary-value">+{{ value_add_display }}</div>
                <div class="summary-label">{% trans "More than GA" %}</div>
              </div>
            {% endif %}
          </div>
        </div>

        <div class="card" data-lpignore="true" data-form-type="other">
          <h2>{% trans "Traffic split" %}</h2>
          <div class="donut-container">
            <canvas id="donutChart"></canvas>
          </div>
        </div>
        <div class="card" style="grid-column: 1 / -1;" data-lpignore="true" data-form-type="other">
          <h2>{% trans "Visitors per day" %}</h2>
          <div class="chart-container">
            <canvas id="visitorChart"></canvas>
          </div>
        </div>

        <div class="card map-card">
          <h2>{% trans "Visitors by country" %}</h2>
          <div class="map-and-stats">
            <div class="map-container" id="worldMap"></div>
            <div class="map-hover-stats empty" id="mapHoverStats">
              <span class="country-flag" id="mapHoverFlag"></span>
              <span class="country-name" id="mapHoverCountry"></span>
              <div class="country-detail" id="mapHoverDetail">{% trans "Hover over a country to see statistics" %}</div>
            </div>
          </div>
          <div class="map-legend">
            <span><span class="swatch unvisited"></span>{% trans "No visitors" %}</span>
            <span class="map-legend-gradient">
              <span class="bar"></span>
              <span>{% trans "Few" %} → {% trans "Many" %}</span>
            </span>
          </div>
          <div class="country-table-wrapper" id="countryTableWrapper" style="margin-top: 20px;">
            <table class="country-table" id="countryTable">
              <thead>
                <tr>
                  <th class="rank">#</th>
                  <th>{% trans "Country" %}</th>
                  <th>{% trans "Visitors" %}</th>
                  <th>{% trans "Share" %}</th>
                </tr>
              </thead>
              <tbody id="countryTableBody"></tbody>
            </table>
            <p id="countryTableEmpty" style="display:none; color:#64748b; padding:20px; text-align:center; font-size:0.9rem;">{% trans "No data for this period" %}</p>
          </div>
        </div>
      </div>
    </div>

    <script>
      (function() {
        try {
          var themeKey = {{ theme_storage_key|default:'"cms-theme"'|safe }};
          function getTheme() {
            try {
              var t = localStorage.getItem(themeKey);
              return (t === 'light' || t === 'dark') ? t : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
            } catch (e) { return 'dark'; }
          }
          function setTheme(theme) {
            document.documentElement.setAttribute('data-theme', theme);
            try { localStorage.setItem(themeKey, theme); } catch (e) {}
          }
          setTheme(getTheme());
          window.addEventListener('storage', function(e) {
            if (e.key === themeKey && e.newValue) setTheme(e.newValue);
          });
        } catch (e) {}

        var labels = {{ chart_labels|safe }};
        var visitors = {{ chart_visitors|safe }};
        var gaVisitors = {{ chart_ga_visitors|safe }};
        var visitorsLabel = {{ visitors_label|safe }};
        var gaVisitorsLabel = {{ ga_visitors_label|safe }};
        var hasGaData = {{ has_ga_data|yesno:"true,false" }};
        var noDataMsg = {{ no_data_msg|safe }};
        var donutGa = {{ donut_ga }};
        var donutInvisible = {{ donut_invisible }};
        var donutGaLabel = {{ donut_ga_label|safe }};
        var donutInvisibleLabel = {{ donut_invisible_label|safe }};

        function initCharts() {
          if (donutGa + donutInvisible > 0) {
            var donutCtx = document.getElementById('donutChart');
            if (donutCtx) {
              new Chart(donutCtx.getContext('2d'), {
                type: 'doughnut',
                data: {
                  labels: [donutGaLabel, donutInvisibleLabel],
                  datasets: [{
                    data: [donutGa, donutInvisible],
                    backgroundColor: ['rgba(34, 197, 94, 0.8)', 'rgba(168, 85, 247, 0.8)'],
                    borderColor: ['rgb(34, 197, 94)', 'rgb(168, 85, 247)'],
                    borderWidth: 2
                  }]
                },
                options: {
                  responsive: true,
                  maintainAspectRatio: false,
                  cutout: '60%',
                  plugins: {
                    legend: { position: 'bottom', labels: { color: '#94a3b8', padding: 16 } }
                  }
                }
              });
            }
          } else {
            var donutWrap = document.getElementById('donutChart');
            if (donutWrap && donutWrap.parentNode) {
              donutWrap.parentNode.innerHTML = '<p style="color:#64748b;padding:60px 20px;text-align:center;">' + noDataMsg + '</p>';
            }
          }

          var visitorChartEl = document.getElementById('visitorChart');
          if (!visitorChartEl) return;
          if (!labels || labels.length === 0) {
            var parent = visitorChartEl.parentNode;
            if (parent) parent.innerHTML = '<p style="color:#64748b;padding:40px;text-align:center;">' + noDataMsg + '</p>';
          } else {
            var datasets = [
              {
                label: visitorsLabel,
                data: visitors,
                borderColor: 'rgb(96, 165, 250)',
                backgroundColor: 'rgba(96, 165, 250, 0.15)',
                fill: true,
                tension: 0.3
              }
            ];
            if (hasGaData && gaVisitors && gaVisitors.length) {
              datasets.push({
                label: gaVisitorsLabel,
                data: gaVisitors,
                borderColor: 'rgb(74, 222, 128)',
                backgroundColor: 'rgba(74, 222, 128, 0.15)',
                fill: true,
                tension: 0.3
              });
            }
            var ctx = visitorChartEl.getContext('2d');
            new Chart(ctx, {
              type: 'line',
              data: {
                labels: labels,
                datasets: datasets
              },
              options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { intersect: false, mode: 'index' },
                scales: {
                  x: {
                    ticks: { maxRotation: 45, minRotation: 45, maxTicksLimit: 12, color: '#64748b' }
                  },
                  y: {
                    beginAtZero: true,
                    ticks: { stepSize: 1, color: '#64748b' }
                  }
                },
                plugins: {
                  legend: { display: datasets.length > 1, labels: { color: '#94a3b8' } }
                }
              }
            });
          }
        }

        function runInit() {
          if (typeof Chart === 'undefined') {
            setTimeout(runInit, 50);
            return;
          }
          if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initCharts);
          } else {
            initCharts();
          }
        }
        runInit();

        var refreshBtn = document.getElementById('refreshBtn');
        if (refreshBtn) refreshBtn.addEventListener('click', function() {
          this.disabled = true;
          location.reload();
        });

        var countryCounts = {{ country_counts|safe }};
        var countryNames = {{ country_names|safe }};
        var monthTotal = {{ month_total }};
        var visitorsSingular = {{ visitors_singular|safe }};
        var visitorsPlural = {{ visitors_plural|safe }};
        var hoverStatsHint = {{ hover_stats_hint|safe }};
        var mapEl = document.getElementById('worldMap');
        var hoverStatsEl = document.getElementById('mapHoverStats');
        var hoverFlagEl = document.getElementById('mapHoverFlag');
        var hoverCountryEl = document.getElementById('mapHoverCountry');
        var hoverDetailEl = document.getElementById('mapHoverDetail');
        function codeToFlag(code) {
          if (!code || code === '__unknown__' || code.length !== 2) return '';
          return String.fromCodePoint(...[...code.toUpperCase()].map(function(c) { return 0x1F1E6 + (c.charCodeAt(0) - 65); }));
        }
        if (mapEl) {
          var map = L.map('worldMap').setView([20, 0], 2);
          var tileLayer;
          function updateMapTiles() {
            var theme = document.documentElement.getAttribute('data-theme') || 'dark';
            var url = theme === 'light' ? 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' : 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png';
            if (tileLayer) map.removeLayer(tileLayer);
            tileLayer = L.tileLayer(url, { attribution: '&copy; OpenStreetMap' + (theme === 'dark' ? ', &copy; CARTO' : '') }).addTo(map);
          }
          updateMapTiles();
          var origSetTheme = setTheme;
          setTheme = function(theme) {
            origSetTheme(theme);
            if (mapEl && typeof updateMapTiles === 'function') updateMapTiles();
          };
          function interpolateColor(count, maxCount) {
            if (count <= 0 || maxCount <= 0) return '#e8e8e8';
            var t = Math.min(count / maxCount, 1);
            var r = Math.round(184 + (65 - 184) * t);
            var g = Math.round(212 + (105 - 212) * t);
            var b = Math.round(240 + (225 - 240) * t);
            return 'rgb(' + r + ',' + g + ',' + b + ')';
          }
          var maxCountryCount = 0;
          for (var k in countryCounts) { if (countryCounts[k] > maxCountryCount) maxCountryCount = countryCounts[k]; }
          function getCountryCode(props) {
            if (!props) return null;
            var code = props.ISO_A2 || props.iso_a2;
            if (code && code !== '-99' && /^[A-Z]{2}$/.test(code)) return code;
            code = props.ISO_A2_EH || props.iso_a2_eh;
            return (code && code !== '-99' && /^[A-Z]{2}$/.test(code)) ? code : null;
          }
          function formatNumber(n) {
            return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '\u00a0');
          }
          fetch('https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_110m_admin_0_countries.geojson')
            .then(function(r) { return r.json(); })
            .then(function(geojson) {
              var rows = [];
              for (var code in countryCounts) {
                var count = countryCounts[code];
                if (count > 0) {
                  var name = countryNames[code] || code;
                  rows.push({ code: code, name: name, count: count });
                }
              }
              rows.sort(function(a, b) { return b.count - a.count; });
              var tbody = document.getElementById('countryTableBody');
              var emptyEl = document.getElementById('countryTableEmpty');
              var tableEl = document.getElementById('countryTable');
              if (rows.length === 0) {
                tableEl.style.display = 'none';
                emptyEl.style.display = 'block';
              } else {
                tableEl.style.display = 'table';
                emptyEl.style.display = 'none';
                tbody.innerHTML = rows.map(function(row, i) {
                  var pct = monthTotal > 0 ? (row.count / monthTotal * 100).toFixed(1) : '0';
                  return '<tr><td class="rank">' + (i + 1) + '</td><td>' + row.name + '</td><td>' + formatNumber(row.count) + '</td><td>' + pct + '%</td></tr>';
                }).join('');
              }
              L.geoJSON(geojson, {
                style: function(feature) {
                  var code = getCountryCode(feature.properties);
                  var count = code ? (countryCounts[code] || 0) : 0;
                  var fillColor = interpolateColor(count, maxCountryCount);
                  return {
                    fillColor: fillColor,
                    fillOpacity: count > 0 ? 0.75 : 0.3,
                    color: '#fff',
                    weight: 0.8
                  };
                },
                onEachFeature: function(feature, layer) {
                  var code = getCountryCode(feature.properties);
                  var name = countryNames[code] || (feature.properties && (feature.properties.NAME || feature.properties.name)) || code;
                  var count = code ? (countryCounts[code] || 0) : 0;
                  layer.on('mouseover', function() {
                    hoverStatsEl.classList.remove('empty');
                    if (hoverFlagEl) hoverFlagEl.textContent = codeToFlag(code);
                    hoverCountryEl.textContent = name;
                    var visitorsWord = count === 1 ? visitorsSingular : visitorsPlural;
                    var pct = monthTotal > 0 ? (count / monthTotal * 100).toFixed(1) : '0';
                    hoverDetailEl.textContent = formatNumber(count) + ' ' + visitorsWord + ' (' + pct + '%)';
                  });
                  layer.on('mouseout', function() {
                    hoverStatsEl.classList.add('empty');
                    if (hoverFlagEl) hoverFlagEl.textContent = '';
                    hoverCountryEl.textContent = '';
                    hoverDetailEl.textContent = hoverStatsHint;
                  });
                }
              }).addTo(map);
              if (hoverDetailEl) {
                hoverDetailEl.textContent = hoverStatsHint;
              }
            })
            .catch(function() {
              mapEl.innerHTML = '<p style="color:#64748b;padding:40px;text-align:center;">Map unavailable</p>';
              var rows = [];
              for (var code in countryCounts) {
                var count = countryCounts[code];
                if (count > 0) {
                  var name = countryNames[code] || code;
                  rows.push({ code: code, name: name, count: count });
                }
              }
              rows.sort(function(a, b) { return b.count - a.count; });
              var tbody = document.getElementById('countryTableBody');
              var emptyEl = document.getElementById('countryTableEmpty');
              var tableEl = document.getElementById('countryTable');
              if (rows.length > 0) {
                tableEl.style.display = 'table';
                emptyEl.style.display = 'none';
                tbody.innerHTML = rows.map(function(row, i) {
                  var pct = monthTotal > 0 ? (row.count / monthTotal * 100).toFixed(1) : '0';
                  return '<tr><td class="rank">' + (i + 1) + '</td><td>' + row.name + '</td><td>' + formatNumber(row.count) + '</td><td>' + pct + '%</td></tr>';
                }).join('');
              }
            });
        }
      })();
    </script>
  </body>
</html>
