{% extends "base.j2" -%}

{%- block append_to_head_tag_section %}
  <title>Analytics - {{ product.title }} - {{ request.shop.name }}</title>
{%- endblock append_to_head_tag_section -%}

{% block content -%}

{% macro line_chart(data, max_value, label, color) %}
{% if data and max_value > 0 %}
<div class="analytics-chart-svg">
  <svg viewBox="0 0 560 160" role="img" aria-label="{{ label }}">
    {% for pct in [25, 50, 75] %}
    <line x1="0" y1="{{ 140 - (pct / 100 * 130) }}" x2="556" y2="{{ 140 - (pct / 100 * 130) }}"
          stroke="var(--border-light, #e9ecef)" stroke-width="1" />
    {% endfor %}
    <line x1="0" y1="140" x2="556" y2="140" stroke="var(--border-color, #dee2e6)" stroke-width="1" />
    <polygon points="{% for b in data %}{{ loop.index0 * 20 + 8 }},{{ 140 - (b.value / max_value * 130) }} {% endfor %}{{ (data|length - 1) * 20 + 8 }},140 8,140"
             fill="{{ color }}" opacity="0.15" />
    <polyline
      points="{% for b in data %}{{ loop.index0 * 20 + 8 }},{{ 140 - (b.value / max_value * 130) }} {% endfor %}"
      fill="none" stroke="{{ color }}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" />
    {% for b in data %}
    <circle cx="{{ loop.index0 * 20 + 8 }}" cy="{{ 140 - (b.value / max_value * 130) }}"
            r="3" fill="{{ color }}">
      <title>{{ b.label }}: {{ b.tooltip }}</title>
    </circle>
    {% endfor %}
    {% for b in data %}
    {% if loop.index0 % 7 == 0 %}
    <text x="{{ loop.index0 * 20 + 8 }}" y="155" text-anchor="middle"
          font-size="9" fill="var(--text-muted, #999)">{{ b.label }}</text>
    {% endif %}
    {% endfor %}
  </svg>
</div>
{% endif %}
{% endmacro %}

