{% extends "base.j2" -%}

{%- block append_to_head_tag_section %}
  <title>Analytics - {{ 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">

  <h3>Analytics</h3>

  {% if overview.total_views == 0 %}
  <p>No view data yet. Analytics appear after visitors spend at least 7 seconds on your content.</p>
  {% else %}

  {# --- Section 1: Overview Strip (last 7 days) --- #}
  <div class="analytics-overview well">
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.total_views }}</span>
      <span class="analytics-overview-label">Views (7d)</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.unique_products }}</span>
      <span class="analytics-overview-label">Products Viewed</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.top_source }}</span>
      <span class="analytics-overview-label">Top Source</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.device_split }}</span>
      <span class="analytics-overview-label">Devices (7d)</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 %}

  {# --- Ring Consumed breakdown --- #}
  <h4>Ring Consumed</h4>
  <p class="analytics-hint">Unique products viewed via the ring as a percentage of all {{ ring_size }} ring products.</p>
  <div class="analytics-overview well">
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.ring_consumed['1d'] }}</span>
      <span class="analytics-overview-label">Today</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.ring_consumed['7d'] }}</span>
      <span class="analytics-overview-label">7 days</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.ring_consumed['28d'] }}</span>
      <span class="analytics-overview-label">28 days</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.ring_consumed['365d'] }}</span>
      <span class="analytics-overview-label">Year</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ overview.ring_consumed['all'] }}</span>
      <span class="analytics-overview-label">Lifetime</span>
    </div>
  </div>

  {# --- Section 2: Top Products by Views --- #}
  {% if top_products %}
  <h4>Top Products by Views</h4>
  <div class="analytics-table-wrap">
    <table class="analytics-table">
      <thead>
        <tr>
          <th>#</th>
          <th>Title</th>
          <th class="analytics-num">7d</th>
          <th class="analytics-num">14d</th>
          <th class="analytics-num">21d</th>
          <th class="analytics-num">Trend</th>
        </tr>
      </thead>
      <tbody>
        {% for p in top_products %}
        <tr>
          <td>{{ p.rank }}</td>
          <td><a href="{{ p.analytics_url }}">{{ p.title }}</a></td>
          <td class="analytics-num">{{ p.views_7d }}<span class="analytics-inline-bar"><span class="analytics-inline-bar-fill" style="width: {{ p.pct_of_max | round(1) }}%"></span></span></td>
          <td class="analytics-num">{{ p.views_14d }}</td>
          <td class="analytics-num">{{ p.views_21d }}</td>
          <td class="analytics-num">{% if p.trend == "rising" %}<span class="analytics-trend-up">&#9650;</span>{% else %}<span class="analytics-trend-down">&#9660;</span>{% endif %}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% endif %}

  {# --- Section 3: Ring Entry Points --- #}
  {% if ring_entries %}
  <h4>Ring Entry Points (top 42 front doors, last 21 days)</h4>
  <p class="analytics-hint">People find your shop through these products &mdash; make sure they're polished.</p>
  <div class="analytics-table-wrap">
    <table class="analytics-table">
      <thead>
        <tr>
          <th>#</th>
          <th>Title</th>
          <th class="analytics-num">Entries</th>
          <th class="analytics-num">% of All</th>
        </tr>
      </thead>
      <tbody>
        {% for r in ring_entries %}
        <tr>
          <td>{{ r.rank }}</td>
          <td><a href="{{ r.analytics_url }}">{{ r.title }}</a></td>
          <td class="analytics-num">{{ r.count }}</td>
          <td class="analytics-num">{{ r.pct }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% endif %}

  {# --- Sections 4 & 5: Engagement & Attention (side by side) --- #}
  {% if engagement or attention %}
  <div class="analytics-pair">
    {% if engagement %}
    <div>
      <h4>Engagement Leaders</h4>
      <p class="analytics-hint">Highest lean-in: active interaction vs wall clock.</p>
      <table class="analytics-table">
        <thead>
          <tr>
            <th>#</th>
            <th>Title</th>
            <th class="analytics-num">Avg</th>
            <th class="analytics-num">Sessions</th>
          </tr>
        </thead>
        <tbody>
          {% for e in engagement %}
          <tr>
            <td>{{ e.rank }}</td>
            <td><a href="{{ e.analytics_url }}">{{ e.title }}</a></td>
            <td class="analytics-num">{{ e.score }}</td>
            <td class="analytics-num">{{ e.sessions }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% endif %}

    {% if attention %}
    <div>
      <h4>Attention Holders</h4>
      <p class="analytics-hint">Highest focused presence: visible time vs wall clock.</p>
      <table class="analytics-table">
        <thead>
          <tr>
            <th>#</th>
            <th>Title</th>
            <th class="analytics-num">Avg</th>
            <th class="analytics-num">Sessions</th>
          </tr>
        </thead>
        <tbody>
          {% for a in attention %}
          <tr>
            <td>{{ a.rank }}</td>
            <td><a href="{{ a.analytics_url }}">{{ a.title }}</a></td>
            <td class="analytics-num">{{ a.score }}</td>
            <td class="analytics-num">{{ a.sessions }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% endif %}
  </div>
  {% endif %}

  {# --- Sections 6 & 7: Study Material & Background Favorites (side by side) --- #}
  {% if learning or passive %}
  <div class="analytics-pair">
    {% if learning %}
    <div>
      <h4>Study Material</h4>
      <p class="analytics-hint">People rewind, slow down, re-read. Score out of 5.</p>
      <table class="analytics-table">
        <thead>
          <tr>
            <th>#</th>
            <th>Title</th>
            <th class="analytics-num">Score</th>
            <th class="analytics-num">Sessions</th>
          </tr>
        </thead>
        <tbody>
          {% for l in learning %}
          <tr>
            <td>{{ l.rank }}</td>
            <td><a href="{{ l.analytics_url }}">{{ l.title }}</a></td>
            <td class="analytics-num">{{ l.score }}</td>
            <td class="analytics-num">{{ l.sessions }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% endif %}

    {% if passive %}
    <div>
      <h4>Background Favorites</h4>
      <p class="analytics-hint">Lean-back plays: visible but hands-off. Score out of 5.</p>
      <table class="analytics-table">
        <thead>
          <tr>
            <th>#</th>
            <th>Title</th>
            <th class="analytics-num">Score</th>
            <th class="analytics-num">Sessions</th>
          </tr>
        </thead>
        <tbody>
          {% for b in passive %}
          <tr>
            <td>{{ b.rank }}</td>
            <td><a href="{{ b.analytics_url }}">{{ b.title }}</a></td>
            <td class="analytics-num">{{ b.score }}</td>
            <td class="analytics-num">{{ b.sessions }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% endif %}
  </div>
  {% endif %}

  {# --- Video Watch Metrics (21d) --- #}
  {% if video_overview %}
  <h4>Video Watch Metrics (last 21 days)</h4>
  <p class="analytics-hint">Aggregate viewing behavior across {{ video_overview.total_sessions }} media sessions.</p>
  <div class="analytics-overview well">
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video_overview.avg_pct_played }}</span>
      <span class="analytics-overview-label">Avg % Played</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video_overview.completion_rate }}</span>
      <span class="analytics-overview-label">Completion Rate</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video_overview.avg_seeks }}</span>
      <span class="analytics-overview-label">Avg Seeks</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video_overview.avg_rewinds }}</span>
      <span class="analytics-overview-label">Avg Rewinds</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video_overview.avg_pauses }}</span>
      <span class="analytics-overview-label">Avg Pauses</span>
    </div>
    <div class="analytics-overview-item">
      <span class="analytics-overview-value">{{ video_overview.avg_speed }}</span>
      <span class="analytics-overview-label">Avg Speed</span>
    </div>
  </div>

  {% if video_products %}
  <h4>Per-Product Video Breakdown</h4>
  <p class="analytics-hint">Top 14 by average % played (min {{ video_products[0].sessions if video_products else 7 }} sessions).</p>
  <div class="analytics-table-wrap">
    <table class="analytics-table">
      <thead>
        <tr>
          <th>#</th>
          <th>Title</th>
          <th class="analytics-num">Avg %</th>
          <th class="analytics-num">Completed</th>
          <th class="analytics-num">Seeks</th>
          <th class="analytics-num">Pauses</th>
          <th class="analytics-num">Sessions</th>
        </tr>
      </thead>
      <tbody>
        {% for v in video_products %}
        <tr>
          <td>{{ v.rank }}</td>
          <td><a href="{{ v.analytics_url }}">{{ v.title }}</a></td>
          <td class="analytics-num">{{ v.avg_pct }}</td>
          <td class="analytics-num">{{ v.completion_rate }}</td>
          <td class="analytics-num">{{ v.avg_seeks }}</td>
          <td class="analytics-num">{{ v.avg_pauses }}</td>
          <td class="analytics-num">{{ v.sessions }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% endif %}
  {% endif %}

  {# --- Sections 8 & 9: Traffic Sources & Device Split (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 your shop.</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 your shop.</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 %}

  {# --- Internal Search Keywords (21d) --- #}
  {% if top_keywords %}
  <h4>Top Search Keywords (last 21 days)</h4>
  <p class="analytics-hint">What visitors search for inside your shop.</p>
  <div class="analytics-table-wrap">
    <table class="analytics-table">
      <thead>
        <tr>
          <th>Keywords</th>
          <th class="analytics-num">Searches</th>
          <th class="analytics-num">Avg Hits</th>
        </tr>
      </thead>
      <tbody>
        {% for k in top_keywords %}
        <tr>
          <td>{{ k.keywords }}</td>
          <td class="analytics-num">{{ k.search_count }}</td>
          <td class="analytics-num">{{ k.avg_hits }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% endif %}

  {% endif %}{# end overview.total_views check #}

  {# --- Comment Sentiment (21d) --- #}
  {% 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 %}

  {# --- Recent Price Changes (21d) --- #}
  {% if price_changes %}
  <h4>Recent Price Changes (last 21 days)</h4>
  <div class="analytics-table-wrap">
    <table class="analytics-table">
      <thead>
        <tr>
          <th>Product</th>
          <th class="analytics-num">Price</th>
          <th>When</th>
        </tr>
      </thead>
      <tbody>
        {% for pc in price_changes %}
        <tr>
          <td><a href="{{ pc.analytics_url }}">{{ pc.title }}</a></td>
          <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 -%}
