{% 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 "Overview of consents" %}</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
    <style>
      * { box-sizing: border-box; }
      body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; padding: 24px; background: #f5f5f5; }
      .overview { max-width: 900px; margin: 0 auto; }
      h1 { font-size: 1.5rem; margin: 0 0 8px; color: #333; }
      .description { color: #666; font-size: 0.9rem; margin-bottom: 8px; line-height: 1.4; }
      .date-range { color: #666; font-size: 0.85rem; margin-bottom: 24px; }
      .date-range strong { color: #333; }
      .grid { display: grid; grid-template-columns: minmax(0, 50%) 1fr; gap: 28px; }
      @media (max-width: 640px) { .grid { grid-template-columns: 1fr; } }
      .card { background: #fff; border: 1px solid #e8e8e8; border-radius: 12px; padding: 28px; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }
      .card.summary-card { display: flex; flex-direction: column; }
      .card h2 { font-size: 1rem; margin: 0 0 16px; color: #555; font-weight: 600; }
      .view-toggle { display: flex; gap: 4px; flex-shrink: 0; }
      .view-toggle-btn { display: inline-flex; align-items: center; justify-content: center; padding: 6px 12px; border: 1px solid #ddd; border-radius: 6px; background: #fff; color: #666; text-decoration: none; font-size: 0.8rem; font-weight: 500; transition: background 0.2s, color 0.2s, border-color 0.2s; }
      .view-toggle-btn:hover { background: #f5f5f5; color: #333; }
      .view-toggle-btn.active { background: #1e40af; border-color: #1e40af; color: #fff; }
      .summary-grid { display: flex; flex-direction: column; gap: 16px; }
      .stats-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
      .summary-stat { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; padding: 18px 20px; border-radius: 8px; background: #f8f9fa; border: 1px solid #eee; }
      .summary-stat.accepts { background: #f0f9f4; border-color: #c8e6d4; }
      .summary-stat.declines { background: #fffbf0; border-color: #f5e6c8; }
      .summary-stat.shows { background: #f5f7fa; border-color: #e2e8f0; }
      .summary-stat.no-interactions { background: #fef5f5; border-color: #f5d4d4; }
      .summary-value { font-size: 1.6rem; font-weight: 700; line-height: 1.2; }
      .summary-stat.accepts .summary-value { color: #15803d; }
      .summary-stat.declines .summary-value { color: #a16207; }
      .summary-stat.shows .summary-value { color: #1e40af; }
      .summary-stat.no-interactions .summary-value { color: #b91c1c; }
      .summary-label { font-size: 0.8rem; color: #64748b; font-weight: 500; white-space: normal; word-wrap: break-word; }
      .rates-block { margin-top: 24px; padding-top: 24px; border-top: 1px solid #e5e7eb; }
      .rate-main { text-align: center; padding: 24px; background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 10px; margin-bottom: 16px; }
      .rate-main .rate-value { font-size: 2.8rem; font-weight: 800; color: #15803d; line-height: 1; }
      .rate-main .rate-label { font-size: 0.8rem; color: #166534; font-weight: 600; margin-top: 12px; }
      .rate-main .rate-legend { font-size: 0.7rem; color: #64748b; line-height: 1.4; margin-top: 8px; max-width: 220px; margin-left: auto; margin-right: auto; }
      .rate-secondary { display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; padding: 16px 20px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; }
      .rate-secondary .rate-value { font-size: 1.25rem; font-weight: 700; color: #475569; flex-shrink: 0; }
      .rate-secondary .rate-label { font-size: 0.75rem; color: #64748b; }
      .rate-secondary .rate-legend { font-size: 0.65rem; color: #94a3b8; margin-top: 4px; }
      .rate-secondary .rate-text { flex: 1; min-width: 0; }
      .chart-container { position: relative; height: 280px; }
      .rate-charts { display: grid; grid-template-columns: 1fr 1fr; gap: 28px; margin-top: 28px; }
      @media (max-width: 640px) { .rate-charts { grid-template-columns: 1fr; } }
      .rate-charts .chart-container { height: 200px; }
      .rate-charts.hidden { display: none; }
      .period-nav { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 24px; flex-wrap: wrap; }
      .period-nav-center { display: flex; align-items: center; justify-content: center; gap: 16px; flex: 1; min-width: 140px; }
      .month-nav-btn { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; border: 1px solid #ccc; border-radius: 6px; background: #fff; color: #333; text-decoration: none; font-size: 1.5rem; line-height: 1; transition: background 0.2s; }
      .month-nav-btn:hover { background: #f0f0f0; }
      .period-name { font-size: 1.1rem; font-weight: 600; color: #333; min-width: 140px; text-align: center; }
      .period-nav .view-toggle { margin-left: auto; }
      .chart-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }
      .chart-mode-btn { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; padding: 0; border: 1px solid #ddd; border-radius: 6px; background: #fff; color: #666; cursor: pointer; transition: background 0.2s, color 0.2s, border-color 0.2s; }
      .chart-mode-btn:hover { background: #f5f5f5; color: #333; }
      .overview-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 8px; }
      .overview-header h1 { margin: 0; flex: 1; }
      .refresh-btn { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; padding: 0; border: 1px solid #ddd; border-radius: 6px; background: #fff; color: #666; cursor: pointer; transition: background 0.2s, color 0.2s; flex-shrink: 0; }
      .refresh-btn:hover { background: #f5f5f5; color: #333; }
      .refresh-btn:disabled { opacity: 0.6; cursor: not-allowed; }
      .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 #ddd; border-radius: 6px; background: #fff; color: #666; text-decoration: none; font-size: 0.875rem; transition: background 0.2s, color 0.2s; }
      .switch-btn:hover { background: #f5f5f5; color: #333; }
    </style>
  </head>
  <body>
    <div class="overview">
      <div class="overview-header">
        <h1>{% trans "Overview of consents" %}</h1>
        <div class="header-btns">
          <a href="{% url 'cookie_optin:visitor_overview' %}?year={{ year }}&amp;month={{ month }}" class="switch-btn" title="{% trans 'Visitor overview' %}">{% trans "Visitor 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 "This view gives you an overview of the most important consent metrics. It shows at a glance how many visitors gave or refused their consent and how high the acceptance rate was." %}
      </p>
      <div class="period-nav">
        <div class="period-nav-center">
          <a href="{{ prev_url }}" class="month-nav-btn" title="{% trans 'Previous' %}">‹</a>
          <span class="period-name">{{ period_name|capfirst }}</span>
          <a href="{{ next_url }}" class="month-nav-btn" title="{% trans 'Next' %}">›</a>
        </div>
        <div class="view-toggle">
          <a href="{% url 'cookie_optin:overview' %}?view=day&amp;year={{ year }}&amp;month={{ month }}&amp;day={{ day }}" class="view-toggle-btn {% if summary_view == 'day' %}active{% endif %}" title="{% trans 'By day' %}">{% trans "Day" %}</a>
          <a href="{% url 'cookie_optin:overview' %}?view=month&amp;year={{ year }}&amp;month={{ month }}" class="view-toggle-btn {% if summary_view == 'month' %}active{% endif %}" title="{% trans 'By month' %}">{% trans "Month" %}</a>
          <a href="{% url 'cookie_optin:overview' %}?view=year&amp;year={{ year }}" class="view-toggle-btn {% if summary_view == 'year' %}active{% endif %}" title="{% trans 'By year' %}">{% trans "Year" %}</a>
        </div>
      </div>

      <div class="grid">
        <div class="card summary-card">
          <h2>{% trans "Summary" %}</h2>
          <div class="summary-grid">
            <div class="stats-row">
              <div class="summary-stat shows">
                <div class="summary-value">{{ shows_display }}</div>
                <div class="summary-label">{% trans "Banner displays" %}</div>
              </div>
              <div class="summary-stat accepts">
                <div class="summary-value">{{ accepts_display }}</div>
                <div class="summary-label">{% trans "Accepts" %}</div>
              </div>
              <div class="summary-stat declines">
                <div class="summary-value">{{ declines_display }}</div>
                <div class="summary-label">{% trans "Declines" %}</div>
              </div>
              <div class="summary-stat no-interactions">
                <div class="summary-value">{{ no_interactions_display }}</div>
                <div class="summary-label">{% trans "No interaction" %}</div>
              </div>
            </div>
            <div class="rates-block">
              <div class="rate-main">
                <div class="rate-value">{{ acceptance_rate }}%</div>
                <div class="rate-label">{% trans "Acceptance Rate" %}</div>
                <p class="rate-legend">{% trans "Share of visitors who accepted among those who responded (accepted or declined)." %}</p>
              </div>
              <div class="rate-secondary">
                <div class="rate-text">
                  <div class="rate-label">{% trans "Engagement rate" %}</div>
                  <p class="rate-legend">{% trans "Share of visitors who interacted (accepted, declined or saved) among those who saw the banner." %}</p>
                </div>
                <div class="rate-value">{{ engagement_rate }}%</div>
              </div>
            </div>
          </div>
        </div>

        <div class="card">
          <div class="chart-header">
            <h2>{% trans "Consent breakdown" %}</h2>
            <button type="button" id="chartModeBtn" class="chart-mode-btn" title="{% trans 'Toggle count/percentage' %}" aria-pressed="false">
              <svg id="chartModeIconCount" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:block"><rect x="3" y="12" width="4" height="8"/><rect x="10" y="8" width="4" height="12"/><rect x="17" y="4" width="4" height="16"/></svg>
              <svg id="chartModeIconPercent" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:none"><circle cx="7" cy="7" r="3"/><circle cx="17" cy="17" r="3"/><line x1="20" y1="4" x2="4" y2="20"/></svg>
            </button>
          </div>
          <div class="chart-container">
            <canvas id="consentChart"></canvas>
          </div>
        </div>
      </div>

      <div id="rateChartsSection" class="rate-charts">
        <div class="card">
          <h2>{% trans "Acceptance rate" %}</h2>
          <div class="chart-container">
            <canvas id="acceptanceRateChart"></canvas>
          </div>
        </div>
        <div class="card">
          <h2>{% trans "Engagement rate" %}</h2>
          <div class="chart-container">
            <canvas id="engagementRateChart"></canvas>
          </div>
        </div>
      </div>
    </div>

    <script>
      (function() {
        var labels = {{ chart_labels|safe }};
        var accepts = {{ chart_accepts|safe }};
        var declines = {{ chart_declines|safe }};
        var noInteractions = {{ chart_no_interactions|safe }};
        var saves = {{ chart_saves|safe }};
        var shows = {{ chart_shows|safe }};
        var acceptsLabel = {{ accepts_label|safe }};
        var declinesLabel = {{ declines_label|safe }};
        var noInteractionsLabel = {{ no_interactions_label|safe }};
        var savesLabel = {{ saves_label|safe }};
        var rateLabel = {{ rate_label|safe }};
        var noDataMsg = {{ no_data_msg|safe }};
        var btn = document.getElementById('chartModeBtn');
        var iconCount = document.getElementById('chartModeIconCount');
        var iconPercent = document.getElementById('chartModeIconPercent');

        if (!labels || labels.length === 0) {
          btn.style.display = 'none';
          document.getElementById('consentChart').parentNode.innerHTML = '<p style="color:#999;padding:40px;text-align:center;">' + noDataMsg + '</p>';
          document.getElementById('rateChartsSection').classList.add('hidden');
          return;
        }

        var visitsLabel = {{ visits_label|safe }};

        function computeLineChartData() {
          var visits = shows.slice();
          var acceptanceRates = [];
          var engagementRates = [];
          for (var i = 0; i < labels.length; i++) {
            var totalResp = accepts[i] + declines[i];
            acceptanceRates.push(totalResp > 0 ? Math.round(100 * accepts[i] / totalResp) : null);
            var sh = shows[i] || 0;
            var interactions = accepts[i] + declines[i] + saves[i];
            engagementRates.push(sh > 0 ? Math.min(100, Math.round(100 * interactions / sh)) : null);
          }
          return { visits: visits, acceptanceRates: acceptanceRates, engagementRates: engagementRates };
        }

        var lineData = computeLineChartData();

        function computePercentData(acc, dec, noInt, sav, sh) {
          var pctAcc = [], pctDec = [], pctNoInt = [], pctSav = [];
          for (var i = 0; i < acc.length; i++) {
            var total = acc[i] + dec[i] + noInt[i] + sav[i];
            if (total === 0) {
              pctAcc.push(0);
              pctDec.push(0);
              pctNoInt.push(0);
              pctSav.push(0);
            } else {
              var p = [
                Math.round(100 * acc[i] / total),
                Math.round(100 * dec[i] / total),
                Math.round(100 * noInt[i] / total),
                Math.round(100 * sav[i] / total)
              ];
              var sum = p[0] + p[1] + p[2] + p[3];
              if (sum !== 100) {
                var maxIdx = 0;
                for (var j = 1; j < 4; j++) { if (p[j] > p[maxIdx]) maxIdx = j; }
                p[maxIdx] += (100 - sum);
              }
              pctAcc.push(Math.max(0, p[0]));
              pctDec.push(Math.max(0, p[1]));
              pctNoInt.push(Math.max(0, p[2]));
              pctSav.push(Math.max(0, p[3]));
            }
          }
          return { accepts: pctAcc, declines: pctDec, noInteractions: pctNoInt, saves: pctSav };
        }

        var pctData = computePercentData(accepts, declines, noInteractions, saves, shows);
        var isCountMode = (localStorage.getItem('cookie_optin_chart_mode') === 'count');

        function getTooltipItems(args) {
          var tooltipItems = Array.isArray(args[0]) ? args[0] : (args[1] || []);
          return tooltipItems;
        }

        var showsLabel = {{ shows_label|safe }};

        function buildAfterBody() {
          return function() {
            var tooltipItems = getTooltipItems(arguments);
            if (!tooltipItems || tooltipItems.length === 0) return '';
            var idx = tooltipItems[0].dataIndex;
            var totalShows = shows[idx] || 0;
            if (totalShows === 0) return '';
            if (isCountMode) {
              return showsLabel + ': ' + totalShows;
            }
            var totalResp = accepts[idx] + declines[idx];
            if (totalResp === 0) return '';
            var rate = Math.round(100 * accepts[idx] / totalResp);
            return rateLabel + ': ' + rate + '%';
          };
        }

        function buildLabelCallback() {
          return function(context) {
            var label = context.dataset.label || '';
            if (label) label += ': ';
            var value = context.parsed.y;
            label += isCountMode ? value : (value + '%');
            return label;
          };
        }

        function updateChart() {
          var dataAcc = isCountMode ? accepts : pctData.accepts;
          var dataDec = isCountMode ? declines : pctData.declines;
          var dataNoInt = isCountMode ? noInteractions : pctData.noInteractions;
          var dataSav = isCountMode ? saves : pctData.saves;
          chart.data.datasets[0].data = dataAcc;
          chart.data.datasets[1].data = dataDec;
          chart.data.datasets[2].data = dataNoInt;
          chart.data.datasets[3].data = dataSav;
          chart.data.datasets[4].data = lineData.visits;
          chart.data.datasets[4].hidden = !isCountMode;
          if (isCountMode) {
            chart.options.scales.y.max = undefined;
            chart.options.scales.y.min = 0;
            chart.options.scales.y.ticks = { stepSize: 1 };
          } else {
            chart.options.scales.y.min = 0;
            chart.options.scales.y.max = 100;
            chart.options.scales.y.ticks = { stepSize: 25, callback: function(v) { return v + '%'; } };
          }
          chart.options.plugins.tooltip.callbacks.afterBody = buildAfterBody();
          chart.options.plugins.tooltip.callbacks.label = buildLabelCallback();
          chart.update();
          btn.setAttribute('aria-pressed', !isCountMode);
          iconCount.style.display = isCountMode ? 'none' : 'block';
          iconPercent.style.display = isCountMode ? 'block' : 'none';
        }

        var ctx = document.getElementById('consentChart').getContext('2d');
        var chart = new Chart(ctx, {
          type: 'bar',
          data: {
            labels: labels,
            datasets: [
              {
                label: acceptsLabel,
                data: pctData.accepts,
                backgroundColor: 'rgba(34, 197, 94, 0.9)',
                stack: 'stack0'
              },
              {
                label: declinesLabel,
                data: pctData.declines,
                backgroundColor: 'rgba(234, 179, 8, 0.9)',
                stack: 'stack0'
              },
              {
                label: noInteractionsLabel,
                data: pctData.noInteractions,
                backgroundColor: 'rgba(239, 68, 68, 0.9)',
                stack: 'stack0'
              },
              {
                label: savesLabel,
                data: pctData.saves,
                backgroundColor: 'rgba(148, 163, 184, 0.9)',
                stack: 'stack0'
              },
              {
                type: 'line',
                label: visitsLabel,
                data: lineData.visits,
                borderColor: 'rgb(30, 64, 175)',
                backgroundColor: 'rgba(30, 64, 175, 0.1)',
                fill: true,
                tension: 0.2,
                pointRadius: 3,
                yAxisID: 'y',
                order: 0,
                hidden: !isCountMode
              }
            ]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              x: {
                stacked: true,
                ticks: { maxRotation: 45, minRotation: 45, maxTicksLimit: 12 }
              },
              y: {
                stacked: true,
                beginAtZero: true,
                min: 0,
                max: 100,
                ticks: { stepSize: 25, callback: function(v) { return v + '%'; } }
              }
            },
            plugins: {
              legend: {
                display: true,
                position: 'top',
                labels: {
                  filter: function(item, data) {
                    if (!data || !data.datasets) return true;
                    var ds = data.datasets[item.datasetIndex];
                    return !ds || !ds.hidden;
                  }
                }
              },
              tooltip: {
                callbacks: {
                  afterBody: buildAfterBody(),
                  label: buildLabelCallback()
                }
              }
            }
          }
        });

        var lineChartOpts = {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            x: { ticks: { maxRotation: 45, minRotation: 45, maxTicksLimit: 12 } },
            y: { beginAtZero: true, min: 0, max: 100, ticks: { stepSize: 25, callback: function(v) { return v + '%'; } } }
          },
          plugins: { legend: { display: false } }
        };

        new Chart(document.getElementById('acceptanceRateChart').getContext('2d'), {
          type: 'line',
          data: {
            labels: labels,
            datasets: [{
              data: lineData.acceptanceRates,
              borderColor: 'rgb(34, 197, 94)',
              backgroundColor: 'rgba(34, 197, 94, 0.1)',
              fill: true,
              tension: 0.2,
              spanGaps: true,
              pointRadius: 4
            }]
          },
          options: lineChartOpts
        });

        new Chart(document.getElementById('engagementRateChart').getContext('2d'), {
          type: 'line',
          data: {
            labels: labels,
            datasets: [{
              data: lineData.engagementRates,
              borderColor: 'rgb(100, 116, 139)',
              backgroundColor: 'rgba(100, 116, 139, 0.1)',
              fill: true,
              tension: 0.2,
              spanGaps: true,
              pointRadius: 4
            }]
          },
          options: lineChartOpts
        });

        if (isCountMode) {
          updateChart();
        }

        btn.addEventListener('click', function() {
          isCountMode = !isCountMode;
          localStorage.setItem('cookie_optin_chart_mode', isCountMode ? 'count' : 'percent');
          updateChart();
        });

        document.getElementById('refreshBtn').addEventListener('click', function() {
          var btn = this;
          btn.disabled = true;
          btn.style.opacity = '0.6';
          location.reload();
        });
      })();
    </script>
  </body>
</html>