<section class="analytics-page">

  <p><a href="/s/{{ request.shop.uuid_str }}/analytics">&larr; Shop Analytics</a> &middot; <a href="{{ product_url }}">View Product</a></p>

  <p class="analytics-permalink"><a href="{{ product.absolute_url(request) }}">{{ product.absolute_url(request) }}</a></p>

  <h3>{{ product.title }}</h3>

  {# --- Overview Strip --- #}
  <div class="analytics-overview well">
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.views_7d }}</span>
      <span class="analytics-overview-label">Views (7d)</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.avg_session }}</span>
      <span class="analytics-overview-label">Avg Session</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.bounce_rate }}</span>
      <span class="analytics-overview-label">Bounce Rate</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.lifetime_views }}</span>
      <span class="analytics-overview-label">Lifetime Views</span>
    </div>
  </div>

  {# --- Daily Views (28-day bar chart) --- #}
  {% if daily_views and daily_views_max > 0 %}
  <h4>Daily Views (last 28 days)</h4>
  <div class="analytics-chart-svg">
    <svg viewBox="0 0 560 160" role="img" aria-label="Daily views bar chart">
      {# Gridlines #}
      {% for pct in [25, 50, 75] %}
      <line x1="0" y1="{{ 140 - (pct / 100 * 130) }}" x2="556" y2="{{ 140 - (pct / 100 * 130) }}"
            stroke="var(--border-light, #e9ecef)" stroke-width="1" />
      {% endfor %}
      <line x1="0" y1="140" x2="556" y2="140" stroke="var(--border-color, #dee2e6)" stroke-width="1" />
      {# Bars #}
      {% for b in daily_views %}
      {% set bar_h = (b.count / daily_views_max * 130) if daily_views_max > 0 else 0 %}
      <rect x="{{ loop.index0 * 20 }}" y="{{ 140 - bar_h }}" width="16" height="{{ bar_h }}"
            rx="2" fill="var(--green-color, #a3c765)">
        <title>{{ b.label }}: {{ b.count }} view{{ 's' if b.count != 1 else '' }}</title>
      </rect>
      {% endfor %}
      {# Date labels every 7th bar #}
      {% for b in daily_views %}
      {% if loop.index0 % 7 == 0 %}
      <text x="{{ loop.index0 * 20 + 8 }}" y="155" text-anchor="middle"
            font-size="9" fill="var(--text-muted, #999)">{{ b.label }}</text>
      {% endif %}
      {% endfor %}
    </svg>
  </div>
  {% endif %}

  {# --- Trend Line Charts (28 days) --- #}
  {% if daily_session_duration_max > 0 %}
  <h4>Session Duration Trend (last 28 days)</h4>
  <p class="analytics-hint">Average time visitors spend per session.</p>
  {{ line_chart(daily_session_duration, daily_session_duration_max, "Session duration trend", "var(--blue-color, #98b6fa)") }}
  {% endif %}

  {% if daily_engagement %}
  <h4>Engagement Trend (last 28 days)</h4>
  <p class="analytics-hint">Active interaction time as a fraction of total session time.</p>
  {{ line_chart(daily_engagement, 1.0, "Engagement trend", "var(--green-color, #a3c765)") }}
  {% endif %}

  {% if daily_bounce %}
  <h4>Bounce Rate Trend (last 28 days)</h4>
  <p class="analytics-hint">Sessions under 7 seconds visible. Lower is better.</p>
  {{ line_chart(daily_bounce, 1.0, "Bounce rate trend", "var(--red-color, #bc2131)") }}
  {% endif %}

  {# --- Views Over Time --- #}
  <h4>Views Over Time</h4>
  <div class="analytics-overview well">
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ views_over_time['7d'] }}</span>
      <span class="analytics-overview-label">7 days</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ views_over_time['14d'] }}</span>
      <span class="analytics-overview-label">14 days</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ views_over_time['21d'] }}</span>
      <span class="analytics-overview-label">21 days</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ views_over_time['28d'] }}</span>
      <span class="analytics-overview-label">28 days</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ views_over_time['365d'] }}</span>
      <span class="analytics-overview-label">Year</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ views_over_time['lifetime'] }}</span>
      <span class="analytics-overview-label">Lifetime</span>
    </div>
  </div>

  {# --- Video Watch Metrics --- #}
  {% if video %}
  <h4>Video Watch Metrics (last 21 days)</h4>
  <p class="analytics-hint">Based on {{ video.sessions }} media sessions.</p>
  <div class="analytics-overview well">
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video.avg_pct_played }}</span>
      <span class="analytics-overview-label">Avg % Played</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video.completion_rate }}</span>
      <span class="analytics-overview-label">Completion Rate</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video.avg_seeks }}</span>
      <span class="analytics-overview-label">Avg Seeks</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video.avg_rewinds }}</span>
      <span class="analytics-overview-label">Avg Rewinds</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video.avg_pauses }}</span>
      <span class="analytics-overview-label">Avg Pauses</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video.avg_speed }}</span>
      <span class="analytics-overview-label">Avg Speed</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video.play_duration_ratio }}</span>
      <span class="analytics-overview-label">Play/Duration</span>
    </div>
  </div>
  {% endif %}

  {# --- Traffic Sources & Devices (side by side) --- #}
  {% if traffic or devices %}
  <div class="analytics-pair">
    {% if traffic %}
    <div>
      <h4>Traffic Sources (last 21 days)</h4>
      <div class="analytics-bar-rows">
        {% for t in traffic %}
        <div class="analytics-bar-row">
          <span class="analytics-bar-label">{{ t.source }}</span>
          <span class="analytics-bar-track">
            <span class="analytics-bar-fill" style="width: {{ t.pct_raw | round(1) }}%"></span>
          </span>
          <span class="analytics-bar-value">{{ t.count }} ({{ t.pct }})</span>
        </div>
        {% endfor %}
      </div>
    </div>
    {% endif %}

    {% if devices %}
    <div>
      <h4>Device Split (last 21 days)</h4>
      <div class="analytics-bar-rows">
        {% for d in devices %}
        <div class="analytics-bar-row">
          <span class="analytics-bar-label">{{ d.device }}</span>
          <span class="analytics-bar-track">
            <span class="analytics-bar-fill" style="width: {{ d.pct_raw | round(1) }}%"></span>
          </span>
          <span class="analytics-bar-value">{{ d.count }} ({{ d.pct }})</span>
        </div>
        {% endfor %}
      </div>
    </div>
    {% endif %}
  </div>
  {% endif %}

  {# --- Daily External Referrer Trend (28 days) --- #}
  {% if daily_referrers_max > 0 %}
  <h4>External Referrer Trend (last 28 days)</h4>
  <p class="analytics-hint">Daily count of visits from external referrers (excludes direct and internal traffic).</p>
  {{ line_chart(daily_referrers, daily_referrers_max, "External referrer trend", "var(--orange-color, #e8a838)") }}
  {% endif %}

  {# --- Top Referrer Domains (21d) --- #}
  {% if top_referrer_domains %}
  <h4>Top Referrer Domains (last 21 days)</h4>
  <p class="analytics-hint">External sites sending visitors to this product.</p>
  <div class="analytics-bar-rows">
    {% for d in top_referrer_domains %}
    <div class="analytics-bar-row analytics-bar-row--wide">
      <span class="analytics-bar-label">{{ d.domain }}</span>
      <span class="analytics-bar-track">
        <span class="analytics-bar-fill" style="width: {{ d.pct_raw | round(1) }}%"></span>
      </span>
      <span class="analytics-bar-value">{{ d.count }} ({{ d.pct }})</span>
    </div>
    {% endfor %}
  </div>
  {% endif %}

  {# --- Search Engine Queries (21d) --- #}
  {% if top_referrer_queries %}
  <h4>Search Engine Queries (last 21 days)</h4>
  <p class="analytics-hint">What people searched before finding this product.</p>
  <div class="analytics-table-wrap">
    <table class="analytics-table">
      <thead>
        <tr>
          <th>Query</th>
          <th class="analytics-num">Visits</th>
        </tr>
      </thead>
      <tbody>
        {% for q in top_referrer_queries %}
        <tr>
          <td>{{ q.query }}</td>
          <td class="analytics-num">{{ q.count }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% endif %}

  {# --- Ring Entries --- #}
  {% if ring_entry_count > 0 %}
  <h4>Ring Entry Sessions (last 21 days)</h4>
  <div class="analytics-overview well">
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ ring_entry_count }}</span>
      <span class="analytics-overview-label">Ring Entries</span>
    </div>
  </div>
  {% endif %}

  {# --- Engagement --- #}
  {% if engagement %}
  <h4>Engagement (last 21 days)</h4>
  <p class="analytics-hint">Based on {{ engagement.sessions }} sessions with 7s+ wall clock.</p>
  <div class="analytics-overview well">
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ engagement.active_ratio }}</span>
      <span class="analytics-overview-label">Active / Wall</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ engagement.visible_ratio }}</span>
      <span class="analytics-overview-label">Visible / Wall</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ engagement.avg_scroll_depth }}</span>
      <span class="analytics-overview-label">Avg Scroll Depth</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ engagement.avg_direction_changes }}</span>
      <span class="analytics-overview-label">Direction Changes</span>
    </div>
  </div>
  {% endif %}

  {# --- Comment Sentiment --- #}
  {% if sentiment and sentiment.total > 0 %}
  <h4>Comment Sentiment (last 21 days)</h4>
  <div class="analytics-overview well">
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ sentiment.positive }}</span>
      <span class="analytics-overview-label">Positive ({{ (sentiment.positive / sentiment.total * 100) | round | int }}%)</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ sentiment.neutral }}</span>
      <span class="analytics-overview-label">Neutral ({{ (sentiment.neutral / sentiment.total * 100) | round | int }}%)</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ sentiment.negative }}</span>
      <span class="analytics-overview-label">Negative ({{ (sentiment.negative / sentiment.total * 100) | round | int }}%)</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ sentiment.total }}</span>
      <span class="analytics-overview-label">Total</span>
    </div>
  </div>
  {% endif %}

  {# --- Price History --- #}
  {% if price_changes %}
  <h4>Price History (last 21 changes)</h4>
  <div class="analytics-table-wrap">
    <table class="analytics-table">
      <thead>
        <tr>
          <th class="analytics-num">Price</th>
          <th>When</th>
        </tr>
      </thead>
      <tbody>
        {% for pc in price_changes %}
        <tr>
          <td class="analytics-num">{{ pc.price }}</td>
          <td>{{ pc.ago }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% endif %}

  <p class="analytics-privacy">All data is anonymous. No individual viewer can be identified. Counts represent aggregate sessions, not people.</p>

</section>

{%- endblock -%}
