(function ($) {
    "use strict";

    wp.customize.bind('ready', function () {

        /**
         * Logic for the Homepage Layout Manager control with eye icons.
         */
        function initLayoutManager() {
            var elementsList = $('#pawfect-frontpage-elements');
            var hiddenInput = elementsList.closest('.customize-control').find('input[type="hidden"]');

            // Debug logging
            if (elementsList.length === 0) {
                return;
            }
            if (hiddenInput.length === 0) {
                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());
                    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);
                },

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

        }

        /**
         * Initialize visibility toggle functionality
         */
        function initVisibilityToggles() {
            $(document).off('click.layout-manager', '.pawfect-visibility-toggle');
            $(document).on('click.layout-manager', '.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
                updateLayoutValue();

            });
        }

        /**
         * Function to update the layout value
         */
        function updateLayoutValue() {
            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');
        }

        /**
         * 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 premium sections like Instagram Gallery and Promo Timer!' +
                '</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);
        }

        // Initialize the layout manager.
        initLayoutManager();

    });

})(jQuery);
