/**
 * Blog Sortable Control JavaScript - Premium Edition
 */
(function($) {
    'use strict';

    /**
     * Initialize Blog Sortable functionality
     */
    function initBlogSortable() {
        var elementsList = $('#pawfect-blog-elements');
        var hiddenInput = elementsList.closest('.customize-control').find('input[type="hidden"]');

        if (!elementsList.length || !hiddenInput.length) {
            return;
        }


        // Initialize visibility toggle functionality
        initVisibilityToggles(elementsList, hiddenInput);

        // Destroy existing sortable if it exists
        if (elementsList.hasClass('ui-sortable')) {
            elementsList.sortable('destroy');
        }

        // Make the list sortable with premium animations
        elementsList.sortable({
            placeholder: "sortable-item-placeholder",
            tolerance: "pointer",
            cursor: "grabbing",
            opacity: 0.9,
            distance: 5,
            delay: 100,
            revert: 150,
            scroll: true,
            scrollSensitivity: 100,
            scrollSpeed: 20,
            containment: "parent",
            helper: "clone",

            // Enhanced animations and feedback
            start: function(event, ui) {
                ui.item.addClass('pawfect-dragging');
                ui.placeholder.height(ui.item.outerHeight());

                // Add visual feedback to container
                elementsList.addClass('pawfect-drag-active');
            },

            stop: function(event, ui) {
                ui.item.removeClass('pawfect-dragging');
                elementsList.removeClass('pawfect-drag-active');

                // Add success animation
                ui.item.addClass('pawfect-drop-success');
                setTimeout(function() {
                    ui.item.removeClass('pawfect-drop-success');
                }, 600);

                // Now trigger the actual update to save changes
                setTimeout(function() {
                    updateSortableValue(elementsList, hiddenInput);
                }, 200);
            },

            over: function(event, ui) {
                $(this).addClass('pawfect-drag-over');
            },

            out: function(event, ui) {
                $(this).removeClass('pawfect-drag-over');
            },

            update: function(event, ui) {
                // Only update the hidden input value, don't trigger any customizer events
                updateHiddenInputOnly(elementsList, hiddenInput);
            }
        }).disableSelection();

    }

    /**
     * Initialize visibility toggle functionality
     */
    function initVisibilityToggles(elementsList, hiddenInput) {
        $(document).off('click.blog-sortable', '.pawfect-visibility-toggle');
        $(document).on('click.blog-sortable', '.pawfect-visibility-toggle', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var $toggle = $(this);
            var $item = $toggle.closest('.sortable-item');
            var elementId = $item.data('element-id');
            var isVisible = $item.data('visible') === true || $item.data('visible') === 'true';


            // Toggle visibility state
            var newVisibility = !isVisible;
            $item.data('visible', newVisibility);
            $item.attr('data-visible', newVisibility ? 'true' : 'false');


            if (newVisibility) {
                // Show element
                $item.removeClass('pawfect-disabled').css('opacity', '');
                $toggle.html('<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>').attr('title', 'Click to hide');
            } else {
                // Hide element
                $item.addClass('pawfect-disabled').css('opacity', '0.5');
                $toggle.html('<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>').attr('title', 'Click to show');
            }

            // Update the stored value and trigger customizer setting
            updateSortableValue(elementsList, hiddenInput);
        });
    }

    // Function to update the sortable value
    function updateSortableValue(elementsList, hiddenInput) {
        if (!elementsList || !hiddenInput) {
            return;
        }

        // Build the new configuration object
        var newConfig = {};

        elementsList.find('.sortable-item').each(function(index) {
            var $item = $(this);
            var elementId = $item.data('element-id');
            var isVisible = $item.data('visible') === true || $item.data('visible') === 'true';

            newConfig[elementId] = {
                order: index,
                visible: isVisible
            };
        });


        // Update the hidden input field with the new configuration
        hiddenInput.val(JSON.stringify(newConfig));

        // Manually trigger customizer setting update
        if (typeof wp !== 'undefined' && wp.customize) {
            var controlId = hiddenInput.closest('.customize-control').attr('id').replace('customize-control-', '');

            if (wp.customize.control(controlId) && wp.customize.control(controlId).setting) {
                wp.customize.control(controlId).setting.set(newConfig);
            } else {
                hiddenInput.trigger('change');
            }
        } else {
            hiddenInput.trigger('change');
        }

        // Show save notification
        showSaveNotification();
    }

    // Silent update function that doesn't trigger preview refresh
    function updateSortableValueSilent(elementsList, hiddenInput) {
        if (!elementsList || !hiddenInput) {
            return;
        }

        // Build the new configuration object
        var newConfig = {};

        elementsList.find('.sortable-item').each(function(index) {
            var $item = $(this);
            var elementId = $item.data('element-id');
            var isVisible = $item.data('visible') === true || $item.data('visible') === 'true';

            newConfig[elementId] = {
                order: index,
                visible: isVisible
            };
        });


        // Update the hidden input field WITHOUT triggering change event
        hiddenInput.val(JSON.stringify(newConfig));

        // Save to WordPress database directly without triggering preview refresh
        if (typeof wp !== 'undefined' && wp.customize) {
            var controlId = hiddenInput.closest('.customize-control').attr('id').replace('customize-control-', '');
            if (wp.customize.control(controlId) && wp.customize.control(controlId).setting) {
                // Temporarily disable transport to prevent preview refresh
                var originalTransport = wp.customize.control(controlId).setting.transport;
                wp.customize.control(controlId).setting.transport = 'refresh';

                // Update the setting
                wp.customize.control(controlId).setting.set(newConfig);

                // Restore original transport
                wp.customize.control(controlId).setting.transport = originalTransport;
            }
        }

        // Show save notification
        showSaveNotification();
    }

    // Function that only updates the hidden input without any customizer events
    function updateHiddenInputOnly(elementsList, hiddenInput) {
        if (!elementsList || !hiddenInput) {
            return;
        }

        // Build the new configuration object
        var newConfig = {};

        elementsList.find('.sortable-item').each(function(index) {
            var $item = $(this);
            var elementId = $item.data('element-id');
            var isVisible = $item.data('visible') === true || $item.data('visible') === 'true';

            newConfig[elementId] = {
                order: index,
                visible: isVisible
            };
        });


        // Only update the hidden input field, no events, no customizer updates
        hiddenInput.val(JSON.stringify(newConfig));

        // Show save notification to indicate changes need to be saved
        showSaveNotification();
    }

    // Show save notification
    function showSaveNotification() {
        // Remove any existing notifications
        $('.pawfect-save-notification').remove();

        var notification = $('<div class="pawfect-save-notification">Changes Ready - Click "Publish" to Save!</div>');
        $('body').append(notification);

        setTimeout(function() {
            notification.addClass('pawfect-show');
        }, 10);

        setTimeout(function() {
            notification.removeClass('pawfect-show');
            setTimeout(function() {
                notification.remove();
            }, 300);
        }, 4000);
    }

    // Re-initialize when customizer controls are added dynamically
    $(document).on('widget-added widget-updated', function() {
        setTimeout(initBlogSortable, 100);
    });

    // Also re-initialize when customizer is ready and when sections are expanded
    wp.customize.bind('ready', function() {
        setTimeout(initBlogSortable, 200);

        // Also try to initialize when the blog section is expanded
        if (wp.customize.section('pawfect_blog_section')) {
            wp.customize.section('pawfect_blog_section').expanded.bind(function(isExpanded) {
                if (isExpanded) {
                    setTimeout(initBlogSortable, 300);
                }
            });
        }
    });

    // Re-initialize when any customizer section is expanded
    wp.customize.section.each(function(section) {
        section.expanded.bind(function(isExpanded) {
            if (isExpanded) {
                setTimeout(initBlogSortable, 100);
            }
        });
    });

    // Additional initialization attempts
    $(document).on('DOMNodeInserted', function(e) {
        if ($(e.target).find('#pawfect-blog-elements').length) {
            setTimeout(initBlogSortable, 100);
        }
    });

    // Force re-initialization every few seconds as fallback
    setInterval(function() {
        if ($('#pawfect-blog-elements').length && !$('#pawfect-blog-elements').hasClass('ui-sortable')) {
            initBlogSortable();
        }
    }, 3000);

    // Listen for customizer save events to actually update the setting
    if (typeof wp !== 'undefined' && wp.customize) {
        wp.customize.bind('save', function() {
            // When user clicks save/publish, trigger the actual setting update
            var elementsList = $('#pawfect-blog-elements');
            var hiddenInput = elementsList.closest('.customize-control').find('input[type="hidden"]');

            if (elementsList.length && hiddenInput.length) {
                // Now actually trigger the setting update
                updateSortableValue(elementsList, hiddenInput);
            }
        });
    }

})(jQuery);
