<?php
namespace WalletUpPro\Core\Assets;

use WalletUpPro\Core\Error\ErrorHandler;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
class AssetManager
{
    private static $instance = null;
    private $version;
    private $errorHandler;
    private $scripts = [];
    private $styles = [];

    // Define dependencies for admin
    private static $ADMIN_DEPS = null;

    private static function getAdminDeps(): array
    {
        if (self::$ADMIN_DEPS === null) {
            self::$ADMIN_DEPS = [
                'scripts' => [
                    'wp-element',
                    'wp-components',
                    'wp-i18n',
                    ...(self::isWooCommerceActive() ? ['wc-blocks-registry'] : []),
                ],
                'styles' => ['wp-components']
            ];
        }
        return self::$ADMIN_DEPS;
    }

    public static function getInstance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public static function resetInstance()
    {
        static::$instance = null;
    }

    private function __construct()
    {
        $this->version = WALLET_UP_PRO_VERSION;
        $this->errorHandler = ErrorHandler::getInstance(); // Initialize errorHandler
        $this->registerHooks();
        // $this->registerDefaultAssets(); // Commented out since we're not using frontend assets

    }

    private function registerHooks(): void
    {
        add_action('admin_enqueue_scripts', [$this, 'enqueueAdminAssets']);
        //add_action('enqueue_block_editor_assets', [$this, 'enqueueEditorAssets']);
        add_action('wp_enqueue_scripts', [$this, 'enqueueFrontendQRProtect']);

        // Click tracking JS on ALL frontend pages — like Google Analytics, always present
        // 600 bytes, does nothing if no [data-wallet-up-method] elements exist
        add_action('wp_enqueue_scripts', [$this, 'enqueueClickTracking']);

        // Freemius CSS Override — standalone hook at late priority
        // Must NOT be nested inside enqueueAdminAssets to avoid early-return issues
        add_action('admin_enqueue_scripts', [$this, 'enqueueFreemiusOverride'], 9999);
    }

    /**
     * Enqueue Freemius CSS override on all WalletUp admin pages
     * Runs at priority 9999 to load AFTER Freemius styles
     */
    public function enqueueFreemiusOverride(string $hook_suffix): void
    {
        // Match any Freemius page under our plugin menu
        if (strpos($hook_suffix, 'wallet-up') === false) {
            return;
        }

        // Build dependency list from whichever Freemius styles are actually registered
        $deps = [];
        foreach (['fs_common', 'fs_account', 'fs_checkout'] as $handle) {
            if (wp_style_is($handle, 'registered') || wp_style_is($handle, 'enqueued')) {
                $deps[] = $handle;
            }
        }

        wp_enqueue_style(
            'walletup-freemius-override',
            WALLET_UP_URL . 'assets/css/walletup-freemius.css',
            $deps,
            WALLET_UP_VERSION,
            'all'
        );
    }

    /**
     * Enqueue QR protection CSS on frontend pages that may display QR codes
     */
    public function enqueueFrontendQRProtect(): void
    {
        $is_wc_page = function_exists('is_checkout') && (
            is_checkout()
            || (function_exists('is_cart') && is_cart()) // WalletUp Pay express lane renders in the cart express area too
            || is_wc_endpoint_url('order-received')
        );
        $has_shortcode = $this->pageHasWalletUpShortcode();

        if ($is_wc_page || $has_shortcode) {
            wp_enqueue_style(
                'walletup-qr-protect',
                WALLET_UP_URL . 'assets/css/walletup-qr-protect.css',
                [],
                $this->version
            );
            // Cap gateway icon size on legacy WC checkout — themes often leave
            // gateway PNGs at native dimensions and they blow up the row.
            wp_enqueue_style(
                'walletup-wc-checkout-icons',
                WALLET_UP_URL . 'assets/css/wc-checkout-icons.css',
                [],
                $this->version
            );
            // WalletUp Pay express lane — button + method drawer.
            wp_enqueue_style(
                'walletup-pay',
                WALLET_UP_URL . 'assets/css/walletup-pay.css',
                [],
                $this->version
            );
            // Stripe.js for the WalletUp Pay one-tap path. Loaded here rather than
            // as a Blocks payment-method script dependency (WC Blocks drops the
            // method if an external handle has no asset metadata). Stripe also
            // recommends loading v3 on checkout pages for fraud signals.
            if (!wp_script_is('stripe-js', 'enqueued')) {
                wp_enqueue_script('stripe-js', 'https://js.stripe.com/v3/', [], null, true);
            }
        }
    }

    /**
     * Enqueue click tracking JS on ALL frontend pages unconditionally.
     * Like Google Analytics — always present, 600 bytes, does nothing if
     * no [data-wallet-up-method] elements exist on the page.
     * Fires sendBeacon to admin-ajax.php on click (uses existing CF session).
     */
    public function enqueueClickTracking(): void
    {
        if (is_admin()) {
            return;
        }

        wp_enqueue_script(
            'walletup-events',
            WALLET_UP_URL . 'assets/js/wup-events.js',
            [],
            $this->version . '.2',
            true
        );
        wp_localize_script('walletup-events', 'wupEvt', [
            'u' => admin_url('admin-ajax.php'),
            'n' => wp_create_nonce('wallet_up_admin_nonce'),
        ]);
    }

