/**
 * SEO Forge — Google Indexing API UI
 * Metabox: submit current post URL to Google.
 * Admin page: render history table.
 *
 * DOM-API-only (no innerHTML) to stay XSS-safe — all content inserted
 * via textContent / createElement / setAttribute.
 */
(function () {
  if (typeof window.seoforgeIndexing === 'undefined') return;
  var cfg = window.seoforgeIndexing;
  var i18n = cfg.i18n;

  function post(formData) {
    return fetch(cfg.ajaxUrl, { method: 'POST', body: formData, credentials: 'same-origin' })
      .then(function (r) { return r.json(); });
  }

  // ─── Metabox ────────────────────────────────────────────

  var box = document.querySelector('.sf-indexing-box');
  if (box) {
    var url = box.getAttribute('data-url');
    var status = box.querySelector('.sf-indexing-status');
    var submitBtn = box.querySelector('.sf-indexing-submit');
    var removeBtn = box.querySelector('.sf-indexing-remove');

    function showStatus(kind, msg) {
      status.style.display = 'block';
      status.style.background = kind === 'error' ? '#fee2e2' : '#dcfce7';
      status.style.color = kind === 'error' ? '#991b1b' : '#166534';
      status.textContent = msg;
    }

    function fire(type, btn) {
      btn.disabled = true;
      // Swap only the label span's text so the button's icon survives the
      // "Submitting…" state (falls back to the button itself for the plain
      // "Mark URL as deleted" link, which has no icon).
      var label = btn.querySelector('.sf-indexing-label') || btn;
      var orig = label.textContent;
      label.textContent = i18n.submitting;
      var fd = new FormData();
      fd.append('action', 'seoforge_indexing_submit');
      fd.append('nonce', cfg.nonce);
      fd.append('url', url);
      fd.append('type', type);
      post(fd).then(function (r) {
        btn.disabled = false;
        label.textContent = orig;
        if (r && r.success) {
          showStatus('ok', i18n.submitted_at + ' ' + ((r.data && r.data.notify_time) || '—'));
        } else {
          showStatus('error', (r && r.data && r.data.error) || i18n.submit_failed);
 // ownership/permission failures → open the one-time setup
          // panel so the user sees exactly what to fix.
          if (r && r.data && r.data.needs_setup) {
            var setup = box.querySelector('.sf-indexing-setup');
            if (setup) setup.open = true;
          }
        }
      }).catch(function () {
        btn.disabled = false;
        label.textContent = orig;
        showStatus('error', i18n.network_error);
      });
    }

    submitBtn && submitBtn.addEventListener('click', function () { fire('URL_UPDATED', this); });
    removeBtn && removeBtn.addEventListener('click', function () { fire('URL_DELETED', this); });
  }

  // ─── History table ─────────────────────────────────────

  var table = document.getElementById('sf-indexing-table');
  var refresh = document.getElementById('sf-indexing-refresh');
  if (!table || !refresh) return;

  function renderHistory(rows) {
    var tbody = table.querySelector('tbody');
    while (tbody.firstChild) tbody.removeChild(tbody.firstChild);
    if (!rows.length) {
      var tr = document.createElement('tr');
      var td = document.createElement('td');
      td.setAttribute('colspan', '5');
      td.style.padding = '24px';
      td.style.textAlign = 'center';
      td.style.color = '#64748b';
      td.textContent = i18n.no_history;
      tr.appendChild(td);
      tbody.appendChild(tr);
      return;
    }
    rows.forEach(function (r) {
      var tr = document.createElement('tr');

      var tdUrl = document.createElement('td');
      var a = document.createElement('a');
      a.href = r.url;
      a.target = '_blank';
      a.rel = 'noopener';
      a.textContent = r.url;
      tdUrl.appendChild(a);
      tr.appendChild(tdUrl);

      var tdType = document.createElement('td');
      tdType.textContent = r.type || '';
      tr.appendChild(tdType);

      var tdStatus = document.createElement('td');
      var span = document.createElement('span');
      span.style.fontWeight = '600';
      if (r.status === 'ok') {
        span.style.color = '#166534';
        span.textContent = '✓ ' + r.status;
      } else {
        span.style.color = '#991b1b';
        span.textContent = '✗ ' + r.status;
        if (r.error) span.title = r.error;
      }
      tdStatus.appendChild(span);
      tr.appendChild(tdStatus);

      var tdSub = document.createElement('td');
      tdSub.textContent = r.submitted_at || '';
      tr.appendChild(tdSub);

      var tdNotify = document.createElement('td');
      tdNotify.textContent = r.notify_time || '—';
      tr.appendChild(tdNotify);

      tbody.appendChild(tr);
    });
  }

  function showError(msg) {
    var tbody = table.querySelector('tbody');
    while (tbody.firstChild) tbody.removeChild(tbody.firstChild);
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    td.setAttribute('colspan', '5');
    td.style.padding = '24px';
    td.style.color = '#991b1b';
    td.textContent = msg;
    tr.appendChild(td);
    tbody.appendChild(tr);
  }

  function load() {
    var fd = new FormData();
    fd.append('action', 'seoforge_indexing_history');
    fd.append('nonce', cfg.nonce);
 // any failure leaves the table in a clear error state instead
    // of an eternal "Loading…". The original code was missing .catch, so
    // a network failure or a non-JSON 5xx (PHP fatal, proxy timeout) left
    // the placeholder spinning forever.
    post(fd).then(function (r) {
      if (r && r.success) {
        renderHistory(r.data.submissions || []);
      } else {
        showError((r && r.data && r.data.error) || i18n.load_failed);
      }
    }).catch(function () {
      showError(i18n.network_error || i18n.load_failed);
    });
  }

  refresh.addEventListener('click', load);
  load();
})();
