function changeImage(thumbnailElement) {
  const imageUrl = thumbnailElement.getAttribute('data-image-url');

  document.getElementById('mainImage').src = imageUrl;

  document.querySelectorAll('.thumbnail-container').forEach(thumb => {
    thumb.classList.remove('active');
  });
  thumbnailElement.classList.add('active');
}

function deleteImage(imageId) {
  if (confirm('Are you sure you want to delete this image?')) {
    fetch(`/admin/delete-image/${imageId}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      }
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          const imageElement = document.querySelector(`[data-image-id="${imageId}"]`);
          if (imageElement) {
            imageElement.remove();
          }
          alert('Image deleted successfully');
        } else {
          alert('Failed to delete image');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        alert('Error deleting image');
      });
  }
}

document.addEventListener('DOMContentLoaded', function () {
  const thumbnails = document.querySelectorAll('.thumbnail-container');

  thumbnails.forEach((thumb, index) => {
    thumb.addEventListener('keydown', function (e) {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        changeImage(this);
      }

      if (e.key === 'ArrowRight') {
        e.preventDefault();
        const next = thumbnails[index + 1];
        if (next) {
          next.focus();
          changeImage(next);
        }
      }

      if (e.key === 'ArrowLeft') {
        e.preventDefault();
        const prev = thumbnails[index - 1];
        if (prev) {
          prev.focus();
          changeImage(prev);
        }
      }
    });

    thumb.setAttribute('tabindex', '0');
  });
});