    private function pageHasWalletUpShortcode(): bool
    {
        global $post;
        if (!is_object($post) || empty($post->post_content)) {
            return false;
        }
        return has_shortcode($post->post_content, 'walletup_qr_generator')
            || has_shortcode($post->post_content, 'wallet_up_payer')
            || has_shortcode($post->post_content, 'wallet_up_donation');
    }
    public static function isWooCommerceActive(): bool
    {
        $checks = [
            defined('WC_VERSION'),
            class_exists('WooCommerce'),
            class_exists('WC_Payment_Gateway'),
            function_exists('WC')
        ];
        if (!in_array(false, $checks, true)) {
            return true;
        }
        return false;
    }
    /**
     * Enqueue assets for the admin area, including the React app
     */
    public function enqueueAdminAssets($hook_suffix): void
    {
        if (strpos($hook_suffix, 'wallet-up') === false) {
            return;
        }

        // Media library — needed by the per-method custom QR image uploader (Zelle).
        if (function_exists('wp_enqueue_media')) {
            wp_enqueue_media();
        }

        // Enqueue core WordPress dependencies
        foreach (self::getAdminDeps()['scripts'] as $dep) {
            if (wp_script_is($dep, 'registered')) {
                wp_enqueue_script($dep);
            } else {
            }
        }

        foreach (self::getAdminDeps()['styles'] as $dep) {
            if (wp_style_is($dep, 'registered')) {
                wp_enqueue_style($dep);
            } else {
            }
        }

        // Enqueue registered admin assets
        foreach ($this->scripts['admin'] ?? [] as $handle => $script) {
            wp_enqueue_script($handle, $script['src'], $script['deps'], $script['ver'], $script['in_footer']);
        }

        foreach ($this->styles['admin'] ?? [] as $handle => $style) {
            wp_enqueue_style($handle, $style['src'], $style['deps'], $style['ver'], $style['media']);
        }

        // Enqueue React application
        $this->enqueueReactApp();


        // Optional: Add Spectrum color picker for enhanced color selection if walletup_qr_generator shortcode exists
        /* global $post;
        if (is_object($post) && has_shortcode($post->post_content, 'walletup_qr_generator')) {
            wp_enqueue_style(
                'walletup-spectrum',
                WALLET_UP_URL . 'assets/vendor/spectrum/spectrum.min.css',
                [],
                '1.8.1'
            );

            wp_enqueue_script(
                'walletup-spectrum',
                WALLET_UP_URL . 'assets/vendor/spectrum/spectrum.min.js',
                ['jquery'],
                '1.8.1',
                true
            );
        } */

        // Freemius CSS override is enqueued via enqueueFreemiusOverride() at priority 9999

    }
    // WORKING >>
    /**
     * Enqueue the React application specifically
     */
    /* private function enqueueReactApp(): void
     {
         try {
             // Get manifest
             $manifest_path = WALLET_UP_BASE_DIR . 'walup-react/dist/.vite/manifest.json';
             if (!file_exists($manifest_path)) {
                 throw new \Exception(esc_html('React build manifest not found'));
             }

             $manifest = json_decode(file_get_contents($manifest_path), true);
             if (!isset($manifest['src/main.jsx'])) {
                 throw new \Exception(esc_html('React entry point not found in manifest'));
             }

             $entry = $manifest['src/main.jsx'];
             $dist_url = WALLET_UP_BASE_URL . 'walup-react/dist/';

             // Enqueue the React app bundle
             wp_enqueue_script(
                 'wallet-up-react',
                 $dist_url . $entry['file'],
                 self::getAdminDeps()['scripts'],
                 $this->version,
                 true
             );

             // Enqueue CSS files from the manifest
             if (isset($entry['css']) && is_array($entry['css'])) {
                 foreach ($entry['css'] as $index => $css_file) {
                     wp_enqueue_style(
                         'wallet-up-styles-' . $index,
                         $dist_url . $css_file,
                         [],
                         $this->version
                     );
                 }
             }

             // Localize script
             wp_localize_script(
                 'wallet-up-react',
                 'walletUpData',
                 $this->getAdminDataForReact()
             );

         } catch (\Exception $e) {
             // Here you might want to show an error in the admin area
         }
     }

    /* private function getAdminDataForReact(): array
     {
         return [
             'nonce' => wp_create_nonce('wallet_up_admin_nonce'),
             'ajaxUrl' => admin_url('admin-ajax.php'),
             'settings' => get_option('wallet_up_transfer_call', []),
             'displaySettings' => get_option('wallet_up_display_settings', []),
             'paths' => [
                 'assets' => esc_url_raw(WALLET_UP_BASE_URL . 'assets/'),
             ],
             'i18n' => [
                 'saveSuccess' => __('Settings saved successfully', 'walletup'),
                 'saveError' => __('Error saving settings', 'walletup'),
                 'confirmReset' => __('Are you sure you want to reset all settings?', 'walletup'),
                 'loading' => __('Loading...', 'walletup'),
                 'validationErrors' => [
                     'email' => __('Please enter a valid email address', 'walletup'),
                     'required' => __('This field is required', 'walletup'),
                     'phoneNumber' => __('Please enter a valid phone number', 'walletup')
                 ]
             ],
             'qrExtensionsAvailable' => $this->checkQRStatus()['qr_available'],
             'gdAvailable' => $this->checkQRStatus()['gd_available'],
             'imagickAvailable' => $this->checkQRStatus()['imagick_available'],
             'debug' => defined('WP_DEBUG') && WP_DEBUG
         ];
     } */  // WORKING <<< 
    /* WORKING
    private function enqueueReactApp(): void
    {
        try {
            // Get manifest
            $manifest_path = WALLET_UP_BASE_DIR . 'walup-react/dist/.vite/manifest.json';
            if (!file_exists($manifest_path)) {
                throw new \Exception(esc_html('React build manifest not found'));
            }

            $manifest = json_decode(file_get_contents($manifest_path), true);
            if (!isset($manifest['src/main.jsx'])) {
                throw new \Exception(esc_html('React entry point not found in manifest'));
            }

            $entry = $manifest['src/main.jsx'];
            $dist_url = WALLET_UP_BASE_URL . 'walup-react/dist/';

            // Register script with a unique handle
            $script_handle = 'wallet-up-react-admin';
            wp_register_script(
                $script_handle,
                $dist_url . $entry['file'],
                self::getAdminDeps()['scripts'], // Use existing ADMIN_DEPS
                $this->version,
                true
            );

            // Add module type attribute + Cloudflare Rocket Loader bypass
            add_filter('script_loader_tag', function ($tag, $handle) use ($script_handle) {
                if ($script_handle === $handle) {
                    return str_replace('<script ', '<script type="module" crossorigin data-cfasync="false" ', $tag);
                }
                return $tag;
            }, 10, 2);

            // Register and enqueue CSS files
            if (isset($entry['css']) && is_array($entry['css'])) {
                foreach ($entry['css'] as $index => $css_file) {
                    $style_handle = $script_handle . '-' . $index;
                    wp_register_style(
                        $style_handle,
                        $dist_url . $css_file,
                        self::getAdminDeps()['styles'],
                        $this->version,
                        'all'
                    );
                    wp_enqueue_style($style_handle);
                }
            }

            // Localize script
            wp_localize_script(
                $script_handle,
                'walletUpData',
                $this->getAdminDataForReact()

            );
            $data = $this->getAdminDataForReact();

            // Enqueue the script
            wp_enqueue_script($script_handle);


        } catch (\Exception $e) {
            $this->errorHandler->log('Failed to load React admin assets: ' . $e->getMessage());
        }
    } */

