jQuery(document).ready(function($) {

    const commonRadioOptions = [ 'like', 'love', 'care', 'haha', 'sad', 'angry', 'suprise', 'cry', 'dislike', 'happy', 'thinking', 'why', 'wink', 'worry'];
    const emojiBaseUrl = RF_JSObject.emojiBaseUrl;
    const minEmojiLimit = 3;
    const maxEmojiLimit = 7;

    // Handle click event on main emojis
    function openEmojiSelector($targetEmoji) {

        // Create the wrapper div
        const $wrapper = $('<div>', { class: 'reactify-emoji-popup-wrapper' });

        // Create the emoji-radio-container
        const $radioContainer = $('<div>', { class: 'emoji-radio-container' });

                // Add the title to the container
                const $title = $('<div>', {
                    text: 'Choose your favourite emoji',
                    class: 'emoji-radio-title'
                })
                $radioContainer.append($title);

        // Get the list of already selected emojis
        const selectedEmojis = [];
        $('.reactify-emoji').each(function () {
            selectedEmojis.push($(this).data('emoji'));
        });

        // Create image options for common emojis excluding already selected ones
        commonRadioOptions.forEach(function (option) {
            if (!selectedEmojis.includes(option)) {
                const $image = $('<img>', {
                    src: `${emojiBaseUrl}/emoji-${option}.png`,
                    alt: option,
                    class: 'emoji-radio-option',
                    'data-emoji': option
                });

                $radioContainer.append($image);
            }
        });


        // Append the radio container to the wrapper
        $wrapper.append($radioContainer);

        // Append the wrapper to the body
        $('body').append($wrapper);

        // Position the popup relative to the clicked emoji
        const emojiOffset = $targetEmoji.offset();
        const popupTop = emojiOffset.top + $targetEmoji.outerHeight() + 10; // Add some spacing
        const popupLeft = emojiOffset.left;


        // Handle selection of the emoji image
        $radioContainer.on('click', '.emoji-radio-option', function () {
            const newEmoji = $(this).data('emoji');
            if (newEmoji) {
                // Highlight the selected image
                $radioContainer.find('.emoji-radio-option').removeClass('selected');
                $(this).addClass('selected');

                const $emojiElement = $targetEmoji;
                $emojiElement.data('emoji', newEmoji);
                $emojiElement.find('img').attr('src', `${emojiBaseUrl}/emoji-${newEmoji}.png`);
                $emojiElement.closest('.reactify-react-emoji').find('.reactify-emoji-name').text(newEmoji.charAt(0).toUpperCase() + newEmoji.slice(1));

                $radioContainer.remove();
            }
        });
    }

    // Open emoji selector on clicking an emoji
    $(document).on('click', '.reactify-emoji', function (e) {
        e.stopPropagation();
        openEmojiSelector($(this));
    });

    // Close the popup when clicking outside of it
    $(document).click(function () {
        $('.reactify-emoji-popup-wrapper').remove();
    });

    // Handle click event on the close button
    $(document).on('click', '.reactify-close-btn', function () {
        const $emojiDiv = $(this).closest('.reactify-react-emoji'); // Find the closest emoji container
        if ($('.reactify-react-emoji').length > minEmojiLimit) {
            $emojiDiv.remove(); // Remove the emoji from the DOM
        } else {
            alert(`You must have at least ${minEmojiLimit} emojis.`);
        }
    });

    // Handle click event on the add emoji button
    $(document).on('click', '.add-emoji-btn', function () {
        const $emojiContainer = $('.reactify-react-emoji-wrapper');
        const currentCount = $emojiContainer.find('.reactify-react-emoji').length;

        if (currentCount >= maxEmojiLimit) {
            alert('You can only have up to 7 emojis.');
            return;
        }

        // Create a new emoji container with a placeholder image
        const $newEmojiDiv = $(`
            <div class="reactify-react-emoji">
                <div class="reactify-close-btn">X</div>
                <div class="reactify-emoji" data-emoji="placeholder">
                    <img src="${emojiBaseUrl}/emoji-placeholder.png" alt="placeholder">
                </div>
                <h4 class="reactify-emoji-name">Choose emoji</h4>
            </div>
        `);

        // Insert it before the `+` button
        $emojiContainer.find('.add-emoji-btn').before($newEmojiDiv);

        // Open the emoji selector immediately for the new emoji
        openEmojiSelector($newEmojiDiv.find('.reactify-emoji'));
    });

    // Save updated emoji array
    $('#save-reaction-view').click(function () {

         var reactionTitle = $('#reaction-title').val();
        var selectedValue = $('#reaction-type').val();
        if (reactionTitle.trim() === '') {
            reactionTitle = 'What do you feel about this post?';
        }
        var switchChecked = $('#reaction-title-switch').is(':checked') ? 'yes' : 'no';

        $.ajax({
            url: RF_JSObject.ajaxUrl,
            type: 'POST',
            data: {
                action: 'reactify_save_reaction_title',
                reaction_title: reactionTitle,
                reaction_title_enabled: switchChecked,
                selected_value: selectedValue,
                security: RF_JSObject._wpnonce
            },
            success: function(response) {
            }
        });

        const updatedEmojis = [];
        $('.reactify-emoji').each(function () {
            updatedEmojis.push($(this).data('emoji'));
        });

        // Check if the emoji count is less than the minimum limit
        if (updatedEmojis.length < minEmojiLimit) {
            alert(`You must have at least ${minEmojiLimit} emojis.`);
            return;
        }

        // Check if the emoji count exceeds the maximum limit
        if (updatedEmojis.length > maxEmojiLimit) {
            alert('You can only save up to 7 emojis.');
            return;
        }

        // Send the updated emojis to the server
        $.ajax({
            url: RF_JSObject.ajaxUrl,
            method: 'POST',
            data: {
                action: 'reactify_update_emojis',
                emojis: updatedEmojis,
                security: RF_JSObject._wpnonce
            },
            success: function (response) {
                console.log('Emojis updated:', response);
            },
            error: function (error) {
                alert('Failed to save emojis. Please try again.');
            }
        });
    });

    $("#save-reaction-view, #reactify-save-reaction-title").on("click", function () {
        const $button = $(this);

        // Add loading state
        $button.text("Updating...");
        $button.css({
            "background-color": "#ccc", // Optional: gray for loading
            "color": "#fff"
        }).prop("disabled", true);

        // Simulate a 3-second delay
        setTimeout(function () {
            // Change button to green with tick mark
            $button.text("Update")
                .css({
                    "background-color": "#28a745", // Green color
                    "color": "#fff"
                })
                .prop("disabled", false);
        }, 3000);
    });

    $(".reactify-react-emoji-wrapper").sortable({
        stop: function (event, ui) {
          let sortedArray = $("#reactify-react-emoji-wrapper").sortable("toArray", { attribute: "data-emoji" });
        }
      });
    $(".reactify-react-emoji-wrapper").disableSelection();

    const checkbox = $('#reactify_disable_reactions');
    const emojisContainer = $('#reactify-emojis-container');

    // Initial state
    emojisContainer.toggle(!checkbox.is(':checked'));

    // Toggle visibility on checkbox change
    checkbox.on('change', function () {
        emojisContainer.toggle(!$(this).is(':checked'));
    });

});
