// AJAX comment submission — progressive enhancement.
// When JS is available, intercepts the comment form POST and submits
// via fetch so media playback is not interrupted by a page reload.
// When JS is disabled, the form falls back to the normal POST + redirect.
(function() {
  var form = document.querySelector('.comment-form form');
  if (!form) return;

  form.addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(form);
    var submitBtn = form.querySelector('input[type="submit"]');
    var originalLabel = submitBtn.value;
    submitBtn.disabled = true;
    submitBtn.value = 'Sending...';

    fetch(form.action, {
      method: 'POST',
      body: formData,
      redirect: 'manual',
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(function(response) {
      if (!response.ok) {
        // Auth redirect or server error — fall back to regular form submit
        submitBtn.disabled = false;
        submitBtn.value = originalLabel;
        form.submit();
        return;
      }
      return response.json();
    })
    .then(function(data) {
      if (!data) return;
      insertComment(data);
      form.querySelector('textarea[name="data"]').value = '';
      updateCommentCount(1);
    })
    .catch(function() {
      // Network error — fall back to regular form submit
      submitBtn.disabled = false;
      submitBtn.value = originalLabel;
      form.submit();
    })
    .finally(function() {
      submitBtn.disabled = false;
      submitBtn.value = originalLabel;
    });
  });

  function insertComment(data) {
    var commentDiv = document.createElement('div');
    commentDiv.id = 'comment-' + data.id;
    commentDiv.className = 'comment';
    commentDiv.style.marginLeft = (data.depth * 20) + 'px';
    commentDiv.style.marginBottom = '20px';

    var header = '<div class="comment-header">'
      + '<strong>' + escapeHtml(data.author_name) + '</strong> '
      + '<span class="comment-date">' + escapeHtml(data.ago_string) + '</span>';
    if (!data.approved) {
      header += ' <span class="comment-status comment-pending">[Pending Approval]</span>';
    }
    header += '</div>';

    var content = '<div class="comment-content">' + data.data_html + '</div>';

    commentDiv.innerHTML = header + content;

    var commentsList = document.getElementById('comments-list');
    if (commentsList) {
      commentsList.insertBefore(commentDiv, commentsList.firstChild);
    }

    commentDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }

  function updateCommentCount(delta) {
    var heading = document.querySelector('.comments-section h3');
    if (!heading) {
      var section = document.querySelector('.comments-section');
      if (!section) return;
      var firstChild = document.getElementById('comments-list') || section.firstChild;
      heading = document.createElement('h3');
      heading.textContent = 'Comments & Reviews (1)';
      section.insertBefore(heading, firstChild);
      return;
    }
    var match = heading.textContent.match(/\((\d+)\)/);
    if (match) {
      var count = parseInt(match[1]) + delta;
      heading.textContent = heading.textContent.replace(/\(\d+\)/, '(' + count + ')');
    }
  }

  function escapeHtml(str) {
    var div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
  }
})();
