<?php
/**
 * Theme Compatibility Handler for Text to Speech TTS
 * 
 * Ensures the player works correctly with various themes
 * 
 * @package    TTSWP
 * @subpackage Mementor_TTS/includes
 * @since      1.4.3
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Theme Compatibility Class
 */
class Mementor_TTS_Theme_Compatibility {
    
    /**
     * Instance of this class
     */
    private static $instance = null;
    
    /**
     * Current theme info
     */
    private $theme_name;
    private $theme_slug;
    
    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Get current theme info
        $theme = wp_get_theme();
        $this->theme_name = $theme->get('Name');
        $this->theme_slug = $theme->get_stylesheet();
        
        // Initialize compatibility hooks
        add_action('init', array($this, 'init_theme_compatibility'), 20);
    }
    
    /**
     * Initialize theme-specific compatibility
     */
    public function init_theme_compatibility() {
        // Uncode theme compatibility
        if ($this->is_uncode_theme()) {
            $this->add_uncode_compatibility();
        }
        
        // Divi theme compatibility
        if ($this->is_divi_theme()) {
            $this->add_divi_compatibility();
        }
        
        // Elementor compatibility (theme builder)
        if ($this->is_elementor_theme()) {
            $this->add_elementor_compatibility();
        }
        
        // Avada theme compatibility
        if ($this->is_avada_theme()) {
            $this->add_avada_compatibility();
        }
        
        // Astra theme compatibility
        if ($this->is_astra_theme()) {
            $this->add_astra_compatibility();
        }
        
        // GeneratePress theme compatibility
        if ($this->is_generatepress_theme()) {
            $this->add_generatepress_compatibility();
        }
        
        // Add generic compatibility for all themes
        $this->add_generic_compatibility();
    }
    
    /**
     * Check if Uncode theme is active
     */
    private function is_uncode_theme() {
        return strpos(strtolower($this->theme_name), 'uncode') !== false ||
               strpos(strtolower($this->theme_slug), 'uncode') !== false ||
               defined('UNCODE_THEME_VERSION');
    }
    
    /**
     * Add Uncode theme compatibility
     */
    private function add_uncode_compatibility() {
        // Uncode uses custom content wrappers, we need higher priority
        add_filter('the_content', array($this, 'uncode_content_filter'), 99);
        
        // Add specific CSS for Uncode
        add_action('wp_head', array($this, 'uncode_compatibility_css'), 100);
        
        // Handle Uncode's Visual Composer content
        add_filter('mementor_tts_content_selector', function($selector) {
            return '.uncode_text_column, .post-content, .wpb_wrapper, .single-internal-gutter';
        });
        
        // Ensure player works with Uncode's ajax loading
        add_action('wp_footer', array($this, 'uncode_ajax_compatibility'));
        
        // Hook into Uncode's content areas
        add_action('uncode_before_content', array($this, 'maybe_add_player_uncode'));
        add_action('uncode_after_page_header', array($this, 'maybe_add_player_uncode'));
        
        // Filter for Uncode's main content
        add_filter('uncode_get_content_html', array($this, 'uncode_filter_content'), 10, 2);
        
        // Hook into Visual Composer content
        add_filter('vc_shortcode_content_filter_after', array($this, 'vc_content_filter'), 10, 2);
        
        // Add support for Uncode's content processing
        add_action('wp', array($this, 'setup_uncode_content_processing'), 20);
    }
    
    /**
     * Uncode content filter
     */
    public function uncode_content_filter($content) {
        // Only process on singular posts/pages
        if (!is_singular()) {
            return $content;
        }

        // Skip content fallback for positions handled elsewhere
        $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
        if (in_array($position, array('before_excerpt', 'after_excerpt', 'sticky_footer'))) {
            return $content;
        }

        // Check if this is inside an Uncode text column
        if (doing_filter('the_content') && strpos($content, 'uncode_text_column') === false) {
            // Get the public instance
            $public_instance = new Mementor_TTS_Public('text-to-speech-tts', MEMENTOR_TTS_VERSION);
            
            // Check if we should add player
            $post_id = get_the_ID();
            if ($post_id && method_exists($public_instance, 'should_post_have_player')) {
                // Use reflection to access private method
                $reflection = new ReflectionMethod($public_instance, 'should_post_have_player');
                $reflection->setAccessible(true);
                
                if ($reflection->invoke($public_instance, $post_id)) {
                    // Get audio URL
                    $audio_url = '';
                    if (method_exists($public_instance, 'get_audio_url')) {
                        $get_audio_method = new ReflectionMethod($public_instance, 'get_audio_url');
                        $get_audio_method->setAccessible(true);
                        $audio_url = $get_audio_method->invoke($public_instance, $post_id);
                    }
                    
                    // Don't render player if no audio URL exists
                    if (empty($audio_url)) {
                        return $content;
                    }
                    
                    // Render player HTML
                    if (method_exists($public_instance, 'render_player')) {
                        $player_html = '<div class="mementor-tts-player-container mementor-tts-automatic">';
                        $player_html .= $public_instance->render_player($audio_url, $post_id);
                        $player_html .= '</div>';
                        
                        if (!empty($player_html)) {
                            $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
                            
                            // Handle placement based on position setting
                            if (in_array($position, array('before_title', 'after_title_before_excerpt', 'after_title_after_excerpt'))) {
                                // These positions should place the player before content
                                $content = $player_html . $content;
                            } else {
                                // after_content position
                                $content = $content . $player_html;
                            }
                        }
                    }
                }
            }
        }
        
        return $content;
    }
    
    /**
     * Add Uncode compatibility CSS
     */
    public function uncode_compatibility_css() {
        ?>
        <style id="mementor-tts-uncode-compatibility">
        /* Uncode theme compatibility */
        .uncode_text_column .mementor-tts-player-container,
        .post-content .mementor-tts-player-container,
        .uncont .mementor-tts-player-container,
        .single-item .mementor-tts-player-container,
        .single-internal-gutter .mementor-tts-player-container,
        .row-child .mementor-tts-player-container,
        .wpb_wrapper .mementor-tts-player-container {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            position: relative !important;
            z-index: 10 !important;
            margin: 1.5em 0 !important;
            clear: both !important;
            width: 100% !important;
            max-width: 100% !important;
        }
        
        /* Ensure player is visible in Uncode's nested structure */
        .vc_row .mementor-tts-player-container,
        .wpb_row .mementor-tts-player-container,
        .wpb_column .mementor-tts-player-container,
        .uncol .mementor-tts-player-container,
        .vc_column_inner .mementor-tts-player-container,
        .wpb_text_column .mementor-tts-player-container {
            display: block !important;
            visibility: visible !important;
        }
        
        /* Fix for Uncode's column styles */
        .single-internal-gutter .mementor-tts-player-container {
            padding-left: 0 !important;
            padding-right: 0 !important;
        }
        
        /* Target Uncode's specific content wrapper structure */
        .single-item .row-child .single-internal-gutter .uncode_text_column .mementor-tts-player-container {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            position: relative !important;
            width: 100% !important;
            margin: 1.5em 0 !important;
        }
        
        /* Ensure controls are clickable */
        .uncode_text_column .mementor-tts-player *,
        .post-content .mementor-tts-player *,
        .wpb_wrapper .mementor-tts-player * {
            pointer-events: auto !important;
        }
        
        /* Override any Uncode animations that might hide the player */
        .mementor-tts-player-container,
        .mementor-tts-player-container * {
            animation-fill-mode: none !important;
            animation-play-state: running !important;
        }
        </style>
        <?php
    }
    
    /**
     * Add Uncode AJAX compatibility
     */
    public function uncode_ajax_compatibility() {
        ?>
        <script>
        // Uncode AJAX compatibility
        (function($) {
            // Re-initialize players after Uncode AJAX content loads
            $(document).on('uncode-ajax-loaded', function() {
                if (typeof mementorTTSInit === 'function') {
                    mementorTTSInit();
                }
            });
            
            // Also check for Uncode's custom events
            $(window).on('uncode-custom-cursor', function() {
                setTimeout(function() {
                    $('.mementor-tts-player-container').each(function() {
                        if (!$(this).data('initialized')) {
                            if (typeof mementorTTSInit === 'function') {
                                mementorTTSInit();
                            }
                        }
                    });
                }, 100);
            });
        })(jQuery);
        </script>
        <?php
    }
    
    /**
     * Check if Divi theme is active
     */
    private function is_divi_theme() {
        return strpos(strtolower($this->theme_name), 'divi') !== false ||
               strpos(strtolower($this->theme_slug), 'divi') !== false ||
               defined('ET_BUILDER_VERSION');
    }
    
    /**
     * Add Divi compatibility
     */
    private function add_divi_compatibility() {
        // Add Divi-specific CSS
        add_action('wp_head', function() {
            ?>
            <style>
            /* Divi theme compatibility */
            .et_pb_section .mementor-tts-player-container,
            .et_pb_row .mementor-tts-player-container,
            .et_pb_column .mementor-tts-player-container,
            .et_pb_text .mementor-tts-player-container {
                display: block !important;
                margin: 20px 0 !important;
            }
            </style>
            <?php
        });
    }
    
    /**
     * Check if Elementor theme is active
     */
    private function is_elementor_theme() {
        return did_action('elementor/loaded');
    }
    
    /**
     * Add Elementor compatibility
     */
    private function add_elementor_compatibility() {
        // Already handled in main CSS, but add extra specificity
        add_action('wp_head', function() {
            ?>
            <style>
            /* Elementor theme compatibility */
            .elementor-widget-container .mementor-tts-player-container {
                display: block !important;
                width: 100% !important;
                margin: 15px 0 !important;
            }
            </style>
            <?php
        });
    }
    
    /**
     * Check if Avada theme is active
     */
    private function is_avada_theme() {
        return strpos(strtolower($this->theme_name), 'avada') !== false ||
               strpos(strtolower($this->theme_slug), 'avada') !== false ||
               defined('AVADA_VERSION');
    }
    
    /**
     * Add Avada compatibility
     */
    private function add_avada_compatibility() {
        add_action('wp_head', function() {
            ?>
            <style>
            /* Avada theme compatibility */
            .fusion-text .mementor-tts-player-container,
            .post-content .mementor-tts-player-container {
                display: block !important;
                margin: 20px 0 !important;
                clear: both !important;
            }
            </style>
            <?php
        });
    }
    
    /**
     * Check if Astra theme is active
     */
    private function is_astra_theme() {
        return strpos(strtolower($this->theme_name), 'astra') !== false ||
               strpos(strtolower($this->theme_slug), 'astra') !== false ||
               defined('ASTRA_THEME_VERSION');
    }
    
    /**
     * Add Astra compatibility
     */
    private function add_astra_compatibility() {
        add_action('wp_head', function() {
            ?>
            <style>
            /* Astra theme compatibility */
            .ast-container .mementor-tts-player-container,
            .entry-content .mementor-tts-player-container {
                display: block !important;
                margin: 1.5em 0 !important;
            }
            </style>
            <?php
        });
    }
    
    /**
     * Check if GeneratePress theme is active
     */
    private function is_generatepress_theme() {
        return strpos(strtolower($this->theme_name), 'generatepress') !== false ||
               strpos(strtolower($this->theme_slug), 'generatepress') !== false ||
               defined('GENERATE_VERSION');
    }
    
    /**
     * Add GeneratePress compatibility
     */
    private function add_generatepress_compatibility() {
        add_action('wp_head', function() {
            ?>
            <style>
            /* GeneratePress theme compatibility */
            .inside-article .mementor-tts-player-container,
            .entry-content .mementor-tts-player-container {
                display: block !important;
                margin: 1.5em 0 !important;
                clear: both !important;
            }
            </style>
            <?php
        });
    }
    
    /**
     * Add generic compatibility for all themes
     */
    private function add_generic_compatibility() {
        // Add high-priority content filter as fallback
        add_filter('the_content', array($this, 'ensure_player_visibility'), 999);
        
        // Add generic CSS fixes
        add_action('wp_head', array($this, 'generic_compatibility_css'), 200);
    }
    
    /**
     * Ensure player visibility as last resort
     */
    public function ensure_player_visibility($content) {
        // Skip when the_content is being applied for TTS extraction; we must
        // not fold the player into the audio payload.
        if (function_exists('ttswp_is_extracting_for_tts') && ttswp_is_extracting_for_tts()) {
            return $content;
        }

        // Only on singular posts/pages
        if (!is_singular()) {
            return $content;
        }

        // Skip product pages when product-specific placement is configured
        if (is_singular('product') && class_exists('WooCommerce')) {
            $product_short = get_option('mementor_tts_product_player_short_desc', 'disabled');
            $product_long = get_option('mementor_tts_product_player_long_desc', 'before');
            if ($product_short !== 'disabled' || $product_long !== 'disabled') {
                return $content;
            }
        }

        // Skip content fallback for positions handled elsewhere
        $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
        if (in_array($position, array('before_excerpt', 'after_excerpt', 'sticky_footer'))) {
            return $content;
        }

        // Check if player is already in content
        if (strpos($content, 'mementor-tts-player-container') !== false) {
            return $content;
        }
        
        // Check if we should add player
        $post_id = get_the_ID();
        if (!$post_id) {
            return $content;
        }
        
        // Get enabled post types
        $enabled_post_types = get_option('mementor_tts_post_types', array('post'));
        if (!in_array(get_post_type($post_id), $enabled_post_types)) {
            return $content;
        }
        
        // Check if auto-add is enabled
        $auto_add = get_option('mementor_tts_auto_add_player', '1') === '1';
        if (!$auto_add) {
            return $content;
        }
        
        // Try to get player HTML
        $public_instance = new Mementor_TTS_Public('text-to-speech-tts', MEMENTOR_TTS_VERSION);
        
        // Get audio URL
        $audio_url = '';
        if (method_exists($public_instance, 'get_audio_url')) {
            $get_audio_method = new ReflectionMethod($public_instance, 'get_audio_url');
            $get_audio_method->setAccessible(true);
            $audio_url = $get_audio_method->invoke($public_instance, $post_id);
        }
        
        // Don't render player if no audio URL exists
        if (empty($audio_url)) {
            return $content;
        }
        
        if (method_exists($public_instance, 'render_player')) {
            $player_html = '<div class="mementor-tts-player-container mementor-tts-automatic">';
            $player_html .= $public_instance->render_player($audio_url, $post_id);
            $player_html .= '</div>';
            
            if (!empty($player_html)) {
                $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
                
                // Handle placement based on position setting
                if (in_array($position, array('before_title', 'after_title_before_excerpt', 'after_title_after_excerpt'))) {
                    // These positions should place the player before content
                    $content = $player_html . $content;
                } else {
                    // after_content position
                    $content = $content . $player_html;
                }
            }
        }
        
        return $content;
    }
    
    /**
     * Add generic compatibility CSS
     */
    public function generic_compatibility_css() {
        // Get dynamic margin and padding values from settings
        $margin_top = intval(get_option('mementor_tts_player_margin_top', 0));
        $margin_bottom = intval(get_option('mementor_tts_player_margin_bottom', 0));
        $player_padding = absint(get_option('mementor_tts_player_padding', 15));
        ?>
        <style id="mementor-tts-generic-compatibility">
        /* Generic theme compatibility - Ultra high specificity */
        body .mementor-tts-player-container,
        body .entry-content .mementor-tts-player-container,
        body .post-content .mementor-tts-player-container,
        body article .mementor-tts-player-container,
        body main .mementor-tts-player-container,
        body .content-area .mementor-tts-player-container,
        body .site-content .mementor-tts-player-container,
        body .site-main .mementor-tts-player-container,
        body #content .mementor-tts-player-container,
        body #main .mementor-tts-player-container,
        body [class*="content"] .mementor-tts-player-container,
        body [class*="post"] .mementor-tts-player-container,
        body [class*="entry"] .mementor-tts-player-container,
        body [class*="article"] .mementor-tts-player-container,
        body [id*="content"] .mementor-tts-player-container,
        body [id*="post"] .mementor-tts-player-container {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            position: relative !important;
            z-index: 10 !important;
            clear: both !important;
            float: none !important;
            margin-top: <?php echo esc_attr($margin_top); ?>px !important;
            margin-bottom: <?php echo esc_attr($margin_bottom); ?>px !important;
            padding: 0 !important;
            width: 100% !important;
            max-width: var(--mementor-tts-max-width, 100%) !important;
            height: auto !important;
            min-height: auto !important;
            transform: none !important;
            transition: none !important;
            animation: none !important;
            filter: none !important;
            backdrop-filter: none !important;
            clip-path: none !important;
            mask: none !important;
            -webkit-mask: none !important;
        }
        
        /* Ensure all child elements are visible */
        body .mementor-tts-player-container *,
        body .mementor-tts-player * {
            visibility: visible !important;
            opacity: 1 !important;
            pointer-events: auto !important;
        }
        
        /* Fix potential overflow issues */
        body .mementor-tts-player-container,
        body .mementor-tts-player {
            overflow: visible !important;
        }
        
        /* Ensure player shows in various content wrappers */
        .content > .mementor-tts-player-container:first-child,
        .entry-content > .mementor-tts-player-container:first-child,
        .post-content > .mementor-tts-player-container:first-child,
        article > .mementor-tts-player-container:first-child {
            margin-top: 0 !important;
        }
        
        /* Fix for themes that hide content initially */
        .mementor-tts-player-container[style*="display: none"],
        .mementor-tts-player-container[style*="display:none"],
        .mementor-tts-player-container.hidden,
        .mementor-tts-player-container.hide,
        .mementor-tts-player-container.invisible {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
        }
        
        /* Ensure alignment classes work with higher specificity than generic rules */
        body .mementor-tts-player-container.mementor-tts-align-center,
        body .entry-content .mementor-tts-player-container.mementor-tts-align-center,
        body .post-content .mementor-tts-player-container.mementor-tts-align-center,
        body article .mementor-tts-player-container.mementor-tts-align-center,
        body main .mementor-tts-player-container.mementor-tts-align-center,
        body .content-area .mementor-tts-player-container.mementor-tts-align-center,
        body .site-content .mementor-tts-player-container.mementor-tts-align-center,
        body .site-main .mementor-tts-player-container.mementor-tts-align-center,
        body #content .mementor-tts-player-container.mementor-tts-align-center,
        body #main .mementor-tts-player-container.mementor-tts-align-center,
        body [class*="content"] .mementor-tts-player-container.mementor-tts-align-center,
        body [class*="post"] .mementor-tts-player-container.mementor-tts-align-center,
        body [class*="entry"] .mementor-tts-player-container.mementor-tts-align-center,
        body [class*="article"] .mementor-tts-player-container.mementor-tts-align-center,
        body [id*="content"] .mementor-tts-player-container.mementor-tts-align-center,
        body [id*="post"] .mementor-tts-player-container.mementor-tts-align-center {
            margin-left: auto !important;
            margin-right: auto !important;
        }
        
        body .mementor-tts-player-container.mementor-tts-align-left,
        body .entry-content .mementor-tts-player-container.mementor-tts-align-left,
        body .post-content .mementor-tts-player-container.mementor-tts-align-left,
        body article .mementor-tts-player-container.mementor-tts-align-left,
        body main .mementor-tts-player-container.mementor-tts-align-left,
        body [class*="content"] .mementor-tts-player-container.mementor-tts-align-left,
        body [id*="content"] .mementor-tts-player-container.mementor-tts-align-left {
            margin-left: 0 !important;
            margin-right: auto !important;
        }
        
        body .mementor-tts-player-container.mementor-tts-align-right,
        body .entry-content .mementor-tts-player-container.mementor-tts-align-right,
        body .post-content .mementor-tts-player-container.mementor-tts-align-right,
        body article .mementor-tts-player-container.mementor-tts-align-right,
        body main .mementor-tts-player-container.mementor-tts-align-right,
        body [class*="content"] .mementor-tts-player-container.mementor-tts-align-right,
        body [id*="content"] .mementor-tts-player-container.mementor-tts-align-right {
            margin-left: auto !important;
            margin-right: 0 !important;
        }
        </style>
        <?php
    }
    
    /**
     * Maybe add player for Uncode theme
     */
    public function maybe_add_player_uncode() {
        // Only on singular posts/pages
        if (!is_singular()) {
            return;
        }

        // Skip for excerpt positions - handled via the_excerpt filter
        $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
        if (in_array($position, array('before_excerpt', 'after_excerpt'))) {
            return;
        }
        
        $post_id = get_the_ID();
        if (!$post_id) {
            return;
        }
        
        // Check if this post type should have a player
        $enabled_post_types = get_option('mementor_tts_post_types', array('post'));
        if (!in_array(get_post_type($post_id), $enabled_post_types)) {
            return;
        }
        
        // Check if auto-add is enabled
        $auto_add = get_option('mementor_tts_auto_add_player', '1') === '1';
        if (!$auto_add) {
            return;
        }
        
        // Get player HTML
        $public_instance = new Mementor_TTS_Public('text-to-speech-tts', MEMENTOR_TTS_VERSION);
        
        // Get audio URL
        $audio_url = '';
        if (method_exists($public_instance, 'get_audio_url')) {
            $get_audio_method = new ReflectionMethod($public_instance, 'get_audio_url');
            $get_audio_method->setAccessible(true);
            $audio_url = $get_audio_method->invoke($public_instance, $post_id);
        }
        
        // Only render player if we have a valid audio URL
        if (empty($audio_url)) {
            return;
        }
        
        if (method_exists($public_instance, 'render_player')) {
            $player_html = '<div class="mementor-tts-player-container mementor-tts-automatic">';
            $player_html .= $public_instance->render_player($audio_url, $post_id);
            $player_html .= '</div>';
            
            if (!empty($player_html)) {
                echo $player_html;
            }
        }
    }
    
    /**
     * Filter Uncode content
     */
    public function uncode_filter_content($content, $post_id) {
        // Check if we should add player
        $enabled_post_types = get_option('mementor_tts_post_types', array('post'));
        if (!in_array(get_post_type($post_id), $enabled_post_types)) {
            return $content;
        }
        
        // Check if auto-add is enabled
        $auto_add = get_option('mementor_tts_auto_add_player', '1') === '1';
        if (!$auto_add) {
            return $content;
        }
        
        // Check if player is already in content
        if (strpos($content, 'mementor-tts-player-container') !== false) {
            return $content;
        }
        
        // Get player HTML
        $public_instance = new Mementor_TTS_Public('text-to-speech-tts', MEMENTOR_TTS_VERSION);
        
        // Get audio URL
        $audio_url = '';
        if (method_exists($public_instance, 'get_audio_url')) {
            $get_audio_method = new ReflectionMethod($public_instance, 'get_audio_url');
            $get_audio_method->setAccessible(true);
            $audio_url = $get_audio_method->invoke($public_instance, $post_id);
        }
        
        // Don't render player if no audio URL exists
        if (empty($audio_url)) {
            return $content;
        }
        
        if (method_exists($public_instance, 'render_player')) {
            $player_html = '<div class="mementor-tts-player-container mementor-tts-automatic">';
            $player_html .= $public_instance->render_player($audio_url, $post_id);
            $player_html .= '</div>';
            
            if (!empty($player_html)) {
                $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
                
                // Handle placement based on position setting
                if (in_array($position, array('before_title', 'after_title_before_excerpt', 'after_title_after_excerpt'))) {
                    // These positions should place the player before content
                    $content = $player_html . $content;
                } else {
                    // after_content position
                    $content = $content . $player_html;
                }
            }
        }
        
        return $content;
    }
    
    /**
     * Visual Composer content filter
     */
    public function vc_content_filter($content, $shortcode) {
        // Only process text blocks
        if (!in_array($shortcode, array('vc_column_text', 'vc_custom_heading'))) {
            return $content;
        }

        // Only on singular posts/pages
        if (!is_singular()) {
            return $content;
        }

        // Skip for excerpt positions - handled via the_excerpt filter
        $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
        if (in_array($position, array('before_excerpt', 'after_excerpt'))) {
            return $content;
        }
        
        $post_id = get_the_ID();
        if (!$post_id) {
            return $content;
        }
        
        // Check if this is the main content area
        static $processed = false;
        if ($processed) {
            return $content;
        }
        
        // Check if we should add player
        $enabled_post_types = get_option('mementor_tts_post_types', array('post'));
        if (!in_array(get_post_type($post_id), $enabled_post_types)) {
            return $content;
        }
        
        // Check if auto-add is enabled
        $auto_add = get_option('mementor_tts_auto_add_player', '1') === '1';
        if (!$auto_add) {
            return $content;
        }
        
        // Get player HTML
        $public_instance = new Mementor_TTS_Public('text-to-speech-tts', MEMENTOR_TTS_VERSION);
        
        // Get audio URL
        $audio_url = '';
        if (method_exists($public_instance, 'get_audio_url')) {
            $get_audio_method = new ReflectionMethod($public_instance, 'get_audio_url');
            $get_audio_method->setAccessible(true);
            $audio_url = $get_audio_method->invoke($public_instance, $post_id);
        }
        
        // Don't render player if no audio URL exists
        if (empty($audio_url)) {
            return $content;
        }
        
        if (method_exists($public_instance, 'render_player')) {
            $player_html = '<div class="mementor-tts-player-container mementor-tts-automatic">';
            $player_html .= $public_instance->render_player($audio_url, $post_id);
            $player_html .= '</div>';
            
            if (!empty($player_html)) {
                $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
                
                // Handle placement based on position setting
                if (in_array($position, array('before_title', 'after_title_before_excerpt', 'after_title_after_excerpt'))) {
                    // These positions should place the player before content
                    $content = $player_html . $content;
                    $processed = true;
                } else if ($position === 'after_content') {
                    // For after_content, we need to add it after
                    $content = $content . $player_html;
                    $processed = true;
                }
            }
        }
        
        return $content;
    }
    
    /**
     * Setup Uncode content processing
     */
    public function setup_uncode_content_processing() {
        // Only on singular posts/pages
        if (!is_singular()) {
            return;
        }
        
        // Check if this post type should have a player
        $post_id = get_the_ID();
        if (!$post_id) {
            return;
        }
        
        $enabled_post_types = get_option('mementor_tts_post_types', array('post'));
        if (!in_array(get_post_type($post_id), $enabled_post_types)) {
            return;
        }
        
        // Check if auto-add is enabled
        $auto_add = get_option('mementor_tts_auto_add_player', '1') === '1';
        if (!$auto_add) {
            return;
        }
        
        // Add output buffer to catch Uncode content
        add_action('the_post', array($this, 'start_uncode_buffer'));
        add_action('wp_footer', array($this, 'end_uncode_buffer'), -1);
    }
    
    /**
     * Start output buffering for Uncode
     */
    public function start_uncode_buffer() {
        ob_start(array($this, 'process_uncode_buffer'));
    }
    
    /**
     * End output buffering for Uncode
     */
    public function end_uncode_buffer() {
        if (ob_get_level() > 0) {
            ob_end_flush();
        }
    }
    
    /**
     * Process Uncode output buffer
     */
    public function process_uncode_buffer($buffer) {
        // Skip for excerpt positions - handled via the_excerpt filter
        $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
        if (in_array($position, array('before_excerpt', 'after_excerpt'))) {
            return $buffer;
        }

        // Check if player is already in the buffer
        if (strpos($buffer, 'mementor-tts-player-container') !== false) {
            return $buffer;
        }
        
        // Get player HTML
        $post_id = get_the_ID();
        if (!$post_id) {
            return $buffer;
        }
        
        $public_instance = new Mementor_TTS_Public('text-to-speech-tts', MEMENTOR_TTS_VERSION);
        
        // Get audio URL
        $audio_url = '';
        if (method_exists($public_instance, 'get_audio_url')) {
            $get_audio_method = new ReflectionMethod($public_instance, 'get_audio_url');
            $get_audio_method->setAccessible(true);
            $audio_url = $get_audio_method->invoke($public_instance, $post_id);
        }
        
        // Don't render player if no audio URL exists
        if (empty($audio_url)) {
            return $buffer;
        }
        
        if (!method_exists($public_instance, 'render_player')) {
            return $buffer;
        }
        
        $player_html = '<div class="mementor-tts-player-container mementor-tts-automatic">';
        $player_html .= $public_instance->render_player($audio_url, $post_id);
        $player_html .= '</div>';
        
        if (empty($player_html)) {
            return $buffer;
        }
        
        $position = get_option('mementor_tts_player_position', 'after_title_before_excerpt');
        
        // Try to insert player based on position setting
        if (in_array($position, array('before_title', 'after_title_before_excerpt', 'after_title_after_excerpt'))) {
            // These positions should place the player at the beginning of content
            // Look for the uncode_text_column class
            $pattern = '/(<div[^>]*class="[^"]*uncode_text_column[^"]*"[^>]*>)/i';
            if (preg_match($pattern, $buffer, $matches)) {
                $buffer = preg_replace($pattern, $matches[1] . $player_html, $buffer, 1);
                return $buffer;
            }
            
            // Try wpb_wrapper as fallback
            $pattern = '/(<div[^>]*class="[^"]*wpb_wrapper[^"]*"[^>]*>)/i';
            if (preg_match($pattern, $buffer, $matches)) {
                $buffer = preg_replace($pattern, $matches[1] . $player_html, $buffer, 1);
                return $buffer;
            }
        } else {
            // after_content position - try to insert at the end of content
            // Look for closing uncode_text_column div
            $pattern = '/(<\/div>)([^<]*<div[^>]*class="[^"]*uncode_text_column[^"]*")/i';
            if (preg_match($pattern, $buffer)) {
                // Find the last occurrence of closing div before another uncode_text_column
                $parts = preg_split($pattern, $buffer);
                if (count($parts) > 1) {
                    $last_part = array_pop($parts);
                    $buffer = implode('</div>', $parts) . $player_html . '</div>' . $last_part;
                    return $buffer;
                }
            }
        }
        
        return $buffer;
    }
}

// Initialize the theme compatibility handler
add_action('after_setup_theme', array('Mementor_TTS_Theme_Compatibility', 'get_instance'), 20);