(function($) {
    'use strict';

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

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


        // Initialize visibility toggle functionality
        initVisibilityToggles();

        // 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);
            },

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

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

            update: function(event, ui) {
                updateSortableValue();
            }
        }).disableSelection();

    }

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

            var $toggle = $(this);
            var $item = $toggle.closest('.sortable-item');
            var sectionId = $item.data('section-id');
            var isProOnly = $toggle.data('pro-only') === true || $toggle.data('pro-only') === 'true';
            var currentlyVisible = $item.data('visible') === true || $item.data('visible') === 'true';


            // Prevent enabling pro-only sections
            if (isProOnly && !currentlyVisible) {
                showProOnlyNotice(sectionId);
                return;
            }

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

            // Update visual state
            if (newVisibility) {
                $item.removeClass('pawfect-disabled').css('opacity', '');
                $toggle.html('<span class="dashicons dashicons-visibility" title="Click to hide"></span>');
                $toggle.attr('title', 'Click to hide');
            } else {
                $item.addClass('pawfect-disabled').css('opacity', '0.5');
                if (isProOnly) {
                    $toggle.html('<span class="dashicons dashicons-lock" title="Pro Only"></span>');
                    $toggle.attr('title', 'Pro Only');
                } else {
                    $toggle.html('<span class="dashicons dashicons-hidden" title="Click to show"></span>');
                    $toggle.attr('title', 'Click to show');
                }
            }

            // Update the value
            updateSortableValue();

        });
    }

    /**
     * Show pro-only notice
     */
    function showProOnlyNotice(sectionId) {
        // Remove any existing notices
        $('.pawfect-pro-only-notice').remove();

        // Create notice
        var notice = $('<div class="pawfect-pro-only-notice notice notice-info" style="margin: 10px 0; padding: 8px 12px; border-left: 4px solid #72aee6; background: #fff; font-size: 12px;">' +
            '<p style="margin: 0;">' +
            '<strong>Upgrade to <a href="https://wpmatcha.com/wordpress-themes/pawfect/" target="_blank" rel="noopener" style="color: #0073aa; text-decoration: none;">Pawfect Pro</a></strong> ' +
            'to unlock this section and premium features!' +
            '</p>' +
            '</div>');

        // Insert notice after the control
        $('#pawfect-frontpage-elements').closest('.customize-control').after(notice);

        // Auto-hide notice after 4 seconds
        setTimeout(function() {
            notice.fadeOut(300, function() {
                notice.remove();
            });
        }, 4000);
    }

    /**
     * Function to update the sortable value
     */
    function updateSortableValue() {
        var elementsList = $('#pawfect-frontpage-elements');
        var hiddenInput = elementsList.closest('.customize-control').find('input[type="hidden"]');

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

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

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

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


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

        // Verify the value was set

        // Show save notification
        showSaveNotification();
    }

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

        // Create notification
        var notification = $('<div class="pawfect-save-notification" style="position: fixed; top: 32px; right: 20px; background: #00a32a; color: white; padding: 8px 16px; border-radius: 4px; font-size: 12px; z-index: 999999; box-shadow: 0 2px 8px rgba(0,0,0,0.2);">' +
            '✓ Layout updated' +
            '</div>');

        $('body').append(notification);

        // Auto-hide after 2 seconds
        setTimeout(function() {
            notification.fadeOut(300, function() {
                notification.remove();
            });
        }, 2000);
    }

    // Initialize when document is ready
    $(document).ready(function() {
        setTimeout(initFrontpageSortable, 100);
    });

    // Also re-initialize when customizer is ready and when sections are expanded
    if (typeof wp !== 'undefined' && wp.customize) {
        wp.customize.bind('ready', function() {
            setTimeout(initFrontpageSortable, 200);

            // Also try to initialize when the frontpage layout section is expanded
            if (wp.customize.section('frontpage_layout')) {
                wp.customize.section('frontpage_layout').expanded.bind(function(isExpanded) {
                    if (isExpanded) {
                        setTimeout(initFrontpageSortable, 300);
                    }
                });
            }
        });
    }

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

})(jQuery);
