// Lets every file input in the admin panel accept a drag-and-drop drop,
// not just a click. Wires up the <label> wrapping each <input type="file">
// found on the page, so it works for both the big cover/screenshot
// dropzones and the compact "Choose file" buttons without per-page code.
document.addEventListener('DOMContentLoaded', function () {
  // Stop the browser from navigating away when a file is dropped outside a
  // dropzone (e.g. missed the target by a few pixels).
  ['dragover', 'drop'].forEach(function (evt) {
    document.addEventListener(evt, function (e) { e.preventDefault(); });
  });

  document.querySelectorAll('input[type="file"]').forEach(function (input) {
    var zone = input.closest('label');
    if (!zone) return;

    ['dragenter', 'dragover'].forEach(function (evt) {
      zone.addEventListener(evt, function (e) {
        e.preventDefault();
        e.stopPropagation();
        zone.classList.add('drag-over');
      });
    });

    ['dragleave', 'drop'].forEach(function (evt) {
      zone.addEventListener(evt, function (e) {
        e.preventDefault();
        e.stopPropagation();
        zone.classList.remove('drag-over');
      });
    });

    zone.addEventListener('drop', function (e) {
      var files = e.dataTransfer ? e.dataTransfer.files : null;
      if (!files || !files.length) return;

      if (!input.multiple && files.length > 1) {
        var dt = new DataTransfer();
        dt.items.add(files[0]);
        input.files = dt.files;
      } else {
        input.files = files;
      }

      input.dispatchEvent(new Event('change', { bubbles: true }));
    });
  });
});
