<?php
/**
 * Activation Modal - Shown on plugin pages after fresh activation
 * Shows license installation form overlay (one-time only)
 * 
 * @package VMPFence
 * @since 2.2.2
 * @since 2.2.3 - Improved logic to avoid conflict with setup overlay
 * @since 2.2.4 - Updated styles for a more polished look, Added License Success/Error Modals, Updated styles for activation modal
 */

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



// Check if this is a forced activation (resume from overlay)
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking GET parameter for display logic only
$is_forced = isset($_GET['forced']) && $_GET['forced'] === '1';

// Also treat help page as forced when setup is needed
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking GET parameter for display logic only
$is_help_page = isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'vmpfence-help';
if ($is_help_page) {
    $is_forced = true;
}

// Only show if setup is needed
$needs_setup = get_option('vmpfence_needs_setup', false);
if (!$needs_setup) {
    return;
}

// Check if this is immediately after activation OR forced mode
$show_modal = get_transient('vmpfence_show_activation_modal') || $is_forced;
if (!$show_modal) {
    return;
}

// Skip dismissal check if forced
if (!$is_forced) {
    // Check if user already dismissed this modal
    $dismissed = get_user_meta(get_current_user_id(), 'vmpfence_dismissed_activation_modal', true);
    if ($dismissed) {
        return;
    }
}

// If forced, show on help page only (for resume installation)
// If not forced, only show on plugins page
if (!$is_forced) {
    $screen = get_current_screen();
    $is_plugins_page = $screen && $screen->id === 'plugins';
    if (!$is_plugins_page) {
        return;
    }
} else {
    // Forced mode: only show on help page
    $screen = get_current_screen();
    $is_help_page = $screen && strpos($screen->id, 'vmpfence-help') !== false;
    if (!$is_help_page) {
        return;
    }
}

// Check for license activation errors (set by process_setup_form() on failed activation)
$license_errors = get_transient('vmpfence_license_error');
$has_license_errors = !empty($license_errors) && is_array($license_errors);
if ($has_license_errors) {
    delete_transient('vmpfence_license_error');
}

?>

