jQuery(document).ready(function ($) {
    // Tabs
    var $tabsWrapper = $('#publishpress-permissions-teaser-tabs');
    $tabsWrapper.find('li').click(function (e) {
        e.preventDefault();
        $tabsWrapper.children('li').filter('.nav-tab-active').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');

        var panel = $(this).find('a').first().attr('href');

        $('section[id^="ppp-"]').hide();
        $(panel).show();

        var current_tab = $(this).find('a').attr('href').replace('#','');
        $('#current_tab').val(current_tab);
    });

    // Expand / Collapse teaser custom code
    $('.ppp-expand-code').bind('click', function(e) {
        e.preventDefault();
        var codeArea = $(this).closest('.ppp-code-sample').find('textarea');
        if( $(this).attr('data-expand') === 'closed' ) {
            codeArea.css( 'height', codeArea[0].scrollHeight );
            $(this).attr('data-expand', 'opened');
            $(this).find('.ppp-expand-msg').hide();
            $(this).find('.ppp-collapse-msg').show();
        } else {
            codeArea.css( 'height', 200 );
            $(this).attr('data-expand', 'closed');
            $(this).find('.ppp-collapse-msg').hide();
            $(this).find('.ppp-expand-msg').show();
        }
    });

    // Copy teaser custom code
    $('.ppp-copy-code').bind('click', function(e) {
        e.preventDefault();
        var codeArea = $(this).closest('.ppp-code-sample').find('textarea');
        codeArea.select();
        document.execCommand('copy');
        if( $(this).attr('data-copy') === 'uncopied' ) {
            $(this).find('.ppp-uncopied-msg').hide();
            $(this).find('.ppp-copied-msg').show();
        } else {
            $(this).attr('data-expand', 'closed');
            $(this).find('.ppp-copied-msg').hide();
            $(this).find('.ppp-uncopied-msg').show();
        }
    });

    // Search posts
    $('.permissions_select_posts').select2( {
        placeholder: presspermitTeaser.strings.select_a_page,
        allowClear: true,
        ajax: {
            url: presspermitTeaser.url,
            dataType: 'json',
            method: 'get',
            delay: 250,
            data: function (params) {
                var postType = $(this).attr('data-post-type') || 'page';
                
                return {
                    search: params.term,
                    action: 'pp_search_posts',
                    post_type: postType,
                    nonce: presspermitTeaser.nonce
                }
            },
            processResults: function( data ) {
                var options = [];
    			if ( data ) {

                    $.each( data, function( index, item ) {
    					options.push( { id: item.ID, text: item.post_title  } );
    				});

                    return {
        				results: options
        			};
    			}
            },
        }
    } );
    
    // Handle post type selector change
    $(document).on('change', '.teaser-redirect-post-type', function() {
        var newPostType = $(this).val();
        var targetSelectId = $(this).attr('data-target-select');
        var $targetSelect = $('#' + targetSelectId);
        
        // Update the data-post-type attribute
        $targetSelect.attr('data-post-type', newPostType);
        
        // Clear the current selection
        $targetSelect.val(null).trigger('change');
        
        // Reinitialize select2 to use the new post type
        $targetSelect.select2('destroy');
        $targetSelect.select2({
            placeholder: presspermitTeaser.strings.select_a_page,
            allowClear: true,
            ajax: {
                url: presspermitTeaser.url,
                dataType: 'json',
                method: 'get',
                delay: 250,
                data: function (params) {
                    return {
                        search: params.term,
                        action: 'pp_search_posts',
                        post_type: newPostType,
                        nonce: presspermitTeaser.nonce
                    }
                },
                processResults: function( data ) {
                    var options = [];
                    if ( data ) {
                        $.each( data, function( index, item ) {
                            options.push( { id: item.ID, text: item.post_title  } );
                        });
                        return {
                            results: options
                        };
                    }
                },
            }
        });
    });

    // Search terms
    $('.permissions_select_terms').select2( {
        placeholder: presspermitTeaser.strings.select_terms,
        ajax: {
            url: presspermitTeaser.url,
            dataType: 'json',
            method: 'get',
            delay: 250,
            data: function (params) {
                return {
                    search: params.term,
                    action: 'pp_search_terms',
                    taxonomy: $('#teaser_hide_links_taxonomy').val(),
                    nonce: presspermitTeaser.nonce
                }
            },
            processResults: function( data ) {
                var options = [];
    			if ( data ) {
                    $.each( data, function( index, item ) {
    					options.push( { id: item.term_id, text: item.name  } );
    				});

                    return {
        				results: options
        			};
    			}
            },
        }
    } );

    $('div.teaser-coverage-post select').on('change', function () {
        $(this).siblings('span.teaser-num-chars').toggle($(this).val() == 'x_chars');
    });

    $('#ppp-tab-redirect select.teaser-redirect-mode').on('change', function() {
        $(this).parent('td').siblings('td').find('div.pp-select-dynamic-wrapper').toggle($(this).val() == '(select)');
    });

    // Expandable Row Functionality
    // Handle expand/collapse icon click
    $(document).on('click', '.pp-expand-icon', function (e) {
        e.preventDefault();
        e.stopPropagation();

        var $icon = $(this);
        var $mainRow = $icon.closest('tr.pp-main-row');
        var postType = $mainRow.data('post-type');
        var $detailRow = $('.pp-detail-' + postType);

        if ($detailRow.is(':visible')) {
            // Collapse
            $icon.removeClass('pp-expanded');
            $mainRow.removeClass('pp-expanded');
            setTimeout(function() {
                $detailRow.toggle();
                $detailRow.removeClass("expanded");
            }, 150);
        } else {
            // Expand
            $icon.addClass('pp-expanded');
            $mainRow.addClass('pp-expanded');
            setTimeout(function() {
                $detailRow.toggle();
                $detailRow.addClass("expanded");
            }, 150);
        }
    });

    // Handle teaser type change - show/hide expand icon and detail row
    $(document).on('change', 'select.teaser-type-select', function () {
        var $select = $(this);
        var $mainRow = $select.closest('tr.pp-main-row');
        var postType = $mainRow.data('post-type');
        var $expandIcon = $mainRow.find('.pp-expand-icon');
        var $detailRow = $('.pp-detail-' + postType);
        var $userApplicationDiv = $mainRow.find('div.teaser_vspace');
        var $numCharsSpan = $select.siblings('span.teaser-num-chars');

        var isEnabled = $select.val() != '0';

        // Show/hide expand icon
        $expandIcon.toggle(isEnabled);

        // Show/hide user application radio buttons
        $userApplicationDiv.toggle(isEnabled);

        // Show/hide num chars input
        $numCharsSpan.toggle($select.val() == 'x_chars');

        // Update row active state
        $mainRow.attr('data-row-active', isEnabled ? '1' : '0');

        // If disabled, collapse the detail row
        if (!isEnabled) {
            $expandIcon.removeClass('pp-expanded');
            $mainRow.removeClass('pp-expanded');
            $detailRow.slideUp(200);
        }

        // Update header column visibility
        var ppAnyTeaserTypesEnabled = $('select.teaser-type-select option:selected[value!="0"]').length;
        $('th.pp-teaser-user-application span').toggle(ppAnyTeaserTypesEnabled > 0);
    });

    // Handle redirect dropdown change in the separate redirect section
    $('.teaser-redirect-section select.teaser-redirect-mode').on('change', function() {
        $(this).parent('td').siblings('td').find('div.pp-select-dynamic-wrapper').toggle($(this).val() == '(select)');
    });

    // ========================================================================
    // Progressive Disclosure UI - Teaser Settings
    // ========================================================================

    // Function to update preview text based on teaser type and active tab
    function updateTeaserPreviewText($container) {
        var teaserType = $container.find('.pp-teaser-type-select').val();
        var $preview = $container.find('.pp-teaser-notice-preview');
        
        if (!$preview.length) {
            return; // No preview element found
        }
        
        var messageText = '';
        
        if (teaserType == '1') {
            // Teaser Text mode - check which tab is active
            var activeTab = $container.find('.pp-teaser-text-tabs .active').data('tab');
            if (activeTab == 'anon-content') {
                messageText = $preview.data('teaser-text-anon') || '';
            } else {
                messageText = $preview.data('teaser-text-logged') || '';
            }
        } else if (teaserType == 'read_more') {
            messageText = $preview.data('read-more-msg');
        } else if (teaserType == 'excerpt') {
            messageText = $preview.data('excerpt-msg');
        } else if (teaserType == 'x_chars' || teaserType == 'more') {
            messageText = $preview.data('x-chars-msg');
        }
        
        // Fallback to default if empty
        if (!messageText) {
            messageText = 'To read the full content, please log in to this site.';
        }
        
        $preview.text(messageText);
    }

    // Function to update teaser settings visibility based on selected type
    function updateTeaserSettings(selectedType, $container) {
        // Show/hide number input based on type
        if (selectedType == 'x_chars') {
            $container.find('.pp-num-chars-setting').fadeIn(300);
            $container.find('.pp-excerpt-chars-setting').fadeOut(300);
        } else if (selectedType == 'excerpt') {
            $container.find('.pp-excerpt-chars-setting').fadeIn(300);
            $container.find('.pp-num-chars-setting').fadeOut(300);
        } else {
            $container.find('.pp-num-chars-setting').fadeOut(300);
            $container.find('.pp-excerpt-chars-setting').fadeOut(300);
        }

        // Show/hide Teaser Notice Style field based on teaser type
        // Hide for redirect and no teaser, show for all other types
        var $teaserNoticeStyleRow = $container.find('select[name^="teaser_notice_style_mode"]').closest('tr');
        var $teaserNoticeStyleCard = $container.find('.pp-teaser-notice-style-settings')
        if (selectedType == '0' || selectedType == 'redirect') {
            $teaserNoticeStyleCard.hide();
            $teaserNoticeStyleRow.hide();
        } else {
            $teaserNoticeStyleRow.show();
            var $teaserNoticeStyleValue = $teaserNoticeStyleRow.find('select[name^="teaser_notice_style_mode"]').val();
            if ($teaserNoticeStyleValue === 'custom') {
                $teaserNoticeStyleCard.show();
            } else {
                $teaserNoticeStyleCard.hide();
            }
        }

        // Hide all notice cards first for smooth transition
        var $noticeCards = $container.find('.pp-read-more-notice-card, .pp-excerpt-notice-card, .pp-x-chars-notice-card');
        
        // Show/hide sections based on teaser type
        if (selectedType == '0') {
            // No Teaser: hide everything
            $container.find('.pp-teaser-application-fields').slideUp(300);
            $container.find('.pp-teaser-text-card').slideUp(300);
            $container.find('.pp-teaser-redirect-settings').slideUp(300);
            $noticeCards.stop(true, false).fadeOut(250);
        } else if (selectedType == 'redirect') {
            // Redirect: show only redirect settings and application fields
            $container.find('.pp-teaser-application-fields').slideDown(300);
            $container.find('.pp-teaser-text-card').slideUp(300);
            $container.find('.pp-teaser-redirect-settings').slideDown(300);
            $noticeCards.stop(true, false).fadeOut(250);
        } else if (selectedType == '1') {
            // Teaser Text: show teaser text card and application fields, hide redirect
            $container.find('.pp-teaser-application-fields').slideDown(300);
            $container.find('.pp-teaser-text-card').slideDown(300);
            $container.find('.pp-teaser-redirect-settings').slideUp(300);
            $noticeCards.stop(true, false).fadeOut(250);
        } else if (selectedType == 'read_more') {
            // Read More: show read more notice and application fields
            $container.find('.pp-teaser-application-fields').slideDown(300);
            $container.find('.pp-teaser-text-card').slideUp(300);
            $container.find('.pp-teaser-redirect-settings').slideUp(300);
            // Hide other notice cards first, then show read more notice
            $noticeCards.not('.pp-read-more-notice-card').stop(true, false).fadeOut(250);
            $container.find('.pp-read-more-notice-card').stop(true, false).delay(250).fadeIn(300);
        } else if (selectedType == 'excerpt') {
            // Excerpt: show excerpt notice and application fields
            $container.find('.pp-teaser-application-fields').slideDown(300);
            $container.find('.pp-teaser-text-card').slideUp(300);
            $container.find('.pp-teaser-redirect-settings').slideUp(300);
            // Hide other notice cards first, then show excerpt notice
            $noticeCards.not('.pp-excerpt-notice-card').stop(true, false).fadeOut(250);
            $container.find('.pp-excerpt-notice-card').stop(true, false).delay(250).fadeIn(300);
        } else if (selectedType == 'x_chars' || selectedType == 'more') {
            // X Chars or More: show x chars notice and application fields
            $container.find('.pp-teaser-application-fields').slideDown(300);
            $container.find('.pp-teaser-text-card').slideUp(300);
            $container.find('.pp-teaser-redirect-settings').slideUp(300);
            // Hide other notice cards first, then show x chars notice
            $noticeCards.not('.pp-x-chars-notice-card').stop(true, false).fadeOut(250);
            $container.find('.pp-x-chars-notice-card').stop(true, false).delay(250).fadeIn(300);
        } else {
            // Other teaser types: show application fields only
            $container.find('.pp-teaser-application-fields').slideDown(300);
            $container.find('.pp-teaser-text-card').slideUp(300);
            $container.find('.pp-teaser-redirect-settings').slideUp(300);
            $noticeCards.stop(true, false).fadeOut(250);
        }
        
        // Update preview text based on new teaser type
        updateTeaserPreviewText($container);
    }

    // Post type selector - switch between different post type settings
    $('#pp_current_post_type').on('change', function() {
        var selectedType = $(this).val();
        
        // Save selected post type to hidden field for persistence
        $('#selected_post_type').val(selectedType);
        
        // Hide all containers
        $('.pp-teaser-settings-container').removeClass('active').hide();
        
        // Show selected container with animation
        var $selectedContainer = $('.pp-teaser-settings-container[data-post-type="' + selectedType + '"]');
        $selectedContainer.addClass('active pp-fade-in').show();

        // Check the teaser type of the selected post type and show/hide sections
        var teaserType = $selectedContainer.find('.pp-teaser-type-select').val();

        updateTeaserSettings(teaserType, $selectedContainer);
    });

    // Teaser type select dropdown - show/hide conditional settings
    $(document).on('change', '.pp-teaser-type-select', function() {
        var $container = $(this).closest('.pp-teaser-settings-container');
        var selectedType = $(this).val();
        var postType = $container.data('post-type');

        updateTeaserSettings(selectedType, $container);
    });

    // Teaser text tabs - switch between logged in and not logged in
    $(document).on('click', '.pp-teaser-text-tab', function() {
        var tab = $(this).data('tab');
        var $container = $(this).closest('.pp-teaser-text-card, .pp-teaser-notice-style-settings');
        
        // Update tab active state
        $container.find('.pp-teaser-text-tab').removeClass('active');
        $(this).addClass('active');
        
        // Show corresponding content
        $container.find('.pp-teaser-text-content').removeClass('active').hide();
        $container.find('.pp-teaser-text-content[data-tab-content="' + tab + '"]')
            .addClass('active')
            .fadeIn(200);
    });

    // Initialize visibility on page load for progressive disclosure UI
    function initializeProgressiveUIVisibility() {
        // Check if there's a previously selected post type
        var savedPostType = $('#selected_post_type').val();
        var $container;
        
        if (savedPostType && $('.pp-teaser-settings-container[data-post-type="' + savedPostType + '"]').length) {
            // Restore previously selected post type
            $container = $('.pp-teaser-settings-container[data-post-type="' + savedPostType + '"]');
            $('#pp_current_post_type').val(savedPostType);
        } else {
            // Show first post type by default
            $container = $('.pp-teaser-settings-container').first();
            if ($container.length) {
                // Try to find the first enabled option in the post type selector
                var $firstEnabledOption = $('#pp_current_post_type option:not(:disabled)').first();
                var firstPostType = $firstEnabledOption.length ? $firstEnabledOption.val() : $container.data('post-type');
                $('#pp_current_post_type').val(firstPostType);
                $('#selected_post_type').val(firstPostType);
            }
        }

        if ($container && $container.length) {
            $container.addClass('active').show();

            // Check the post type's teaser setting and show/hide elements accordingly
            var selectedType = $container.find('.pp-teaser-type-select').val();
            
            // Show/hide number input based on type
            if (selectedType == 'x_chars') {
                $container.find('.pp-num-chars-setting').show();
                $container.find('.pp-excerpt-chars-setting').hide();
            } else if (selectedType == 'excerpt') {
                $container.find('.pp-excerpt-chars-setting').show();
                $container.find('.pp-num-chars-setting').hide();
            } else {
                $container.find('.pp-num-chars-setting').hide();
                $container.find('.pp-excerpt-chars-setting').hide();
            }

            // Show/hide Teaser Notice Style field based on teaser type
            // Hide for redirect and no teaser, show for all other types
            var $teaserNoticeStyleRow = $container.find('select[name^="teaser_notice_style_mode"]').closest('tr');
            var $teaserNoticeStyleCard = $container.find('.pp-teaser-notice-style-settings')
            if (selectedType == '0' || selectedType == 'redirect') {
                $teaserNoticeStyleCard.hide();
                $teaserNoticeStyleRow.hide();
            } else {
                $teaserNoticeStyleRow.show();
                var $teaserNoticeStyleValue = $teaserNoticeStyleRow.find('select[name^="teaser_notice_style_mode"]').val();
                if ($teaserNoticeStyleValue === 'custom') {
                    $teaserNoticeStyleCard.show();
                } else {
                    $teaserNoticeStyleCard.hide();
                }
            }

            // Hide all notice cards first for smooth transition
            var $noticeCards = $container.find('.pp-read-more-notice-card, .pp-excerpt-notice-card, .pp-x-chars-notice-card');
            
            if (selectedType == '0') {
                // No Teaser: hide everything
                $container.find('.pp-teaser-application-fields').hide();
                $container.find('.pp-teaser-text-card').hide();
                $container.find('.pp-teaser-redirect-settings').hide();
                $noticeCards.hide();
            } else if (selectedType == 'redirect') {
                // Redirect: show only redirect settings and application fields
                $container.find('.pp-teaser-application-fields').show();
                $container.find('.pp-teaser-text-card').hide();
                $container.find('.pp-teaser-redirect-settings').show();
                $noticeCards.hide();
            } else if (selectedType == '1') {
                // Teaser Text: show teaser text card and application fields, hide redirect
                $container.find('.pp-teaser-application-fields').show();
                $container.find('.pp-teaser-text-card').show();
                $container.find('.pp-teaser-redirect-settings').hide();
                $noticeCards.hide();
            } else if (selectedType == 'read_more') {
                // Read More: show read more notice and application fields
                $container.find('.pp-teaser-application-fields').show();
                $container.find('.pp-teaser-text-card').hide();
                $container.find('.pp-teaser-redirect-settings').hide();
                // Hide other notice cards first, then show read more notice
                $noticeCards.not('.pp-read-more-notice-card').hide();
                $container.find('.pp-read-more-notice-card').show();
            } else if (selectedType == 'excerpt') {
                // Excerpt: show excerpt notice and application fields
                $container.find('.pp-teaser-application-fields').show();
                $container.find('.pp-teaser-text-card').hide();
                $container.find('.pp-teaser-redirect-settings').hide();
                // Hide other notice cards first, then show excerpt notice
                $noticeCards.not('.pp-excerpt-notice-card').hide();
                $container.find('.pp-excerpt-notice-card').show();
            } else if (selectedType == 'x_chars' || selectedType == 'more') {
                // X Chars or More: show x chars notice and application fields
                $container.find('.pp-teaser-application-fields').show();
                $container.find('.pp-teaser-text-card').hide();
                $container.find('.pp-teaser-redirect-settings').hide();
                // Hide other notice cards first, then show x chars notice
                $noticeCards.not('.pp-x-chars-notice-card').hide();
                $container.find('.pp-x-chars-notice-card').show();
            } else {
                // Other teaser types: show application fields only
                $container.find('.pp-teaser-application-fields').show();
                $container.find('.pp-teaser-text-card').hide();
                $container.find('.pp-teaser-redirect-settings').hide();
                $noticeCards.hide();
            }
            
            // Update preview text based on current teaser type
            updateTeaserPreviewText($container);
        }
    }

    // Run progressive UI initialization
    initializeProgressiveUIVisibility();

    // Redirect settings handlers for progressive UI
    $('#teaser_redirect_anon').on('change', function() {
        var $pageSelect = $('#teaser_redirect_anon_page').closest('.pp-select-dynamic-wrapper');
        if ($(this).val() == '(select)') {
            $pageSelect.show();
        } else {
            $pageSelect.hide();
            $('#teaser_redirect_anon_page').val('');
        }
    });

    $('#teaser_redirect').on('change', function() {
        var $pageSelect = $('#teaser_redirect_page').closest('.pp-select-dynamic-wrapper');
        if ($(this).val() == '(select)') {
            $pageSelect.show();
        } else {
            $pageSelect.hide();
            $('#teaser_redirect_page').val('');
        }
    });

    // Login form shortcode insertion for progressive UI
    $('.pp-add-login-form a').on('click', function(e) {
        e.preventDefault();
        
        // Find the editor - works for both table-based (td) and div-based layouts
        var $container = $(this).closest('td, div');
        var editorId = $container.find('.wp-editor-area').attr('id');
        
        if (editorId) {
            // Check if TinyMCE is active for this editor
            if (typeof tinymce !== 'undefined' && tinymce.get(editorId) && !tinymce.get(editorId).isHidden()) {
                var editor = tinymce.get(editorId);
                var content = editor.getContent();
                
                if (content.indexOf('[login_form]') === -1) {
                    editor.setContent(content + '[login_form]');
                }
            } else {
                // Fallback to textarea (when in Text/HTML mode)
                var $textarea = $('#' + editorId);
                if ($textarea.length && $textarea.val().indexOf('[login_form]') === -1) {
                    $textarea.val($textarea.val() + '[login_form]');
                }
            }
        }
        return false;
    });

    // Teaser Notice Style Mode Toggle
    function toggleTeaserNoticeStyleSettings() {
        // Check if any visible teaser notice style select has 'custom' selected
        var hasCustomMode = false;
        $('.pp-teaser-notice-style-select:visible').each(function() {
            if ($(this).val() === 'custom') {
                hasCustomMode = true;
                return false; // break the loop
            }
        });
        
        if (hasCustomMode) {
            $('.pp-teaser-notice-style-settings').slideDown(300, function() {
                // Scroll to the customization section after it's fully visible
                $('html, body').animate({
                    scrollTop: $('.pp-teaser-notice-style-settings').offset().top - 100
                }, 500);
            });
        } else {
            $('.pp-teaser-notice-style-settings').slideUp(300);
        }
    }

    // Handle change event for any teaser notice style select
    $(document).on('change', '.pp-teaser-notice-style-select', function() {
        toggleTeaserNoticeStyleSettings();
    });

    // Monitor TinyMCE editor changes for teaser text
    $(document).on('input keyup', 'textarea[id*="tease_replace_content"]', function() {
        var editorId = $(this).attr('id');
        var $container = $(this).closest('.pp-teaser-settings-container');
        var $preview = $container.find('.pp-teaser-notice-preview');
        var value = '';
        
        // Try to get content from TinyMCE if active
        if (typeof tinymce !== 'undefined' && tinymce.get(editorId) && !tinymce.get(editorId).isHidden()) {
            value = tinymce.get(editorId).getContent({format: 'text'});
        } else {
            value = $(this).val();
        }
        
        // Strip HTML tags for preview
        var tempDiv = document.createElement('div');
        tempDiv.innerHTML = value;
        value = tempDiv.textContent || tempDiv.innerText || '';

        if (editorId.indexOf('tease_replace_content_anon') > -1) {
            $preview.data('teaser-text-anon', value);
        } else if (editorId.indexOf('tease_replace_content') > -1 && editorId.indexOf('_anon') === -1) {
            $preview.data('teaser-text-logged', value);
        }
        
        updateTeaserPreviewText($container);
    });

    // Monitor textarea changes for notice message editors
    $(document).on('input keyup', 'textarea[id*="read_more_login_notice"], textarea[id*="excerpt_login_notice"], textarea[id*="x_chars_login_notice"]', function() {
        var editorId = $(this).attr('id');
        var $container = $(this).closest('.pp-teaser-settings-container');
        var $preview = $container.find('.pp-teaser-notice-preview');
        var value = '';
        
        // Try to get content from TinyMCE if active
        if (typeof tinymce !== 'undefined' && tinymce.get(editorId) && !tinymce.get(editorId).isHidden()) {
            value = tinymce.get(editorId).getContent({format: 'text'});
        } else {
            value = $(this).val();
        }
        
        // Strip HTML tags for preview
        var tempDiv = document.createElement('div');
        tempDiv.innerHTML = value;
        value = tempDiv.textContent || tempDiv.innerText || '';

        if (editorId.indexOf('read_more_login_notice') > -1) {
            $preview.data('read-more-msg', value);
        } else if (editorId.indexOf('excerpt_login_notice') > -1) {
            $preview.data('excerpt-msg', value);
        } else if (editorId.indexOf('x_chars_login_notice') > -1) {
            $preview.data('x-chars-msg', value);
        }
        
        updateTeaserPreviewText($container);
    });

    // Function to bind all TinyMCE editor events (preview updates and error removal)
    function bindTinyMCEEditor(editor) {
        // Handle preview text updates for teaser content editors
        if (editor.id.indexOf('tease_replace_content') > -1) {
            editor.on('keyup change', function() {
                var value = editor.getContent({format: 'text'});
                var $container = $('#' + editor.id).closest('.pp-teaser-settings-container');
                var $preview = $container.find('.pp-teaser-notice-preview');
                
                if (editor.id.indexOf('tease_replace_content_anon') > -1) {
                    $preview.data('teaser-text-anon', value);
                } else if (editor.id.indexOf('tease_replace_content') > -1 && editor.id.indexOf('_anon') === -1) {
                    $preview.data('teaser-text-logged', value);
                }
                
                updateTeaserPreviewText($container);
            });
        }
        
        // Handle preview text updates for message editors
        if (editor.id.indexOf('read_more_login_notice') > -1 || 
            editor.id.indexOf('excerpt_login_notice') > -1 || 
            editor.id.indexOf('x_chars_login_notice') > -1) {
            editor.on('keyup change', function() {
                var value = editor.getContent({format: 'text'});
                var $container = $('#' + editor.id).closest('.pp-teaser-settings-container');
                var $preview = $container.find('.pp-teaser-notice-preview');
                
                // Strip HTML tags for preview
                var tempDiv = document.createElement('div');
                tempDiv.innerHTML = value;
                value = tempDiv.textContent || tempDiv.innerText || '';
                
                if (editor.id.indexOf('read_more_login_notice') > -1) {
                    $preview.data('read-more-msg', value);
                } else if (editor.id.indexOf('excerpt_login_notice') > -1) {
                    $preview.data('excerpt-msg', value);
                } else if (editor.id.indexOf('x_chars_login_notice') > -1) {
                    $preview.data('x-chars-msg', value);
                }
                
                updateTeaserPreviewText($container);
            });
        }
        
        // Handle error removal for required fields
        var $editorArea = $('#' + editor.id);
        var $requiredField = $editorArea.closest('.pp-required-field');
        
        if ($requiredField.length) {
            editor.on('keyup change input', function() {
                var content = editor.getContent();
                
                // Check if content is not empty (after stripping HTML tags)
                var tempDiv = document.createElement('div');
                tempDiv.innerHTML = content;
                var textContent = (tempDiv.textContent || tempDiv.innerText || '').trim();
                
                if (textContent) {
                    $('#wp-' + editor.id + '-wrap').removeClass('pp-editor-error');
                    $requiredField.find('.error-msg').remove();
                }
            });
        }
    }

    // Bind to existing TinyMCE editors on page load
    if (typeof tinymce !== 'undefined') {
        // Bind to already-initialized editors
        tinymce.editors.forEach(function(editor) {
            bindTinyMCEEditor(editor);
        });
        
        // Bind to new editors as they're added
        tinymce.on('AddEditor', function(e) {
            bindTinyMCEEditor(e.editor);
        });
    }

    // Monitor tab switches in teaser text section
    $(document).on('click', '.pp-teaser-text-tabs .pp-teaser-text-tab', function() {
        var $container = $(this).closest('.pp-teaser-settings-container');

        // Small delay to allow tab content to switch
        setTimeout(function() {
            updateTeaserPreviewText($container);
        }, 50);
    });
    
    // Function to validate a required field
    function validateRequiredField($requiredField, postType) {
        var $editorArea = $requiredField.find('.wp-editor-area');

        if ($editorArea.length) {
            var editorId = $editorArea.attr('id');
            var content = '';
            
            // Get content from TinyMCE if active
            if (typeof tinymce !== 'undefined' && tinymce.get(editorId) && !tinymce.get(editorId).isHidden()) {
                content = tinymce.get(editorId).getContent();
            } else {
                content = $editorArea.val();
            }
            
            // Check if content is empty (after stripping HTML tags)
            var tempDiv = document.createElement('div');
            tempDiv.innerHTML = content;
            var textContent = (tempDiv.textContent || tempDiv.innerText || '').trim();

            if (!textContent) {
                // Highlight
                $('#wp-' + editorId + '-wrap').addClass('pp-editor-error');

                // Add error message if not already present
                if (!$requiredField.find('.error-msg').length) {
                    var errorMsg = $requiredField.data('error-message') || 'This field is required';
                    $requiredField.find('.wp-editor-wrap').after('<div class="error-msg" style="color: #dc3232; margin-top: 5px;">' + errorMsg + '</div>');
                }

                return {
                    hasError: true,
                    editorId: editorId,
                    tabContent: $requiredField.closest('.pp-teaser-text-content').data('tab-content'),
                    postType: postType
                };
            } else {
                $('#wp-' + editorId + '-wrap').removeClass('pp-editor-error');
                $requiredField.find('.error-msg').remove();
                return {
                    hasError: false
                };
            }
        }
        
        return {
            hasError: false
        };
    }
    
    // Form validation before submission
    $('#pp_settings_form').on('submit', function(e) {
        // Only run validation if we're on the teaser settings tab
        var $teaserSettingsSection = $('#ppp-tab-teaser-settings');
        if (!$teaserSettingsSection.is(':visible')) {
            return; // Not on teaser settings tab, allow form submission
        }

        var errors = [];

        // Check each teaser settings container (not just visible ones)
        $('.pp-teaser-settings-container').each(function() {
            var $container = $(this);
            var postType = $container.data('post-type');
            var teaserType = $container.find('.pp-teaser-type-select').val();

            // Only validate if teaser type is 1 (Teaser text)
            if (teaserType == '1') {
                // Check all tabs (anon and logged) for required fields
                $container.find('.pp-teaser-text-content').each(function() {
                    var $tabContent = $(this);
                    var $requiredFields = $tabContent.find('.pp-required-field[data-field-action="replace"][data-field-item="content"]');
                    
                    $requiredFields.each(function() {
                        var validationResult = validateRequiredField($(this), postType);
                        if (validationResult.hasError) {
                            errors.push(validationResult);
                        }
                    });
                });
            }
        });
        
        // Display errors and prevent submission
        if (errors.length > 0) {
            e.preventDefault();

            // Get first error
            var firstError = errors[0];
            if (firstError) {
                // Switch to the post type with error if needed
                var $targetContainer = $('.pp-teaser-settings-container[data-post-type="' + firstError.postType + '"]');
                
                if (!$targetContainer.hasClass('active')) {
                    // Update post type selector
                    $('#pp_current_post_type').val(firstError.postType);
                    
                    // Hide all containers
                    $('.pp-teaser-settings-container').removeClass('active').hide();
                    
                    // Show target container
                    $targetContainer.addClass('active pp-fade-in').show();
                }
                
                // Switch to the tab with error if needed
                var $teaserTextCard = $targetContainer.find('.pp-teaser-text-card .teaser-message-section');
                var $targetTab = $teaserTextCard.find('.pp-teaser-text-tab[data-tab="' + firstError.tabContent + '"]');
                
                if ($targetTab.length && !$targetTab.hasClass('active')) {
                    // Update tab active state
                    $teaserTextCard.find('.pp-teaser-text-tab').removeClass('active');
                    $targetTab.addClass('active');
                    
                    // Show corresponding content
                    $teaserTextCard.find('.pp-teaser-text-content').removeClass('active').hide();
                    $teaserTextCard.find('.pp-teaser-text-content[data-tab-content="' + firstError.tabContent + '"]')
                        .addClass('active')
                        .fadeIn(200);
                }
                
                // Scroll to first error with animation
                setTimeout(function() {
                    var $errorElement = $('#wp-' + firstError.editorId + '-wrap');
                    if ($errorElement.length) {
                        $('html, body').animate({
                            scrollTop: $errorElement.offset().top - 100
                        }, 500);
                        
                        // Add a subtle pulse effect to draw attention
                        $errorElement.addClass('pp-pulse-error');
                        setTimeout(function() {
                            $errorElement.removeClass('pp-pulse-error');
                        }, 2000);
                    }
                }, 300);
            }
            
            return false;
        }
    });
    
    // Handle error removal for textarea input (when in Text/HTML mode)
    $(document).on('input keyup', '.pp-required-field textarea.wp-editor-area', function() {
        var $requiredField = $(this).closest('.pp-required-field');
        var editorId = $(this).attr('id');
        var content = '';
        
        // Get content from TinyMCE if active
        if (typeof tinymce !== 'undefined' && tinymce.get(editorId) && !tinymce.get(editorId).isHidden()) {
            content = tinymce.get(editorId).getContent();
        } else {
            content = $(this).val();
        }
        
        // Check if content is not empty (after stripping HTML tags)
        var tempDiv = document.createElement('div');
        tempDiv.innerHTML = content;
        var textContent = (tempDiv.textContent || tempDiv.innerText || '').trim();
        
        if (textContent) {
            $('#wp-' + editorId + '-wrap').removeClass('pp-editor-error');
            $requiredField.find('.error-msg').remove();
        }
    });

    // PRO Feature Handling
    // Prevent selecting disabled PRO options
    $(document).on('change', 'select.pp-teaser-type-select', function() {
        var $select = $(this);
        var $selected = $select.find('option:selected');
        
        if ($selected.is(':disabled')) {
            // Revert to previous valid selection
            var $firstEnabled = $select.find('option:not(:disabled)').first();
            $select.val($firstEnabled.val());
            
            // Show upgrade notice
            alert('This feature is only available in PublishPress Permissions PRO.\n\nUpgrade now to unlock advanced teaser types including Read More links, excerpts, and redirects.');
        }
    });

    // Prevent interaction with disabled post type options
    $(document).on('change', '#pp_current_post_type', function() {
        var $select = $(this);
        var $selected = $select.find('option:selected');
        
        if ($selected.is(':disabled')) {
            // Revert to first enabled option
            var $firstEnabled = $select.find('option:not(:disabled)').first();
            $select.val($firstEnabled.val()).trigger('change');
            
            // Show upgrade notice
            alert('This post type is only available in PublishPress Permissions PRO.\n\nUpgrade now to apply teasers to Pages, WooCommerce Products, and all custom post types.');
        }
    });

    // Handle disabled radio buttons for user application
    $(document).on('click', 'input[type="radio"][name^="tease_logged_only"]:disabled', function(e) {
        e.preventDefault();
        alert('User-specific targeting is only available in PublishPress Permissions PRO.\n\nUpgrade now to show different teaser messages to logged-in vs anonymous users.');
        return false;
    });

    // PRO badge click handlers
    $(document).on('click', '.pp-pro-badge', function(e) {
        e.stopPropagation();
        var upgradeUrl = 'https://publishpress.com/links/permissions-banner';
        if (confirm('This feature is only available in PublishPress Permissions PRO.\n\nWould you like to learn more about upgrading?')) {
            window.open(upgradeUrl, '_blank');
        }
    });

    // Style disabled options
    $('select option:disabled').css({
        'color': '#999',
        'font-style': 'italic'
    });

    $('input[type="radio"]:disabled').each(function() {
        $(this).closest('label').css({
            'opacity': '0.5',
            'cursor': 'not-allowed'
        });
    });
});
