jQuery(document).ready(function($) {
    // Use centralized debug utility
    if (window.mementorTTSDebug) {
        window.mementorTTSDebug.log('Mementor TTS Content Page JS loaded');
    }

    // Hide available types initially
    $('.tts-type-dropdown').hide();

    // Remove any existing dropdown indicators to prevent duplicates
    $('.tts-type-dropdown-icon').remove();

    // Add visual indicator for dropdown
    $('.tts-type-selector').append('<span class="tts-type-dropdown-icon dashicons dashicons-arrow-down-alt2"></span>');

    // Store original post type items for easy reference
    let originalTypeItems = {};
    $('.tts-type-dropdown-item').each(function() {
        const type = $(this).data('type');
        originalTypeItems[type] = {
            element: $(this).clone(),
            name: $(this).text().trim()
        };
    });

    // Simple toggle for the dropdown
    $('.tts-type-selector').on('click', function(e) {
        // Don't toggle if clicking on a child element that has its own click handler
        if ($(e.target).hasClass('remove-type') || $(e.target).hasClass('tts-type-dropdown-item')) {
            return;
        }

        var $dropdown = $(this).find('.tts-type-dropdown');
        $dropdown.toggle();

        // Ensure the dropdown is visible
        if ($dropdown.is(':visible')) {
            $dropdown.css({
                'display': 'block',
                'visibility': 'visible',
                'opacity': '1',
                'z-index': '999999'
            });
        }
    });

    // Handle clicking on available post types
    $(document).on('click', '.tts-type-dropdown-item', function(e) {
        e.preventDefault();
        e.stopPropagation();

        // Skip if it's a PRO feature
        if ($(this).hasClass('tts-pro-feature')) {
            return;
        }

        const type = $(this).data('type');
        const name = $(this).text().replace('PRO', '').trim();

        // Check if this type is already selected
        if ($('.tts-type-tag[data-type="' + type + '"]').length > 0) {
            return;
        }

        // Create the selected type element
        const selectedType = $('<div class="tts-type-tag" data-type="' + type + '">' +
            name +
            '<span class="remove-type dashicons dashicons-no-alt"></span>' +
            '<input type="hidden" name="mementor_tts_post_types[]" value="' + type + '">' +
            '</div>');

        // Add to selected types
        $('.tts-type-tags').append(selectedType);

        // Remove from available types
        $(this).remove();

        // Notify console for debugging
        if (window.mementorTTSDebug) {
            window.mementorTTSDebug.log('Added post type: ' + type);
        }
    });

    // Handle removing a selected post type
    $(document).on('click', '.remove-type', function(e) {
        e.preventDefault();
        e.stopPropagation();

        const $selectedType = $(this).parent();
        const type = $selectedType.data('type');

        // Check if we have the original item stored
        if (originalTypeItems[type]) {
            // Add back to available types
            $('.tts-type-dropdown').append(originalTypeItems[type].element.clone());
        } else {
            // Fallback if original not stored
            const name = $selectedType.text().trim();
            const availableType = $('<div class="tts-type-dropdown-item" data-type="' + type + '">' + name + '</div>');
            $('.tts-type-dropdown').append(availableType);
        }

        // Remove from selected types
        $selectedType.remove();

        // Notify console for debugging
        if (window.mementorTTSDebug) {
            window.mementorTTSDebug.log('Removed post type: ' + type);
        }
    });

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

    // Make sure to trigger form submit correctly
    $('.post-types-form').on('submit', function() {
        if (window.mementorTTSDebug) {
            window.mementorTTSDebug.log('Post types form submitted');
        }
        const selectedTypes = [];
        $('.tts-type-tag input').each(function() {
            selectedTypes.push($(this).val());
        });
        if (window.mementorTTSDebug) {
            window.mementorTTSDebug.log('Selected post types:', selectedTypes);
        }

        // Ensure at least one post type is selected
        if (selectedTypes.length === 0) {
            alert('Please select at least one post type.');
            return false;
        }
    });

    // === Product Audio Settings: show/hide based on post type selection ===
    function updateProductSectionVisibility() {
        var hasProduct = false;
        $('.tts-type-tag').each(function() {
            if ($(this).data('type') === 'product') {
                hasProduct = true;
            }
        });

        var $section = $('#mementor-tts-product-audio-section');
        var $hint = $('#mementor-tts-product-hint');
        if (hasProduct) {
            $section.addClass('tts-product-visible');
            $hint.addClass('tts-info-visible');
        } else {
            $section.removeClass('tts-product-visible');
            $hint.removeClass('tts-info-visible');
        }
    }

    // Run on page load
    updateProductSectionVisibility();

    // Re-check when post types change (observe via MutationObserver on selected-types container)
    var selectedTypesContainer = document.querySelector('.tts-type-tags');
    if (selectedTypesContainer) {
        var observer = new MutationObserver(function() {
            updateProductSectionVisibility();
        });
        observer.observe(selectedTypesContainer, { childList: true });
    }

    // Image sub-options toggle
    $('#mementor_tts_product_include_image').on('change', function() {
        if ($(this).is(':checked')) {
            $('#mementor-tts-image-sub-options').addClass('tts-sub-visible');
        } else {
            $('#mementor-tts-image-sub-options').removeClass('tts-sub-visible');
        }
    });

    // Hide label disables custom label text input
    function updateLabelTextState() {
        var hidden = $('#mementor_tts_product_hide_label').is(':checked');
        $('#mementor-tts-product-label-text-option').css('opacity', hidden ? '0.5' : '1');
        $('#mementor_tts_product_player_label').prop('disabled', hidden);
    }
    updateLabelTextState();
    $('#mementor_tts_product_hide_label').on('change', updateLabelTextState);
});
