<?php
/**
 * CSS Compatibility Handler for Text to Speech TTS
 * 
 * Ensures CSS loads correctly with caching and optimization plugins
 * 
 * @package    TTSWP
 * @subpackage Mementor_TTS/includes
 * @since      1.4.3
 */

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

/**
 * CSS Compatibility Class
 * 
 * Handles CSS loading, exclusions, and inline critical CSS for maximum compatibility
 */
class Mementor_TTS_CSS_Compatibility {
    
    /**
     * Instance of this class
     */
    private static $instance = null;
    
    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Initialize compatibility hooks
        $this->init_hooks();
    }
    
    /**
     * Initialize all compatibility hooks
     */
    private function init_hooks() {
        // CSS exclusion filters for various optimization plugins
        add_filter('litespeed_optimize_css_excludes', array($this, 'exclude_from_litespeed'));
        add_filter('rocket_exclude_css', array($this, 'exclude_from_wp_rocket'));
        add_filter('autoptimize_filter_css_exclude', array($this, 'exclude_from_autoptimize'));
        add_filter('w3tc_minify_css_do_exclude_files', array($this, 'exclude_from_w3tc'));
        add_filter('bwp_minify_style_ignore', array($this, 'exclude_from_bwp_minify'));
        add_filter('wpo_minify_exclude_css', array($this, 'exclude_from_wp_optimize'));
        add_filter('sg_optimizer_css_exclude', array($this, 'exclude_from_sg_optimizer'));
        add_filter('swift_performance_css_exclude', array($this, 'exclude_from_swift_performance'));
        add_filter('breeze_filter_css_exclude', array($this, 'exclude_from_breeze'));
        
        // Prevent CSS from being deferred or async loaded
        add_filter('litespeed_optimize_css_defer', array($this, 'prevent_defer_litespeed'), 10, 2);
        add_filter('rocket_async_css', array($this, 'prevent_async_wp_rocket'), 10, 2);
        add_filter('autoptimize_filter_css_defer', array($this, 'prevent_defer_autoptimize'), 10, 2);
        
        // Add critical inline CSS as fallback
        add_action('wp_head', array($this, 'add_critical_inline_css'), 5);
        
        // Ensure our CSS has proper priority
        add_filter('style_loader_tag', array($this, 'modify_style_tag'), 10, 4);
        
        // Add preload hint for our CSS
        add_action('wp_head', array($this, 'add_preload_hints'), 2);
    }
    
    /**
     * Get TTS CSS file patterns
     */
    private function get_css_patterns() {
        return array(
            'mementor-tts-shared',
            'mementor-tts-public',
            'text-to-speech-tts',
            '/text-to-speech-tts/public/css/',
            'mementor-tts'
        );
    }
    
    /**
     * Exclude from LiteSpeed Cache
     */
    public function exclude_from_litespeed($excludes) {
        if (!is_array($excludes)) {
            $excludes = array();
        }
        
        $patterns = $this->get_css_patterns();
        foreach ($patterns as $pattern) {
            $excludes[] = $pattern;
        }
        
        return $excludes;
    }
    
    /**
     * Exclude from WP Rocket
     */
    public function exclude_from_wp_rocket($excluded_files) {
        if (!is_array($excluded_files)) {
            $excluded_files = array();
        }
        
        $excluded_files[] = '/wp-content/plugins/text-to-speech-tts/public/css/(.*).css';
        $excluded_files[] = 'mementor-tts';
        
        return $excluded_files;
    }
    
    /**
     * Exclude from Autoptimize
     */
    public function exclude_from_autoptimize($exclude) {
        $patterns = $this->get_css_patterns();
        $exclude_string = implode(',', $patterns);
        
        if (!empty($exclude)) {
            $exclude .= ',' . $exclude_string;
        } else {
            $exclude = $exclude_string;
        }
        
        return $exclude;
    }
    
    /**
     * Exclude from W3 Total Cache
     */
    public function exclude_from_w3tc($exclude_files) {
        if (!is_array($exclude_files)) {
            $exclude_files = array();
        }
        
        $exclude_files[] = MEMENTOR_TTS_PLUGIN_URL . 'public/css/mementor-tts-shared.css';
        $exclude_files[] = MEMENTOR_TTS_PLUGIN_URL . 'public/css/mementor-tts-public.css';
        
        return $exclude_files;
    }
    
    /**
     * Exclude from BWP Minify
     */
    public function exclude_from_bwp_minify($excluded) {
        if (!is_array($excluded)) {
            $excluded = array();
        }
        
        $patterns = $this->get_css_patterns();
        foreach ($patterns as $pattern) {
            $excluded[] = $pattern;
        }
        
        return $excluded;
    }
    
    /**
     * Exclude from WP-Optimize
     */
    public function exclude_from_wp_optimize($exclude_list) {
        if (!is_array($exclude_list)) {
            $exclude_list = array();
        }
        
        $exclude_list[] = 'mementor-tts';
        $exclude_list[] = 'text-to-speech-tts';
        
        return $exclude_list;
    }
    
    /**
     * Exclude from SG Optimizer
     */
    public function exclude_from_sg_optimizer($exclude_list) {
        if (!is_array($exclude_list)) {
            $exclude_list = array();
        }
        
        $patterns = $this->get_css_patterns();
        foreach ($patterns as $pattern) {
            $exclude_list[] = $pattern;
        }
        
        return $exclude_list;
    }
    
    /**
     * Exclude from Swift Performance
     */
    public function exclude_from_swift_performance($exclude_list) {
        return $this->exclude_from_autoptimize($exclude_list);
    }
    
    /**
     * Exclude from Breeze
     */
    public function exclude_from_breeze($exclude_list) {
        if (!is_array($exclude_list)) {
            $exclude_list = array();
        }
        
        $exclude_list[] = 'mementor-tts';
        
        return $exclude_list;
    }
    
    /**
     * Prevent defer loading in LiteSpeed
     */
    public function prevent_defer_litespeed($defer, $handle) {
        if (strpos($handle, 'mementor-tts') !== false) {
            return false;
        }
        return $defer;
    }
    
    /**
     * Prevent async loading in WP Rocket
     */
    public function prevent_async_wp_rocket($exclude, $handle) {
        if (strpos($handle, 'mementor-tts') !== false) {
            $exclude[] = $handle;
        }
        return $exclude;
    }
    
    /**
     * Prevent defer loading in Autoptimize
     */
    public function prevent_defer_autoptimize($defer, $tag) {
        if (strpos($tag, 'mementor-tts') !== false) {
            return false;
        }
        return $defer;
    }
    
    /**
     * Add critical inline CSS
     */
    public function add_critical_inline_css() {
        // Only add on frontend where player will appear
        if (is_admin() || !is_singular()) {
            return;
        }
        if (!apply_filters('mementor_tts_should_load_assets', false)) {
            return;
        }

        $critical_css = $this->get_critical_css();
        
        if (!empty($critical_css)) {
            echo "\n<!-- Mementor TTS Critical CSS -->\n";
            echo '<style id="mementor-tts-critical-css">' . "\n";
            echo $critical_css . "\n";
            echo "</style>\n";
            echo "<!-- /Mementor TTS Critical CSS -->\n\n";
        }
    }
    
    /**
     * Get critical CSS for inline injection
     */
    private function get_critical_css() {
        // Add dashicons font-face as fallback
        $dashicons_url = includes_url('fonts/dashicons.woff');
        
        $css = '
/* Dashicons font-face fallback */
@font-face {
    font-family: dashicons;
    src: url("' . $dashicons_url . '") format("woff");
    font-weight: normal;
    font-style: normal;
    font-display: block;
}
/* Mementor TTS Critical Player Styles */
.mementor-tts-player-container {
    width: 100% !important;
    max-width: var(--mementor-tts-max-width, 100%) !important;
    margin: 1.5em 0 !important;
    display: block !important;
    clear: both !important;
    position: relative !important;
    box-sizing: border-box !important;
}

.mementor-tts-player {
    width: 100% !important;
    box-sizing: border-box !important;
    overflow: hidden !important;
}

.mementor-tts-custom-controls {
    display: flex !important;
    align-items: center !important;
    gap: 8px !important;
    padding: 15px !important;
    background-color: #f6f7fb !important;
    border: 1px solid #dcdcde !important;
    border-radius: 4px !important;
    flex-wrap: wrap !important;
    width: 100% !important;
    box-sizing: border-box !important;
}

.mementor-tts-play-button {
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    width: 36px !important;
    height: 36px !important;
    background-color: #ffffff !important;
    border: 1px solid #dcdcde !important;
    border-radius: 50% !important;
    cursor: pointer !important;
    padding: 0 !important;
    position: relative !important;
}

.mementor-tts-play-button .dashicons,
.mementor-tts-play-button .mementor-dashicons {
    font-size: 24px !important;
    width: 24px !important;
    height: 24px !important;
    line-height: 1 !important;
    color: #2271b1 !important;
}

.mementor-tts-progress-container {
    flex-grow: 1 !important;
    height: 8px !important;
    background-color: #e0e0e0 !important;
    border-radius: 4px !important;
    cursor: pointer !important;
    position: relative !important;
}

.mementor-tts-progress-bar {
    height: 100% !important;
    background-color: #2271b1 !important;
    border-radius: 4px !important;
    width: 0 !important;
    transition: width 0.1s linear !important;
}

.mementor-tts-time-display,
.mementor-tts-duration-display {
    font-family: monospace !important;
    font-size: 14px !important;
    color: #50575e !important;
    min-width: 45px !important;
}

/* Custom dashicons fallback */
.mementor-dashicons-controls-play:before { content: "\f522" !important; }
.mementor-dashicons-controls-pause:before { content: "\f523" !important; }
.mementor-dashicons-controls-volumeon:before { content: "\f521" !important; }
.mementor-dashicons-controls-volumeoff:before { content: "\f520" !important; }
.mementor-dashicons-download:before { content: "\f316" !important; }
.mementor-dashicons-info:before { content: "\f348" !important; }

/* Mobile responsiveness */
@media (max-width: 600px) {
    .mementor-tts-custom-controls {
        gap: 8px !important;
        padding: 10px !important;
    }
    
    .mementor-tts-progress-container {
        order: 1 !important;
        width: 100% !important;
        flex-basis: 100% !important;
    }
}';
        
        // Minify the CSS
        $css = preg_replace('/\s+/', ' ', $css);
        $css = preg_replace('/\/\*.*?\*\//', '', $css);
        $css = str_replace(array('; ', ' {', '{ ', ' }', '} ', ': ', ' !'), array(';', '{', '{', '}', '}', ':', '!'), $css);
        
        return trim($css);
    }
    
    /**
     * Modify style tag to add attributes
     */
    public function modify_style_tag($html, $handle, $href, $media) {
        if (strpos($handle, 'mementor-tts') !== false) {
            // Only add attributes if not already present
            if (strpos($html, 'data-no-optimize') === false) {
                // Add data attributes to prevent optimization and Weglot translation
                $html = str_replace(
                    '<link',
                    '<link data-no-optimize="1" data-no-defer="1" data-no-minify="1" data-no-combine="1" data-wg-notranslate="true"',
                    $html
                );
            }
        }

        return $html;
    }
    
    /**
     * Add preload hints for CSS
     */
    public function add_preload_hints() {
        // Only on frontend where player will appear
        if (is_admin() || !is_singular()) {
            return;
        }
        if (!apply_filters('mementor_tts_should_load_assets', false)) {
            return;
        }

        // Preload our CSS files
        echo '<link rel="preload" href="' . esc_url(MEMENTOR_TTS_PLUGIN_URL . 'public/css/mementor-tts-shared.css?ver=' . MEMENTOR_TTS_VERSION) . '" as="style">' . "\n";

        // Preload dashicons if not already loaded
        if (!wp_style_is('dashicons', 'registered')) {
            echo '<link rel="preload" href="' . esc_url(includes_url('css/dashicons.min.css')) . '" as="style">' . "\n";
        }
    }
}

// Initialize the compatibility handler
add_action('init', array('Mementor_TTS_CSS_Compatibility', 'get_instance'), 1);