{% extends "admin/base_admin.html" %}
{% set admin_page = "articles" %}

{% block title %}Articles - Admin - {{ config.APP_NAME }}{% endblock %}

{% block head %}{{ super() }}
<style>
.tab-btn { display:inline-flex; align-items:center; gap:0.4rem;
  padding:0.5rem 1rem; font-size:0.8125rem; font-weight:600;
  color:#64748B; text-decoration:none; border-bottom:2px solid transparent;
  transition: color 0.15s, border-color 0.15s; }
.tab-btn:hover { color:#0F172A; }
.tab-btn--active { color:#1D4ED8; border-bottom-color:#1D4ED8; }
.tab-badge { font-size:0.6875rem; font-weight:700;
  background:#F1F5F9; color:#64748B; padding:0.1rem 0.45rem;
  border-radius:9999px; min-width:1.25rem; text-align:center; }
.tab-btn--active .tab-badge { background:#EFF6FF; color:#1D4ED8; }
</style>
{% endblock %}

{% block admin_content %}
  <header class="flex justify-between items-center mb-4">
    <div>
      <h1 class="text-2xl">Articles</h1>
      {% include "admin/partials/article_stats.html" %}
    </div>
    <div class="flex gap-2">
      <a href="{{ url_for('admin.article_new') }}" class="btn btn-sm">New Article</a>
      <form method="post" action="{{ url_for('admin.rebuild_all') }}" class="m-0" style="display:inline" hx-boost="true">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <button type="submit" class="btn-outline btn-sm"
                hx-confirm="Rebuild all articles? This will re-render every article from its template.">Rebuild All</button>
      </form>
    </div>
  </header>

  {# Tab bar #}
  <nav class="flex gap-1 mb-4 border-b border-slate-200" role="tablist">
    {% for key, label in [('cornerstone','Cornerstone'),('editorial','Editorial'),('generated','Generated')] %}
    <a href="{{ url_for('admin.articles', article_type=key) }}"
       role="tab" class="tab-btn {% if current_article_type == key %}tab-btn--active{% endif %}"
       hx-boost="true">
      {{ label }}
      <span class="tab-badge">{{ type_counts[key] }}</span>
    </a>
    {% endfor %}
  </nav>

  {# Filters #}
  <div class="card mb-6" style="padding:1rem 1.25rem">
    <form class="flex flex-wrap gap-3 items-end"
          hx-get="{{ url_for('admin.article_results') }}"
          hx-target="#article-results"
          hx-trigger="change, input delay:300ms"
          hx-indicator="#articles-loading">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <input type="hidden" name="article_type" value="{{ current_article_type }}">

      <div>
        <label class="text-xs font-semibold text-slate block mb-1">Search</label>
        <input type="text" name="search" value="{{ current_search }}" placeholder="Title..."
               class="form-input" style="min-width:180px">
      </div>

      <div>
        <label class="text-xs font-semibold text-slate block mb-1">Status</label>
        <select name="status" class="form-input" style="min-width:120px">
          <option value="">All</option>
          <option value="live" {% if current_status == 'live' %}selected{% endif %}>Live</option>
          <option value="scheduled" {% if current_status == 'scheduled' %}selected{% endif %}>Scheduled</option>
          <option value="draft" {% if current_status == 'draft' %}selected{% endif %}>Draft</option>
        </select>
      </div>

      {% if current_article_type == 'generated' %}
      <div>
        <label class="text-xs font-semibold text-slate block mb-1">Template</label>
        <select name="template" class="form-input" style="min-width:140px">
          <option value="">All</option>
          {% for t in template_slugs %}
          <option value="{{ t }}" {% if t == current_template %}selected{% endif %}>{{ t }}</option>
          {% endfor %}
        </select>
      </div>
      {% endif %}

      <div>
        <label class="text-xs font-semibold text-slate block mb-1">Language</label>
        <select name="language" class="form-input" style="min-width:80px">
          <option value="">All</option>
          <option value="en" {% if current_language == 'en' %}selected{% endif %}>EN</option>
          <option value="de" {% if current_language == 'de' %}selected{% endif %}>DE</option>
        </select>
      </div>

      <svg id="articles-loading" class="htmx-indicator search-spinner" width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <circle cx="12" cy="12" r="10" stroke="#CBD5E1" stroke-width="3"/>
        <path d="M12 2a10 10 0 0 1 10 10" stroke="#0EA5E9" stroke-width="3" stroke-linecap="round"/>
      </svg>
    </form>
  </div>

  {# Bulk action bar #}
  <form id="article-bulk-form" style="display:none">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="article_ids" id="article-bulk-ids" value="">
    <input type="hidden" name="action" id="article-bulk-action" value="">
    <input type="hidden" name="apply_to_all" id="article-bulk-apply-to-all" value="false">
    <input type="hidden" name="search" id="article-bulk-search" value="{{ current_search }}">
    <input type="hidden" name="status" id="article-bulk-status" value="{{ current_status }}">
    <input type="hidden" name="template" id="article-bulk-template" value="{{ current_template }}">
    <input type="hidden" name="language" id="article-bulk-language" value="{{ current_language }}">
    <input type="hidden" name="article_type" id="article-bulk-article-type" value="{{ current_article_type }}">
  </form>
  <div id="article-bulk-bar" class="card mb-4" style="padding:0.75rem 1.25rem;display:none;align-items:center;gap:1rem;flex-wrap:wrap;background:#EFF6FF;border:1px solid #BFDBFE;">
    <span id="article-bulk-count" class="text-sm font-semibold text-navy">0 selected</span>
    <select id="article-bulk-action-select" class="form-input" style="min-width:140px;padding:0.25rem 0.5rem;font-size:0.8125rem">
      <option value="">Action…</option>
      <option value="publish">Publish</option>
      <option value="unpublish">Unpublish</option>
      <option value="toggle_noindex">Toggle noindex</option>
      <option value="rebuild">Rebuild</option>
      <option value="delete">Delete</option>
    </select>
    <button type="button" class="btn btn-sm" onclick="submitArticleBulk()">Apply</button>
    <button type="button" class="btn-outline btn-sm" onclick="clearArticleSelection()">Clear</button>
    <span id="article-select-all-banner" style="display:none;font-size:0.8125rem;color:#1E40AF;margin-left:0.5rem">
      All <strong id="article-page-count"></strong> on this page selected.
      <button type="button" onclick="enableApplyToAll()"
              style="background:none;border:none;color:#1D4ED8;font-weight:600;cursor:pointer;text-decoration:underline;padding:0;font-size:inherit">
        Select all <span id="article-matching-count">…</span> matching instead?
      </button>
    </span>
    <span id="article-apply-to-all-banner" style="display:none;font-size:0.8125rem;color:#991B1B;font-weight:600;margin-left:0.5rem">
      All matching articles selected (<span id="article-matching-count-confirm"></span> total).
      <button type="button" onclick="disableApplyToAll()"
              style="background:none;border:none;color:#1D4ED8;font-weight:400;cursor:pointer;text-decoration:underline;padding:0;font-size:inherit">
        Undo
      </button>
    </span>
  </div>

  {# Results #}
  <div id="article-results">
    {% include "admin/partials/article_results.html" %}
  </div>

<script>
const articleSelectedIds = new Set();
let articleApplyToAll = false;
let articleMatchingCount = 0;

function toggleArticleSelect(id, checked) {
  if (checked) articleSelectedIds.add(id);
  else articleSelectedIds.delete(id);
  disableApplyToAll();
  updateArticleBulkBar();
}

function toggleArticleGroupSelect(checkbox) {
  var ids = (checkbox.dataset.ids || '').split(',').map(Number).filter(Boolean);
  ids.forEach(function(id) {
    if (checkbox.checked) articleSelectedIds.add(id);
    else articleSelectedIds.delete(id);
  });
  disableApplyToAll();
  updateArticleBulkBar();
}

function clearArticleSelection() {
  articleSelectedIds.clear();
  articleApplyToAll = false;
  document.querySelectorAll('.article-checkbox').forEach(function(cb) { cb.checked = false; });
  var selectAll = document.getElementById('article-select-all');
  if (selectAll) selectAll.checked = false;
  updateArticleBulkBar();
}

function enableApplyToAll() {
  articleApplyToAll = true;
  document.getElementById('article-bulk-apply-to-all').value = 'true';
  document.getElementById('article-select-all-banner').style.display = 'none';
  document.getElementById('article-apply-to-all-banner').style.display = 'inline';
  var confirmEl = document.getElementById('article-matching-count-confirm');
  if (confirmEl) confirmEl.textContent = articleMatchingCount.toLocaleString();
  document.getElementById('article-bulk-count').textContent = 'All matching selected';
}

function disableApplyToAll() {
  articleApplyToAll = false;
  document.getElementById('article-bulk-apply-to-all').value = 'false';
  document.getElementById('article-select-all-banner').style.display = 'none';
  document.getElementById('article-apply-to-all-banner').style.display = 'none';
}

function updateArticleBulkBar() {
  var bar = document.getElementById('article-bulk-bar');
  var countEl = document.getElementById('article-bulk-count');
  var ids = document.getElementById('article-bulk-ids');

  if (articleSelectedIds.size === 0 && !articleApplyToAll) {
    bar.style.display = 'none';
    return;
  }
  bar.style.display = 'flex';

  if (!articleApplyToAll) {
    countEl.textContent = articleSelectedIds.size + ' selected';
    ids.value = Array.from(articleSelectedIds).join(',');
  }

  // Check if select-all is checked → show "select all matching" banner
  var selectAll = document.getElementById('article-select-all');
  var allOnPage = document.querySelectorAll('.article-checkbox');
  var pageCount = 0;
  allOnPage.forEach(function(cb) {
    if (cb.dataset.ids) {
      pageCount += (cb.dataset.ids || '').split(',').filter(Boolean).length;
    } else {
      pageCount += 1;
    }
  });

  var selectAllBanner = document.getElementById('article-select-all-banner');
  if (!articleApplyToAll && selectAll && selectAll.checked && pageCount > 0) {
    document.getElementById('article-page-count').textContent = pageCount;
    selectAllBanner.style.display = 'inline';
    // Fetch count of matching articles
    var params = new URLSearchParams({
      search: document.getElementById('article-bulk-search').value,
      status: document.getElementById('article-bulk-status').value,
      template: document.getElementById('article-bulk-template').value,
      language: document.getElementById('article-bulk-language').value,
      article_type: document.getElementById('article-bulk-article-type').value,
    });
    fetch('{{ url_for("admin.articles_matching_count") }}?' + params.toString())
      .then(function(r) { return r.text(); })
      .then(function(text) {
        articleMatchingCount = parseInt(text.replace(/,/g, ''), 10) || 0;
        var el = document.getElementById('article-matching-count');
        if (el) el.textContent = text;
      });
  } else if (!articleApplyToAll) {
    selectAllBanner.style.display = 'none';
  }
}

function submitArticleBulk() {
  var action = document.getElementById('article-bulk-action-select').value;
  if (!action) return;
  if (!articleApplyToAll && articleSelectedIds.size === 0) return;

  function doSubmit() {
    document.getElementById('article-bulk-action').value = action;
    htmx.ajax('POST', '{{ url_for("admin.articles_bulk") }}', {
      source: document.getElementById('article-bulk-form'),
      target: '#article-results',
      swap: 'innerHTML'
    });
    clearArticleSelection();
  }

  if (action === 'delete') {
    var subject = articleApplyToAll
      ? 'Delete all ' + articleMatchingCount.toLocaleString() + ' matching articles? This cannot be undone.'
      : 'Delete ' + articleSelectedIds.size + ' articles? This cannot be undone.';
    showConfirm(subject).then(function(ok) { if (ok) doSubmit(); });
  } else if (articleApplyToAll) {
    var verb = action.charAt(0).toUpperCase() + action.slice(1);
    showConfirm(verb + ' all ' + articleMatchingCount.toLocaleString() + ' matching articles?').then(function(ok) {
      if (ok) doSubmit();
    });
  } else {
    doSubmit();
  }
}

// Sync filter values into bulk form hidden inputs when filters change
document.addEventListener('DOMContentLoaded', function() {
  var filterForm = document.querySelector('form[hx-get*="article_results"]');
  if (!filterForm) return;
  filterForm.addEventListener('change', syncBulkFilters);
  filterForm.addEventListener('input', syncBulkFilters);
});

function syncBulkFilters() {
  var filterForm = document.querySelector('form[hx-get*="article_results"]');
  if (!filterForm) return;
  var fd = new FormData(filterForm);
  var searchEl = document.getElementById('article-bulk-search');
  var statusEl = document.getElementById('article-bulk-status');
  var templateEl = document.getElementById('article-bulk-template');
  var languageEl = document.getElementById('article-bulk-language');
  var typeEl = document.getElementById('article-bulk-article-type');
  if (searchEl) searchEl.value = fd.get('search') || '';
  if (statusEl) statusEl.value = fd.get('status') || '';
  if (templateEl) templateEl.value = fd.get('template') || '';
  if (languageEl) languageEl.value = fd.get('language') || '';
  if (typeEl) typeEl.value = fd.get('article_type') || '';
  // Changing filters clears apply-to-all and resets selection
  clearArticleSelection();
}

document.body.addEventListener('htmx:afterSwap', function(evt) {
  if (evt.detail.target.id === 'article-results') {
    document.querySelectorAll('.article-checkbox').forEach(function(cb) {
      if (cb.dataset.ids) {
        var ids = cb.dataset.ids.split(',').map(Number).filter(Boolean);
        cb.checked = ids.length > 0 && ids.every(function(id) { return articleSelectedIds.has(id); });
      } else {
        cb.checked = articleSelectedIds.has(Number(cb.dataset.id));
      }
    });
  }
});
</script>
{% endblock %}