    // private function enqueueReactApp(): void
    // {
    //     try {
    //         // Get manifest
    //         $manifest_path = WALLET_UP_BASE_DIR . 'walup-react/dist/.vite/manifest.json';
    //         if (!file_exists($manifest_path)) {
    //             throw new \Exception(esc_html('React build manifest not found'));
    //         }

    //         $manifest = json_decode(file_get_contents($manifest_path), true);
    //         if (!isset($manifest['src/main.jsx'])) {
    //             throw new \Exception(esc_html('React entry point not found in manifest'));
    //         }

    //         $entry = $manifest['src/main.jsx'];
    //         $dist_url = WALLET_UP_BASE_URL . 'walup-react/dist/';

    //         // Register script with a unique handle
    //         $script_handle = 'wallet-up-react-admin';
    //         wp_register_script(
    //             $script_handle,
    //             $dist_url . $entry['file'],
    //             self::getAdminDeps()['scripts'], // Use existing ADMIN_DEPS
    //             $this->version,
    //             true
    //         );

    //         // Add module type attribute
    //         add_filter('script_loader_tag', function ($tag, $handle) use ($script_handle) {
    //             if ($script_handle === $handle) {
    //                 return str_replace('<script ', '<script type="module" crossorigin ', $tag);
    //             }
    //             return $tag;
    //         }, 10, 2);

    //         // Register and enqueue CSS files
    //         if (isset($entry['css']) && is_array($entry['css'])) {
    //             foreach ($entry['css'] as $index => $css_file) {
    //                 $style_handle = $script_handle . '-' . $index;
    //                 wp_register_style(
    //                     $style_handle,
    //                     $dist_url . $css_file,
    //                     self::getAdminDeps()['styles'],
    //                     $this->version,
    //                     'all'
    //                 );
    //                 wp_enqueue_style($style_handle);
    //             }
    //         }