<div id="vmpfence-activation-modal-overlay" class="vmpfence-activation-overlay">
    <div class="vmpfence-activation-modal<?php echo $is_forced ? ' vmpfence-modal--forced' : ''; ?>">
        <?php if ($is_forced) : ?>
        <div class="vmpfence-modal-setup-header">
            <span class="vmpfence-setup-header-text"><?php esc_html_e('Please Complete VMP Security Installation', 'vmpfence-security'); ?></span>
            <button type="button" class="vmpfence-header-close" id="vmpfence-header-close-btn" aria-label="<?php esc_attr_e('Close', 'vmpfence-security'); ?>">
                <span class="dashicons dashicons-dismiss"></span>
            </button>
        </div>
        <?php endif; ?>
        <div class="vmpfence-ac-modal-body">
            <!-- Step 1: License Prompt (hidden if returning from error) -->
            <div id="vmpfence-license-prompt" class="vmpfence-license-prompt" style="text-align: center; border-radius: 12px;<?php echo $has_license_errors ? ' display: none;' : ''; ?>">
                <?php if (!$is_forced) : ?>
                <div class="vmpfence-overlay-branding" style="display: flex; align-items: center; justify-content: center; padding-bottom: 1rem;">
                    <img src="<?php echo esc_url(VMPFENCE_PLUGIN_URL . 'admin/assets/images/VMP-logo.svg'); ?>" alt="VMP Security" class="vmpfence-logo" width="60" height="60" style="margin-right: 15px; flex-shrink: 0;">
                    <div class="vmpfence-tagline" style="display: flex; flex-direction: column;">
                        <span class="vmpfence-brand-name" style="font-size: 36px; font-weight: 700; color: #191970; line-height: 1.2; margin-bottom: 3px;">VMP Security</span>
                        <span class="vmpfence-brand-subtitle" style="font-size: 14px; color: #666; line-height: 1.3;"><?php esc_html_e('Securing your', 'vmpfence-security'); ?> <span class="vmpfence-wp-highlight" style="font-weight: 600; color: #191970;">WordPress</span> <?php esc_html_e('website', 'vmpfence-security'); ?></span>
                    </div>
                </div>
                <h3 style="margin: 0; color: #2d2d2d; font-size: 15px; font-weight:700; font-family: 'Roboto', sans-serif;  padding: 0.25rem 0;">
                    <?php 
                    printf(
                        /* translators: %s: plugin version number */
                        esc_html__('You have successfully installed VMP Security %s', 'vmpfence-security'),
                        esc_html(VMPFENCE_VERSION)
                    ); 
                    ?>
                </h3>
                <?php endif; ?>
                <p style="margin: 1rem 0; color: #3c434a; font-size: 13px; font-weight: 700;">
                    <?php esc_html_e('Register with VMP Security to secure your site with the latest threat intelligence.', 'vmpfence-security'); ?>
                </p>
                
                <a href="https://vmpsecurity.com/pricing/" 
                   target="_blank"
                   onclick="document.getElementById('vmpfence-license-form-container').style.display='block'; document.getElementById('vmpfence-license-prompt').style.display='none'; return true;"
                   class="button button-primary" 
                   style="background: #191970; border-color: #191970; box-shadow: none; text-shadow: none; font-size: 14px; font-weight: 400; height: auto; padding: 0.5rem 1.25rem; border-radius: 4px;">
                    <?php esc_html_e('GET YOUR VMP SECURITY LICENSE', 'vmpfence-security'); ?>
                </a>
                
                <div style="margin-top: 1rem;">
                    <button type="button" 
                            id="vmpfence-show-license-form-btn"
                            class="button vmpfence-show-license-form"
                            style="border:0; background: none; text-decoration: underline; color:#191970; font-size: 13px; font-weight: 400; padding: 0 0 1rem 0;">
                        <?php esc_html_e('Install an existing license', 'vmpfence-security'); ?>
                    </button>
                </div>
            </div>
            
            <!-- Step 2: License Installation Form (shown if returning from error) -->
            <div id="vmpfence-license-form-container" style="<?php echo $has_license_errors ? 'display: block;' : 'display: none;'; ?>">
                <?php
                // Display license activation errors from transient
                if ($has_license_errors) {
                    // Allowed HTML tags for rich error messages (e.g., "already registered" with site URLs and instructions)
                    $allowed_html = array(
                        'strong' => array(),
                        'br'     => array(),
                        'code'   => array(),
                        'em'     => array(),
                        'a'      => array(
                            'href'   => array(),
                            'target' => array(),
                            'style'  => array(),
                            'rel'    => array(),
                        ),
                        'div'    => array(
                            'style' => array(),
                        ),
                    );
                    foreach ($license_errors as $error) {
                        if (isset($error['message']) && !empty($error['message'])) {
                            $error_type = isset($error['type']) ? $error['type'] : 'error';
                            ?>
                            <div class="notice notice-<?php echo esc_attr($error_type); ?>" style="margin: 0 15px 15px; padding: 12px 16px; border-left-width: 4px;">
                                <p style="margin: 0;"><?php echo wp_kses($error['message'], $allowed_html); ?></p>
                            </div>
                            <?php
                        }
                    }
                }
                ?>
                <div style="text-align: center; border-radius: 12px;">
                    <?php if (!$is_forced) : ?>
                    <div class="vmpfence-overlay-branding" style="display: flex; align-items: center; justify-content: center; padding: 0 0 1rem 0;">
                        <img src="<?php echo esc_url(VMPFENCE_PLUGIN_URL . 'admin/assets/images/VMP-logo.svg'); ?>" alt="VMP Security" class="vmpfence-logo" width="60" height="60" style="margin-right: 15px; flex-shrink: 0;">
                        <div class="vmpfence-tagline" style="display: flex; flex-direction: column;">
                            <span class="vmpfence-brand-name" style="font-size: 36px; font-weight: 700; color: #191970; line-height: 1.2; margin-bottom: 3px;">VMP Security</span>
                            <span class="vmpfence-brand-subtitle" style="font-size: 14px; color: #666; line-height: 1.3;"><?php esc_html_e('Securing your', 'vmpfence-security'); ?> <span class="vmpfence-wp-highlight" style="font-weight: 600; color: #191970;">WordPress</span> <?php esc_html_e('website', 'vmpfence-security'); ?></span>
                        </div>
                    </div>
                    <h3 style="margin: 0; color: #2d2d2d; font-size: 15px; font-family: 'Roboto', sans-serif;  padding: 0.25rem 0;">
                        <?php 
                        printf(
                            /* translators: %s: plugin version number */
                            esc_html__('You have successfully installed VMP Security %s', 'vmpfence-security'),
                            esc_html(VMPFENCE_VERSION)
                        ); 
                        ?>
                    </h3>
                <?php endif; ?>
                    <p style="margin: 1rem 0; color: #3c434a; font-size: 13px; font-weight: 700; font-family: 'Roboto', sans-serif;">
                        <?php esc_html_e('Register with VMP Security to secure your site with the latest threat intelligence.', 'vmpfence-security'); ?>
                    </p>
                </div>
                
                <form method="post" id="vmpfence-modal-license-form" style="padding: 0;">
                    <?php wp_nonce_field('vmpfence_license_setup', 'vmpfence_license_setup_nonce'); ?>
                    
                    <div style="margin-bottom: 1rem;">
                        <label for="modal_license_email" style="display: block; font-weight: 700; color: #3c434a; font-size: 13px; font-family: 'Roboto', sans-serif;">
                            <?php esc_html_e('Email', 'vmpfence-security'); ?>
                        </label>
                        <input type="email" 
                               id="modal_license_email" 
                               name="license_email" 
                               class="regular-text"
                               style="width: 100%; height: 38px; border-radius: 6px; border: 1px solid #8c8f94; padding: 0.25rem 0.5rem; font-size: 14px; font-weight: 400;"
                               placeholder=""
                               required />
                        <p style="color: #3c434a; font-size: 11px; font-weight: 400; margin: 0;">
                            <?php esc_html_e('This is where future security alerts for your website will be sent. This can also be changed in Global Options.', 'vmpfence-security'); ?>
                        </p>
                    </div>
                    
                    <div style="margin-bottom: 1rem;">
                        <label for="modal_license_key" style="display: block; font-weight: 700; font-family: 'Roboto', sans-serif; color: #3c434a; font-size: 13px;">
                            <?php esc_html_e('License Key — each VMP Security installation should have a unique key', 'vmpfence-security'); ?>
                        </label>
                        <input type="text" 
                               id="modal_license_key" 
                               name="license_key" 
                               class="regular-text"
                               style="width: 100%; height: 70px; border-radius: 6px; border: 1px solid #8c8f94; padding: 0.25rem 0.5rem; font-family: monospace; font-size: 14px;"
                               placeholder=""
                               required />
                    </div>
                    
                    <div style="margin-bottom: 1rem;">
                        <p style="margin: 0; color: #3c434a; margin-bottom: 5px; font-size: 13px; font-weight: 700; font-family: 'Roboto', sans-serif;">
                            <?php esc_html_e('Would you like WordPress security and vulnerability alerts sent to you via email?', 'vmpfence-security'); ?>
                        </p>
                        <style>
                            .vmpfence-modal-toggle-group { display: inline-flex; border: 1px solid #8c8f94; border-radius: 3px; overflow: hidden; margin-top: 0.25rem; }
                            .vmpfence-modal-toggle-group input[type="radio"] { position: absolute; opacity: 0; pointer-events: none; }
                            .vmpfence-modal-toggle-group label { padding: 6px 16px; font-size: 13px; cursor: pointer; background: #f6f7f7; color: #3c434a; margin: 0; line-height: 1.5; font-weight: 400; border-right: 1px solid #8c8f94; user-select: none; }
                            .vmpfence-modal-toggle-group label:last-child { border-right: none; }
                            .vmpfence-modal-toggle-group input[type="radio"]:checked + label { background: #191970; color: #fff; }
                        </style>
                        <div class="vmpfence-modal-toggle-group">
                            <input type="radio" name="email_alerts" id="modal_email_yes" value="1" checked />
                            <label for="modal_email_yes"><?php esc_html_e('YES', 'vmpfence-security'); ?></label>
                            <input type="radio" name="email_alerts" id="modal_email_no" value="0" />
                            <label for="modal_email_no"><?php esc_html_e('NO', 'vmpfence-security'); ?></label>
                        </div>
                    </div>
                    
                    <button type="submit" 
                            name="activate_license_setup"
                            class="button button-primary"
                            style="display: block; margin: 0 auto; background: #191970; border-color: #191970; box-shadow: none; text-shadow: none; font-size: 14px; height: auto; padding: 0.5rem 1.25rem; font-weight: 400; border-radius: 4px; line-height: 1.3125rem;">
                        <?php esc_html_e('INSTALL LICENSE', 'vmpfence-security'); ?>
                    </button>
                    
                    <p style="margin: 1rem 0 0; text-align: center; font-size: 13px; color: #191970; font-weight: 400; padding-bottom: 1rem;">
                        <button type="button" 
                                id="vmpfence-back-to-prompt-btn"
                                class="button"
                                style="border: 0; background: none; text-decoration: underline;">
                            ← <?php esc_html_e('Back', 'vmpfence-security'); ?>
                        </button>
                        <span style="margin: 0 8px; color: #c3c4c7;">|</span>
                        <a href="https://vmpsecurity.com/pricing/" 
                           target="_blank"
                           style="color: #191970; text-decoration: underline;">
                            <?php esc_html_e('Get a new license', 'vmpfence-security'); ?>
                        </a>
                    </p>
                </form>
            </div>
        </div>
        
        <button type="button" class="vmpfence-modal-close" id="vmpfence-modal-close-btn" aria-label="<?php esc_attr_e('Close', 'vmpfence-security'); ?>">
            <span class="dashicons dashicons-no-alt"></span>
        </button>
    </div>
</div>

<style>
.vmpfence-activation-overlay {
    position: fixed;
    top: 32px;
    left: 160px;
    right: 0;
    bottom: 0;
    background: rgba(241,241,241,0.95);
    z-index: 100000;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: vmpfenceFadeIn 0.3s ease-in-out;
}

/* Responsive adjustments for mobile */
@media screen and (max-width: 782px) {
    .vmpfence-activation-overlay {
        top: 46px;
        left: 0;
    }
}

/* When admin menu is folded */
.folded .vmpfence-activation-overlay {
    left: 36px;
}

@keyframes vmpfenceFadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

.vmpfence-activation-modal {
    background: #fff;
    /* border-radius: 8px; */
    max-width: 850px;
    width: 100%;
    position: relative;
    /* box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3); */
    padding: 1rem;
    animation: vmpfenceSlideUp 0.3s ease-out;
}

@keyframes vmpfenceSlideUp {
    from {
        transform: translateY(50px);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}

.vmpfence-modal-header {
    text-align: center;
    margin-bottom: 10px;
}

.vmpfence-modal-logo {
    width: 60px;
    height: 60px;
    margin-bottom: 20px;
}

.vmpfence-modal-header h2 {
    font-size: 24px;
    font-weight: 600;
    color: #1d2327;
    margin: 0;
    line-height: 1.4;
}

.vmpfence-ac-modal-body {
    text-align: left;
}

.vmpfence-modal-close {
    position: absolute;
    top: 15px;
    right: 15px;
    background: transparent;
    border: none;
    cursor: pointer;
    padding: 5px;
    color: #646970;
    font-size: 20px;
    line-height: 1;
    transition: color 0.2s;
}

.vmpfence-modal-close:hover {
    color: #191970;
}

.vmpfence-modal-close .dashicons {
    width: 20px;
    height: 20px;
    font-size: 20px;
}

.vmpfence-modal-setup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background: #fcb214;
    margin: -1rem -1rem 0 -1rem;
}

.vmpfence-setup-header-text {
    font-size: 15px;
    font-weight: 400;
    color: #000;
    font-family: 'Roboto', 'Segoe UI', sans-serif;
    line-height: 1.4;
}

.vmpfence-header-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 0;
    color: #000;
    font-size: 20px;
    line-height: 1;
    display: flex;
    align-items: center;
    flex-shrink: 0;
    opacity: 0.7;
    transition: opacity 0.2s;
}

.vmpfence-header-close:hover {
    opacity: 1;
}

.vmpfence-header-close .dashicons {
    width: 20px;
    height: 20px;
    font-size: 20px;
}

/* Hide the default corner X when the amber header bar is shown */
.vmpfence-modal--forced > .vmpfence-modal-close {
    display: none;
}

/* License result overlay — centered within WP content area */
#vmpfence-license-result-overlay {
    position: fixed;
    top: 32px;
    left: 160px;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
    z-index: 100002;
    display: flex;
    align-items: center;
    justify-content: center;
}
@media screen and (max-width: 782px) {
    #vmpfence-license-result-overlay { top: 46px; left: 0; }
}
.folded #vmpfence-license-result-overlay { left: 36px; }
</style>

<script>
jQuery(document).ready(function($) {
    var overlay = $('#vmpfence-activation-modal-overlay');
    var isForced = <?php echo $is_forced ? 'true' : 'false'; ?>;
    var dashboardUrl = '<?php echo esc_url(admin_url('admin.php?page=vmpfence-dashboard')); ?>';
    var supportUrl = 'https://vmpsecurity.com/help/';
    var activateNonce = '<?php echo wp_create_nonce('vmpfence_license_setup'); ?>';
    
    // Toggle to show license form
    $('#vmpfence-show-license-form-btn').on('click', function() {
        $('#vmpfence-license-prompt').hide();
        $('#vmpfence-license-form-container').show();
    });
    
    // Toggle back to prompt
    $('#vmpfence-back-to-prompt-btn').on('click', function() {
        $('#vmpfence-license-form-container').hide();
        $('#vmpfence-license-prompt').show();
    });
    
    // AJAX license activation
    $('#vmpfence-modal-license-form').on('submit', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var $submitBtn = $form.find('button[name="activate_license_setup"]');
        var originalText = $submitBtn.text();
        
        // Disable button and show loading
        $submitBtn.prop('disabled', true).text('<?php echo esc_js(__('Installing...', 'vmpfence-security')); ?>');
        
        $.post(ajaxurl, {
            action: 'vmpfence_activate_license',
            nonce: activateNonce,
            license_key: $form.find('input[name="license_key"]').val(),
            license_email: $form.find('input[name="license_email"]').val(),
            email_alerts: $form.find('input[name="email_alerts"]:checked').val() || 1
        }, function(response) {
            if (response.success) {
                $('body').append(buildSuccessModal(response.data.license_type));
            } else {
                var errorMsg = response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Unknown error occurred.', 'vmpfence-security')); ?>';
                $('body').append(buildErrorModal(errorMsg));
                
                // Re-enable button
                $submitBtn.prop('disabled', false).text(originalText);
            }
        }).fail(function() {
            // Network error
            $submitBtn.prop('disabled', false).text(originalText);
            alert('<?php echo esc_js(__('Network error. Please check your connection and try again.', 'vmpfence-security')); ?>');
        });
    });
    
    function closeModalPermanently() {
        // Save dismissal preference
        $.post(ajaxurl, {
            action: 'vmpfence_dismiss_activation_modal',
            nonce: '<?php echo wp_create_nonce('vmpfence_dismiss_activation_modal'); ?>'
        });
        
        // Hide modal
        $('#vmpfence-activation-modal-overlay').fadeOut(300, function() {
            $(this).remove();
        });
    }
    
    // TEMP: helper to build success modal (reused by form handler + test button)
    function buildSuccessModal(licenseType) {
        return $(
            '<div id="vmpfence-license-result-overlay">' +
                '<div style="max-width:500px;width:100%;box-shadow:0 3px 30px rgba(0,0,0,0.3);border-radius:4px;overflow:hidden;">' +
                    '<div style="background:linear-gradient(135deg, #191970 0%, #192990 50%, #193390  100%);padding:4px;text-align:center;position:relative;">' +
                        '<img src="data:image/svg+xml;charset=utf-8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA5MS42NSA3MC43OSI+PHBhdGggZD0iTTkwLjA4LDguNzMsODIuOTEsMS41N2E1LjE5LDUuMTksMCwwLDAtNy40MywwTDMzLjMxLDQzLjc0LDE2LjE2LDI2LjU5YTUuMiw1LjIsMCwwLDAtNy40MywwTDEuNTcsMzMuNzdhNS4xOSw1LjE5LDAsMCwwLDAsNy40M2wyOCwyOGE1LjIsNS4yLDAsMCwwLDcuNDMsMEw5MC4wOCwxNi4xN2E1LjE5LDUuMTksMCwwLDAsMC03LjQzWm0wLDAiIGZpbGw9IiMwMDdjYWMiLz48L3N2Zz4=" alt="" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:160px;height:160px;opacity:0.15; filter: brightness(0) invert(1);" />' +
                        '<h2 style="margin:0; padding: 2rem 1rem 1rem 1rem; color:#fff; font-size:21px; font-weight:300; font-family:Roboto, sans-serif; position: relative; z-index: 1; line-height: 1.5rem;">' + licenseType + ' <?php echo esc_js(__('License Installed', 'vmpfence-security')); ?></h2>' +
                        '<p style="margin:0;color: #fff; font-size: 13px; font-weight:400; position:relative; line-height: 1.4em; z-index:1; padding: 0 1.5rem 2rem 1.5rem;"><?php echo esc_js(__('Congratulations! VMP Security', 'vmpfence-security')); ?> ' + licenseType + ' <?php echo esc_js(__('is now active on your website.', 'vmpfence-security')); ?></p>' +
                    '</div>' +
                    '<div style="background: #ccc; padding: 1rem; text-align:right; border-top: 1px solid #bfbfbf;">' +
                        '<a href="' + dashboardUrl + '" class="button button-primary" style="background: #191970;border:1px solid #191970;color: #fff; font-size:14px; font-family: Roboto, sans-serif; font-weight:400; padding: 0.5rem 1.25rem; height:auto; line-height:1.4em;box-shadow:none;text-shadow:none;border-radius:3px;text-decoration:none;"><?php echo esc_js(__('GO TO DASHBOARD', 'vmpfence-security')); ?></a>' +
                    '</div>' +
                '</div>' +
            '</div>'
        );
    }
    
    // TEMP: helper to build error modal (reused by form handler + test button)
    function buildErrorModal(errorMsg) {
        var modal = $(
            '<div id="vmpfence-license-result-overlay">' +
                '<div style="background:#fff;max-width:460px;width:100%;border-radius:2px;box-shadow:0 3px 30px rgba(0,0,0,0.3);">' +
                    '<h2 style="margin:0; font-family: \'Roboto\', sans-serif; font-size:15px; font-weight:600; color: #333; padding:1rem; border-bottom:1px solid #d9d9d9; line-height: 1.4;"><?php echo esc_js(__('Error Installing License', 'vmpfence-security')); ?></h2>' +
                    '<div style="padding: 1rem;">' +
                        '<p style="margin:0 0 1em 0; color: #333; font-family: \'Roboto\', sans-serif; font-size:13px; font-weight: 400; line-height:1.5; "><?php echo esc_js(__('We received an error while trying to activate the license with the VMP Security servers:', 'vmpfence-security')); ?> ' + $('<span>').text(errorMsg).html() + '</p>' +
                        '<p style="margin:0 0 1em 0; color: #333; font-family: \'Roboto\', sans-serif; font-size:13px; font-weight: 400; line-height:1.5;"><?php echo esc_js(__('Please try again. If the problem persists, please', 'vmpfence-security')); ?> <a href="' + supportUrl + '" target="_blank" style="color:#0073aa;text-decoration:underline;"><?php echo esc_js(__('contact VMP Security Support', 'vmpfence-security')); ?></a>.</p>' +
                    '</div>' +
                    '<div style="padding: 1rem; border-top: 1px solid #d9d9d9; text-align: right; background: #f1f1f1">' +
                        '<button type="button" class="button button-primary vmpfence-error-close" style="background:#191970;border-color:#191970; color:#fff; font-size:14px;font-weight:400; font-family: \'Roboto\', sans-serif; padding: 0.5rem 1.25rem; height:auto; line-height:1.3125rem; box-shadow:none;text-shadow:none;"><?php echo esc_js(__('CLOSE', 'vmpfence-security')); ?></button>' +
                    '</div>' +
                '</div>' +
            '</div>'
        );
        modal.find('.vmpfence-error-close').on('click', function() {
            modal.fadeOut(300, function() { $(this).remove(); });
        });
        modal.on('click', function(e) {
            if (e.target === this) { $(this).fadeOut(300, function() { $(this).remove(); }); }
        });
        return modal;
    }
    
    // TEMP: Dev preview buttons — remove before release
    $('#vmpfence-test-success-modal').on('click', function() {
        $('#vmpfence-license-result-overlay').remove();
        $('body').append(buildSuccessModal('Free'));
    });
    $('#vmpfence-test-error-modal').on('click', function() {
        $('#vmpfence-license-result-overlay').remove();
        $('body').append(buildErrorModal('Your license key is invalid or has already been used on another site. Please check your key and try again.'));
    });
    
    function closeModalTemporarily() {
        // Just hide modal without saving dismissal (will reappear on refresh)
        $('#vmpfence-activation-modal-overlay').fadeOut(300, function() {
            $(this).remove();
        });
    }
    
    if (isForced) {
        // In forced mode (help page): only allow X button to close temporarily
        $('#vmpfence-modal-close-btn, #vmpfence-header-close-btn').on('click', function() {
            closeModalTemporarily();
        });
    } else {
        // In normal mode (plugins page): allow all close methods with permanent dismissal
        
        // Close modal on X button
        $('#vmpfence-modal-close-btn').on('click', function() {
            closeModalPermanently();
        });
        
        // Close on outside click
        $('#vmpfence-activation-modal-overlay').on('click', function(e) {
            if (e.target === this) {
                closeModalPermanently();
            }
        });
        
        // Close on Escape key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' || e.keyCode === 27) {
                closeModalPermanently();
            }
        });
        
        // Auto-dismiss when clicking any navigation link (navigating away from plugins page)
        // but NOT links inside the activation modal (e.g. "Get your license" opens a new tab)
        $(document).on('click', 'a', function(e) {
            if ($(this).closest('#vmpfence-activation-modal-overlay, #vmpfence-license-result-overlay').length) {
                return; // Don't dismiss for links inside the modal
            }
            var href = $(this).attr('href');
            // Only dismiss if it's a real navigation (not # or javascript:)
            if (href && href !== '#' && !href.startsWith('javascript:')) {
                closeModalPermanently();
            }
        });
    }
});
</script>
