(function () {
  'use strict';

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

  document.addEventListener('click', function (event) {
    var button = event.target.closest('[data-move-path]');
    if (!button) return;

    var currentPath = button.getAttribute('data-move-path');
    var baseHash = button.getAttribute('data-move-hash');
    var destination = window.prompt('Move document to:', currentPath);
    if (destination === null || destination.trim() === '' || destination.trim() === currentPath) return;

    button.disabled = true;
    fetch('/api/documents/' + apiDocumentPath(currentPath) + '/move', {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ path: destination.trim(), baseHash: baseHash }),
    })
      .then(function (response) {
        return response.json().then(function (data) {
          if (!response.ok) throw new Error(data.error || 'Move failed');
          return data;
        });
      })
      .then(function (data) {
        window.location.assign(data.url);
      })
      .catch(function (error) {
        window.alert(error.message || 'Failed to move document');
        button.disabled = false;
      });
  });
})();
