<?php
/**
 * HVAC Scripts and Styles Manager
 *
 * Centralized management of all plugin scripts and styles
 *
 * @package HVAC_Community_Events
 * @since 2.0.0
 */

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

/**
 * HVAC_Scripts_Styles class
 */
class HVAC_Scripts_Styles {
    
    /**
     * Instance
     * 
     * @var HVAC_Scripts_Styles
     */
    private static $instance = null;
    
    /**
     * Script version for cache busting
     * 
     * @var string
     */
    private $version;
    
    /**
     * Get instance
     * 
     * @return HVAC_Scripts_Styles
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        $this->version = HVAC_PLUGIN_VERSION;
        $this->init_hooks();
        
        // Add Safari body class for CSS targeting
        if ($this->is_safari_browser()) {
            add_filter('body_class', array($this, 'add_safari_body_class'));
        }
    }
    
    /**
     * Detect if user is using Safari browser
     * Uses centralized browser detection service
     * 
     * @return bool
     */
    public function is_safari_browser() {
        return HVAC_Browser_Detection::instance()->is_safari_browser();
    }
    
    /**
     * Check if we should use legacy scripts system
     * CRITICAL: Prevents conflicts with bundled assets system
     * 
     * @return bool
     */
    private function should_use_legacy_scripts() {
        // Always use legacy if bundled assets are disabled
        if (defined('HVAC_FORCE_LEGACY_SCRIPTS') && HVAC_FORCE_LEGACY_SCRIPTS) {
            return true;
        }
        
        // Use legacy in development by default
        if (defined('WP_DEBUG') && WP_DEBUG && (!defined('HVAC_USE_BUNDLES') || !HVAC_USE_BUNDLES)) {
            return true;
        }
        
        // Use legacy for Safari browsers for compatibility
        if (class_exists('HVAC_Browser_Detection')) {
            $browser_detection = HVAC_Browser_Detection::instance();
            if ($browser_detection->is_safari_browser()) {
                return true;
            }
        }
        
        // Check if bundled assets class is using legacy fallback
        if (class_exists('HVAC_Bundled_Assets')) {
            // If bundled assets are not being used, use legacy
            return true; 
        }
        
        return false;
    }
    
