<?php
namespace Mamba\Lifecycle;

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

use Mamba\Lifecycle\ConflictDetector;

/**
 * Welcome modal for first-time plugin activation
 * Informing users that caching is enabled by default
 */
final class Welcome {
    private const WELCOME_SHOWN_OPTION = 'mamba_welcome_shown';
    private const REDIRECT_TRANSIENT = 'mamba_activation_redirect';
    
    /**
     * Register welcome modal hooks
     */
    public static function register(): void {
        // Set redirect flag on activation
        add_action('activated_plugin', [__CLASS__, 'setActivationRedirect'], 10, 2);
        
        // Handle redirect after activation
        add_action('admin_init', [__CLASS__, 'maybeRedirect'], 1);
        
        // Show welcome modal on Mamba admin page
        add_action('admin_footer', [__CLASS__, 'renderWelcomeModal']);
        
        // AJAX handler to dismiss welcome modal
        add_action('wp_ajax_mamba_dismiss_welcome', [__CLASS__, 'dismissWelcome']);
        
        // AJAX handler to enable caching from welcome modal
        add_action('wp_ajax_mamba_welcome_enable_cache', [__CLASS__, 'enableCacheFromWelcome']);
    }
    
    /**
     * Set activation redirect flag when plugin is activated
     * Note: Freemius handles the actual redirect via 'first-path' setting,
     * but we keep this for non-Freemius scenarios and to reset welcome state.
     */
    public static function setActivationRedirect(string $plugin, bool $network_wide): void {
        if ($network_wide) {
            return;
        }
        
        // Check if this is our plugin being activated
        // Match various possible plugin paths/names
        $isOurPlugin = strpos($plugin, 'mamba-woo-cache.php') !== false || 
                       strpos($plugin, 'mamba-caching') !== false ||
                       strpos($plugin, 'mamba-cache-for-woocommerce') !== false ||
                       strpos($plugin, 'mamba-cache-premium') !== false;
        
        if (!$isOurPlugin) {
            return;
        }
        
        // Don't redirect if bulk activating
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking for bulk activation flag
        if (isset($_GET['activate-multi'])) {
            return;
        }
        
        // Reset welcome shown flag on fresh activation so welcome modal appears
        // This ensures the welcome modal shows on first activation
        delete_option(self::WELCOME_SHOWN_OPTION);
        
        // Set transient for redirect (Freemius may handle this, but keep as backup)
        set_transient(self::REDIRECT_TRANSIENT, 1, 60);
    }
    
    /**
     * Redirect to Mamba admin page after activation
     */
    public static function maybeRedirect(): void {
        // Check for redirect transient
        if (!get_transient(self::REDIRECT_TRANSIENT)) {
            return;
        }
        
        // Delete transient to prevent repeated redirects
        delete_transient(self::REDIRECT_TRANSIENT);
        
        // Don't redirect if activating from network or doing AJAX
        if (is_network_admin() || defined('DOING_AJAX') || isset($_GET['activate-multi'])) {
            return;
        }
        
        // Redirect to Mamba admin page with welcome flag
        wp_safe_redirect(admin_url('admin.php?page=mamba&mamba_welcome=1'));
        exit;
    }
    
    /**
     * Check if welcome modal should be shown
     */
    public static function shouldShowWelcome(): bool {
        // Check if already shown
        if (get_option(self::WELCOME_SHOWN_OPTION, false)) {
            return false;
        }
        
        // Check if on Mamba admin page with welcome flag
        if (!is_admin() || !current_user_can('manage_options')) {
            return false;
        }
        
        // Check if we're on the Mamba admin page
        // Screen ID is 'toplevel_page_mamba' for the main page registered via Freemius
        $screen = get_current_screen();
        if (!$screen) {
            return false;
        }
        
        // Match the Mamba admin page - could be 'toplevel_page_mamba' or contain 'mamba'
        $validScreens = ['toplevel_page_mamba', 'mamba_page_mamba-account', 'mamba_page_mamba-pricing'];
        $isValidScreen = in_array($screen->id, $validScreens, true) || strpos($screen->id, 'page_mamba') !== false;
        
        if (!$isValidScreen) {
            return false;
        }
        
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking for welcome flag presence
        // Show welcome if flag is set or if this is first visit to Mamba page
        return isset($_GET['mamba_welcome']) || !get_option('mamba_first_visit_done', false);
    }
    