    //         // Localize script - Combine all necessary data here
    //         $data = $this->getAdminDataForReact();

    //         $data['nonces'] = [
    //             'classManager' => wp_create_nonce('wp_rest'), // For REST API interactions in ClassManager
    //             'wallet_up_save_settings' => wp_create_nonce('wallet_up_save_settings'), // For saving settings
    //             'wallet_up_check_qr_status' => wp_create_nonce('wallet_up_check_qr_status') // For checking QR status
    //         ];

    //         $data['ajaxUrl'] = admin_url('admin-ajax.php');

    //         // Determine premium status and upgrade URL with fallbacks
    //         // First try using the function
    //         $isPremium = false;
    //         $upgradeUrl = admin_url('admin.php?page=wallet-up-pricing');

    //         // Safety check hierarchy:
    //         // 1. Check if function exists
    //         // 2. Check if function returns valid object
    //         // 3. Check if needed methods exist
    //         // 4. Try to get values with fallbacks

    //         if (function_exists('wallet_up_fs')) {
    //             try {
    //                 $fs = wallet_up_fs();
    //                 if ($fs && is_object($fs)) {
    //                     // Check for premium status
    //                     if (method_exists($fs, 'can_use_premium_code')) {
    //                         $isPremium = $fs->can_use_premium_code();
    //                     }

    //                     // Get upgrade URL - ensure it points to the pricing page
    //                     if (method_exists($fs, 'get_upgrade_url')) {
    //                         // Get the URL but ensure it has the correct endpoint
    //                         $rawUrl = $fs->get_upgrade_url();
    //                         if (strpos($rawUrl, 'page=wallet-up-pricing') === false) {
    //                             // Force the pricing page if not present
    //                             $upgradeUrl = admin_url('admin.php?page=wallet-up-pricing');
    //                         } else {
    //                             $upgradeUrl = $rawUrl;
    //                         }
    //                     }
    //                 }
    //             } catch (\Exception $fsException) {
    //                 // Log but continue with defaults
    //             }
    //         }