    /**
     * Get script path based on browser compatibility
     * Uses centralized browser detection service
     * 
     * @param string $script_name
     * @return string
     */
    public function get_compatible_script_path($script_name) {
        $browser_detection = HVAC_Browser_Detection::instance();
        
        // If Safari and doesn't support ES6, load Safari-compatible version
        if ($browser_detection->is_safari_browser() && !$browser_detection->safari_supports_es6()) {
            $safari_script = HVAC_PLUGIN_DIR . 'assets/js/' . $script_name . '-safari-compatible.js';
            if (file_exists($safari_script)) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('[HVAC Scripts Styles] Loading Safari-compatible script: ' . $script_name . '-safari-compatible.js');
                }
                return HVAC_PLUGIN_URL . 'assets/js/' . $script_name . '-safari-compatible.js';
            }
        }
        
        // Default to standard version
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $browser_info = $browser_detection->get_browser_info();
            error_log('[HVAC Scripts Styles] Loading standard script: ' . $script_name . '.js | Browser: ' . json_encode($browser_info));
        }
        return HVAC_PLUGIN_URL . 'assets/js/' . $script_name . '.js';
    }
    
    /**
     * Initialize hooks
     * 
     * @return void
     */
    private function init_hooks() {
        // CRITICAL FIX: Only initialize if bundled assets system is not active
        // This prevents dual script loading conflicts
        if ($this->should_use_legacy_scripts()) {
            // Safari-specific resource loading bypass to prevent resource cascade hanging
            if ($this->is_safari_browser()) {
                add_action('wp_enqueue_scripts', array($this, 'enqueue_safari_minimal_assets'), 5);
                // Prevent other components from loading excessive resources
                add_action('wp_enqueue_scripts', array($this, 'disable_non_critical_assets'), 999);
            } else {
                // Frontend scripts and styles for non-Safari browsers
                add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_assets'), 10);
            }
        }
        
        // BULLETPROOF FALLBACK: Ensure jQuery loads on critical master trainer pages
        // This runs regardless of whether bundled or legacy scripts are active
        add_action('wp_enqueue_scripts', array($this, 'ensure_jquery_on_master_pages'), 1);
        
        // Admin scripts and styles (always load)
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        
        // Login page scripts and styles (always load)
        add_action('login_enqueue_scripts', array($this, 'enqueue_login_assets'));
    }
    
    /**
     * Enqueue minimal assets for Safari browsers to prevent resource cascade hanging
     * Enhanced with bulletproof jQuery loading for master trainer pages
     * 
     * @return void
     */
    public function enqueue_safari_minimal_assets() {
        // BULLETPROOF JQUERY LOADING: Always load jQuery for master trainer pages
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        $force_jquery_pages = array('master-trainer/master-dashboard', 'master-trainer/announcements', 'master-trainer/import-export');
        $should_force_jquery = false;
        
        foreach ($force_jquery_pages as $force_page) {
            if (strpos($current_path, $force_page) !== false) {
                $should_force_jquery = true;
                break;
            }
        }
        
        // Only enqueue on plugin pages OR force jQuery for problematic master trainer pages
        if (!$this->is_plugin_page() && !$should_force_jquery) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('[HVAC Scripts] Safari assets skipped - not a plugin page: ' . $current_path);
            }
            return;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $detection_method = $should_force_jquery ? 'FORCED for master trainer page' : 'plugin page detected';
            error_log('[HVAC Scripts Styles] Loading Safari minimal assets - ' . $detection_method . ': ' . $current_path);
        }
        
        // Load Safari reload prevention FIRST (critical for preventing crashes)
        wp_enqueue_script(
            'hvac-safari-reload-prevention',
            HVAC_PLUGIN_URL . 'assets/js/safari-reload-prevention.js',
            array(), // No dependencies - needs to run immediately
            $this->version,
            false // Load in header for early execution
        );
        
        // CRITICAL FIX: Force jQuery to load first with highest priority for Safari
        wp_enqueue_script('jquery');
        
        // Enhanced jQuery validation and error reporting
        $jquery_validation_script = '
        /* HVAC Safari jQuery dependency validation */
        if (typeof jQuery === "undefined") {
            console.error("HVAC CRITICAL ERROR: jQuery failed to load on master trainer page - Path: " + window.location.pathname);
            // Attempt to detect and report the specific issue
            if (window.hvac_jquery_error_callback) {
                window.hvac_jquery_error_callback("master_trainer_page_jquery_failure");
            }
            // Store error for debugging
            window.hvac_jquery_load_error = {
                page: window.location.pathname,
                timestamp: new Date().toISOString(),
                userAgent: navigator.userAgent.substring(0, 100)
            };
        } else {
            console.log("HVAC: jQuery successfully loaded on master trainer page - " + window.location.pathname);
            // Mark jQuery as successfully loaded for other scripts
            window.hvac_jquery_loaded = true;
        }';
        
        wp_add_inline_script('jquery', $jquery_validation_script, 'after');
        
        // Load Safari AJAX handler with timeout and retry logic
        wp_enqueue_script(
            'hvac-safari-ajax-handler',
            HVAC_PLUGIN_URL . 'assets/js/safari-ajax-handler.js',
            array('jquery'),
            $this->version,
            false // Load in header for early availability
        );
        
        // Load Safari ITP-compatible storage
        wp_enqueue_script(
            'hvac-safari-storage',
            HVAC_PLUGIN_URL . 'assets/js/safari-storage.js',
            array(),
            $this->version,
            false // Load in header for early availability
        );
        
        // Load feature detection system
        wp_enqueue_script(
            'hvac-feature-detection',
            HVAC_PLUGIN_URL . 'assets/js/feature-detection.js',
            array(),
            $this->version,
            false // Load in header for early detection
        );
        
        // Load only ONE consolidated CSS file to prevent cascade
        wp_enqueue_style(
            'hvac-safari-minimal',
            HVAC_PLUGIN_URL . 'assets/css/hvac-community-events.css',
            array(),
            $this->version
        );
        
        // CRITICAL: Load Master Trainer layout fixes for Safari browsers
        // This ensures Master Trainer pages have proper single-column layout
        wp_enqueue_style(
            'hvac-page-templates-safari',
            HVAC_PLUGIN_URL . 'assets/css/hvac-page-templates.css',
            array('hvac-safari-minimal'),
            $this->version
        );
        
        // Load minimal JavaScript - ensure jQuery dependency is met
        wp_enqueue_script(
            'hvac-safari-minimal-js',
            HVAC_PLUGIN_URL . 'assets/js/hvac-community-events.js',
            array('jquery'),
            $this->version,
            true
        );
        
        // Essential localization only
        wp_localize_script('hvac-safari-minimal-js', 'hvac_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_ajax_nonce'),
            'is_logged_in' => is_user_logged_in(),
            'plugin_url' => HVAC_PLUGIN_URL,
        ));
        
        // Apply Safari-specific CSS fixes for Safari 18 float bug
        $this->add_safari_css_fixes();
        
        // DISABLED - Using TEC Community Events 5.x instead
        // if ($this->is_event_manage_page() || $this->is_create_event_page() || $this->is_edit_event_page()) {
        //     wp_enqueue_script(
        //         'hvac-rest-api-event-submission',
        //         HVAC_PLUGIN_URL . 'assets/js/hvac-rest-api-event-submission.js',
        //         array('jquery'),
        //         $this->version,
        //         true
        //     );
        //     
        //     wp_localize_script('hvac-rest-api-event-submission', 'hvac_ajax', array(
        //         'ajaxurl' => admin_url('admin-ajax.php'),
        //         'nonce' => wp_create_nonce('hvac_ajax_nonce')
        //     ));
        // }
    }
    
    /**
     * Disable non-critical assets for Safari browsers to prevent resource overload
     * 
     * @return void
     */
    public function disable_non_critical_assets() {
        // Only run on plugin pages
        if (!$this->is_plugin_page()) {
            return;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[HVAC Scripts Styles] CRITICAL: Disabling ALL plugin component assets for Safari resource bypass');
        }
        
        // CRITICAL FIX: Remove ALL hooks from other plugin components that load assets
        // This prevents the resource cascade that Safari can't handle
        $this->remove_conflicting_asset_hooks();
        
        // Dequeue ALL additional CSS files that may have been enqueued by other components
        // CRITICAL: Keep hvac-page-templates for Master Trainer layout fixes
        $css_handles_to_remove = [
            // 'hvac-page-templates', // REMOVED - This contains critical Master Trainer layout fixes
            'hvac-layout', 
            'hvac-common',
            'hvac-accessibility-fixes',
            'hvac-mobile-responsive',
            'hvac-dashboard',
            'hvac-dashboard-enhanced',
            'hvac-registration',
            'communication-templates',
            'hvac-certificates',
            'hvac-certificates-enhanced',
            'hvac-certificate-reports',
            'hvac-generate-certificates',
            'hvac-organizers',
            'hvac-venues',
            'hvac-trainer-profile',
            'hvac-profile-sharing',
            'hvac-event-manage',
            'hvac-menu-system',
            'hvac-breadcrumbs',
            'hvac-welcome-popup',
            'hvac-announcements',
            'hvac-help-system',
        ];
        
        foreach ($css_handles_to_remove as $handle) {
            wp_dequeue_style($handle);
            wp_deregister_style($handle);
        }
        
        // Dequeue ALL non-essential JavaScript to prevent resource cascade
        $js_handles_to_remove = [
            'hvac-dashboard',
            'hvac-dashboard-enhanced',
            'hvac-registration',
            'hvac-profile-sharing',
            'hvac-help-system',
            'hvac-menu-system',
            'hvac-breadcrumbs',
            'hvac-welcome-popup',
            'hvac-organizers',
            'hvac-venues',
            'hvac-announcements',
        ];
        
        foreach ($js_handles_to_remove as $handle) {
            wp_dequeue_script($handle);
            wp_deregister_script($handle);
        }
    }
    
    /**
     * Remove conflicting asset hooks from other plugin components
     * Prevents 15+ plugin components from loading assets when Safari is detected
     * 
     * @return void
     */
    private function remove_conflicting_asset_hooks() {
        global $wp_filter;
        
        // List of plugin components that load assets via wp_enqueue_scripts
        $conflicting_components = [
            'HVAC_Find_Trainer_Assets' => 'enqueue_find_trainer_assets',
            'HVAC_Dashboard' => 'enqueue_dashboard_assets',
            'HVAC_Organizers' => 'enqueue_organizer_assets',
            'HVAC_Venues' => 'enqueue_venue_assets',
            'HVAC_Menu_System' => 'enqueue_menu_assets',
            'HVAC_Breadcrumbs' => 'enqueue_breadcrumb_assets',
            'HVAC_Welcome_Popup' => 'enqueue_popup_assets',
            'HVAC_Announcements' => 'enqueue_announcement_assets',
            'HVAC_Help_System' => 'enqueue_help_assets',
            'HVAC_Certificate_Reports' => 'enqueue_certificate_assets',
            'HVAC_Generate_Certificates' => 'enqueue_generate_assets',
            'HVAC_Training_Leads' => 'enqueue_leads_assets',
            'HVAC_Communication_Templates' => 'enqueue_templates_assets',
            'HVAC_Master_Events' => 'enqueue_master_events_assets',
            'HVAC_Import_Export' => 'enqueue_import_export_assets'
        ];
        
        // Remove wp_enqueue_scripts hooks from all components to prevent resource cascade
        foreach ($conflicting_components as $class_name => $method_name) {
            if (class_exists($class_name) && method_exists($class_name, 'instance')) {
                $instance = call_user_func(array($class_name, 'instance'));
                
                // Try multiple common callback formats
                $callbacks_to_remove = [
                    array($instance, $method_name),
                    array($instance, 'enqueue_assets'),
                    array($instance, 'enqueue_scripts'),
                    array($instance, 'enqueue_styles')
                ];
                
                foreach ($callbacks_to_remove as $callback) {
                    if (method_exists($instance, $callback[1])) {
                        remove_action('wp_enqueue_scripts', $callback, 10);
                        remove_action('wp_enqueue_scripts', $callback, 20);
                        remove_action('wp_enqueue_scripts', $callback, 999);
                        
                        // Log hook removal for debugging
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                            error_log('[SAFARI-BLOCKER] Removed wp_enqueue_scripts hook: ' . $class_name . '::' . $callback[1]);
                        }
                    }
                }
            }
        }
        
        // Also remove hooks by examining wp_filter directly for any remaining asset loading hooks
        if (isset($wp_filter['wp_enqueue_scripts'])) {
            foreach ($wp_filter['wp_enqueue_scripts']->callbacks as $priority => $callbacks) {
                foreach ($callbacks as $callback_key => $callback_data) {
                    $callback = $callback_data['function'];
                    
                    // Check if callback is from HVAC plugin component
                    if (is_array($callback) && is_object($callback[0])) {
                        $class_name = get_class($callback[0]);
                        if (strpos($class_name, 'HVAC_') === 0 && $class_name !== 'HVAC_Scripts_Styles') {
                            remove_action('wp_enqueue_scripts', $callback, $priority);
                            
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                                error_log('[SAFARI-BLOCKER] Removed wp_enqueue_scripts hook via filter: ' . $class_name . '::' . (is_string($callback[1]) ? $callback[1] : 'unknown'));
                            }
                        }
                    }
                }
            }
        }
        
        // Additional safety: disable asset loading flags for components
        if (!defined('HVAC_SAFARI_MINIMAL_MODE')) {
            define('HVAC_SAFARI_MINIMAL_MODE', true);
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[SAFARI-BLOCKER] Conflicting asset hooks removed - Safari minimal mode activated');
        }
    }
    
    /**
     * Add Safari body class for CSS targeting
     * 
     * @param array $classes Existing body classes
     * @return array Modified body classes
     */
    public function add_safari_body_class($classes) {
        $classes[] = 'safari-browser';
        
        // Add version-specific class if available
        $browser_info = HVAC_Browser_Detection::instance()->get_browser_info();
        if (!empty($browser_info['safari_version'])) {
            $version = floor(floatval($browser_info['safari_version']));
            $classes[] = 'safari-' . $version;
        }
        
        // Add mobile Safari class if applicable
        if (!empty($browser_info['is_mobile_safari'])) {
            $classes[] = 'safari-mobile';
        }
        
        return $classes;
    }
    
    /**
     * Add Safari-specific CSS fixes for known issues
     * Particularly addresses Safari 18 float bug that breaks layouts
     * 
     * @return void
     */
    public function add_safari_css_fixes() {
        if (!$this->is_safari_browser()) {
            return;
        }
        
        // Critical Safari 18 CSS float bug fix and other compatibility fixes
        $safari_css = '
            /* Safari 18 Float Bug Fix - Prevents layout crash */
            .hvac-trainer-grid,
            .hvac-find-trainer-container,
            .hvac-trainer-card,
            #postbox-container-2 {
                clear: left !important;
                float: none !important;
                width: auto !important;
            }
            
            /* Prevent Safari rendering crashes with GPU acceleration */
            .hvac-trainer-card,
            .hvac-modal,
            .hvac-map-container {
                -webkit-transform: translate3d(0, 0, 0);
                -webkit-backface-visibility: hidden;
                -webkit-perspective: 1000;
            }
            
            /* Safari-specific flexbox fixes */
            .hvac-trainer-grid {
                display: -webkit-flex;
                display: flex;
                -webkit-flex-wrap: wrap;
                flex-wrap: wrap;
            }
            
            /* Prevent Safari overflow issues */
            body.safari-browser {
                -webkit-overflow-scrolling: touch;
            }
            
            /* Fix Safari z-index stacking context issues */
            .hvac-modal-overlay {
                -webkit-transform: translateZ(0);
                transform: translateZ(0);
            }
            
            /* Safari iOS specific fixes */
            @supports (-webkit-touch-callout: none) {
                /* iOS Safari fixes */
                .hvac-trainer-card {
                    -webkit-tap-highlight-color: transparent;
                }
                
                /* Prevent iOS Safari zoom on form inputs */
                input[type="text"],
                input[type="email"],
                input[type="tel"],
                textarea {
                    font-size: 16px !important;
                }
            }
        ';
        
        // Add inline styles with high priority
        wp_add_inline_style('hvac-community-events', $safari_css);
        
        // Also add to find-trainer specific styles if that's loaded
        if (wp_style_is('hvac-find-trainer', 'enqueued')) {
            wp_add_inline_style('hvac-find-trainer', $safari_css);
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[HVAC Safari CSS] Applied Safari 18 float bug fixes and compatibility styles');
        }
    }
    
    /**
     * Enqueue frontend assets
     * 
     * @return void
     */
    public function enqueue_frontend_assets() {
        // Only enqueue on plugin pages
        if (!$this->is_plugin_page()) {
            return;
        }
        
        // Always include mobile navigation fix
        wp_enqueue_style(
            'hvac-mobile-nav-fix',
            HVAC_PLUGIN_URL . 'assets/css/hvac-mobile-navigation-fix.css',
            array(),
            $this->version
        );
        
        // Check if CSS optimization is enabled and consolidated file exists
        if ($this->should_use_consolidated_css()) {
            $this->enqueue_consolidated_css();
            return;
        }
        
        // Fallback to individual CSS files (original system)
        $this->enqueue_individual_css_files();
    }
    
    /**
     * Check if consolidated CSS should be used
     * 
     * @return bool
     */
    private function should_use_consolidated_css() {
        // Check if consolidated CSS file exists
        $consolidated_file = HVAC_PLUGIN_DIR . 'assets/css/hvac-consolidated.css';
        return file_exists($consolidated_file) && !defined('HVAC_CSS_DEBUG');
    }
    
    /**
     * Enqueue consolidated CSS file
     * 
     * @return void
     */
    private function enqueue_consolidated_css() {
        // Load design system first
        wp_enqueue_style(
            'hvac-design-system',
            HVAC_PLUGIN_URL . 'assets/css/hvac-design-system.css',
            array(),
            $this->version
        );
        
        // Load component library
        wp_enqueue_style(
            'hvac-components',
            HVAC_PLUGIN_URL . 'assets/css/hvac-components.css',
            array('hvac-design-system'),
            $this->version
        );
        
        // Navigation styles now handled by consolidated core CSS
        // Removed hvac-navigation-simple.css to prevent CSS conflicts
        // The consolidated core CSS has proper flex-direction: row declarations
        
        // Always load full core bundle (contains navigation CSS)
        wp_enqueue_style(
            'hvac-consolidated-core',
            HVAC_PLUGIN_URL . 'assets/css/hvac-consolidated-core.css',
            array('hvac-design-system', 'hvac-components'),
            $this->version
        );
        
        // CRITICAL: Load navigation overflow fix - MUST be after consolidated-core
        wp_enqueue_style(
            'hvac-navigation-fix',
            HVAC_PLUGIN_URL . 'assets/css/hvac-navigation-fix.css',
            array('hvac-consolidated-core'),
            $this->version . '.2'  // Force cache bust
        );
        
        // Load master trainer navigation styles for users with master trainer role
        $user = wp_get_current_user();
        if (in_array('hvac_master_trainer', $user->roles) || current_user_can('manage_options')) {
            wp_enqueue_style(
                'hvac-master-navigation',
                HVAC_PLUGIN_URL . 'assets/css/hvac-master-navigation.css',
                array('hvac-navigation-fix'),
                $this->version
            );
        }
        
        // Load fixed dashboard bundle for dashboard/management pages
        if ($this->is_dashboard_page() || $this->is_event_manage_page()) {
            wp_enqueue_style(
                'hvac-consolidated-dashboard',
                HVAC_PLUGIN_URL . 'assets/css/hvac-consolidated-dashboard-fixed.css',
                array('hvac-consolidated-core'),
                $this->version
            );
            
            // Load master dashboard specific styles to fix layout issues
            if ($this->is_master_dashboard_page()) {
                wp_enqueue_style(
                    'hvac-master-dashboard',
                    HVAC_PLUGIN_URL . 'assets/css/hvac-master-dashboard.css',
                    array('hvac-consolidated-dashboard'),
                    $this->version
                );
            }
        }
        
        // Load fixed forms bundle for registration/profile pages
        if ($this->is_registration_page() || $this->is_trainer_profile_page() || 
            $this->is_organizers_page() || $this->is_venues_page()) {
            wp_enqueue_style(
                'hvac-consolidated-forms',
                HVAC_PLUGIN_URL . 'assets/css/hvac-consolidated-forms-fixed.css',
                array('hvac-consolidated-core'),
                $this->version
            );
        }
        
        // Load pending approvals styles
        if ($this->is_pending_approvals_page()) {
            wp_enqueue_style(
                'hvac-master-pending-approvals',
                HVAC_PLUGIN_URL . 'assets/css/hvac-master-pending-approvals.css',
                array('hvac-consolidated-core'),
                $this->version
            );
        }
        
        // Load master events overview styles
        if ($this->is_master_events_page()) {
            wp_enqueue_style(
                'hvac-master-events-overview',
                HVAC_PLUGIN_URL . 'assets/css/hvac-master-events-overview.css',
                array('hvac-consolidated-core'),
                $this->version
            );
        }
        
        // Load certificates bundle for certificate pages
        if ($this->is_certificate_page()) {
            wp_enqueue_style(
                'hvac-consolidated-certificates',
                HVAC_PLUGIN_URL . 'assets/css/hvac-consolidated-certificates.css',
                array('hvac-consolidated-core'),
                $this->version
            );
        }
        
        // Note: page-specific JavaScript is still enqueued separately
        $this->enqueue_page_specific_scripts();
    }
    
    /**
     * Enqueue page-specific JavaScript
     * 
     * @return void
     */
    private function enqueue_page_specific_scripts() {
        // CRITICAL FIX: Force jQuery to load first with highest priority
        wp_enqueue_script('jquery');
        
        // Add detection script to verify jQuery is loaded
        wp_add_inline_script('jquery', '
            if (typeof jQuery === "undefined") {
                console.error("HVAC CRITICAL ERROR: jQuery failed to load on master trainer page");
                if (window.hvac_jquery_error_callback) {
                    window.hvac_jquery_error_callback();
                }
            } else {
                console.log("HVAC: jQuery successfully loaded");
            }
        ', 'after');
        
        // Main plugin scripts
        wp_enqueue_script(
            'hvac-community-events',
            HVAC_PLUGIN_URL . 'assets/js/hvac-community-events.js',
            array('jquery'),
            $this->version,
            true
        );
        
        // Robust navigation functionality
        wp_enqueue_script(
            'hvac-navigation-robust',
            HVAC_PLUGIN_URL . 'assets/js/hvac-navigation-robust.js',
            array('jquery'),
            $this->version,
            true
        );
        
        // Mobile responsive functionality
        wp_enqueue_script(
            'hvac-mobile-responsive',
            HVAC_PLUGIN_URL . 'assets/js/hvac-mobile-responsive.js',
            array('jquery', 'hvac-community-events'),
            $this->version,
            true
        );
        
        // Dashboard scripts
        if ($this->is_dashboard_page()) {
            wp_enqueue_script(
                'hvac-dashboard',
                HVAC_PLUGIN_URL . 'assets/js/hvac-dashboard.js',
                array('jquery', 'hvac-community-events'),
                $this->version,
                true
            );
            
            wp_enqueue_script(
                'hvac-dashboard-enhanced',
                HVAC_PLUGIN_URL . 'assets/js/hvac-dashboard-enhanced.js',
                array('hvac-dashboard'),
                $this->version,
                true
            );
        }
        
        // Registration scripts
        if ($this->is_registration_page()) {
            wp_enqueue_script(
                'hvac-registration',
                $this->get_compatible_script_path('hvac-registration'),
                array('jquery', 'hvac-community-events'),
                $this->version,
                true
            );
        }
        
        // Trainer profile scripts
        if ($this->is_trainer_profile_page()) {
            wp_enqueue_script(
                'hvac-profile-sharing',
                HVAC_PLUGIN_URL . 'assets/js/hvac-profile-sharing.js',
                array('jquery', 'hvac-community-events'),
                $this->version,
                true
            );
        }
        
        // Master events overview scripts
        if ($this->is_master_events_page()) {
            wp_enqueue_script(
                'hvac-master-events-overview',
                HVAC_PLUGIN_URL . 'assets/js/hvac-master-events-overview.js',
                array('jquery', 'hvac-community-events'),
                $this->version,
                true
            );
        }
        
        // Help system scripts
        wp_enqueue_script(
            'hvac-help-system',
            HVAC_PLUGIN_URL . 'assets/js/hvac-help-system.js',
            array('jquery'),
            $this->version,
            true
        );
        
        // Localize scripts
        wp_localize_script('hvac-community-events', 'hvac_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_ajax_nonce'),
            'is_logged_in' => is_user_logged_in(),
            'plugin_url' => HVAC_PLUGIN_URL,
        ));
        
        // Localize dashboard script
        if ($this->is_dashboard_page()) {
            wp_localize_script('hvac-dashboard', 'hvac_dashboard', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('hvac_dashboard_nonce'),
                'strings' => array(
                    'loading' => __('Loading...', 'hvac-community-events'),
                    'error' => __('An error occurred. Please try again.', 'hvac-community-events'),
                ),
            ));
        }
        
        // Localize profile sharing script
        if ($this->is_trainer_profile_page()) {
            wp_localize_script('hvac-profile-sharing', 'hvac_sharing', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('hvac_profile_sharing'),
                'strings' => array(
                    'loading' => __('Loading...', 'hvac-community-events'),
                    'error' => __('An error occurred. Please try again.', 'hvac-community-events'),
                    'copied' => __('Copied to clipboard!', 'hvac-community-events'),
                    'copy_error' => __('Unable to copy. Please select and copy manually.', 'hvac-community-events'),
                    'loading_error' => __('Unable to load profile card. Please try again.', 'hvac-community-events')
                ),
            ));
        }
        
        // Enqueue pending approvals assets
        $this->enqueue_pending_approvals_assets();
        
        // Import/Export scripts
        if ($this->is_import_export_page()) {
            wp_enqueue_script(
                'hvac-import-export',
                HVAC_PLUGIN_URL . 'assets/js/hvac-import-export.js',
                array('jquery', 'hvac-community-events'),
                $this->version,
                true
            );
        }
    }
    
    /**
     * Enqueue individual CSS files (original system)
     * 
     * @return void
     */
    private function enqueue_individual_css_files() {
        // Main plugin styles - load on ALL plugin pages
        wp_enqueue_style(
            'hvac-community-events',
            HVAC_PLUGIN_URL . 'assets/css/hvac-community-events.css',
            array(),
            $this->version
        );
        
        // Page templates styles - ensures proper layout for all HVAC pages
        wp_enqueue_style(
            'hvac-page-templates',
            HVAC_PLUGIN_URL . 'assets/css/hvac-page-templates.css',
            array(),
            $this->version
        );
        
        // Layout styles - ensure proper container width and padding
        wp_enqueue_style(
            'hvac-layout',
            HVAC_PLUGIN_URL . 'assets/css/hvac-layout.css',
            array('hvac-community-events'),
            $this->version
        );
        
        // Common styles for all trainer pages - ensures consistent styling
        wp_enqueue_style(
            'hvac-common',
            HVAC_PLUGIN_URL . 'assets/css/hvac-common.css',
            array(),
            $this->version
        );
        
        // Accessibility fixes
        wp_enqueue_style(
            'hvac-accessibility-fixes',
            HVAC_PLUGIN_URL . 'assets/css/hvac-accessibility-fixes.css',
            array('hvac-common'),
            $this->version
        );
        
        // Mobile responsive optimizations - Load after base styles
        wp_enqueue_style(
            'hvac-mobile-responsive',
            HVAC_PLUGIN_URL . 'assets/css/hvac-mobile-responsive.css',
            array('hvac-common', 'hvac-accessibility-fixes'),
            $this->version
        );
        
        // CRITICAL: Load navigation overflow fix - MUST be loaded after other styles
        wp_enqueue_style(
            'hvac-navigation-fix',
            HVAC_PLUGIN_URL . 'assets/css/hvac-navigation-fix.css',
            array('hvac-mobile-responsive'),
            $this->version . '.2'  // Force cache bust
        );
        
        // Load master trainer navigation styles for users with master trainer role
        $user = wp_get_current_user();
        if (in_array('hvac_master_trainer', $user->roles) || current_user_can('manage_options')) {
            wp_enqueue_style(
                'hvac-master-navigation',
                HVAC_PLUGIN_URL . 'assets/css/hvac-master-navigation.css',
                array('hvac-navigation-fix'),
                $this->version
            );
        }
        
        // Load the rest of the page-specific CSS
        $this->enqueue_page_specific_css();
    }
    
    /**
     * Enqueue page-specific CSS (used by both consolidated and individual systems)
     * 
     * @return void
     */
    private function enqueue_page_specific_css() {
        // Dashboard styles
        if ($this->is_dashboard_page()) {
            wp_enqueue_style(
                'hvac-dashboard',
                HVAC_PLUGIN_URL . 'assets/css/hvac-dashboard.css',
                array('hvac-community-events'),
                $this->version
            );
            
            wp_enqueue_style(
                'hvac-dashboard-enhanced',
                HVAC_PLUGIN_URL . 'assets/css/hvac-dashboard-enhanced.css',
                array('hvac-dashboard'),
                $this->version
            );
        }
        
        // Registration styles
        if ($this->is_registration_page()) {
            wp_enqueue_style(
                'hvac-registration',
                HVAC_PLUGIN_URL . 'assets/css/hvac-registration.css',
                array('hvac-community-events'),
                $this->version
            );
        }
        
        // Communication templates styles
        if ($this->is_communication_page()) {
            wp_enqueue_style(
                'communication-templates',
                HVAC_PLUGIN_URL . 'assets/css/communication-templates.css',
                array('hvac-community-events'),
                $this->version
            );
        }
        
        // Certificate pages styles
        if ($this->is_certificate_page()) {
            wp_enqueue_style(
                'hvac-certificates',
                HVAC_PLUGIN_URL . 'assets/css/hvac-certificates.css',
                array('hvac-community-events'),
                $this->version
            );
            
            wp_enqueue_style(
                'hvac-certificates-enhanced',
                HVAC_PLUGIN_URL . 'assets/css/hvac-certificates-enhanced.css',
                array('hvac-certificates'),
                $this->version
            );
            
            // Load specific certificate page styles
            if (strpos($_SERVER['REQUEST_URI'], 'certificate-reports') !== false) {
                wp_enqueue_style(
                    'hvac-certificate-reports',
                    HVAC_PLUGIN_URL . 'assets/css/hvac-certificate-reports.css',
                    array('hvac-certificates'),
                    $this->version
                );
            }
            
            if (strpos($_SERVER['REQUEST_URI'], 'generate-certificates') !== false) {
                wp_enqueue_style(
                    'hvac-generate-certificates',
                    HVAC_PLUGIN_URL . 'assets/css/hvac-generate-certificates.css',
                    array('hvac-certificates'),
                    $this->version
                );
            }
        }
        
        // Organizers pages styles
        if ($this->is_organizers_page()) {
            wp_enqueue_style(
                'hvac-organizers',
                HVAC_PLUGIN_URL . 'assets/css/hvac-organizers.css',
                array('hvac-community-events'),
                $this->version
            );
        }
        
        // Pending approvals styles
        if ($this->is_pending_approvals_page()) {
            wp_enqueue_style(
                'hvac-master-pending-approvals',
                HVAC_PLUGIN_URL . 'assets/css/hvac-master-pending-approvals.css',
                array('hvac-community-events'),
                $this->version
            );
        }
        
        // Venues pages styles
        if ($this->is_venues_page()) {
            wp_enqueue_style(
                'hvac-venues',
                HVAC_PLUGIN_URL . 'assets/css/hvac-venues.css',
                array('hvac-community-events'),
                $this->version
            );
        }
        
        // Trainer profile pages styles
        if ($this->is_trainer_profile_page()) {
            wp_enqueue_style(
                'hvac-trainer-profile',
                HVAC_PLUGIN_URL . 'assets/css/hvac-trainer-profile.css',
                array('hvac-community-events'),
                $this->version
            );
            
            // Profile sharing styles - includes modal and QR code display
            wp_enqueue_style(
                'hvac-profile-sharing',
                HVAC_PLUGIN_URL . 'assets/css/hvac-profile-sharing.css',
                array('hvac-trainer-profile'),
                $this->version
            );
        }
        
        // Event manage page styles
        if ($this->is_event_manage_page()) {
            // First ensure common CSS is loaded
            wp_enqueue_style(
                'hvac-common',
                HVAC_PLUGIN_URL . 'assets/css/hvac-common.css',
                array(),
                $this->version
            );
            
            // Then dashboard CSS
            wp_enqueue_style(
                'hvac-dashboard',
                HVAC_PLUGIN_URL . 'assets/css/hvac-dashboard.css',
                array('hvac-community-events', 'hvac-common'),
                $this->version
            );
            
            // Layout CSS for proper container styling
            wp_enqueue_style(
                'hvac-layout',
                HVAC_PLUGIN_URL . 'assets/css/hvac-layout.css',
                array('hvac-community-events'),
                $this->version
            );
            
            // Finally event manage CSS
            wp_enqueue_style(
                'hvac-event-manage',
                HVAC_PLUGIN_URL . 'assets/css/hvac-event-manage.css',
                array('hvac-community-events', 'hvac-common', 'hvac-dashboard', 'hvac-layout'),
                $this->version
            );
        }
        
        // CRITICAL FIX: Force jQuery to load first with highest priority for all browsers
        wp_enqueue_script('jquery');
        
        // Add detection script to verify jQuery is loaded
        wp_add_inline_script('jquery', '
            if (typeof jQuery === "undefined") {
                console.error("HVAC CRITICAL ERROR: jQuery failed to load on plugin page");
            } else {
                console.log("HVAC: jQuery successfully loaded on plugin page");
            }
        ', 'after');
        
        // Main plugin scripts
        wp_enqueue_script(
            'hvac-community-events',
            HVAC_PLUGIN_URL . 'assets/js/hvac-community-events.js',
            array('jquery'),
            $this->version,
            true
        );
        
        // Mobile responsive functionality - Load on all plugin pages
        wp_enqueue_script(
            'hvac-mobile-responsive',
            HVAC_PLUGIN_URL . 'assets/js/hvac-mobile-responsive.js',
            array('jquery', 'hvac-community-events'),
            $this->version,
            true
        );
        
        // Dashboard scripts
        if ($this->is_dashboard_page()) {
            wp_enqueue_script(
                'hvac-dashboard',
                HVAC_PLUGIN_URL . 'assets/js/hvac-dashboard.js',
                array('jquery', 'hvac-community-events'),
                $this->version,
                true
            );
            
            wp_enqueue_script(
                'hvac-dashboard-enhanced',
                HVAC_PLUGIN_URL . 'assets/js/hvac-dashboard-enhanced.js',
                array('hvac-dashboard'),
                $this->version,
                true
            );
        }
        
        // DISABLED - Using TEC Community Events 5.x instead
        // if ($this->is_event_manage_page() || $this->is_create_event_page() || $this->is_edit_event_page()) {
        //     wp_enqueue_script(
        //         'hvac-rest-api-event-submission',
        //         HVAC_PLUGIN_URL . 'assets/js/hvac-rest-api-event-submission.js',
        //         array('jquery'),
        //         $this->version,
        //         true
        //     );
        //     
        //     // Localize script with necessary data
        //     wp_localize_script('hvac-rest-api-event-submission', 'hvac_ajax', array(
        //         'ajaxurl' => admin_url('admin-ajax.php'),
        //         'nonce' => wp_create_nonce('hvac_ajax_nonce')
        //     ));
        // }
        
        // Registration scripts
        if ($this->is_registration_page()) {
            wp_enqueue_script(
                'hvac-registration',
                $this->get_compatible_script_path('hvac-registration'),
                array('jquery', 'hvac-community-events'),
                $this->version,
                true
            );
        }
        
        // Trainer profile scripts
        if ($this->is_trainer_profile_page()) {
            wp_enqueue_script(
                'hvac-profile-sharing',
                HVAC_PLUGIN_URL . 'assets/js/hvac-profile-sharing.js',
                array('jquery', 'hvac-community-events'),
                $this->version,
                true
            );
        }
        
        // Help system scripts
        wp_enqueue_script(
            'hvac-help-system',
            HVAC_PLUGIN_URL . 'assets/js/hvac-help-system.js',
            array('jquery'),
            $this->version,
            true
        );
        
        // Safari debugging script - temporarily disabled to isolate other script issues
        /*
        if ($this->is_find_trainer_page()) {
            wp_enqueue_script(
                'hvac-safari-debug',
                HVAC_PLUGIN_URL . 'assets/js/hvac-safari-debug.js',
                array(), // No dependencies - load early
                $this->version,
                false // Load in head for early debugging
            );
        }
        */
        
        // Localize main script
        wp_localize_script('hvac-community-events', 'hvac_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_ajax_nonce'),
            'is_logged_in' => is_user_logged_in(),
            'plugin_url' => HVAC_PLUGIN_URL,
        ));
        
        // Localize dashboard script
        if ($this->is_dashboard_page()) {
            wp_localize_script('hvac-dashboard', 'hvac_dashboard', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('hvac_dashboard_nonce'),
                'strings' => array(
                    'loading' => __('Loading...', 'hvac-community-events'),
                    'error' => __('An error occurred. Please try again.', 'hvac-community-events'),
                ),
            ));
        }
        
        // Localize profile sharing script
        if ($this->is_trainer_profile_page()) {
            wp_localize_script('hvac-profile-sharing', 'hvac_sharing', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('hvac_profile_sharing'),
                'strings' => array(
                    'loading' => __('Loading...', 'hvac-community-events'),
                    'error' => __('An error occurred. Please try again.', 'hvac-community-events'),
                    'copied' => __('Copied to clipboard!', 'hvac-community-events'),
                    'copy_error' => __('Unable to copy. Please select and copy manually.', 'hvac-community-events'),
                    'loading_error' => __('Unable to load profile card. Please try again.', 'hvac-community-events')
                ),
            ));
        }
    }
    
    /**
     * Enqueue admin assets
     * 
     * @param string $hook Current admin page hook
     * @return void
     */
    public function enqueue_admin_assets($hook) {
        // Global admin styles
        wp_enqueue_style(
            'hvac-admin',
            HVAC_PLUGIN_URL . 'assets/css/hvac-admin.css',
            array(),
            $this->version
        );
        
        // Global admin scripts
        wp_enqueue_script(
            'hvac-admin',
            HVAC_PLUGIN_URL . 'assets/js/hvac-admin.js',
            array('jquery'),
            $this->version . '.2', // Force cache refresh for jQuery fix
            true
        );
        
        // Localize admin script
        wp_localize_script('hvac-admin', 'hvac_admin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_admin_nonce'),
        ));
        
        // Plugin-specific admin pages
        if (strpos($hook, 'hvac-community-events') !== false) {
            // Add any additional plugin-specific admin assets here
        }
        
        // Certificate admin scripts
        if (strpos($hook, 'certificate') !== false) {
            wp_enqueue_script(
                'hvac-certificate-admin',
                HVAC_PLUGIN_URL . 'assets/js/hvac-certificate-admin.js',
                array('jquery'),
                $this->version,
                true
            );
        }
    }
    
    /**
     * Enqueue login page assets
     * 
     * @return void
     */
    public function enqueue_login_assets() {
        // Check if we're on the custom login page
        if (!$this->is_custom_login_page()) {
            return;
        }
        
        wp_enqueue_style(
            'hvac-login',
            HVAC_PLUGIN_URL . 'assets/css/hvac-login.css',
            array(),
            $this->version
        );
        
        wp_enqueue_script(
            'hvac-login',
            HVAC_PLUGIN_URL . 'assets/js/hvac-login.js',
            array('jquery'),
            $this->version,
            true
        );
    }
    
    /**
     * Check if current page is a plugin page
     * Enhanced to work during wp_enqueue_scripts hook before templates load
     * 
     * @return bool
     */
    private function is_plugin_page() {
        // Check if we're in a page template context
        if (defined('HVAC_IN_PAGE_TEMPLATE') && HVAC_IN_PAGE_TEMPLATE) {
            return true;
        }
        
        // CRITICAL FIX: Enhanced URL-based detection for master trainer pages
        // This works during wp_enqueue_scripts before template constants are available
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        
        // Debug logging for troubleshooting
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[HVAC Scripts] Checking plugin page: ' . $current_path);
        }
        
        // Enhanced plugin path patterns for better detection
        $plugin_paths = array(
            'trainer/',                    // Match /trainer/* paths
            'trainer',                     // Match /trainer path
            'master-trainer/',             // Match /master-trainer/* paths  
            'master-trainer',              // Match /master-trainer path
            'training-login',
            'hvac-dashboard',
            'manage-event',
            'event-summary',
            'certificate-reports',
            'generate-certificates',
            'find-a-trainer',
        );
        
        foreach ($plugin_paths as $path) {
            // Enhanced matching to handle both with and without trailing slashes
            if (strpos($current_path, $path) !== false) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('[HVAC Scripts] Plugin page detected via URL: ' . $path);
                }
                return true;
            }
        }
        
        // Check using template loader if available
        if (class_exists('HVAC_Template_Loader')) {
            $is_plugin_template = HVAC_Template_Loader::is_plugin_template();
            if ($is_plugin_template) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('[HVAC Scripts] Plugin page detected via template loader');
                }
                return true;
            }
        }
        
        // Check by page template (may not work during wp_enqueue_scripts)
        if (is_page_template()) {
            $template = get_page_template_slug();
            if (strpos($template, 'page-trainer') !== false || 
                strpos($template, 'page-master') !== false ||
                strpos($template, 'page-certificate') !== false ||
                strpos($template, 'page-generate') !== false ||
                strpos($template, 'page-manage-event') !== false) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('[HVAC Scripts] Plugin page detected via template: ' . $template);
                }
                return true;
            }
        }
        
        // ADDITIONAL FALLBACK: Check for specific master trainer page slugs
        // This handles cases where URL detection might not catch everything
        $master_trainer_pages = array(
            'master-dashboard',
            'master-announcements', 
            'master-import-export',
            'master-pending-approvals',
            'master-events',
            'master-manage-announcements'
        );
        
        foreach ($master_trainer_pages as $page_slug) {
            if (is_page($page_slug) || strpos($current_path, $page_slug) !== false) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('[HVAC Scripts] Plugin page detected via master trainer slug: ' . $page_slug);
                }
                return true;
            }
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[HVAC Scripts] Not a plugin page: ' . $current_path);
        }
        
        return false;
    }
    
    /**
     * Bulletproof jQuery loading for critical master trainer pages
     * This ensures jQuery is always available regardless of page detection issues
     * 
     * @return void
     */
    public function ensure_jquery_on_master_pages() {
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        
        // Critical master trainer pages that MUST have jQuery
        $critical_master_pages = array(
            'master-trainer/master-dashboard',
            'master-trainer/announcements', 
            'master-trainer/import-export'
        );
        
        $is_critical_page = false;
        foreach ($critical_master_pages as $critical_page) {
            if (strpos($current_path, $critical_page) !== false) {
                $is_critical_page = true;
                break;
            }
        }
        
        if (!$is_critical_page) {
            return;
        }
        
        // Force jQuery loading with highest priority for critical pages
        wp_enqueue_script('jquery');
        
        // Add comprehensive error detection and fallback
        $critical_jquery_script = '
        /* HVAC CRITICAL PAGE jQuery Validation */
        (function() {
            var checkJQuery = function() {
                if (typeof jQuery === "undefined") {
                    console.error("HVAC CRITICAL FAILURE: jQuery missing on critical page: " + window.location.pathname);
                    
                    // Attempt emergency jQuery loading
                    if (!window.hvac_emergency_jquery_attempted) {
                        window.hvac_emergency_jquery_attempted = true;
                        var script = document.createElement("script");
                        script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js";
                        script.onload = function() {
                            console.log("HVAC: Emergency jQuery loaded successfully");
                            window.hvac_emergency_jquery_loaded = true;
                        };
                        script.onerror = function() {
                            console.error("HVAC: Emergency jQuery loading failed");
                            window.hvac_emergency_jquery_failed = true;
                        };
                        document.head.appendChild(script);
                    }
                } else {
                    console.log("HVAC: jQuery confirmed available on critical page: " + window.location.pathname);
                    window.hvac_jquery_confirmed = true;
                }
            };
            
            // Check immediately
            checkJQuery();
            
            // Double-check after DOM ready
            if (document.readyState === "loading") {
                document.addEventListener("DOMContentLoaded", checkJQuery);
            }
        })();';
        
        wp_add_inline_script('jquery', $critical_jquery_script, 'after');
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[HVAC Scripts] BULLETPROOF: jQuery forced for critical page: ' . $current_path);
        }
    }
    
    /**
     * Check if current page is a dashboard page
     * 
     * @return bool
     */
    private function is_dashboard_page() {
        // Check by page slug
        $dashboard_pages = array(
            'trainer-dashboard',
            'master-dashboard',
            'hvac-dashboard',
            'trainer/dashboard',
            'master-trainer/dashboard',
            'master-trainer/master-dashboard',
            'trainer/event/manage',
            'manage-event',
            'trainer/certificate-reports',
            'trainer/generate-certificates'
        );
        
        foreach ($dashboard_pages as $page_slug) {
            if (is_page($page_slug)) {
                return true;
            }
        }
        
        // Also check URL path as fallback
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        $dashboard_paths = array(
            'trainer/dashboard',
            'master-trainer/dashboard',
            'master-trainer/master-dashboard',
            'trainer/event/manage',
            'manage-event',
            'trainer/certificate-reports',
            'trainer/generate-certificates'
        );
        
        foreach ($dashboard_paths as $path) {
            if (strpos($current_path, $path) !== false) {
                return true;
            }
        }
        
        // Check if this is a community events submission page
        if (function_exists('tribe_is_community_edit_event_page') && tribe_is_community_edit_event_page()) {
            return true;
        }
        
        if (function_exists('tribe_is_community_my_events_page') && tribe_is_community_my_events_page()) {
            return true;
        }
        
        return false;
    }
    
    /**
     * Check if current page is master dashboard page specifically
     * 
     * @return bool
     */
    private function is_master_dashboard_page() {
        // Check by page slug
        $master_pages = array(
            'master-trainer/master-dashboard',
            'master-dashboard'
        );
        
        foreach ($master_pages as $page_slug) {
            if (is_page($page_slug)) {
                return true;
            }
        }
        
        // Also check by URL path
        $current_path = $_SERVER['REQUEST_URI'];
        return (strpos($current_path, 'master-trainer/master-dashboard') !== false);
    }
    
    /**
     * Check if current page is registration page
     * 
     * @return bool
     */
    private function is_registration_page() {
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        return $current_path === 'trainer/registration' || 
               is_page('registration') || 
               is_page('trainer-registration');
    }
    
    /**
     * Check if current page is communication page
     * 
     * @return bool
     */
    private function is_communication_page() {
        return is_page('communication-templates') ||
               is_page('trainer/communication-templates') ||
               is_page('communication-schedules') ||
               is_page('trainer/communication-schedules');
    }
    
    /**
     * Check if current page is event manage page
     * 
     * @return bool
     */
    private function is_event_manage_page() {
        // Check by page ID (most reliable)
        global $post;
        if ($post && $post->ID == 5344) { // Event manage page ID
            return true;
        }
        
        // Check by page slug
        if (is_page('manage') || is_page('trainer/event/manage') || is_page('manage-event') || is_page('trainer-event-manage')) {
            return true;
        }
        
        // Check by page template
        if (is_page_template('page-manage-event.php')) {
            return true;
        }
        
        // Check URL path
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        if ($current_path === 'trainer/event/manage' || $current_path === 'trainer/event/manage/') {
            return true;
        }
        
        // Check if this is a community events submission page
        if (function_exists('tribe_is_community_edit_event_page') && tribe_is_community_edit_event_page()) {
            return true;
        }
        
        return false;
    }
    
    /**
     * Check if current page is create event page
     * 
     * @return bool
     */
    private function is_create_event_page() {
        // Check by page slug
        if (is_page('create-event') || is_page('trainer/create-event')) {
            return true;
        }
        
        // Check by page template
        if (is_page_template('page-create-event.php') || is_page_template('templates/page-create-event.php')) {
            return true;
        }
        
        // Check URL path
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        if ($current_path === 'trainer/create-event' || $current_path === 'trainer/create-event/') {
            return true;
        }
        
        return false;
    }
    
    /**
     * Check if current page is edit event page
     * 
     * @return bool
     */
    private function is_edit_event_page() {
        // Check by page slug
        if (is_page('edit-event') || is_page('trainer/edit-event')) {
            return true;
        }
        
        // Check by page template
        if (is_page_template('page-edit-event.php') || is_page_template('templates/page-edit-event.php')) {
            return true;
        }
        
        // Check URL path
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        if ($current_path === 'trainer/edit-event' || $current_path === 'trainer/edit-event/') {
            return true;
        }
        
        return false;
    }
    
    /**
     * Check if current page is custom login page
     * 
     * @return bool
     */
    private function is_custom_login_page() {
        return is_page('training-login') ||
               is_page('community-login') ||
               is_page('trainer/login');
    }
    
    /**
     * Check if current page is certificate page
     * 
     * @return bool
     */
    private function is_certificate_page() {
        return is_page('certificate-reports') ||
               is_page('trainer/certificate-reports') ||
               is_page('generate-certificates') ||
               is_page('trainer/generate-certificates') ||
               strpos($_SERVER['REQUEST_URI'], 'certificate-reports') !== false ||
               strpos($_SERVER['REQUEST_URI'], 'generate-certificates') !== false;
    }
    
    /**
     * Check if current page is organizers page
     * 
     * @return bool
     */
    private function is_organizers_page() {
        return is_page('trainer-organizers-list') ||
               is_page('trainer/organizer/list') ||
               is_page('trainer-organizer-manage') ||
               is_page('trainer/organizer/manage') ||
               strpos($_SERVER['REQUEST_URI'], 'organizer') !== false;
    }
    
    /**
     * Check if current page is pending approvals page
     * 
     * @return bool
     */
    private function is_pending_approvals_page() {
        return is_page('master-pending-approvals') ||
               is_page('master-trainer/pending-approvals') ||
               strpos($_SERVER['REQUEST_URI'], 'master-trainer/pending-approvals') !== false ||
               strpos($_SERVER['REQUEST_URI'], 'pending-approvals') !== false;
    }
    
    /**
     * Check if current page is master events page
     * 
     * @return bool
     */
    private function is_master_events_page() {
        return is_page('master-events') ||
               is_page('master-trainer/events') ||
               strpos($_SERVER['REQUEST_URI'], 'master-trainer/events') !== false;
    }
    
    /**
     * Check if current page is venues page
     * 
     * @return bool
     */
    private function is_venues_page() {
        return is_page('trainer-venues-list') ||
               is_page('trainer/venue/list') ||
               is_page('trainer-venue-manage') ||
               is_page('trainer/venue/manage') ||
               strpos($_SERVER['REQUEST_URI'], 'venue') !== false;
    }
    
    /**
     * Check if current page is a trainer profile page
     * 
     * @return bool
     */
    private function is_trainer_profile_page() {
        return is_page('trainer/profile') ||
               is_page('trainer/profile/edit') ||
               is_page('trainer/my-profile') ||
               strpos($_SERVER['REQUEST_URI'], '/trainer/profile') !== false;
    }
    
    /**
     * Check if current page is the find-a-trainer page
     * 
     * @return bool
     */
    private function is_find_trainer_page() {
        return is_page('find-a-trainer') ||
               strpos($_SERVER['REQUEST_URI'], 'find-a-trainer') !== false;
    }
    
    /**
     * Check if current page is import-export page
     * 
     * @return bool
     */
    private function is_import_export_page() {
        return is_page('master-import-export') ||
               is_page('master-trainer/import-export') ||
               strpos($_SERVER['REQUEST_URI'], 'master-trainer/import-export') !== false;
    }
    
    /**
     * Get script version with cache busting
     * 
     * @param string $file File path
     * @return string
     */
    public function get_asset_version($file = '') {
        // In development, use file modification time
        if (defined('WP_DEBUG') && WP_DEBUG && $file) {
            $file_path = HVAC_PLUGIN_DIR . $file;
            if (file_exists($file_path)) {
                return filemtime($file_path);
            }
        }
        
        return $this->version;
    }
    
    /**
     * Enqueue pending approvals scripts and styles
     * Called from enqueue_page_specific_scripts
     */
    public function enqueue_pending_approvals_assets() {
        if (!$this->is_pending_approvals_page()) {
            return;
        }
        
        // Enqueue JavaScript
        wp_enqueue_script(
            'hvac-master-pending-approvals',
            HVAC_PLUGIN_URL . 'assets/js/hvac-master-pending-approvals.js',
            array('jquery', 'hvac-community-events'),
            $this->version,
            true
        );
        
        // Localize script
        wp_localize_script('hvac-master-pending-approvals', 'hvac_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_master_approvals'),
            'strings' => array(
                'loading' => __('Loading...', 'hvac-community-events'),
                'error' => __('An error occurred. Please try again.', 'hvac-community-events'),
                'confirm_approve' => __('Are you sure you want to approve this trainer?', 'hvac-community-events'),
                'confirm_reject' => __('Are you sure you want to reject this trainer?', 'hvac-community-events'),
                'no_selection' => __('Please select trainers to perform this action.', 'hvac-community-events'),
            ),
        ));
    }
    
    /**
     * Localize sharing data for profile pages
     * 
     * @param array $data Sharing data to localize
     * @return void
     */
    public function localize_sharing_data($data) {
        if ($this->is_trainer_profile_page() && wp_script_is('hvac-profile-sharing', 'enqueued')) {
            wp_localize_script('hvac-profile-sharing', 'hvac_sharing_data', $data);
        }
    }
}