(function () {
  'use strict';

  function apiDocumentPath(path) {
    return (path || '')
      .replace(/^\/+/, '')
      .split('/')
      .map(encodeURIComponent)
      .join('/');
  }

  document.addEventListener('click', function (e) {
    var btn = e.target.closest('[data-archive-path]');
    if (!btn) return;

    var path = btn.getAttribute('data-archive-path');
    if (!path) return;

    if (!confirm('Archive this document? It will be hidden from the site but can be restored later.')) {
      return;
    }

    btn.disabled = true;
    btn.textContent = 'Archiving...';

    fetch('/api/documents/' + apiDocumentPath(path) + '/archive', {
      method: 'POST',
      credentials: 'same-origin',
    })
      .then(function (res) {
        if (res.ok) {
          window.location.href = '/';
          return;
        }
        return res.json().then(function (data) {
          throw new Error(data.error || 'Archive failed');
        });
      })
      .catch(function (err) {
        alert(err.message || 'Failed to archive document');
        btn.disabled = false;
        btn.textContent = 'Archive';
      });
  });
})();
