{% extends "admin/base_admin.html" %}
{% set admin_page = "seo" %}
{% block title %}SEO Hub - Admin - {{ config.APP_NAME }}{% endblock %}

{% block admin_head %}
<style>
  .seo-tabs { display: flex; gap: 0; border-bottom: 2px solid #E2E8F0; margin-bottom: 1.5rem; }
  .seo-tabs button {
    padding: 0.625rem 1.25rem; font-size: 0.8125rem; font-weight: 600;
    color: #64748B; background: none; border: none; cursor: pointer;
    border-bottom: 2px solid transparent; margin-bottom: -2px; transition: all 0.15s;
  }
  .seo-tabs button:hover { color: #1D4ED8; }
  .seo-tabs button.active { color: #1D4ED8; border-bottom-color: #1D4ED8; }
  .date-pills { display: flex; gap: 4px; }
  .date-pills button {
    padding: 4px 12px; font-size: 0.75rem; font-weight: 600;
    border-radius: 999px; border: 1px solid #E2E8F0; background: #fff;
    color: #64748B; cursor: pointer; transition: all 0.15s;
  }
  .date-pills button:hover { border-color: #1D4ED8; color: #1D4ED8; }
  .date-pills button.active { background: #1D4ED8; color: #fff; border-color: #1D4ED8; }
  .sync-row { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; }
  .sync-badge { display: inline-flex; align-items: center; gap: 4px; font-size: 0.6875rem; padding: 2px 8px; border-radius: 4px; }
  .sync-ok { background: #F0FDF4; color: #16A34A; }
  .sync-fail { background: #FEF2F2; color: #DC2626; }
  .sync-none { background: #F8FAFC; color: #94A3B8; }
</style>
{% endblock %}

{% block admin_content %}
  <header class="flex justify-between items-center mb-6">
    <div>
      <h1 class="text-2xl">SEO & Analytics Hub</h1>
      <p class="text-sm text-slate mt-1">Search performance, funnel metrics, and article scorecard</p>
    </div>
    <div class="flex gap-2 items-center">
      <form method="post" action="{{ url_for('admin.seo_sync_now') }}" class="m-0">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <input type="hidden" name="source" value="all">
        <button type="submit" class="btn btn-sm">Sync Now</button>
      </form>
      <a href="{{ url_for('admin.index') }}" class="btn-outline btn-sm">Dashboard</a>
    </div>
  </header>

  <!-- Sync Status -->
  <div class="sync-row mb-4">
    <span class="text-xs font-semibold text-slate uppercase tracking-wider">Last sync:</span>
    {% for s in sync_status %}
    <span class="sync-badge {% if s.status == 'success' %}sync-ok{% elif s.status == 'failed' %}sync-fail{% else %}sync-none{% endif %}">
      {{ s.source | upper }}
      {% if s.status == 'success' %}
        {{ s.completed_at[:16] if s.completed_at else '' }} ({{ s.rows_synced }} rows)
      {% elif s.status == 'failed' %}
        failed
      {% endif %}
    </span>
    {% endfor %}
    {% if not sync_status %}
    <span class="sync-badge sync-none">No syncs yet</span>
    {% endif %}
  </div>

  <!-- Date range selector -->
  <div class="flex justify-between items-center mb-6">
    <div class="date-pills" id="date-pills">
      {% for d, label in [(7, '7d'), (28, '28d'), (90, '3m'), (180, '6m'), (365, '12m')] %}
      <button class="{% if date_range_days == d %}active{% endif %}"
              onclick="setDateRange({{ d }})">{{ label }}</button>
      {% endfor %}
    </div>
  </div>

  <!-- Overview Cards -->
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:0.75rem" class="mb-8">
    <div class="card text-center" style="padding:0.75rem">
      <p class="text-xs text-slate">Impressions</p>
      <p class="text-xl font-bold text-navy">{{ "{:,}".format(overview.total_impressions | int) }}</p>
    </div>
    <div class="card text-center" style="padding:0.75rem">
      <p class="text-xs text-slate">Clicks</p>
      <p class="text-xl font-bold text-navy">{{ "{:,}".format(overview.total_clicks | int) }}</p>
    </div>
    <div class="card text-center" style="padding:0.75rem">
      <p class="text-xs text-slate">Avg CTR</p>
      <p class="text-xl font-bold text-navy">{{ "%.1f" | format(overview.avg_ctr * 100) }}%</p>
    </div>
    <div class="card text-center" style="padding:0.75rem">
      <p class="text-xs text-slate">Avg Position</p>
      <p class="text-xl font-bold text-navy">{{ "%.1f" | format(overview.avg_position) }}</p>
    </div>
  </div>

  <!-- Tabs -->
  <div class="seo-tabs" id="seo-tabs">
    <button class="active" data-tab="search"
            hx-get="{{ url_for('admin.seo_search') }}?days={{ date_range_days }}"
            hx-target="#tab-content" hx-swap="innerHTML"
            hx-trigger="click">Search Performance</button>
    <button data-tab="funnel"
            hx-get="{{ url_for('admin.seo_funnel') }}?days={{ date_range_days }}"
            hx-target="#tab-content" hx-swap="innerHTML"
            hx-trigger="click">Full Funnel</button>
    <button data-tab="scorecard"
            hx-get="{{ url_for('admin.seo_scorecard') }}?days={{ date_range_days }}"
            hx-target="#tab-content" hx-swap="innerHTML"
            hx-trigger="click">Article Scorecard</button>
  </div>

  <!-- Tab Content -->
  <div id="tab-content"
       hx-get="{{ url_for('admin.seo_search') }}?days={{ date_range_days }}"
       hx-trigger="load"
       hx-swap="innerHTML">
    <div class="card text-center" style="padding:2rem">
      <p class="text-slate">Loading...</p>
    </div>
  </div>

  <script>
    // Tab switching
    document.getElementById('seo-tabs').addEventListener('click', function(e) {
      if (e.target.tagName === 'BUTTON') {
        this.querySelectorAll('button').forEach(b => b.classList.remove('active'));
        e.target.classList.add('active');
      }
    });

    // Date range switching
    var currentDays = {{ date_range_days }};
    function setDateRange(days) {
      currentDays = days;
      // Update pills
      document.querySelectorAll('#date-pills button').forEach(function(b) {
        b.classList.toggle('active', b.textContent.trim() === {7:'7d',28:'28d',90:'3m',180:'6m',365:'12m'}[days]);
      });
      // Re-fetch active tab with new date range
      var activeTab = document.querySelector('#seo-tabs button.active');
      if (activeTab) {
        var url = activeTab.getAttribute('hx-get').split('?')[0] + '?days=' + days;
        activeTab.setAttribute('hx-get', url);
        htmx.ajax('GET', url, '#tab-content');
      }
      // Update overview cards
      window.location.href = '{{ url_for("admin.seo") }}?days=' + days;
    }
  </script>
{% endblock %}
