/**
 * Keywords / Pages: track, untrack, category assign without full page reload (no scroll jump).
 */
(function () {
  var cfg = window.seoscopeTrackConfig;
  if (!cfg) {
    return;
  }

  function esc(s) {
    return String(s || '').replace(/[&<>"']/g, function (c) {
      return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c] || c;
    });
  }

  function showFlash(message, level) {
    var main = document.querySelector('main');
    if (!main) {
      return;
    }
    main.querySelectorAll('.alert-success, .alert-danger, .ss-ajax-flash').forEach(function (el) {
      el.remove();
    });
    var div = document.createElement('div');
    div.className = 'alert ss-ajax-flash ' + (level === 'error' ? 'alert-danger' : 'alert-success');
    div.textContent = message;
    var anchor = main.querySelector('section.mb-4');
    if (anchor) {
      anchor.insertAdjacentElement('afterend', div);
    } else {
      main.insertBefore(div, main.firstChild);
    }
  }

  function trackedStarHtml() {
    var t = esc(cfg.labels.tracked);
    return (
      '<span class="text-warning" title="' + t + '" aria-label="' + t + '">' +
      '<i class="fa-solid fa-star" aria-hidden="true"></i></span>'
    );
  }

  function applyDom(form, data) {
    var action = data.action || form.getAttribute('data-ss-action') || '';
    if (action === 'assign') {
      return;
    }
    var td = form.closest('td');
    if (!td) {
      return;
    }
    if (action === 'track' && data.tracked) {
      td.innerHTML = trackedStarHtml();
      return;
    }
    if (action === 'untrack') {
      var tr = form.closest('tr');
      if (cfg.show === 'tracked' && tr) {
        var next = tr.nextElementSibling;
        tr.remove();
        if (
          next &&
          (next.classList.contains('ss-kw-pages-row') || next.classList.contains('ss-page-kws-row'))
        ) {
          next.remove();
        }
      }
    }
  }

  function handleAsyncForm(form) {
    var btn = form.querySelector('button[type="submit"]');
    if (btn) {
      btn.disabled = true;
    }
    var fd = new FormData(form);
    return fetch(form.getAttribute('action') || '', {
      method: 'POST',
      body: fd,
      headers: { 'X-SeoScope-Async': '1', Accept: 'application/json' },
      credentials: 'same-origin',
    })
      .then(function (res) {
        var ct = res.headers.get('content-type') || '';
        if (ct.indexOf('application/json') === -1) {
          throw new Error('not_json');
        }
        return res.json().then(function (data) {
          if (!res.ok && !data.message) {
            throw new Error('http');
          }
          return data;
        });
      })
      .then(function (data) {
        showFlash(data.message || '', data.level || (data.ok ? 'ok' : 'error'));
        if (data.ok) {
          applyDom(form, data);
        }
      })
      .catch(function () {
        showFlash(cfg.networkError || 'Request failed.', 'error');
      })
      .finally(function () {
        if (btn) {
          btn.disabled = false;
        }
      });
  }

  document.addEventListener('change', function (ev) {
    var sel = ev.target;
    if (!sel || sel.tagName !== 'SELECT' || !sel.classList.contains('ss-track-category-select')) {
      return;
    }
    var form = sel.closest('form.ss-track-async-form');
    if (!form || form.getAttribute('data-ss-action') !== 'assign') {
      return;
    }
    handleAsyncForm(form);
  });

  document.addEventListener(
    'submit',
    function (ev) {
      var form = ev.target;
      if (!form || !form.classList || !form.classList.contains('ss-track-async-form')) {
        return;
      }
      ev.preventDefault();
      handleAsyncForm(form);
    },
    true
  );
})();
