let deletedImages = [];

document.addEventListener('DOMContentLoaded', function () {
  const imageInput = document.getElementById('image-input');
  const imagePreview = document.getElementById('image-preview');
  const uploadArea = document.getElementById('image-upload-area');

  imageInput.addEventListener('change', function (e) {
    updatePreview();
  });

  ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    uploadArea.addEventListener(eventName, preventDefaults, false);
  });

  function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
  }

  ['dragenter', 'dragover'].forEach(eventName => {
    uploadArea.addEventListener(eventName, highlight, false);
  });

  ['dragleave', 'drop'].forEach(eventName => {
    uploadArea.addEventListener(eventName, unhighlight, false);
  });

  function highlight() {
    uploadArea.style.borderColor = '#007bff';
    uploadArea.style.background = '#f8f9fa';
  }

  function unhighlight() {
    uploadArea.style.borderColor = '#ccc';
    uploadArea.style.background = '';
  }

  uploadArea.addEventListener('drop', handleDrop, false);

  function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    imageInput.files = files;
    updatePreview();
  }

  function updatePreview() {
    imagePreview.innerHTML = '';
    const files = imageInput.files;

    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      if (!file.type.match('image.*')) continue;

      const reader = new FileReader();

      reader.onload = function (e) {
        const previewItem = document.createElement('div');
        previewItem.className = 'preview-item';

        const img = document.createElement('img');
        img.src = e.target.result;

        const removeBtn = document.createElement('button');
        removeBtn.className = 'remove-image';
        removeBtn.innerHTML = '×';
        removeBtn.onclick = function () {
          previewItem.remove();
          const dt = new DataTransfer();
          const inputFiles = imageInput.files;

          for (let j = 0; j < inputFiles.length; j++) {
            if (j !== i) {
              dt.items.add(inputFiles[j]);
            }
          }

          imageInput.files = dt.files;
        };

        previewItem.appendChild(img);
        previewItem.appendChild(removeBtn);
        imagePreview.appendChild(previewItem);
      };

      reader.readAsDataURL(file);
    }
  }
});

function deleteImage(imageId) {
  if (confirm('Delete this image?')) {
    deletedImages.push(imageId);
    document.getElementById('deleted-images').value = JSON.stringify(deletedImages);

    const imageItem = document.querySelector('.image-item[data-id="' + imageId + '"]');
    if (imageItem) {
      imageItem.style.display = 'none';
    }

    fetch('/admin/image/delete/' + imageId, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({})
    }).then(function (response) {
      return response.json();
    }).then(function (data) {
      if (!data.success) {
        alert('Error deleting image: ' + data.error);
      }
    }).catch(function (error) {
      console.error('Error:', error);
    });
  }
}