    private function enqueueReactApp(): void
    {
        try {
            // Get manifest
            $manifest_path = WALLET_UP_BASE_DIR . 'walup-react/dist/.vite/manifest.json';
            if (!file_exists($manifest_path)) {
                throw new \Exception(esc_html('React build manifest not found'));
            }

            $manifest = json_decode(file_get_contents($manifest_path), true);
            if (!isset($manifest['src/main.jsx'])) {
                throw new \Exception(esc_html('React entry point not found in manifest'));
            }

            $entry = $manifest['src/main.jsx'];
            $dist_url = WALLET_UP_BASE_URL . 'walup-react/dist/';

            // Register script with a unique handle
            $script_handle = 'wallet-up-react-admin';
            wp_register_script(
                $script_handle,
                $dist_url . $entry['file'],
                self::getAdminDeps()['scripts'],
                $this->version,
                true
            );

            // Add module type attribute + Cloudflare Rocket Loader bypass
            add_filter('script_loader_tag', function ($tag, $handle) use ($script_handle) {
                if ($script_handle === $handle) {
                    return str_replace('<script ', '<script type="module" crossorigin data-cfasync="false" ', $tag);
                }
                return $tag;
            }, 10, 2);

            // Register and enqueue CSS files
            if (isset($entry['css']) && is_array($entry['css'])) {
                foreach ($entry['css'] as $index => $css_file) {
                    $style_handle = $script_handle . '-' . $index;
                    wp_register_style(
                        $style_handle,
                        $dist_url . $css_file,
                        self::getAdminDeps()['styles'],
                        $this->version,
                        'all'
                    );
                    wp_enqueue_style($style_handle);
                }
            }

            // Prepare localization data
            $data = $this->getAdminDataForReact();
            // Merge additional nonces (don't overwrite ones from getAdminDataForReact)
            $data['nonces'] = array_merge($data['nonces'] ?? [], [
                'wallet_up_admin' => wp_create_nonce('wallet_up_admin_nonce'),
                'classManager' => wp_create_nonce('wp_rest'),
                'wallet_up_save_settings' => wp_create_nonce('wallet_up_save_settings'),
                'wallet_up_check_qr_status' => wp_create_nonce('wallet_up_check_qr_status'),
            ]);
            $data['ajaxUrl'] = admin_url('admin-ajax.php');
            $data['restUrl'] = esc_url_raw(rest_url());
            $data['restNonce'] = wp_create_nonce('wp_rest');

            // Get Freemius premium status and upgrade URL
            $freemiusData = $this->getFreemiusData();
            $data['isPremium'] = $freemiusData['isPremium'];
            $data['isProBuild'] = $freemiusData['isProBuild'] ?? false;
            $data['upgradeUrl'] = $freemiusData['upgradeUrl'];
            $data['checkoutUrl'] = $freemiusData['checkoutUrl'];

            $premiumManager = \WalletUpPro\Core\Manager\PremiumFeaturesManager::getInstance();
            $data = $premiumManager->addScriptData($data);

            // Localize script for the main React admin app
            wp_localize_script($script_handle, 'walletUpData', $data);

            // Localize script for QR generator specifically
            if (wp_script_is('wallet-up-qr-generator', 'registered')) {
                wp_localize_script(
                    'wallet-up-qr-generator',
                    'walletUpData',
                    $data
                );
            }

            // Enqueue the main React admin script
            wp_enqueue_script($script_handle);

            // Cloudflare protection: inline fallback if main JS fails to load
            $js_url = esc_url($dist_url . $entry['file']);
            $this->addAssetLoadFallback($script_handle, $js_url);

        } catch (\Exception $e) {
            $this->errorHandler->log('Failed to load React admin assets: ' . $e->getMessage());
            // Show admin notice when assets can't load at all
            add_action('admin_notices', function () use ($e) {
                if (strpos($GLOBALS['hook_suffix'] ?? '', 'wallet-up') === false) {
                    return;
                }
                echo '<div class="notice notice-error"><p><strong>WalletUp Pro:</strong> ';
                echo esc_html('Unable to load admin interface. ');
                if (strpos($e->getMessage(), 'manifest') !== false) {
                    echo esc_html('Build files are missing. Please re-upload the plugin or run the build pipeline.');
                } else {
                    echo esc_html('Error: ' . $e->getMessage());
                }
                echo '</p></div>';
            });
        }
        // Add direct premium status check in page (most reliable method)
        add_action('admin_footer', function () {
            // Only add this script on plugin admin pages
            global $hook_suffix;
            if (strpos($hook_suffix, 'wallet-up') === false) {
                return;
            }

            $can_use_premium = function_exists('wallet_up_fs') && wallet_up_fs()->can_use_premium_code();
            $is_paying = function_exists('wallet_up_fs') && !wallet_up_fs()->is_not_paying();
            $is_trial = function_exists('wallet_up_fs') && wallet_up_fs()->is_trial();

            $trial_days = 0;
            if ($is_trial && method_exists(wallet_up_fs(), 'get_trial_days_left')) {
                $trial_days = wallet_up_fs()->get_trial_days_left();
            }

            // Get plan ID if available
            $plan_id = '';
            if (function_exists('wallet_up_fs')) {
                $license = wallet_up_fs()->_get_license();
                if (is_object($license)) {
                    $plan_id = $license->plan_id;
                }
            }

            ?>
                        <script type="text/javascript">
                            (function () {
                                window.walletUpData = window.walletUpData || {};
                                window.walletUpData.premium_status = {
                                    can_use_premium_code: <?php echo wp_json_encode($can_use_premium); ?>,
                                    is_paying: <?php echo wp_json_encode($is_paying); ?>,
                                    is_trial: <?php echo wp_json_encode($is_trial); ?>,
                                    trial_days_left: <?php echo wp_json_encode($trial_days); ?>,
                                    plan_id: <?php echo wp_json_encode($plan_id); ?>,
                                    last_check: <?php echo esc_js(intval(time())); ?>
                                };

                                // Debug notice
                                if (window.walletUpData.debug) {
                                }

                                // Dispatch a custom event so components can react to premium status updates
                                document.dispatchEvent(new CustomEvent('walletUpPremiumStatusUpdated', {
                                    detail: window.walletUpData.premium_status
                                }));
                            })();
                        </script>
                        <?php
        });
    }
    /**
     * Retrieve Freemius premium status and URLs with fallbacks.
     * 
     * This method follows a chain of fallbacks to ensure the most accurate
     * premium status information possible is always provided.
     * 
     * @return array Associative array with 'isPremium', 'upgradeUrl', 'checkoutUrl', and 'trialInfo'.
     */
    private function getFreemiusData(): array
    {
        $isPremium = false;
        $isPaying = false;
        $defaultUpgradeUrl = admin_url('admin.php?page=wallet-up-pricing');
        $upgradeUrl = $defaultUpgradeUrl;
        $checkoutUrl = '';
        $planId = '';
        $licenseId = '';
        $trialInfo = null;

        // Get data from transient cache first
        $cachedData = get_transient('wallet_up_premium_status_check');
        if ($cachedData && is_array($cachedData)) {
            // Only use cache if it's less than 5 minutes old
            if (!empty($cachedData['timestamp']) && (time() - $cachedData['timestamp'] < 300)) {
                return $cachedData;
            }
        }

        // Pro codebase present (regardless of license). Source of truth is our own build
        // constant — Freemius's is_premium() depends on plugin registration state which
        // returns false on fresh installs even with a valid license.
        $isProBuild = defined('WALLET_UP_IS_PRO_BUILD') && WALLET_UP_IS_PRO_BUILD;

        if (function_exists('wallet_up_fs')) {
            try {
                $fs = wallet_up_fs();
                if (is_object($fs)) {
                    // Licensed/paying status — for places that need to actually *unlock* paid behavior.
                    if (method_exists($fs, 'can_use_premium_code')) {
                        $isPremium = $fs->can_use_premium_code();
                    }

                    if (method_exists($fs, 'is_not_paying')) {
                        $isPaying = !$fs->is_not_paying();
                    }

                    // Get trial info if applicable
                    if (method_exists($fs, 'is_trial') && $fs->is_trial()) {
                        $trialInfo = [
                            'is_trial' => true,
                            'plan' => method_exists($fs, 'get_trial_plan') ? $fs->get_trial_plan() : null,
                            'days_left' => method_exists($fs, 'get_trial_days_left') ? $fs->get_trial_days_left() : null
                        ];
                    }

                    // Get plan information if available
                    if (method_exists($fs, 'get_current_or_network_user_id')) {
                        $user_id = $fs->get_current_or_network_user_id();
                        if ($user_id) {
                            $license = $fs->_get_license();
                            if (is_object($license)) {
                                $planId = $license->plan_id;
                                $licenseId = $license->id;
                            }
                        }
                    }

                    if (method_exists($fs, 'checkout_url')) {
                        $checkoutUrl = $fs->checkout_url();
                        if (empty($checkoutUrl)) {
                        }
                    }

                    // Get upgrade URL as secondary option (pricing page)
                    if (method_exists($fs, 'get_upgrade_url')) {
                        $rawUrl = $fs->get_upgrade_url();
                        if (!empty($rawUrl)) {
                            $upgradeUrl = $rawUrl;
                        } else {
                        }
                    }
                }
            } catch (\Exception $e) {
                // Silently fall back to defaults
            }
        }

        $result = [
            'isPremium' => $isPremium,
            'isProBuild' => $isProBuild,
            'isPaying' => $isPaying,
            'upgradeUrl' => $upgradeUrl,
            'checkoutUrl' => $checkoutUrl,
            'planId' => $planId,
            'licenseId' => $licenseId,
            'trialInfo' => $trialInfo,
            'timestamp' => time()
        ];

        set_transient('wallet_up_premium_status_check', $result, 300);

        return $result;
    }
    private function getAdminDataForReact(): array
    {
        // Get clean site URL with proper path structure
        $siteUrl = rtrim(get_home_url(), '/');

        $customPaths = [
            'payer' => [
                'path' => 'pay',
                'shortcode' => 'wallet_up_payer'
            ],
            'donation' => [
                'path' => 'donate',
                'shortcode' => 'wallet_up_donation'
            ]

        ];
        return [
            'nonce' => wp_create_nonce('wallet_up_admin_nonce'),
            'dismissNonce' => wp_create_nonce('wallet_up_dismiss_notice'),
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'locale' => get_locale(),
            'pluginUrl' => WALLET_UP_URL,
            'settings' => $this->mergeCustomQrImages(get_option('wallet_up_transfer_call', [])),
            'customQrImages' => get_option('wallet_up_custom_qr_images', []),
            'displaySettings' => get_option('wallet_up_display_settings', []),
            'siteUrl' => $siteUrl,
            'mobileMoneySettings' => get_option('wallet_up_mobile_money_settings', []),
            'stripeConfig' => $this->getSafeStripeConfig(),
            'paypalCommerceSettings' => $this->getSafePaypalCommerceConfig(),
            'customPaths' => $customPaths,
            'paths' => [
                'assets' => esc_url_raw(WALLET_UP_BASE_URL . 'assets/'),
            ],
            'i18n' => [
                'saveSuccess' => __('Settings saved successfully', 'walletup'),
                'saveError' => __('Error saving settings', 'walletup'),
                'confirmReset' => __('Are you sure you want to reset all settings?', 'walletup'),
                'loading' => __('Loading...', 'walletup'),
                'validationErrors' => [
                    'email' => __('Please enter a valid email address', 'walletup'),
                    'required' => __('This field is required', 'walletup'),
                    'phoneNumber' => __('Please enter a valid phone number', 'walletup')
                ]
            ],
            'woocommerce' => [
                'nonces' => [
                    'wcSettings' => wp_create_nonce('wallet_up_wc_save_settings'),
                    'wcGetSettings' => wp_create_nonce('wallet_up_wc_settings'),
                    'wcPaymentDisplay' => wp_create_nonce('wallet_up_wc_payment_display'),
                    'wcMethodSettings' => wp_create_nonce('wallet_up_admin_nonce'),
                    'wcDisplayMode' => wp_create_nonce('wallet_up_admin_nonce'),
                ]
            ],

            // Invoice Generator
            'payment' => [
                'nonces' => [
                    'payment' => wp_create_nonce('wallet_up_payment_nonce'),
                    'generate' => wp_create_nonce('wallet_up_generate_payment')
                ],
                'settings' => [
                    'rateLimit' => defined('WALLET_UP_RATE_LIMIT') ? WALLET_UP_RATE_LIMIT : 10,
                    'ratePeriod' => defined('WALLET_UP_RATE_PERIOD') ? WALLET_UP_RATE_PERIOD : 300
                ]
            ],
            'qrExtensionsAvailable' => $this->checkQRStatus()['qr_available'],
            'gdAvailable' => $this->checkQRStatus()['gd_available'],
            'imagickAvailable' => $this->checkQRStatus()['imagick_available'],
            'wooCommerceActive' => class_exists('WooCommerce'),
            'healthCheck' => \WalletUpPro\Core\Admin\ElevationTracker::runChecks(),
            'enabledMethods' => get_option('wallet_up_enabled_methods', []),
            'methodStatus' => \WalletUpPro\Core\Payments\MethodStatusResolver::snapshot(),
            'allPaymentMethods' => $this->getAllPaymentMethodsForReact(),
            'adminV2' => get_option('wallet_up_admin_v2', 'yes') === 'yes',
            'cashappApi' => class_exists(\WalletUpPro\Payments\CashAppPayAPI::class) ? \WalletUpPro\Payments\CashAppPayAPI::getCredentials() : [],
            'venmoApi' => class_exists(\WalletUpPro\Payments\VenmoBraintreeAPI::class) ? \WalletUpPro\Payments\VenmoBraintreeAPI::getCredentials() : [],
            // WPForms Data
            'wpforms' => $this->getWPFormsData(),

            // Security Nonces
            'nonces' => [
                'wallet_up_admin' => wp_create_nonce('wallet_up_admin_nonce'),
                'wallet_up_save_settings' => wp_create_nonce('wallet_up_save_settings'),
                'wallet_up_check_qr_status' => wp_create_nonce('wallet_up_check_qr_status'),
                'wallet_up_toggle_wpforms' => wp_create_nonce('wallet_up_toggle_wpforms'),
                'wallet_up_check_wpforms' => wp_create_nonce('wallet_up_check_wpforms'),
                'walup_submit_donation' => wp_create_nonce('walup_submit_donation'),
                'walup_get_form_config' => wp_create_nonce('walup_get_form_config'),
                'wallet_up_complete_donation' => wp_create_nonce('wallet_up_complete_donation'),
                'wallet_up_create_donation_payment' => wp_create_nonce('wallet_up_create_donation_payment'),
            ]
        ];

    }