    /**
     * Render the welcome modal
     */
    public static function renderWelcomeModal(): void {
        if (!self::shouldShowWelcome()) {
            return;
        }
        
        // Mark first visit as done
        update_option('mamba_first_visit_done', true, false);
        
        $cacheEnabled = (bool) get_option('mamba_enable_page_cache', 0);
        $hasConflicts = ConflictDetector::hasConflicts();
        $conflictingPlugins = $hasConflicts ? ConflictDetector::getActiveConflicts() : [];
        ?>
        <div id="mamba-welcome-overlay" style="
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(15, 23, 42, 0.6);
            backdrop-filter: blur(4px);
            z-index: 999999;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        ">
            <div id="mamba-welcome-modal" style="
                background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
                border-radius: 16px;
                box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
                max-width: 480px;
                width: 90%;
                padding: 0;
                transform: scale(0.9) translateY(20px);
                transition: transform 0.3s ease;
                overflow: hidden;
            ">
                <!-- Header with gradient -->
                <div style="
                    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
                    padding: 32px 32px 24px;
                    text-align: center;
                ">
                    <div style="
                        width: 64px;
                        height: 64px;
                        background: rgba(255, 255, 255, 0.2);
                        border-radius: 16px;
                        display: inline-flex;
                        align-items: center;
                        justify-content: center;
                        margin-bottom: 16px;
                    ">
                        <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/>
                        </svg>
                    </div>
                    <h2 style="
                        color: white;
                        font-size: 24px;
                        font-weight: 700;
                        margin: 0 0 8px;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                    "><?php esc_html_e('Welcome to Mamba!', 'mamba-cache-for-woocommerce'); ?></h2>
                    <p style="
                        color: rgba(255, 255, 255, 0.9);
                        font-size: 14px;
                        margin: 0;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                    "><?php esc_html_e('High-performance caching for WooCommerce', 'mamba-cache-for-woocommerce'); ?></p>
                </div>
                
                <!-- Content -->
                <div style="padding: 24px 32px;">
                    <?php if ($hasConflicts): ?>
                    <!-- Conflict Warning Box -->
                    <div style="
                        background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
                        border: 1px solid #fca5a5;
                        border-radius: 12px;
                        padding: 16px;
                        margin-bottom: 20px;
                        display: flex;
                        align-items: flex-start;
                        gap: 12px;
                    ">
                        <div style="
                            width: 24px;
                            height: 24px;
                            background: #ef4444;
                            border-radius: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            flex-shrink: 0;
                        ">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                                <line x1="12" y1="9" x2="12" y2="13"/>
                                <line x1="12" y1="17" x2="12.01" y2="17"/>
                            </svg>
                        </div>
                        <div>
                            <p style="
                                margin: 0 0 4px;
                                font-weight: 600;
                                color: #991b1b;
                                font-size: 14px;
                                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                            ">
                                <?php esc_html_e('Caching Plugin Conflict Detected', 'mamba-cache-for-woocommerce'); ?>
                            </p>
                            <p style="
                                margin: 0 0 8px;
                                color: #b91c1c;
                                font-size: 13px;
                                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                            ">
                                <?php 
                                $pluginNames = array_values($conflictingPlugins);
                                printf(
                                    /* translators: %s: list of conflicting plugin names */
                                    esc_html__('Please deactivate %s before enabling Mamba Cache to avoid conflicts.', 'mamba-cache-for-woocommerce'),
                                    '<strong>' . esc_html(implode(', ', $pluginNames)) . '</strong>'
                                );
                                ?>
                            </p>
                            <a href="<?php echo esc_url(admin_url('plugins.php')); ?>" style="
                                display: inline-flex;
                                align-items: center;
                                gap: 4px;
                                color: #dc2626;
                                font-size: 12px;
                                font-weight: 600;
                                text-decoration: none;
                                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                            ">
                                <span class="dashicons dashicons-admin-plugins" style="font-size: 14px; width: 14px; height: 14px;"></span>
                                <?php esc_html_e('Go to Plugins', 'mamba-cache-for-woocommerce'); ?>
                            </a>
                        </div>
                    </div>
                    <?php else: ?>
                    <!-- Normal Status Box -->
                    <div style="
                        background: <?php echo esc_attr( $cacheEnabled ? '#dcfce7' : '#fef3c7' ); ?>;
                        border: 1px solid <?php echo esc_attr( $cacheEnabled ? '#86efac' : '#fcd34d' ); ?>;
                        border-radius: 12px;
                        padding: 16px;
                        margin-bottom: 20px;
                        display: flex;
                        align-items: flex-start;
                        gap: 12px;
                    ">
                        <div style="
                            width: 24px;
                            height: 24px;
                            background: <?php echo esc_attr( $cacheEnabled ? '#22c55e' : '#f59e0b' ); ?>;
                            border-radius: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            flex-shrink: 0;
                        ">
                            <?php if ($cacheEnabled): ?>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="20 6 9 17 4 12"/>
                            </svg>
                            <?php else: ?>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                                <circle cx="12" cy="12" r="10"/>
                                <line x1="12" y1="8" x2="12" y2="12"/>
                                <line x1="12" y1="16" x2="12.01" y2="16"/>
                            </svg>
                            <?php endif; ?>
                        </div>
                        <div>
                            <p style="
                                margin: 0 0 4px;
                                font-weight: 600;
                                color: <?php echo esc_attr( $cacheEnabled ? '#166534' : '#92400e' ); ?>;
                                font-size: 14px;
                                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                            ">
                                <?php echo $cacheEnabled 
                                    ? esc_html__('Caching has been automatically enabled', 'mamba-cache-for-woocommerce')
                                    : esc_html__('Page caching is currently disabled', 'mamba-cache-for-woocommerce'); ?>
                            </p>
                            <p style="
                                margin: 0;
                                color: <?php echo esc_attr( $cacheEnabled ? '#15803d' : '#a16207' ); ?>;
                                font-size: 13px;
                                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                            ">
                                <?php echo $cacheEnabled 
                                    ? esc_html__('Your store is now optimized and ready to serve cached pages.', 'mamba-cache-for-woocommerce')
                                    : esc_html__('Enable caching to dramatically improve your store\'s performance.', 'mamba-cache-for-woocommerce'); ?>
                            </p>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <p style="
                        margin: 0 0 12px;
                        font-size: 13px;
                        font-weight: 600;
                        color: #475569;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                    "><?php echo ($cacheEnabled || $hasConflicts)
                        ? esc_html__('What Mamba Cache offers:', 'mamba-cache-for-woocommerce')
                        : esc_html__('What you\'ll get when you enable caching:', 'mamba-cache-for-woocommerce'); ?></p>
                    <ul style="
                        list-style: none;
                        padding: 0;
                        margin: 0 0 24px;
                    ">
                        <li style="
                            display: flex;
                            align-items: center;
                            gap: 10px;
                            padding: 6px 0;
                            color: #334155;
                            font-size: 13px;
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        ">
                            <span style="
                                display: inline-flex;
                                align-items: center;
                                justify-content: center;
                                width: 20px;
                                height: 20px;
                                background: #dcfce7;
                                border-radius: 50%;
                                flex-shrink: 0;
                            ">
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                                    <polyline points="20 6 9 17 4 12"/>
                                </svg>
                            </span>
                            <?php esc_html_e('Lightning-fast product, category & shop page caching', 'mamba-cache-for-woocommerce'); ?>
                        </li>
                        <li style="
                            display: flex;
                            align-items: center;
                            gap: 10px;
                            padding: 6px 0;
                            color: #334155;
                            font-size: 13px;
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        ">
                            <span style="
                                display: inline-flex;
                                align-items: center;
                                justify-content: center;
                                width: 20px;
                                height: 20px;
                                background: #dcfce7;
                                border-radius: 50%;
                                flex-shrink: 0;
                            ">
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                                    <polyline points="20 6 9 17 4 12"/>
                                </svg>
                            </span>
                            <?php esc_html_e('Smart cart fragment caching for faster add-to-cart', 'mamba-cache-for-woocommerce'); ?>
                        </li>
                        <li style="
                            display: flex;
                            align-items: center;
                            gap: 10px;
                            padding: 6px 0;
                            color: #334155;
                            font-size: 13px;
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        ">
                            <span style="
                                display: inline-flex;
                                align-items: center;
                                justify-content: center;
                                width: 20px;
                                height: 20px;
                                background: #dcfce7;
                                border-radius: 50%;
                                flex-shrink: 0;
                            ">
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                                    <polyline points="20 6 9 17 4 12"/>
                                </svg>
                            </span>
                            <?php esc_html_e('Auto-purge on stock, price & inventory changes', 'mamba-cache-for-woocommerce'); ?>
                        </li>
                        <li style="
                            display: flex;
                            align-items: center;
                            gap: 10px;
                            padding: 6px 0;
                            color: #334155;
                            font-size: 13px;
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        ">
                            <span style="
                                display: inline-flex;
                                align-items: center;
                                justify-content: center;
                                width: 20px;
                                height: 20px;
                                background: #dcfce7;
                                border-radius: 50%;
                                flex-shrink: 0;
                            ">
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                                    <polyline points="20 6 9 17 4 12"/>
                                </svg>
                            </span>
                            <?php esc_html_e('Smart warmup keeps your store blazing fast', 'mamba-cache-for-woocommerce'); ?>
                        </li>
                    </ul>
                </div>
                
                <!-- Footer -->
                <div style="
                    padding: 16px 32px 24px;
                    display: flex;
                    gap: 12px;
                    justify-content: center;
                ">
                    <?php if ($hasConflicts): ?>
                    <!-- Conflict state: Show Go to Plugins button -->
                    <a href="<?php echo esc_url(admin_url('plugins.php')); ?>" style="
                        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
                        color: white;
                        border: none;
                        padding: 12px 24px;
                        border-radius: 8px;
                        font-size: 14px;
                        font-weight: 600;
                        cursor: pointer;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        text-decoration: none;
                        display: inline-flex;
                        align-items: center;
                        gap: 8px;
                        transition: transform 0.15s ease, box-shadow 0.15s ease;
                        box-shadow: 0 4px 6px -1px rgba(245, 158, 11, 0.3);
                    " onmouseover="this.style.transform='translateY(-1px)';this.style.boxShadow='0 6px 8px -1px rgba(245, 158, 11, 0.4)';" onmouseout="this.style.transform='translateY(0)';this.style.boxShadow='0 4px 6px -1px rgba(245, 158, 11, 0.3)';">
                        <span class="dashicons dashicons-admin-plugins" style="font-size: 16px; width: 16px; height: 16px;"></span>
                        <?php esc_html_e('Manage Plugins', 'mamba-cache-for-woocommerce'); ?>
                    </a>
                    <button type="button" id="mamba-welcome-dismiss" style="
                        background: #f1f5f9;
                        color: #475569;
                        border: 1px solid #e2e8f0;
                        padding: 12px 24px;
                        border-radius: 8px;
                        font-size: 14px;
                        font-weight: 600;
                        cursor: pointer;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        transition: background 0.15s ease;
                    " onmouseover="this.style.background='#e2e8f0';" onmouseout="this.style.background='#f1f5f9';">
                        <?php esc_html_e('Close', 'mamba-cache-for-woocommerce'); ?>
                    </button>
                    <?php elseif (!$cacheEnabled): ?>
                    <!-- Normal state: Show Enable Caching button -->
                    <button type="button" id="mamba-welcome-enable" style="
                        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
                        color: white;
                        border: none;
                        padding: 12px 24px;
                        border-radius: 8px;
                        font-size: 14px;
                        font-weight: 600;
                        cursor: pointer;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        transition: transform 0.15s ease, box-shadow 0.15s ease;
                        box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.3);
                    " onmouseover="this.style.transform='translateY(-1px)';this.style.boxShadow='0 6px 8px -1px rgba(59, 130, 246, 0.4)';" onmouseout="this.style.transform='translateY(0)';this.style.boxShadow='0 4px 6px -1px rgba(59, 130, 246, 0.3)';">
                        <?php esc_html_e('Enable Caching Now', 'mamba-cache-for-woocommerce'); ?>
                    </button>
                    <button type="button" id="mamba-welcome-dismiss" style="
                        background: #f1f5f9;
                        color: #475569;
                        border: 1px solid #e2e8f0;
                        padding: 12px 24px;
                        border-radius: 8px;
                        font-size: 14px;
                        font-weight: 600;
                        cursor: pointer;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        transition: background 0.15s ease;
                    " onmouseover="this.style.background='#e2e8f0';" onmouseout="this.style.background='#f1f5f9';">
                        <?php esc_html_e('Maybe Later', 'mamba-cache-for-woocommerce'); ?>
                    </button>
                    <?php else: ?>
                    <!-- Cache already enabled: Show Get Started button -->
                    <button type="button" id="mamba-welcome-dismiss" style="
                        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
                        color: white;
                        border: none;
                        padding: 12px 24px;
                        border-radius: 8px;
                        font-size: 14px;
                        font-weight: 600;
                        cursor: pointer;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        transition: background 0.15s ease;
                    " onmouseover="this.style.background='linear-gradient(135deg, #2563eb 0%, #1e40af 100%)';" onmouseout="this.style.background='linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%)';">
                        <?php esc_html_e('Get Started', 'mamba-cache-for-woocommerce'); ?>
                    </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <?php
        $welcome_nonce = esc_attr(wp_create_nonce('mamba_welcome_nonce'));
        $i18n_enabling = esc_js(__('Enabling...', 'mamba-cache-for-woocommerce'));
        $i18n_cache_enabled = esc_js(__('Caching Enabled Successfully!', 'mamba-cache-for-woocommerce'));
        $i18n_warmup_running = esc_js(__('Cache warmup is running in the background.', 'mamba-cache-for-woocommerce'));
        $i18n_redirecting = esc_js(__('This may take a few minutes depending on your site size. Redirecting...', 'mamba-cache-for-woocommerce'));
        $i18n_error = esc_js(__('Error - Try Again', 'mamba-cache-for-woocommerce'));

