<?php

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

// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- This file uses $wpdb->prepare() correctly throughout

// Ensure database manager is available
require_once VASP_ANALYTICS_PLUGIN_DIR . 'admin/AdminUtils/class-vasp-database-manager.php';

/**
 * Manages all script and style enqueues for SentinelPro admin pages.
 */
class VASP_Admin_Script_Manager {



    /**
     * Get the correct plugin URL using WordPress helpers
     */
    private static function get_plugin_url($path = '') {
        return trailingslashit(VASP_ANALYTICS_PLUGIN_URL) . ltrim($path, '/');
    }

    /**
     * Get the correct AJAX URL using WordPress helpers
     */
    private static function get_ajax_url() {
        return admin_url('admin-ajax.php');
    }

    /**
     * Conditionally enqueue admin scripts based on the current page.
     */
    public static function enqueue(string $current_page): void {
        // Check if user has access to any SentinelPro pages (instead of just manage_options)
        // This allows editors with explicit permissions to access the dashboard
        $user_id = get_current_user_id();
        $has_api_access = VASP_User_Access_Manager::user_has_access('api_input', $user_id);
        $has_dashboard_access = VASP_User_Access_Manager::user_has_access('dashboard', $user_id);
        $has_user_mgmt_access = VASP_User_Access_Manager::user_has_access('user_mgmt', $user_id);
        
        // Allow if user has access to at least one page, or if they're an admin (for backwards compatibility)
        if (!$has_api_access && !$has_dashboard_access && !$has_user_mgmt_access && !current_user_can('manage_options')) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG is enabled
                error_log("SentinelPro Script Manager: User {$user_id} does not have access to any SentinelPro pages");
            }
            return;
        }

        // Sanitize current page for defense-in-depth
        $current_page = sanitize_key($current_page);
        
        // Debug: Log which page we're enqueuing for
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG is enabled
            error_log("SentinelPro Script Manager: Enqueuing for page: " . $current_page);
        }

        // Common Scripts
        // Enqueue Chart.js itself as a dependency for other Chart.js related scripts
        wp_enqueue_script(
            'chartjs',
            self::get_plugin_url('assets/external-libs/chart.umd.min.js'),
            [],
            '4.4.1',
            true
        );

        wp_enqueue_script(
            'chartjs-adapter-date-fns',
            self::get_plugin_url('assets/external-libs/chartjs-adapter-date-fns.js'),
            ['chartjs'],
            VASP_ANALYTICS_VERSION,
            true
        );

        wp_enqueue_script(
            'sentinelpro-gauge-svg',
            self::get_plugin_url('admin/js/DashboardHelpers/GaugeSVGRenderer.js'),
            [], // no dependencies
            VASP_ANALYTICS_VERSION,
            true
        );

        wp_enqueue_style(
            'sentinelpro-shared',
            self::get_plugin_url('admin/css/shared-components.css'),
            [],
            VASP_ANALYTICS_VERSION
        );

        wp_enqueue_style(
            'sentinelpro-layout',
            self::get_plugin_url('admin/css/layout.css'),
            [],
            VASP_ANALYTICS_VERSION
        );

        wp_enqueue_style(
            'sentinelpro-base',
            self::get_plugin_url('admin/css/base.css'),
            [],
            VASP_ANALYTICS_VERSION
        );

         // Add jQuery UI Autocomplete
        wp_enqueue_script('jquery-ui-autocomplete');

        // Include jQuery UI CSS (optional if your theme already includes it)
        wp_enqueue_style('jquery-ui-css', self::get_plugin_url('assets/external-libs/jquery-ui.css'), [], VASP_ANALYTICS_VERSION);

        // Localize for AJAX

        // SentinelPro Pages
        switch ($current_page) {
            case 'toplevel_page_sentinelpro-api-input':
            case 'toplevel_page_sentinelpro-settings':

                // Also enqueue settings specific JS if dashboard is the main settings page
                wp_enqueue_script(
                    'sentinelpro-api-settings',
                    self::get_plugin_url('admin/js/api-settings-page.js'),
                    [], // No specific JS dependencies
                    VASP_ANALYTICS_VERSION,
                    true
                );
                wp_enqueue_style(
                    'sentinelpro-api-settings',
                    self::get_plugin_url('admin/css/api-settings.css'),
                    [],
                    VASP_ANALYTICS_VERSION
                );

                wp_localize_script('sentinelpro-api-settings', 'SentinelProAuth', [
                    'ajax_url' => self::get_ajax_url(),
                    'nonce'    => wp_create_nonce('vasp_auth_nonce'),
                ]);
                
                wp_localize_script('sentinelpro-api-settings', 'SentinelProClearance', [
                    'ajax_url' => self::get_ajax_url(),
                    'nonce'    => wp_create_nonce('vasp_nonce'),
                ]);
                break;

            case 'sentinelpro-settings_page_sentinelpro-event-data':
            case 'vasp_page_sentinelpro-event-data':
            case 'toplevel_page_sentinelpro-event-data':
            case 'sentinelpro_page_sentinelpro-event-data':

                // Debug: Log that we're enqueuing for event-data page
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG is enabled
                    error_log("SentinelPro Script Manager: Enqueuing amCharts for event-data page. Current page: " . $current_page);
                }

                // Enqueue amCharts v4 library only
                // CRITICAL: These must load as regular scripts (not modules) to attach to window object
                // The script_loader_tag filter ensures they're not loaded as modules
                wp_enqueue_script(
                    'amcharts-core',
                    self::get_plugin_url('assets/external-libs/amcharts-core.js'),
                    [],
                    '4.0',
                    true
                );

                wp_enqueue_script(
                    'amcharts-charts',
                    self::get_plugin_url('assets/external-libs/amcharts-charts.js'),
                    ['amcharts-core'],
                    '4.0',
                    true
                );

                wp_enqueue_script(
                    'amcharts-animated',
                    self::get_plugin_url('assets/external-libs/amcharts-animated.js'),
                    ['amcharts-core', 'amcharts-charts'],
                    '4.0',
                    true
                );
                
                // Add inline script to verify amCharts loads and log to console
                wp_add_inline_script('amcharts-animated', '
                    (function() {
                        console.log("SentinelPro: amCharts scripts should be loaded. Checking...");
                        setTimeout(function() {
                            console.log("SentinelPro: amCharts check - am4core:", typeof window.am4core !== "undefined", "am4charts:", typeof window.am4charts !== "undefined", "am4themes_animated:", typeof window.am4themes_animated !== "undefined");
                            if (typeof window.am4core === "undefined" || typeof window.am4charts === "undefined" || typeof window.am4themes_animated === "undefined") {
                                console.error("SentinelPro: amCharts libraries failed to load!");
                                console.log("SentinelPro: Checking for script tags in DOM...");
                                var amchartsScripts = document.querySelectorAll("script[src*=\'amcharts\']");
                                console.log("SentinelPro: Found", amchartsScripts.length, "amCharts script tag(s)");
                                amchartsScripts.forEach(function(script, index) {
                                    console.log("SentinelPro: Script", index + ":", script.src, "loaded:", script.readyState || "unknown");
                                });
                            } else {
                                console.log("SentinelPro: ✓ amCharts libraries loaded successfully!");
                            }
                        }, 500);
                    })();
                ', 'after');

                // Enqueue ChartRenderer.js first, as event-data-page.js depends on it.
                wp_enqueue_script(
                    'sentinelpro-chart-renderer',
                    self::get_plugin_url('admin/js/DashboardHelpers/ChartRenderer.js'),
                    ['chartjs', 'chartjs-adapter-date-fns', 'moment'],
                    VASP_ANALYTICS_VERSION,
                    true
                );

                // Enqueue StatusPopup first
                wp_enqueue_script(
                    'sentinelpro-status-popup',
                    self::get_plugin_url('admin/js/DashboardHelpers/StatusPopup.js'),
                    ['jquery', 'moment'],
                    VASP_ANALYTICS_VERSION,
                    true
                );

                // Enqueue DateRangeValidator
                wp_enqueue_script(
                    'sentinelpro-date-validator',
                    self::get_plugin_url('admin/js/DashboardHelpers/DateRangeValidator.js'),
                    ['jquery', 'moment', 'sentinelpro-status-popup'],
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-chart-render',
                    self::get_plugin_url('admin/js/dashboard-main.js'),
                    ['jquery', 'sentinelpro-chart-renderer', 'sentinelpro-status-popup', 'sentinelpro-date-validator', 'chartjs', 'chartjs-adapter-date-fns', 'moment'],
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-enhanced-dashboard',
                    self::get_plugin_url('admin/js/enhanced-dashboard.js'),
                    ['jquery', 'chartjs', 'chartjs-adapter-date-fns', 'daterangepicker', 'moment'],
                    VASP_ANALYTICS_VERSION,
                    true
                );
                
                // Add inline script to verify Chart.js loads and make it globally available
                wp_add_inline_script('chartjs', "
                    (function() {
                        console.log('SentinelPro: Chart.js script should be loaded. Checking...');
                        // Function to ensure Chart is globally available
                        function ensureChartGlobal() {
                            if (typeof Chart !== 'undefined') {
                                console.log('SentinelPro: ✓ Chart.js library loaded successfully!');
                                // Make sure Chart is available globally
                                if (typeof window !== 'undefined') {
                                    window.Chart = Chart;
                                    // Also ensure it's available as a global variable (not just window.Chart)
                                    if (typeof globalThis !== 'undefined') {
                                        globalThis.Chart = Chart;
                                    }
                                }
                                return true;
                            }
                            return false;
                        }
                        
                        // Check immediately
                        if (ensureChartGlobal()) {
                            return;
                        }
                        
                        // If not available, wait for script to load
                        var checkInterval = setInterval(function() {
                            if (ensureChartGlobal()) {
                                clearInterval(checkInterval);
                            }
                        }, 100);
                        
                        // Timeout after 10 seconds
                        setTimeout(function() {
                            clearInterval(checkInterval);
                            if (typeof Chart === 'undefined' && typeof window.Chart === 'undefined') {
                                console.error('SentinelPro: Chart.js library failed to load after 10 seconds!');
                                console.log('SentinelPro: Checking for script tags in DOM...');
                                var chartScripts = document.querySelectorAll('script[src*=\"chart\"]');
                                console.log('SentinelPro: Found', chartScripts.length, 'Chart.js script tag(s)');
                                chartScripts.forEach(function(script, index) {
                                    console.log('SentinelPro: Script', index + ':', script.src, 'loaded:', script.readyState || 'unknown');
                                });
                            }
                        }, 10000);
                    })();
                ", 'after');

                $property_id = get_option('vasp_options', [])['property_id'] ?? '';
                
                // Ensure the database manager has run to populate dimensions
                if (class_exists('VASP_Database_Manager')) {
                    $db_manager = VASP_Database_Manager::get_instance();
                    $db_manager->ensure_analytics_events_table_exists();
                }
                
                // Load dimensions from vasp_events_table_dimensions (where they are actually stored)
                $dimensions = get_option('vasp_events_table_dimensions', []);
                
                // If it's an associative array, use the keys as the dimension names
                if ($dimensions && is_array($dimensions) && array_values($dimensions) !== $dimensions) {
                    $dimensions = array_keys($dimensions);
                }
                

                



                
                // Add default dimensions if missing
                $default_dimensions = ['device', 'geo', 'browser', 'os', 'referrer'];
                foreach ($default_dimensions as $dim) {
                    if (!in_array($dim, $dimensions, true)) {
                        $dimensions[] = $dim;
                    }
                }
                wp_localize_script('sentinelpro-enhanced-dashboard', 'SentinelProCanonicalDimensions', $dimensions);
                
                wp_localize_script('sentinelpro-enhanced-dashboard', 'SentinelProAjax', [
                    'ajax_url' => self::get_ajax_url(),
                    'nonce'    => wp_create_nonce('vasp_nonce'),
                ]);

                wp_localize_script('sentinelpro-chart-render', 'SentinelProAjax', [
                    'ajax_url' => self::get_ajax_url(),
                    'nonce'    => wp_create_nonce('vasp_chart_nonce'),
                ]);

                wp_localize_script('sentinelpro-chart-render', 'SentinelProChartData', [
                    'data' => [],
                ]);

                wp_enqueue_style(
                    'sentinelpro-chart-page',
                    self::get_plugin_url('admin/css/event-data.css'),
                    [],
                    VASP_ANALYTICS_VERSION
                );

                wp_enqueue_style(
                    'sentinelpro-enhanced-dashboard',
                    self::get_plugin_url('admin/css/enhanced-dashboard.css'),
                    [],
                    VASP_ANALYTICS_VERSION
                );

                wp_enqueue_style(
                    'sentinelpro-datepicker-theme',
                    self::get_plugin_url('admin/css/datepicker-theme.css'),
                    [],
                    VASP_ANALYTICS_VERSION
                );

                wp_localize_script('sentinelpro-chart-render', 'SentinelProAutocomplete', [
                    'ajax_url' => self::get_ajax_url(),
                    'nonce'    => wp_create_nonce('autocomplete_nonce'),
                ]);

                // Corrected path to daterangepicker.js
                wp_enqueue_script(
                'daterangepicker',
                trailingslashit(VASP_ANALYTICS_PLUGIN_URL) . 'assets/DateRangePicker/daterangepicker.js',
                ['jquery', 'moment'],
                '3.1',
                true
                );

                wp_enqueue_style(
                'daterangepicker-style',
                trailingslashit(VASP_ANALYTICS_PLUGIN_URL) . 'assets/DateRangePicker/daterangepicker.css',
                [],
                VASP_ANALYTICS_VERSION
                );



                break;

            case 'sentinelpro-settings_page_sentinelpro-user-management':
            case 'vasp_page_sentinelpro-user-management':
            case 'toplevel_page_sentinelpro-user-management': // In case it's a top-level menu
            case 'sentinelpro_page_sentinelpro-user-management':
                // Debug: Log that we're in the user management case
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG is enabled
                    error_log("SentinelPro Script Manager: Matched user management page case");
                }
                
                // Enqueue all User Management Helper scripts first, as user-management.js depends on them.
                // The order below is logical based on the import structure:
                // Utils -> DOMCache, TableManager, FileUploader, PreviewRenderer -> UserManager (user-management.js)

                wp_enqueue_script(
                    'sentinelpro-um-utils',
                    self::get_plugin_url('admin/js/UserManagementHelpers/Utils.js'),
                    [], // No specific dependencies for basic utils, unless you add external libraries.
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-um-domcache',
                    self::get_plugin_url('admin/js/UserManagementHelpers/DOMCache.js'),
                    [], // No direct JS dependencies other than internal browser APIs
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-um-tablemanager',
                    self::get_plugin_url('admin/js/UserManagementHelpers/TableManager.js'),
                    ['sentinelpro-um-utils'], // TableManager uses createElement from Utils
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-um-fileuploader',
                    self::get_plugin_url('admin/js/UserManagementHelpers/FileUploader.js'),
                    [], // Depends on global XLSX, not directly on other local modules via import
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sheetjs',
                    self::get_plugin_url('assets/external-libs/xlsx.full.min.js'),
                    [],
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-um-previewrenderer',
                    self::get_plugin_url('admin/js/UserManagementHelpers/PreviewRenderer.js'),
                    ['sentinelpro-um-utils'], // PreviewRenderer uses createElement and exportCSV from Utils
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-um-logviewer',
                    self::get_plugin_url('admin/js/UserManagementHelpers/LogViewer.js'),
                    [], // LogViewer doesn't have explicit dependencies
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-um-userfetcher',
                    self::get_plugin_url('admin/js/UserManagementHelpers/UserFetcher.js'),
                    [], // UserFetcher doesn't have explicit dependencies
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-um-accesstogglemanager',
                    self::get_plugin_url('admin/js/UserManagementHelpers/AccessToggleManager.js'),
                    ['sentinelpro-um-domcache'], // AccessToggleManager uses DOMCache
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-um-usertablerenderer',
                    self::get_plugin_url('admin/js/UserManagementHelpers/UserTableRenderer.js'),
                    ['sentinelpro-um-domcache', 'sentinelpro-um-tablemanager', 'sentinelpro-um-accesstogglemanager'], // UserTableRenderer uses DOMCache, TableManager, and AccessToggleManager
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_script(
                    'sentinelpro-user-management',
                    self::get_plugin_url('admin/js/user-management.js'),
                    ['sheetjs', 'sentinelpro-um-domcache', 'sentinelpro-um-tablemanager', 'sentinelpro-um-fileuploader', 'sentinelpro-um-previewrenderer', 'sentinelpro-um-utils', 'sentinelpro-um-logviewer', 'sentinelpro-um-userfetcher', 'sentinelpro-um-accesstogglemanager', 'sentinelpro-um-usertablerenderer'], // All helpers and SheetJS
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_localize_script('sentinelpro-user-management', 'sentinelpro_user_management_vars', array(
                    'ajaxurl' => self::get_ajax_url(),
                    'nonce'   => wp_create_nonce('vasp_nonce')
                ));


                wp_enqueue_style(
                    'sentinelpro-user-management',
                    self::get_plugin_url('admin/css/user-management.css'),
                    [],
                    VASP_ANALYTICS_VERSION
                );
                break;
            case 'edit.php':
                wp_enqueue_script(
                    'sentinelpro-post-table-totals',
                    self::get_plugin_url('admin/js/post-table-totals.js'),
                    [],
                    VASP_ANALYTICS_VERSION,
                    true
                );

                wp_enqueue_style(
                    'sentinelpro-post-table-totals-style',
                    self::get_plugin_url('admin/css/post-table-totals.css'),
                    [],
                    VASP_ANALYTICS_VERSION
                );
                break;
            default:
                break;
        }
    }

    public static function enqueue_and_localize_post_totals_script($hook_suffix) {
        // Capability check for security
        if (!current_user_can('edit_posts')) {
            return;
        }

        // Target only the 'edit.php' (posts list) screen
        global $pagenow; // Get current page filename (e.g., 'edit.php', 'post-new.php')
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if ('edit.php' !== $pagenow || !$screen || $screen->post_type !== 'post') {
            return; // Not on the "All Posts" screen, so don't enqueue anything
        }

        // Check for cached totals first
        $totals = get_transient('sp_post_totals');
        if (false === $totals) {
            // Fetch posts and calculate totals with safety cap
            $all_posts = get_posts([
                'posts_per_page'          => 5000, // Safety cap to prevent timeouts
                'post_type'               => 'post',
                'fields'                  => 'ids', // Only retrieve post IDs for efficiency
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Using EXISTS meta_query with strict caps and optimized args
                'meta_query'              => [ // Filter to only posts that might have views/sessions data
                    'relation' => 'OR',
                    [
                        'key'     => '_vasp_views',
                        'compare' => 'EXISTS',
                    ],
                    [
                        'key'     => '_vasp_sessions',
                        'compare' => 'EXISTS',
                    ],
                ],
                'no_found_rows'           => true, // Optimize query for no pagination needed
                'orderby'                 => 'none', // Avoid ORDER BY for speed
                // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters -- Performance optimization for admin dashboard totals
                'suppress_filters'        => true,  // Bypass filters for performance
                'update_post_meta_cache'  => false, // We fetch meta individually later if needed
                'update_post_term_cache'  => false, // Not using terms here
            ]);

            $total_views = 0;
            $total_sessions = 0;

            foreach ($all_posts as $post_id) {
                // Retrieve post meta, casting to (int) to ensure numeric operations
                $views = (int) get_post_meta($post_id, '_vasp_views', true);
                $sessions = (int) get_post_meta($post_id, '_vasp_sessions', true);
                $total_views += $views;
                $total_sessions += $sessions;
            }

            // Cache the totals for 5 minutes
            $totals = ['total_views' => $total_views, 'total_sessions' => $total_sessions];
            set_transient('sp_post_totals', $totals, MINUTE_IN_SECONDS * 5);
        }

        $total_views = $totals['total_views'];
        $total_sessions = $totals['total_sessions'];

        // Localize the script with the calculated totals
        // This makes a JavaScript object named `sentinelProPostTotals` available globally
        // to the `sentinelpro-post-table-totals` script.
        wp_localize_script(
            'sentinelpro-post-table-totals', // The handle of the script this data is for
            'sentinelProPostTotals',          // The name of the JS object that will hold the data
            [
                'totalViews'    => $total_views,
                'totalSessions' => $total_sessions,
            ]
        );

        // Enqueue the post-table-totals.js script
        wp_enqueue_script(
            'sentinelpro-post-table-totals',
            self::get_plugin_url('admin/js/post-table-totals.js'),
            [], // No specific JS dependencies for this script, as it reads localized data
            VASP_ANALYTICS_VERSION,
            true // Load in the footer
        );

        // Enqueue the optional CSS for styling the totals row
        wp_enqueue_style(
            'sentinelpro-post-table-totals-style',
            self::get_plugin_url('admin/css/post-table-totals.css'),
            [],
            VASP_ANALYTICS_VERSION
        );
    }
}

