jQuery(document).ready(function ($) {
  $(function () {
    let selectedAttachments = [];
    let hasUnsavedChanges = false;
    let mediaUploader;

    // Initialize selectedAttachments with existing gallery items
    $("#integrate_palace_gallery .gallery li").each(function () {
      const attachmentId = $(this).data("attachmentId");
      selectedAttachments.push(attachmentId);
    });

    // Open the media uploader
    $("#add_integrate_palace_gallery_image").on("click", function (e) {
      e.preventDefault();

      if (mediaUploader) {
        mediaUploader.open();
        return;
      }

      mediaUploader = wp.media({
        title: "Select Gallery Images",
        button: {
          text: "Add to Gallery",
        },
        multiple: "add",
        frame: "select",
        library: {
          type: "image",
        },
      });

      mediaUploader.on("select", function () {
        const attachments = mediaUploader.state().get("selection");

        attachments.each(function (attachment) {
          const attachmentId = attachment.id;
          const attachmentUrl = attachment.attributes.url;

          // Check if the image is already in the gallery
          if (
            !$(
              `#integrate_palace_gallery .gallery li[data-attachment-id="${attachmentId}"]`
            ).length
          ) {
            // Build the gallery item
            const listItem = $(`
                <li data-attachment-id="${attachmentId}">
                  <img src="${attachmentUrl}" width="150" height="150" alt="" />
                  <input type="hidden" name="integrate_palace_gallery[]" value="${attachmentId}" />
                  <button type="button" class="remove_image button">X</button>
                </li>
              `);

            // Append list item to gallery container
            $("#integrate_palace_gallery ul").append(listItem);

            // Update selectedAttachments and mark unsaved changes
            selectedAttachments.push(attachmentId);
            hasUnsavedChanges = true;
          }
        });
      });

      // Add custom class to selected images when the media uploader is opened
      mediaUploader.on("open", function () {
        const addSelectedClass = function () {
          const attachments = mediaUploader.$el.find(".attachment");

          attachments.each(function () {
            const attachmentId = parseInt($(this).data("id"), 10);

            if (selectedAttachments.includes(attachmentId)) {
              $(this).addClass("ipp-selected-gallery");
            } else {
              $(this).removeClass("ipp-selected-gallery");
            }
          });
        };

        // Observer for media library changes
        const observer = new MutationObserver((mutations) => {
          mutations.forEach((mutation) => {
            $(mutation.addedNodes).each(function () {
              if ($(this).hasClass("attachment")) {
                const attachmentId = parseInt($(this).data("id"), 10);

                if (selectedAttachments.includes(attachmentId)) {
                  $(this).addClass("ipp-selected-gallery");
                } else {
                  $(this).removeClass("ipp-selected-gallery");
                }
              }
            });
          });
        });

        // Observe changes in the media uploader
        const attachmentContainer = mediaUploader.$el.find(
          ".attachments-browser .attachments"
        )[0];
        if (attachmentContainer) {
          observer.observe(attachmentContainer, {
            childList: true,
            subtree: true,
          });
        }

        // Add class to attachments when media uploader opens
        addSelectedClass();

        // Clean up the observer when the media uploader is closed
        mediaUploader.on("close", function () {
          observer.disconnect();
        });
      });

      mediaUploader.open();
    });

    // Event delegation for removing images
    $(document).on("click", ".remove_image", function (e) {
      e.preventDefault();
      const attachmentId = $(this).closest("li").data("attachmentId");

      // Remove from the selectedAttachments array
      selectedAttachments = selectedAttachments.filter(
        (value) => value !== attachmentId
      );

      // Remove the gallery item from the DOM
      $(this).closest("li").remove();

      // Mark changes
      hasUnsavedChanges = true;
    });

    // Detect when the post is being saved or updated to avoid the unsaved changes prompt
    $("#post").on("submit", function () {
      hasUnsavedChanges = false; // Reset unsaved changes before post save
    });

    // Handle beforeunload event to prompt for confirmation
    $(window).on("beforeunload", function () {
      if (hasUnsavedChanges) {
        return "You have unsaved changes in the gallery. Are you sure you want to leave?";
      }
    });

    // Reset hasUnsavedChanges flag after saving via AJAX
    $(document).on("ajaxComplete", function () {
      hasUnsavedChanges = false;
    });
  });
});
