// In assets/js/em-shortcode-manager.js
jQuery(function (jQuery) {
    var metabox = jQuery('#event_monster_settings, #Event_Monster_Free_settings');
    var modalContainer = jQuery('#modal-shortcode-manager');

    // 1. Listen for clicks on our "Get Shortcode" button
    metabox.on('click', '#em-get-shortcode-btn', function () {

        jQuery.post(em_shortcode_ajax_object.ajax_url, {
            action: 'em_get_shortcode_modal',
            nonce: em_shortcode_ajax_object.get_nonce
        }).done(function (response) {
            if (response.success) {
                // Find the modal content within the response
                var modalContent = jQuery(response.data.html);

                // Inject the content and show the modal using Tailwind classes
                modalContainer.html(modalContent).removeClass('em-hidden').addClass('em-fixed em-inset-0 em-bg-black em-bg-opacity-50 em-flex em-items-center em-justify-center em-z-50');

                // Now populate the shortcode
                var postId = jQuery('#post_ID').val();
                if (postId) {
                    var shortcode = `[EM id="${postId}"]`;
                    modalContainer.find('#em-shortcode-text').val(shortcode);
                }
            }
        });
    });

    // 2. Listen for the modal to be completely hidden
    modalContainer.on('click', function (e) {
        // Close modal when clicking outside the modal content
        if (e.target === this) {
            jQuery(this).addClass('em-hidden').removeClass('em-fixed em-inset-0 em-bg-black em-bg-opacity-50 em-flex em-items-center em-justify-center em-z-50').html('');
        }
    });

    // Close modal when clicking close button
    modalContainer.on('click', '.close, .close-modal', function () {
        modalContainer.addClass('em-hidden').removeClass('em-fixed em-inset-0 em-bg-black em-bg-opacity-50 em-flex em-items-center em-justify-center em-z-50').html('');
    });

    // 3. Listen for clicks on the "Copy" button INSIDE the modal
    modalContainer.on('click', '#em-copy-shortcode-button', function () {
        var shortcodeField = modalContainer.find('#em-shortcode-text')[0];
        shortcodeField.select();
        navigator.clipboard.writeText(shortcodeField.value);

        var successMsg = modalContainer.find('#em-copy-success-message');
        successMsg.removeClass('em-hidden').addClass('em-block');
        
        // Hide success message after 2 seconds
        setTimeout(function() {
            successMsg.addClass('em-hidden').removeClass('em-block');
        }, 2000);
    });
});