    /**
     * Get all payment methods from PaymentMethodsConfig for React.
     * Returns id, name, and type for each method.
     */
    private function getAllPaymentMethodsForReact(): array
    {
        // Map Tailwind color classes to hex for frontend use
        $colorMap = [
            'green-600' => '#00D632', 'blue-600' => '#2563EB', 'purple-600' => '#6D1ED4',
            'orange-500' => '#F7931A', 'indigo-600' => '#627EEA', 'green-500' => '#26A17B',
            'blue-500' => '#2775CA', 'yellow-500' => '#F3BA2F', 'yellow-600' => '#C3A634',
            'orange-500' => '#FF6600', 'red-600' => '#ED1C24',
        ];

        $methods = [];
        if (class_exists('\WalletUpPro\Core\Config\PaymentMethodsConfig')) {
            $allIds = \WalletUpPro\Core\Config\PaymentMethodsConfig::getAllMethodIds();
            foreach ($allIds as $id) {
                $config = \WalletUpPro\Core\Config\PaymentMethodsConfig::getMethodConfig($id);
                $twColor = $config['icon_color'] ?? '';
                $methods[] = [
                    'id'    => $id,
                    'name'  => $config['name'] ?? $id,
                    'type'  => $config['type'] ?? 'traditional',
                    'color' => $colorMap[$twColor] ?? '#6b7280',
                ];
            }
        }
        return $methods;
    }