        $welcome_js = <<<JS
(function() {
    var overlay = document.getElementById('mamba-welcome-overlay');
    var modal = document.getElementById('mamba-welcome-modal');
    var dismissBtn = document.getElementById('mamba-welcome-dismiss');
    var enableBtn = document.getElementById('mamba-welcome-enable');
    setTimeout(function() {
        overlay.style.opacity = '1';
        modal.style.transform = 'scale(1) translateY(0)';
    }, 100);
    function closeModal() {
        overlay.style.opacity = '0';
        modal.style.transform = 'scale(0.9) translateY(20px)';
        setTimeout(function() { overlay.remove(); }, 300);
        fetch(ajaxurl, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'action=mamba_dismiss_welcome&_wpnonce={$welcome_nonce}'
        });
        if (window.history && history.replaceState) {
            var url = new URL(window.location.href);
            url.searchParams.delete('mamba_welcome');
            history.replaceState({}, document.title, url.toString());
        }
    }
    dismissBtn.addEventListener('click', closeModal);
    overlay.addEventListener('click', function(e) {
        if (e.target === overlay) { closeModal(); }
    });
    if (enableBtn) {
        enableBtn.addEventListener('click', function() {
            enableBtn.disabled = true;
            enableBtn.textContent = '{$i18n_enabling}';
            fetch(ajaxurl, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'action=mamba_welcome_enable_cache&_wpnonce={$welcome_nonce}'
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    var buttonsContainer = enableBtn.parentNode;
                    buttonsContainer.innerHTML = '';
                    var style = document.createElement('style');
                    style.textContent = '@keyframes mamba-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }';
                    document.head.appendChild(style);
                    var successNotice = document.createElement('div');
                    successNotice.style.cssText = 'padding: 16px 20px; background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%); border: 1px solid #86efac; border-radius: 10px; text-align: center;';
                    successNotice.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; gap: 10px; margin-bottom: 8px;"><span class="dashicons dashicons-yes-alt" style="color: #22c55e; font-size: 24px;"></span><span style="color: #166534; font-size: 15px; font-weight: 600;">{$i18n_cache_enabled}</span></div><div style="display: flex; align-items: center; justify-content: center; gap: 8px; color: #166534; font-size: 13px;"><span class="dashicons dashicons-update" style="color: #22c55e; animation: mamba-spin 1s linear infinite;"></span>{$i18n_warmup_running}</div><div style="color: #15803d; font-size: 12px; margin-top: 6px;">{$i18n_redirecting}</div>';
                    buttonsContainer.appendChild(successNotice);
                    setTimeout(function() { window.location.reload(); }, 2500);
                } else {
                    enableBtn.textContent = '{$i18n_error}';
                    enableBtn.disabled = false;
                }
            })
            .catch(function() {
                enableBtn.textContent = '{$i18n_error}';
                enableBtn.disabled = false;
            });
        });
    }
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') { closeModal(); }
    });
})();
JS;
        wp_add_inline_script('mamba-admin', $welcome_js);
        ?>
        <?php
    }
    
    /**
     * AJAX handler to dismiss welcome modal
     */
    public static function dismissWelcome(): void {
        check_ajax_referer('mamba_welcome_nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }
        
        update_option(self::WELCOME_SHOWN_OPTION, true, false);
        wp_send_json_success();
    }
    
    /**
     * AJAX handler to enable caching from welcome modal
     */
    public static function enableCacheFromWelcome(): void {
        check_ajax_referer('mamba_welcome_nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }
        
        // Block if conflicting caching plugins are active
        if (ConflictDetector::hasConflicts()) {
            $conflicts = ConflictDetector::getActiveConflicts();
            wp_send_json_error([
                'message' => sprintf(
                    /* translators: %s: list of conflicting plugin names */
                    __('Cannot enable caching: %s is active. Please deactivate conflicting plugins first.', 'mamba-cache-for-woocommerce'),
                    implode(', ', array_values($conflicts))
                )
            ]);
            return;
        }
        
        // Enable page caching
        update_option('mamba_enable_page_cache', 1);
        
        // Mark welcome as shown
        update_option(self::WELCOME_SHOWN_OPTION, true, false);
        
        // Schedule initial warmup
        if (!wp_next_scheduled('mamba_cache_preload')) {
            wp_schedule_single_event(time() + 30, 'mamba_cache_preload');
        }
        
        wp_send_json_success(['message' => 'Caching enabled']);
    }
}
