document.addEventListener('DOMContentLoaded', function () {
  // Open the WordPress media uploader when the "Add image" button is clicked
  document.querySelectorAll('.add_image_button').forEach(function (element) {
    element.addEventListener('click', function (e) {
      e.preventDefault();
      var image_frame = wp.media({
        title: this.dataset.uploaderTitle,
        button: {
          text: this.dataset.uploaderButtonText,
        },
        multiple: true,
      });
      image_frame.on('select', function () {
        var selection = image_frame.state().get('selection');
        selection.map(function (attachment) {
          attachment = attachment.toJSON();
          if (attachment.id) {
            var image_src = attachment.sizes.thumbnail
              ? attachment.sizes.thumbnail.url
              : attachment.url;
            document.querySelector('.image-gallery-items').innerHTML +=
              '<li class="image-gallery-item"><input type="hidden" name="image_ids[]" value="' +
              attachment.id +
              '"><img src="' +
              image_src +
              '"><p><button type="button" class="button remove-image-button">Remove image</button></p></li>';
          }
        });
      });
      image_frame.open();
    });
  });

  // Remove an image from the gallery when the "Remove image" button is clicked
  if (document.querySelector('.image-gallery-items') != null) {
    console.log(document.querySelector('.image-gallery-items'));
    document
      .querySelector('.image-gallery-items')
      .addEventListener('click', function (e) {
        if (e.target.classList.contains('remove-image-button')) {
          let element = e.target;
          while (element && !element.matches('li.image-gallery-item')) {
            element = element.parentNode;
          }
          if (element) {
            element.remove();
          }
        }
      });
  }

  document.querySelectorAll('.button.rudr-upload').forEach(function (element) {
    element.addEventListener('click', function (e) {
      e.preventDefault();

      const button = jQuery(this);

      var image_frame = wp.media({
        title: this.dataset.uploaderTitle,
        button: {
          text: this.dataset.uploaderButtonText,
        },
        multiple: false,
      });

      image_frame.on('select', function () {
        const attachment = image_frame
          .state()
          .get('selection')
          .first()
          .toJSON();
        button.hide();
        button.after(
          '<img src="' + attachment.url + '" class="rudr-image" width="100px">'
        );
        button.next().next().show();
        button.next().next().next().val(attachment.id);
      });

      image_frame.open();
    });
  });

  // Function to handle image removal
  document.querySelectorAll('.rudr-remove').forEach(function (element) {
    element.addEventListener('click', function (e) {
      e.preventDefault();

      const button = jQuery(this).prev().prev();
      button.show();
      button.next('.rudr-upload-image').remove();
      jQuery(this).hide();
      button.next().val('');
    });
  });

  // Function to handle image removal
  jQuery('.rudr-reglages-remove').click(function (e) {
    e.preventDefault(); // Prevent default link behavior

    var $container = jQuery(this).closest('.immowp-row'); // Get the closest container

    $container.find('.rudr-reglages-remove').hide(); // Hide the "rudr-remove" button
    $container.find('.rudr-upload-image').hide(); // Hide the image
    $container.find('input[name="agence_sidebar_image"]').val(''); // Empty the input
    $container.find('.rudr-upload').show(); // Show the "rudr-upload" button
  });

  jQuery('.rudr-reglages-upload').click(function (e) {
    e.preventDefault();

    const button = jQuery(this);

    var image_frame = wp.media({
      title: this.dataset.uploaderTitle,
      button: {
        text: this.dataset.uploaderButtonText,
      },
      multiple: false,
    });

    image_frame.on('select', function () {
      var attachment = image_frame.state().get('selection').first().toJSON();

      button.hide();
      button.after(
        '<img src="' + attachment.url + '" class="rudr-image" width="100px">'
      );

      var $container = button.closest('.immowp-row'); // Get the closest container
      $container.find('.rudr-upload-image').show(); // Ensure the image container is visible
      $container.find('.rudr-remove').show(); // Show the "rudr-remove" button
      $container.find('input[name="agence_sidebar_image"]').val(attachment.id); // Set the input value to the attachment ID
    });

    image_frame.open();
  });

  // Handle promotional banner dismissal
  document.addEventListener('click', function(e) {
    if (e.target.closest('.immowp-promo-banner .notice-dismiss')) {
      e.preventDefault();
      
      var banner = e.target.closest('.immowp-promo-banner');
      if (banner) {
        // Use WordPress standard notice dismissal
        jQuery(banner).fadeOut(300, function() {
          jQuery(this).remove();
        });
        
        // Send AJAX request to save dismissal preference
        jQuery.post(ajaxurl, {
          action: 'dismiss_immowp_promo_banner',
          notice: 'immowp-promo',
          nonce: jQuery('#immowp_promo_nonce').val()
        });
      }
    }
  });
});