    /**
     * Fold per-method custom QR image URLs into the settings blob React reads, as
     * {methodId}_qr_image keys. They ride back on save and are split out server-side.
     */
    private function mergeCustomQrImages(array $transferCall): array
    {
        $images = get_option('wallet_up_custom_qr_images', []);
        if (is_array($images)) {
            foreach ($images as $methodId => $url) {
                $transferCall[$methodId . '_qr_image'] = $url;
            }
        }
        // The Zelle display name lives in its own option; surface it so the Payments page
        // input shows the saved value and rides back on the next save.
        $zelleName = get_option('wallet_up_zelle_name', '');
        if ($zelleName !== '') {
            $transferCall['zelle_name'] = $zelleName;
        }
        return $transferCall;
    }

    private function getSafeStripeConfig(): array
    {
        $config = get_option('wallet_up_stripe_config', []);
        return [
            'publishable_key' => $config['publishable_key'] ?? '',
            'mode' => $config['mode'] ?? 'test',
        ];
    }

    private function getSafePaypalCommerceConfig(): array
    {
        $config = get_option('wallet_up_paypal_commerce_settings', []);
        return [
            'client_id' => $config['client_id'] ?? '',
            'mode' => $config['mode'] ?? 'sandbox',
        ];
    }

    /**
     * Retrieves WPForms-related data for localization.
     */
    private function getWPFormsData(): array
    {
        if (!class_exists('WalletUpPro\WpForms\Forms\WPFormsService')) {
            return ['available' => false];
        }

        $wpformsService = \WalletUpPro\WpForms\Forms\WPFormsService::getInstance($this->errorHandler);

        // We'll call getTemplateStatus() here, which has been updated to use caching
        $templateStatus = $wpformsService->getTemplateStatus();

        return [
            'available' => $wpformsService->isActive(),
            'enabled' => $wpformsService->isTemplateEnabled(),
            'version' => $wpformsService->getVersion(),
            'template_status' => $templateStatus,
            'initialized' => $wpformsService->isInitialized()
        ];
    }
    private function checkQRStatus(): array
    {
        $has_gd = extension_loaded('gd');
        $has_imagick = extension_loaded('imagick');

        return [
            'qr_available' => $has_gd || $has_imagick,
            'gd_available' => $has_gd,
            'imagick_available' => $has_imagick
        ];
    }

