jQuery(document).ready(function($) {
    var i18n = window.pdtMenuManagerI18n || {};

    var totalItems = parseInt($('.pdt-total').text());
    var visibleItems = totalItems;

    // PRO: Count hidden items
    $('.pdt-hide-selector').each(function() {
        var hideAll = $(this).find('.pdt-hide-all-checkbox:checked').length > 0;
        var hideUsers = $(this).find('.pdt-hide-users-list .pdt-hide-user-checkbox:checked').length > 0;
        if (hideAll || hideUsers) {
            visibleItems--;
        }
    });

    $('.pdt-count').text(visibleItems);

    // PRO: Hide selector toggle
    $(document).on('click', '.pdt-hide-toggle', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var $selector = $(this).closest('.pdt-hide-selector');
        
        // Close other dropdowns
        $('.pdt-hide-selector').not($selector).removeClass('open');
        
        // Toggle this dropdown
        $selector.toggleClass('open');
    });

    // Close dropdown when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.pdt-hide-selector').length) {
            $('.pdt-hide-selector').removeClass('open');
        }
    });

    // PRO: Handle "Hide from everyone" checkbox
    $(document).on('change', '.pdt-hide-all-checkbox', function() {
        var $selector = $(this).closest('.pdt-hide-selector');
        var $toggle = $selector.find('.pdt-hide-toggle');
        var $row = $(this).closest('tr');
        var $usersSection = $selector.find('.pdt-hide-users-section');
        var $optionGroup = $(this).closest('.pdt-option-group');
        var $blockOption = $optionGroup.find('.pdt-block-option');
        
        if (this.checked) {
            // Disable users section
            $usersSection.addClass('disabled');
            $usersSection.find('input[type="checkbox"]').prop('disabled', true);
            $optionGroup.addClass('active');
            
            // Enable block option
            $blockOption.removeClass('disabled');
            $blockOption.find('input[type="checkbox"]').prop('disabled', false);
            
            // Update toggle button
            $toggle.addClass('is-hidden');
            $toggle.find('.dashicons').first().removeClass('dashicons-visibility').addClass('dashicons-hidden');
            $row.addClass('is-hidden');
        } else {
            // Enable users section
            $usersSection.removeClass('disabled');
            $usersSection.find('.pdt-hide-user-checkbox').prop('disabled', false);
            $optionGroup.removeClass('active');
            
            // Disable and uncheck block option
            $blockOption.addClass('disabled').removeClass('active');
            $blockOption.find('input[type="checkbox"]').prop('disabled', true).prop('checked', false);
            
            // Remove block badge
            $toggle.find('.pdt-block-badge').remove();
            $toggle.removeClass('is-blocked');
            
            // Check if any users are selected
            var hasUsers = $usersSection.find('.pdt-hide-user-checkbox:checked').length > 0;
            if (!hasUsers) {
                $toggle.removeClass('is-hidden');
                $toggle.find('.dashicons').first().removeClass('dashicons-hidden').addClass('dashicons-visibility');
                $row.removeClass('is-hidden');
            }
        }
        
        updateVisibleCount();
        
        // Update parent menu if this is a submenu
        if ($row.hasClass('pdt-submenu-row')) {
            var parentSlug = $row.data('parent');
            updateParentHasHiddenSubmenu(parentSlug);
        }
    });

    // PRO: Handle "Block URL access" checkbox (for hide all)
    $(document).on('change', '.pdt-block-all-checkbox', function() {
        var $selector = $(this).closest('.pdt-hide-selector');
        var $toggle = $selector.find('.pdt-hide-toggle');
        var $blockOption = $(this).closest('.pdt-block-option');
        
        if (this.checked) {
            $blockOption.addClass('active');
            $toggle.addClass('is-blocked');
            
            // Add block badge if not exists
            if (!$toggle.find('.pdt-block-badge').length) {
                $toggle.append('<span class="pdt-block-badge" title="' + (i18n.urlAccessBlockedTitle || '') + '">🔒</span>');
            }
        } else {
            $blockOption.removeClass('active');
            $toggle.removeClass('is-blocked');
            
            // Check if any user blocks exist
            var hasUserBlocks = $selector.find('.pdt-block-user-checkbox:checked').length > 0;
            if (!hasUserBlocks) {
                $toggle.find('.pdt-block-badge').remove();
            }
        }
    });

    // PRO: Handle user hide checkbox changes
    $(document).on('change', '.pdt-hide-user-checkbox', function() {
        var $userRow = $(this).closest('.pdt-user-item-row');
        var $blockToggle = $userRow.find('.pdt-block-user-toggle');
        var $blockCheckbox = $blockToggle.find('.pdt-block-user-checkbox');
        
        if (this.checked) {
            // Enable block toggle for this user
            $blockToggle.removeClass('disabled');
            $blockCheckbox.prop('disabled', false);
        } else {
            // Disable and uncheck block toggle for this user
            $blockToggle.addClass('disabled').removeClass('active');
            $blockCheckbox.prop('disabled', true).prop('checked', false);
        }
        
        updateToggleState($(this));
    });

    // PRO: Handle user block checkbox changes
    $(document).on('change', '.pdt-block-user-checkbox', function() {
        var $selector = $(this).closest('.pdt-hide-selector');
        var $toggle = $selector.find('.pdt-hide-toggle');
        var $blockToggle = $(this).closest('.pdt-block-user-toggle');
        
        if (this.checked) {
            $blockToggle.addClass('active');
            
            // Add block badge if not exists
            if (!$toggle.find('.pdt-block-badge').length) {
                $toggle.append('<span class="pdt-block-badge" title="' + (i18n.urlAccessBlockedTitle || '') + '">🔒</span>');
            }
        } else {
            $blockToggle.removeClass('active');
            
            // Check if any blocks exist
            var hasBlockAll = $selector.find('.pdt-block-all-checkbox:checked').length > 0;
            var hasUserBlocks = $selector.find('.pdt-block-user-checkbox:checked').length > 0;
            if (!hasBlockAll && !hasUserBlocks) {
                $toggle.find('.pdt-block-badge').remove();
            }
        }
    });

    // Helper function to update toggle state
    function updateToggleState($checkbox) {
        var $selector = $checkbox.closest('.pdt-hide-selector');
        var $toggle = $selector.find('.pdt-hide-toggle');
        var $row = $checkbox.closest('tr');
        var $usersSection = $selector.find('.pdt-hide-users-section');
        
        var hasUsers = $usersSection.find('.pdt-hide-user-checkbox:checked').length > 0;
        var hideAll = $selector.find('.pdt-hide-all-checkbox:checked').length > 0;
        
        if (hasUsers || hideAll) {
            $toggle.addClass('is-hidden');
            $toggle.find('.dashicons').first().removeClass('dashicons-visibility').addClass('dashicons-hidden');
            $row.addClass('is-hidden');
        } else {
            $toggle.removeClass('is-hidden');
            $toggle.find('.dashicons').first().removeClass('dashicons-hidden').addClass('dashicons-visibility');
            $row.removeClass('is-hidden');
        }
        
        updateVisibleCount();
        
        // Update parent menu if this is a submenu
        if ($row.hasClass('pdt-submenu-row')) {
            var parentSlug = $row.data('parent');
            updateParentHasHiddenSubmenu(parentSlug);
        }
    }

    // PRO: Handle user checkbox changes
    $(document).on('change', '.pdt-hide-users-list input[type="checkbox"]', function() {
        var $selector = $(this).closest('.pdt-hide-selector');
        var $toggle = $selector.find('.pdt-hide-toggle');
        var $row = $(this).closest('tr');
        var $usersSection = $selector.find('.pdt-hide-users-section');
        
        var hasUsers = $usersSection.find('.pdt-hide-user-checkbox:checked').length > 0;
        var hideAll = $selector.find('.pdt-hide-all-checkbox:checked').length > 0;
        
        if (hasUsers || hideAll) {
            $toggle.addClass('is-hidden');
            $toggle.find('.dashicons').removeClass('dashicons-visibility').addClass('dashicons-hidden');
            $row.addClass('is-hidden');
        } else {
            $toggle.removeClass('is-hidden');
            $toggle.find('.dashicons').removeClass('dashicons-hidden').addClass('dashicons-visibility');
            $row.removeClass('is-hidden');
        }
        
        updateVisibleCount();
        
        // Update parent menu if this is a submenu
        if ($row.hasClass('pdt-submenu-row')) {
            var parentSlug = $row.data('parent');
            updateParentHasHiddenSubmenu(parentSlug);
        }
    });

    function filterUserRows($section) {
        var query = $.trim($section.find('.pdt-hide-users-search').val().toLowerCase());
        var hasQuery = query.length > 0;
        var visibleCount = 0;

        $section.find('.pdt-user-item-row').each(function() {
            var $row = $(this);
            var label = String($row.data('user-label') || '');
            var isChecked = $row.find('.pdt-hide-user-checkbox').is(':checked');
            var shouldShow = hasQuery ? (label.indexOf(query) !== -1 || isChecked) : isChecked;

            $row.toggleClass('pdt-user-row-hidden', !shouldShow);
            if (shouldShow) {
                visibleCount++;
            }
        });

        $section.find('.pdt-user-search-empty').toggleClass('is-visible', visibleCount === 0);
    }

    $(document).on('input', '.pdt-hide-users-search', function() {
        filterUserRows($(this).closest('.pdt-hide-users-section'));
    });

    $(document).on('change', '.pdt-hide-user-checkbox', function() {
        filterUserRows($(this).closest('.pdt-hide-users-section'));
    });

    $('.pdt-hide-users-section').each(function() {
        filterUserRows($(this));
    });
    
    // Function to update visible items count
    function updateVisibleCount() {
        var total = parseInt($('.pdt-total').text());
        var hidden = 0;
        
        $('.pdt-hide-selector').each(function() {
            var hideAll = $(this).find('.pdt-hide-all-checkbox:checked').length > 0;
            var hideUsers = $(this).find('.pdt-hide-users-list .pdt-hide-user-checkbox:checked').length > 0;
            if (hideAll || hideUsers) {
                hidden++;
            }
        });
        
        $('.pdt-count').text(total - hidden);
    }
    
    // Function to update parent menu's has-hidden-submenu class
    function updateParentHasHiddenSubmenu(parentSlug) {
        var $parentRow = $('.pdt-menu-row').filter(function() {
            return $(this).next('.pdt-submenu-row[data-parent="' + parentSlug + '"]').length > 0;
        }).first();
        
        if (!$parentRow.length) return;
        
        // Check if any submenu is hidden
        var hasHiddenSubmenu = false;
        $('.pdt-submenu-row[data-parent="' + parentSlug + '"]').each(function() {
            var hideAll = $(this).find('.pdt-hide-all-checkbox:checked').length > 0;
            var hideUsers = $(this).find('.pdt-hide-users-list .pdt-hide-user-checkbox:checked').length > 0;
            if (hideAll || hideUsers) {
                hasHiddenSubmenu = true;
                return false;
            }
        });
        
        if (hasHiddenSubmenu) {
            $parentRow.addClass('has-hidden-submenu');
        } else {
            $parentRow.removeClass('has-hidden-submenu');
        }
    }

    // Submenu toggle
    $('.pdt-submenu-toggle').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var $this = $(this);
        var $row = $this.closest('.pdt-menu-row');
        var parentSlug = $row.data('slug');
        
        $this.toggleClass('open');
        
        // Find and toggle submenu rows
        var $nextRow = $row.next();
        while ($nextRow.hasClass('pdt-submenu-row')) {
            $nextRow.toggle();
            $nextRow = $nextRow.next();
        }
        
        // Initialize submenu sortable after showing submenus
        if ($this.hasClass('open')) {
            setTimeout(function() {
                if (typeof window.pdtInitSubmenuSortable === 'function') {
                    window.pdtInitSubmenuSortable(parentSlug);
                }
            }, 200);
        }
    });

    // Initially hide submenus
    $('.pdt-submenu-row').hide();

    // Icon picker
    var currentIconInput = null;
    var currentIconDisplay = null;

    // Reset button confirmation
    $('#pdt-reset-btn').on('click', function(e) {
        var confirmMsg = $(this).data('confirm');
        if (!confirm(confirmMsg)) {
            e.preventDefault();
            return false;
        }
    });

    // Open icon picker modal
    $('.pdt-icon-btn').on('click', function(e) {
        e.preventDefault();
        var $picker = $(this).closest('.pdt-icon-picker');
        currentIconInput = $picker.find('.pdt-icon-input');
        currentIconDisplay = $picker.find('.pdt-current-icon');
        
        // Mark current icon as selected
        var currentIcon = currentIconInput.val() || currentIconDisplay.attr('class').split(' ').pop();
        $('.pdt-icon-option').removeClass('selected');
        $('.pdt-icon-option[data-icon="' + currentIcon + '"]').addClass('selected');
        
        $('#pdt-icon-modal').removeClass('pdt-hidden');
    });

    // Close modal
    $('.pdt-modal-close, .pdt-modal').on('click', function(e) {
        if (e.target === this) {
            $('#pdt-icon-modal').addClass('pdt-hidden');
            currentIconInput = null;
            currentIconDisplay = null;
        }
    });

    // Select icon
    $('.pdt-icon-option').on('click', function() {
        var icon = $(this).data('icon');
        
        if (currentIconInput && currentIconDisplay) {
            currentIconInput.val(icon);
            currentIconDisplay.attr('class', 'pdt-current-icon dashicons ' + icon);
            
            // Update is-renamed class on the row
            var $row = currentIconInput.closest('tr');
            $row.addClass('is-renamed');
        }
        
        $('#pdt-icon-modal').addClass('pdt-hidden');
    });

    // Search icons
    $('#pdt-icon-search').on('input', function() {
        var search = $(this).val().toLowerCase();
        
        $('.pdt-icon-option').each(function() {
            var icon = $(this).data('icon').toLowerCase();
            if (icon.indexOf(search) > -1) {
                $(this).removeClass('hidden');
            } else {
                $(this).addClass('hidden');
            }
        });
    });

    // Prevent modal content click from closing
    $('.pdt-modal-content').on('click', function(e) {
        e.stopPropagation();
    });

    // Update is-renamed class when rename input changes
    $('.pdt-rename-input').on('input', function() {
        var $row = $(this).closest('tr');
        var hasValue = $(this).val().trim() !== '';
        
        // Check if icon is also changed (for menu rows)
        var iconInput = $row.find('.pdt-icon-input');
        var hasIconChange = iconInput.length && iconInput.val().trim() !== '';
        
        if (hasValue || hasIconChange) {
            $row.addClass('is-renamed');
        } else {
            $row.removeClass('is-renamed');
        }
        
        // Update parent menu if this is a submenu
        if ($row.hasClass('pdt-submenu-row')) {
            var parentSlug = $row.data('parent');
            updateParentHasRenamedSubmenu(parentSlug);
        }
    });
    
    // Function to update parent menu's has-renamed-submenu class
    function updateParentHasRenamedSubmenu(parentSlug) {
        var $parentRow = null;
        
        // Find parent row by data-parent attribute matching
        $('.pdt-submenu-row[data-parent="' + parentSlug + '"]').first().prevAll('.pdt-menu-row').first().each(function() {
            $parentRow = $(this);
        });
        
        // Alternative: find by checkbox id
        if (!$parentRow || !$parentRow.length) {
            $('.pdt-menu-row').each(function() {
                var checkboxId = $(this).find('input[type="checkbox"]').attr('id') || '';
                if (checkboxId.indexOf(parentSlug) > -1 && checkboxId.indexOf('hide-sub-') === -1) {
                    $parentRow = $(this);
                    return false;
                }
            });
        }
        
        if (!$parentRow || !$parentRow.length) return;
        
        // Check if any submenu is renamed
        var hasRenamedSubmenu = false;
        $('.pdt-submenu-row[data-parent="' + parentSlug + '"]').each(function() {
            var renameVal = $(this).find('.pdt-rename-input').val();
            if (renameVal && renameVal.trim() !== '') {
                hasRenamedSubmenu = true;
                return false;
            }
        });
        
        // Only add has-renamed-submenu if no hidden submenu
        if (hasRenamedSubmenu && !$parentRow.hasClass('has-hidden-submenu')) {
            $parentRow.addClass('has-renamed-submenu');
        } else {
            $parentRow.removeClass('has-renamed-submenu');
        }
    }

    // PRO: Track if user has manually reordered menus
    var userHasReordered = false;
    
    // Encode slug for safe form input names (matches PHP pdt_encode_slug)
    function pdtEncodeSlug(slug) {
        // Base64 encode and replace +/= with form-safe chars
        var encoded = btoa(slug);
        return encoded.replace(/\+/g, '.').replace(/\//g, '~').replace(/=/g, '');
    }
    
    // PRO: Drag and drop for menu reordering
    if ($.fn.sortable) {
        // Main menu sortable
        $('.pdt-table tbody').sortable({
            items: 'tr.pdt-menu-row',
            handle: '.pdt-drag-handle',
            axis: 'y',
            placeholder: 'ui-sortable-placeholder',
            helper: function(e, tr) {
                var $originals = tr.children();
                var $helper = tr.clone();
                $helper.children().each(function(index) {
                    $(this).width($originals.eq(index).width());
                });
                return $helper;
            },
            start: function(e, ui) {
                var parentSlug = ui.item.data('slug');
                // Hide submenus of the dragged item
                $('.pdt-submenu-row[data-parent="' + parentSlug + '"]').hide();
                // Set placeholder height
                ui.placeholder.height(ui.item.height());
            },
            update: function(e, ui) {
                // User has manually reordered
                userHasReordered = true;
                // Move submenus with their parent
                var $menuRow = ui.item;
                var parentSlug = $menuRow.data('slug');
                var $submenus = $('.pdt-submenu-row[data-parent="' + parentSlug + '"]').detach();
                $menuRow.after($submenus);
                // Update hidden inputs for menu order
                updateMenuOrderInputs();
            }
        });

        // Submenu sortable - make submenus draggable within their group
        window.pdtInitSubmenuSortable = function(parentSlug) {
            var $submenus = $('.pdt-submenu-row[data-parent="' + parentSlug + '"]:visible');
            
            if ($submenus.length > 1) {
                var $tbody = $('.pdt-table tbody');
                
                // Check if sortable is already initialized
                if ($tbody.hasClass('ui-sortable')) {
                    $tbody.sortable('refresh');
                }
                
                // Make submenus sortable by reinitializing with submenu items included
                $tbody.sortable('destroy');
                $tbody.sortable({
                    items: 'tr.pdt-menu-row, tr.pdt-submenu-row[data-parent="' + parentSlug + '"]',
                    handle: '.pdt-drag-handle, .pdt-submenu-handle',
                    axis: 'y',
                    placeholder: 'ui-sortable-placeholder',
                    helper: function(e, tr) {
                        var $originals = tr.children();
                        var $helper = tr.clone();
                        $helper.children().each(function(index) {
                            $(this).width($originals.eq(index).width());
                        });
                        return $helper;
                    },
                    start: function(e, ui) {
                        ui.placeholder.height(ui.item.height());
                        
                        if (!ui.item.hasClass('pdt-submenu-row')) {
                            // Hide submenus of dragged menu
                            var slug = ui.item.data('slug');
                            $('.pdt-submenu-row[data-parent="' + slug + '"]').hide();
                        }
                    },
                    stop: function(e, ui) {
                        if (ui.item.hasClass('pdt-submenu-row')) {
                            // Ensure submenu stays within its parent group
                            var subParent = ui.item.data('parent');
                            var $parentRow = $('.pdt-menu-row[data-slug="' + subParent + '"]');
                            var $siblings = $('.pdt-submenu-row[data-parent="' + subParent + '"]');
                            
                            // Move all submenus right after parent
                            $siblings.detach();
                            $parentRow.after($siblings);
                            
                            updateSubmenuOrderInputs(subParent);
                        }
                    },
                    update: function(e, ui) {
                        if (ui.item.hasClass('pdt-menu-row')) {
                            // Move submenus with parent
                            var slug = ui.item.data('slug');
                            var $subs = $('.pdt-submenu-row[data-parent="' + slug + '"]').detach();
                            ui.item.after($subs);
                            updateMenuOrderInputs();
                        }
                    }
                });
            }
        };

        // Update menu order hidden inputs
        function updateMenuOrderInputs() {
            // Remove existing menu-order inputs
            $('input[name="pdt_settings[menu-order][]"]').remove();
            
            // Create new inputs based on current order
            var $form = $('.pdt-table').closest('form');
            $('.pdt-menu-row').each(function() {
                var slug = $(this).data('slug');
                if (slug) {
                    $form.append('<input type="hidden" name="pdt_settings[menu-order][]" value="' + slug + '" />');
                }
            });
        }

        // Update submenu order hidden inputs
        function updateSubmenuOrderInputs(parentSlug) {
            // Encode parent slug for safe form input name
            var encodedParent = pdtEncodeSlug(parentSlug);
            
            // Remove existing submenu-order inputs for this parent
            $('input[name="pdt_settings[submenu-order-' + encodedParent + '][]"]').remove();
            
            // Create new inputs based on current order
            var $form = $('.pdt-table').closest('form');
            $('.pdt-submenu-row[data-parent="' + parentSlug + '"]').each(function() {
                var subSlug = $(this).data('sub-slug');
                if (subSlug) {
                    $form.append('<input type="hidden" name="pdt_settings[submenu-order-' + encodedParent + '][]" value="' + subSlug + '" />');
                }
            });
        }

        // Only create menu order inputs if user has reordered OR if there are existing hidden inputs
        // This prevents overwriting original order on page load after reset
        if ($('input[name="pdt_settings[menu-order][]"]').length === 0) {
            // No existing order inputs - don't auto-create them
            // They will be created when user drags to reorder
        }
    }

});