// ✅ Ensure module-based scripts are rendered with type="module"
// ⚠️ IMPORTANT: amCharts scripts (amcharts-core, amcharts-charts, amcharts-animated) 
//    must NOT be loaded as modules - they need to attach to window object
add_filter('script_loader_tag', function ($tag, $handle) {
    // Explicitly exclude amCharts scripts from module loading
    $non_module_handles = [
        'amcharts-core',
        'amcharts-charts',
        'amcharts-animated',
    ];
    
    // If this is an amCharts script, ensure it's NOT a module
    if (in_array($handle, $non_module_handles, true)) {
        // Remove type="module" if it exists
        $tag = str_replace(' type="module"', '', $tag);
        return $tag;
    }
    
    $module_handles = [
        'sentinelpro-chart-render',
        'valserv-dashboard', // Dashboard script from admin renderer
        'valserv-user-management', // User management script from admin renderer
        'sentinelpro-api-settings',
        'sentinelpro-user-management', // Main user-management script
        'sentinelpro-chart-renderer', // Already there
        'sentinelpro-status-popup', // Status popup module
        'sentinelpro-date-validator', // Date range validator module
        // Add all new User Management Helper scripts to ensure they are loaded as modules
        'sentinelpro-um-utils',
        'sentinelpro-um-domcache',
        'sentinelpro-um-tablemanager',
        'sentinelpro-um-fileuploader',
        'sentinelpro-um-previewrenderer',
        'sentinelpro-um-logviewer',
        'sentinelpro-um-userfetcher',
        'sentinelpro-um-accesstogglemanager',
        'sentinelpro-um-usertablerenderer',
        'sentinelpro-post-table-totals',
        'sentinelpro-enhanced-dashboard', // <-- Ensure enhanced-dashboard is loaded as a module
    ];
    if (in_array($handle, $module_handles, true)) {
        return str_replace('<script ', '<script type="module" ', $tag);
    }
    return $tag;
}, 10, 2);

?>