    /**
     * Add inline fallback script that detects if the main JS bundle failed to load.
     * Handles: Cloudflare blocking, stale CDN cache, 403 permissions, network errors.
     * Shows a user-friendly error with actionable steps instead of a blank page.
     *
     * Security: No user-controlled data in output. URL comes from local Vite manifest
     * and is escaped via esc_url() + wp_json_encode(). DOM constructed via textContent
     * where possible; static HTML only for structure (no interpolated values in innerHTML).
     */
    private function addAssetLoadFallback(string $scriptHandle, string $jsUrl): void
    {
        add_action('admin_footer', function () use ($scriptHandle, $jsUrl) {
            if (strpos($GLOBALS['hook_suffix'] ?? '', 'wallet-up') === false) {
                return;
            }
            // Nonce to verify this inline script is legitimate (CSP-friendly)
            $nonce = wp_create_nonce('walletup_asset_fallback');
            ?>
            <script data-cfasync="false" data-walletup-fallback="<?php echo esc_attr($nonce); ?>">
            (function() {
                var rootEl = document.getElementById('walletup-admin-root') || document.getElementById('wallet-up-admin-root');
                if (!rootEl) return;

                // Check after 8 seconds if React mounted anything
                setTimeout(function() {
                    if (rootEl.children.length > 0) return; // React loaded fine

                    // React didn't mount — asset likely blocked or corrupted
                    var container = document.createElement('div');
                    container.setAttribute('role', 'alert');
                    container.style.cssText = 'max-width:600px;margin:40px auto;padding:24px;background:#fff3cd;border:1px solid #ffc107;border-radius:8px;font-family:-apple-system,sans-serif;color:#664d03;';

                    var h3 = document.createElement('h3');
                    h3.style.cssText = 'margin:0 0 12px';
                    h3.textContent = 'WalletUp Pro: Admin interface failed to load';
                    container.appendChild(h3);

                    var p1 = document.createElement('p');
                    p1.style.cssText = 'margin:0 0 8px';
                    p1.textContent = 'The main JavaScript bundle could not be loaded. This is usually caused by:';
                    container.appendChild(p1);

                    var ul = document.createElement('ul');
                    ul.style.cssText = 'margin:0 0 12px;padding-left:20px';
                    var causes = [
                        ['Cloudflare cache', 'Purge cache in your Cloudflare dashboard'],
                        ['Cloudflare Rocket Loader', 'Disable it or add an exception for admin pages'],
                        ['File permissions', 'Ensure plugin files are readable by the web server (chown to correct user)'],
                        ['Browser extension', 'Disable ad blockers or privacy extensions on this page']
                    ];
                    causes.forEach(function(c) {
                        var li = document.createElement('li');
                        var b = document.createElement('strong');
                        b.textContent = c[0];
                        li.appendChild(b);
                        li.appendChild(document.createTextNode(' \u2014 ' + c[1]));
                        ul.appendChild(li);
                    });
                    container.appendChild(ul);

                    var p2 = document.createElement('p');
                    p2.style.cssText = 'margin:0;font-size:13px;color:#856404';
                    p2.textContent = 'If the issue persists after clearing cache and fixing permissions, contact support.';
                    container.appendChild(p2);

                    rootEl.appendChild(container);
                }, 8000);
            })();
            </script>
            <?php
        }, 99);
    }

    public function registerScript(string $handle, string $src, array $deps, bool $inFooter, string $context): void
    {
        $this->scripts[$context][$handle] = [
            'src' => $src,
            'deps' => $deps,
            'ver' => $this->version,
            'in_footer' => $inFooter
        ];
    }

    public function registerStyle(string $handle, string $src, array $deps, string $media, string $context): void
    {
        $this->styles[$context][$handle] = [
            'src' => $src,
            'deps' => $deps,
            'ver' => $this->version,
            'media' => $media
        ];
    }
}