<?php
/**
 * Critical CSS Module
 *
 * Provides Critical CSS inlining and CSS optimization for WooCommerce pages.
 * Improves Core Web Vitals by eliminating render-blocking CSS.
 *
 * @package Mamba\Modules\CriticalCss
 * @since   1.1.0
 */

namespace Mamba\Modules\CriticalCss;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Mamba\Modules\CriticalCss\Services\CriticalCssManager;
use Mamba\Modules\CriticalCss\Services\CssDeferrer;

/**
 * Class Module
 *
 * Main module class for Critical CSS optimization.
 * Handles CSS inlining, deferring, and WooCommerce-specific optimizations.
 *
 * @since 1.1.0
 */
final class Module {
    
    private ?CriticalCssManager $manager = null;
    private ?CssDeferrer $deferrer = null;
    
    /**
     * Register module hooks and services
     */
    public function register(): void {
        // Only run on frontend
        if (is_admin()) {
            return;
        }
        
        // Initialize services
        $this->manager = new CriticalCssManager();
        $this->deferrer = new CssDeferrer();
        
        // Critical CSS Inlining (Free feature)
        if (get_option('mamba_enable_critical_css', 0)) {
            add_action('wp_head', [$this, 'injectCriticalCss'], 1);
        }
        
        // CSS Deferring (Free feature)
        if (get_option('mamba_enable_css_defer', 0)) {
            add_filter('style_loader_tag', [$this->deferrer, 'deferStylesheet'], 10, 4);
            add_action('wp_footer', [$this->deferrer, 'addNoscriptFallback'], 999);
        }
    }
    
    /**
     * Inject critical CSS into the page head
     */
    public function injectCriticalCss(): void {
        if (!$this->manager) {
            return;
        }
        
        $criticalCss = $this->manager->getCriticalCss();
        
        if (empty($criticalCss)) {
            return;
        }
        
        // Output critical CSS via wp_add_inline_style
        wp_register_style('mamba-critical-css', false);
        wp_enqueue_style('mamba-critical-css');
        wp_add_inline_style('mamba-critical-css', wp_strip_all_tags($criticalCss));
    }
    
    /**
     * Check if premium features are available
     */
    private function isPremium(): bool {
        return function_exists('mamba_fs') && mamba_fs()->can_use_premium_code__premium_only();
    }
    
    /**
     * Get the CriticalCssManager instance
     */
    public function getManager(): ?CriticalCssManager {
        return $this->manager;
    }
    
    /**
     * Get the CssDeferrer instance
     */
    public function getDeferrer(): ?CssDeferrer {
        return $this->deferrer;
    }
}
