<?php
/**
 * OnboardingPage - Setup wizard renderer styled with the plugin's own design system.
 *
 * NOTE: This file is intentionally ASCII-only to avoid encoding issues.
 * Special characters use CSS escapes (\2713), JS escapes (\u2713), or HTML entities.
 *
 * @package UltraguardPro\modules\onboarding\pages
 */

namespace UltraguardPro\modules\onboarding\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\onboarding\OnboardingModule;

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

class OnboardingPage {

    private Plugin $plugin;

    public function __construct( Plugin $plugin ) {
        $this->plugin = $plugin;
    }

    public function render(): string {
        ob_start();
        $this->output_styles();
        $this->output_html();
        $this->output_scripts();
        return (string) ob_get_clean();
    }

    // -------------------------------------------------------------------------
    // Minimal wizard-specific CSS only - rest inherited from plugin stylesheets
    // -------------------------------------------------------------------------
    private function output_styles(): void { ?>
<style id="ug-wizard-css">
.ug-wizard-wrap{max-width:800px;margin:24px auto;padding:0 16px 40px}
/* Step bar */
.ug-wizard-steps{display:flex;align-items:center;margin-bottom:24px;background:var(--ug-bg-primary);border:1px solid var(--ug-border);border-radius:var(--ug-radius-lg);padding:14px 20px;box-shadow:var(--ug-shadow-xs)}
.ug-wstep{display:flex;align-items:center;gap:8px;flex:1}.ug-wstep:last-child{flex:0}
.ug-wstep-dot{width:28px;height:28px;border-radius:50%;border:2px solid var(--ug-border);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:var(--ug-gray-light);flex-shrink:0;transition:all 180ms ease;background:var(--ug-bg-primary)}
.ug-wstep.active .ug-wstep-dot{border-color:var(--ug-primary);background:var(--ug-primary);color:#fff;box-shadow:0 0 0 3px rgba(14,165,233,.15)}
.ug-wstep.done   .ug-wstep-dot{border-color:var(--ug-success);background:var(--ug-success);color:#fff}
.ug-wstep-label{font-size:11px;font-weight:500;color:var(--ug-gray-light);white-space:nowrap}
.ug-wstep.active .ug-wstep-label{color:var(--ug-primary);font-weight:700}
.ug-wstep.done   .ug-wstep-label{color:var(--ug-success-dark)}
.ug-wstep-line{flex:1;height:2px;background:var(--ug-border);margin:0 8px;border-radius:2px;min-width:10px;transition:background 180ms ease}
.ug-wstep-line.done{background:var(--ug-success-light)}
/* Wizard card */
.ug-wizard-card{background:var(--ug-bg-primary);border:1px solid var(--ug-border);border-radius:var(--ug-radius-lg);box-shadow:var(--ug-shadow-sm);overflow:hidden}
.ug-wizard-card-header{padding:20px 24px 16px;border-bottom:1px solid var(--ug-border);background:linear-gradient(135deg,rgba(14,165,233,.04),transparent)}
.ug-step-title{font-size:17px;font-weight:700;color:var(--ug-dark);margin:0 0 4px;display:flex;align-items:center;gap:10px}
.ug-step-subtitle{font-size:13px;color:var(--ug-text-secondary);margin:0;line-height:1.6}
.ug-wizard-card-body{padding:24px}
.ug-wizard-card-footer{padding:14px 24px;border-top:1px solid var(--ug-border);background:var(--ug-bg-secondary);display:flex;justify-content:space-between;align-items:center;gap:12px}
/* Pane animation */
.ug-wpane{display:none}.ug-wpane.active{display:block;animation:ugIn .18s ease}
@keyframes ugIn{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:none}}
/* Site-type cards */
.ug-site-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:4px}
.ug-site-card{padding:13px 15px;border:2px solid var(--ug-border);border-radius:var(--ug-radius-md);cursor:pointer;transition:all 150ms ease;text-align:left;background:var(--ug-bg-primary)}
.ug-site-card:hover{border-color:var(--ug-primary-light);background:var(--ug-bg-secondary)}
.ug-site-card.selected{border-color:var(--ug-primary);background:rgba(14,165,233,.05)}
.ug-sc-icon{font-size:20px;margin-bottom:5px;display:block}.ug-sc-name{font-size:13px;font-weight:700;color:var(--ug-dark);display:block}
.ug-sc-desc{font-size:11px;color:var(--ug-text-secondary);margin-top:2px;line-height:1.4;display:block}
/* Module grid */
.ug-module-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.ug-mod-card{padding:12px 14px;border:1px solid var(--ug-border);border-radius:var(--ug-radius-md);display:flex;align-items:flex-start;gap:10px;transition:border-color 150ms;background:var(--ug-bg-primary)}
.ug-mod-card.is-active{border-color:var(--ug-success-light);background:rgba(16,185,129,.03)}.ug-mod-card.is-locked{opacity:.55}
.ug-mod-icon{width:32px;height:32px;border-radius:var(--ug-radius-sm);background:var(--ug-bg-tertiary);display:flex;align-items:center;justify-content:center;flex-shrink:0;color:var(--ug-primary)}
.ug-mod-icon .dashicons{font-size:16px;width:16px;height:16px}.ug-mod-body{flex:1;min-width:0}
.ug-mod-name{font-size:12px;font-weight:700;color:var(--ug-dark);display:flex;align-items:center;gap:5px}
.ug-mod-desc{font-size:11px;color:var(--ug-text-secondary);margin-top:2px;line-height:1.4}
.ug-pro-badge{font-size:9px;padding:1px 5px;border-radius:3px;font-weight:700;letter-spacing:.4px;text-transform:uppercase;background:rgba(139,92,246,.12);color:#7c3aed}
/* Toggle switch */
.ug-toggle{position:relative;display:inline-block;width:36px;height:20px;flex-shrink:0}
.ug-toggle input{opacity:0;width:0;height:0}
.ug-toggle-track{position:absolute;top:0;left:0;right:0;bottom:0;background:var(--ug-border);border-radius:20px;cursor:pointer;transition:background .2s}
.ug-toggle-track::before{content:'';position:absolute;width:14px;height:14px;left:3px;bottom:3px;background:#fff;border-radius:50%;transition:transform .2s;box-shadow:var(--ug-shadow-xs)}
.ug-toggle input:checked+.ug-toggle-track{background:var(--ug-success)}.ug-toggle input:checked+.ug-toggle-track::before{transform:translateX(16px)}
.ug-toggle input:disabled+.ug-toggle-track{opacity:.4;cursor:not-allowed}
/* Preset table */
.ug-preset-table{border:1px solid var(--ug-border);border-radius:var(--ug-radius-md);overflow:hidden;max-height:250px;overflow-y:auto;margin-bottom:4px}
.ug-preset-row{display:flex;justify-content:space-between;align-items:center;padding:7px 14px;border-bottom:1px solid var(--ug-border-light);font-size:12px}
.ug-preset-row:last-child{border-bottom:none}.ug-preset-row:nth-child(even){background:var(--ug-bg-secondary)}
.ug-preset-key{color:var(--ug-text-secondary)}.ug-preset-on{color:var(--ug-success-dark);font-weight:600}
.ug-preset-off{color:var(--ug-error-dark);font-weight:600}.ug-preset-val{color:var(--ug-primary-dark);font-weight:600}
/* Baseline progress */
.ug-baseline-wrap{background:var(--ug-bg-secondary);border:1px solid var(--ug-border);border-radius:var(--ug-radius-md);padding:16px;margin-bottom:14px}
.ug-prog-meta{display:flex;justify-content:space-between;font-size:12px;color:var(--ug-text-secondary);margin-bottom:8px}
.ug-prog-track{background:var(--ug-border);border-radius:var(--ug-radius-round);height:8px;overflow:hidden}
.ug-prog-fill{height:8px;border-radius:var(--ug-radius-round);background:var(--ug-gradient-primary);transition:width .4s ease;width:0%}
.ug-task-list{margin-top:10px}
.ug-task-row{display:flex;align-items:center;gap:9px;padding:5px 0;font-size:12px;color:var(--ug-gray-light);border-bottom:1px solid var(--ug-border-light)}
.ug-task-row:last-child{border-bottom:none}
.ug-task-dot{width:16px;height:16px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:9px;flex-shrink:0;background:var(--ug-border);color:var(--ug-gray)}
.ug-task-row.running .ug-task-dot{background:var(--ug-primary);color:#fff;animation:ugPulse 1s infinite}
.ug-task-row.done{color:var(--ug-dark)}.ug-task-row.done .ug-task-dot{background:var(--ug-success);color:#fff}
.ug-task-row.failed .ug-task-dot{background:var(--ug-error);color:#fff}
@keyframes ugPulse{0%,100%{opacity:1}50%{opacity:.4}}
/* Licence upgrade hero */
.ug-upgrade-hero{background:linear-gradient(135deg,rgba(14,165,233,.06),rgba(99,102,241,.06));border:1px solid rgba(14,165,233,.18);border-radius:var(--ug-radius-md);padding:18px;margin-bottom:18px;text-align:center}
.ug-upgrade-hero h3{font-size:16px;font-weight:700;color:var(--ug-dark);margin:0 0 5px}.ug-upgrade-hero p{font-size:13px;color:var(--ug-text-secondary);margin:0 0 13px;line-height:1.6}
.ug-upgrade-feats{display:grid;grid-template-columns:1fr 1fr;gap:5px;text-align:left}
.ug-upgrade-feat{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ug-text)}
/* CSS unicode escape for checkmark - avoids all encoding issues */
.ug-upgrade-feat::before{content:'\2713';color:var(--ug-success-dark);font-weight:700;flex-shrink:0}
/* Delay warning */
.ug-delay-warning{background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.28);border-radius:var(--ug-radius-md);padding:11px 13px;font-size:12px;color:var(--ug-warning-dark);line-height:1.6;display:none;margin-top:10px}
/* Done pane */
.ug-done-pane{text-align:center;padding:12px 0 6px}
.ug-done-icon{width:64px;height:64px;border-radius:50%;background:var(--ug-gradient-success);display:flex;align-items:center;justify-content:center;font-size:28px;margin:0 auto 16px;box-shadow:0 0 0 10px rgba(16,185,129,.1),0 0 0 20px rgba(16,185,129,.05)}
.ug-done-pane h2{font-size:21px;font-weight:700;color:var(--ug-dark);margin:0 0 6px}.ug-done-pane p{font-size:13px;color:var(--ug-text-secondary)}
/* Inline alerts */
.ug-ialert{padding:10px 14px;border-radius:var(--ug-radius-md);font-size:13px;margin-bottom:14px;display:none;line-height:1.5}
.ug-ialert-success{background:rgba(16,185,129,.08);border:1px solid rgba(16,185,129,.22);color:var(--ug-success-dark)}
.ug-ialert-error{background:rgba(239,68,68,.08);border:1px solid rgba(239,68,68,.22);color:var(--ug-error-dark)}
.ug-ialert-info{background:rgba(14,165,233,.08);border:1px solid rgba(14,165,233,.22);color:var(--ug-primary-dark)}
/* Ghost/dismiss */
.ug-ghost{background:none;border:none;padding:0;font-size:12px;color:var(--ug-gray);cursor:pointer;text-decoration:underline}
.ug-ghost:hover{color:var(--ug-text-secondary)}
/* Button spinner */
.ug-spin{display:inline-block;width:13px;height:13px;border-radius:50%;border:2px solid rgba(255,255,255,.35);border-top-color:#fff;animation:ugSpinA .65s linear infinite;vertical-align:middle}
@keyframes ugSpinA{to{transform:rotate(360deg)}}
@media(max-width:600px){.ug-site-grid,.ug-module-grid,.ug-upgrade-feats{grid-template-columns:1fr}.ug-wstep-label{display:none}.ug-wizard-card-header,.ug-wizard-card-body,.ug-wizard-card-footer{padding-left:14px;padding-right:14px}}
</style>
<?php
    }

    // -------------------------------------------------------------------------
    // HTML
    // -------------------------------------------------------------------------
    private function output_html(): void {
        $nonce    = wp_create_nonce( OnboardingModule::NONCE_ACTION );
        $cur_step = (int) get_option( OnboardingModule::STEP_OPTION, 1 );
        ?>
<div class="wrap ultraguard-framework">
<div class="ug-wizard-wrap">

    <h1 style="display:flex;align-items:center;gap:10px;margin-bottom:20px;font-size:20px;font-weight:700;color:var(--ug-dark);">
        <span class="ultraguard-app-logo-icon"><span class="dashicons dashicons-shield-alt" style="font-size:20px;width:20px;height:20px;color:#fff;"></span></span>
        <?php esc_html_e( 'UltraGuard Pro - Setup Wizard', 'ultraguard-security-suite' ); ?>
        <span class="ug-pill ug-pill-primary"><?php esc_html_e( 'Getting Started', 'ultraguard-security-suite' ); ?></span>
    </h1>

    <div class="ug-wizard-steps" id="ug-step-bar">
        <?php $this->render_step_bar( $cur_step ); ?>
    </div>

    <div class="ug-wizard-card">

        <!-- Step 1: Profile -->
        <div class="ug-wpane<?php echo esc_attr( $cur_step === 1 ? ' active' : '' ); ?>" id="ug-pane-1">
            <div class="ug-wizard-card-header">
                <div class="ug-step-title"><span class="ug-card-title-icon"><span class="dashicons dashicons-admin-users"></span></span><?php esc_html_e( 'Welcome - Tell Us About Your Site', 'ultraguard-security-suite' ); ?></div>
                <p class="ug-step-subtitle"><?php esc_html_e( "Let's get your site secured in minutes. Select your site type so we can recommend the right settings.", 'ultraguard-security-suite' ); ?></p>
            </div>
            <div class="ug-wizard-card-body">
                <div class="ug-ialert ug-ialert-error" id="ug-alert-1"></div>
                <div class="ultraguard-field-wrapper">
                    <label class="ultraguard-field-label" for="ug-admin-email"><span class="dashicons dashicons-email-alt"></span> <?php esc_html_e( 'Admin notification e-mail', 'ultraguard-security-suite' ); ?></label>
                    <input type="email" id="ug-admin-email" class="ultraguard-field" placeholder="you@example.com" value="<?php echo esc_attr( get_option( 'admin_email', '' ) ); ?>">
                    <p class="ultraguard-field-description"><?php esc_html_e( 'Security alerts and reports will be sent to this address.', 'ultraguard-security-suite' ); ?></p>
                </div>
                <div class="ultraguard-field-wrapper">
                    <label class="ultraguard-field-label"><span class="dashicons dashicons-admin-site-alt3"></span> <?php esc_html_e( 'What kind of site is this?', 'ultraguard-security-suite' ); ?></label>
                    <div class="ug-site-grid">
                        <button type="button" class="ug-site-card" data-type="blog"><span class="ug-sc-icon">&#x1F4DD;</span><span class="ug-sc-name"><?php esc_html_e( 'Blog / Content', 'ultraguard-security-suite' ); ?></span><span class="ug-sc-desc"><?php esc_html_e( 'Personal blogs, news sites, magazines', 'ultraguard-security-suite' ); ?></span></button>
                        <button type="button" class="ug-site-card" data-type="ecommerce"><span class="ug-sc-icon">&#x1F6D2;</span><span class="ug-sc-name"><?php esc_html_e( 'E-commerce', 'ultraguard-security-suite' ); ?></span><span class="ug-sc-desc"><?php esc_html_e( 'Online stores, WooCommerce, marketplaces', 'ultraguard-security-suite' ); ?></span></button>
                        <button type="button" class="ug-site-card" data-type="agency"><span class="ug-sc-icon">&#x1F3E2;</span><span class="ug-sc-name"><?php esc_html_e( 'Agency / Business', 'ultraguard-security-suite' ); ?></span><span class="ug-sc-desc"><?php esc_html_e( 'Client sites, corporate, SaaS platforms', 'ultraguard-security-suite' ); ?></span></button>
                        <button type="button" class="ug-site-card" data-type="custom"><span class="ug-sc-icon">&#x2699;</span><span class="ug-sc-name"><?php esc_html_e( 'Custom / Other', 'ultraguard-security-suite' ); ?></span><span class="ug-sc-desc"><?php esc_html_e( "I'll configure settings manually", 'ultraguard-security-suite' ); ?></span></button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Step 2: Modules -->
        <div class="ug-wpane<?php echo esc_attr( $cur_step === 2 ? ' active' : '' ); ?>" id="ug-pane-2">
            <div class="ug-wizard-card-header">
                <div class="ug-step-title"><span class="ug-card-title-icon"><span class="dashicons dashicons-plugins-checked"></span></span><?php esc_html_e( 'Choose Your Security Modules', 'ultraguard-security-suite' ); ?></div>
                <p class="ug-step-subtitle"><?php esc_html_e( 'Activate the features you need. You can change these any time from the Modules Manager.', 'ultraguard-security-suite' ); ?></p>
            </div>
            <div class="ug-wizard-card-body">
                <div class="ug-ialert ug-ialert-error" id="ug-alert-2"></div>
                <div class="ug-module-grid" id="ug-module-grid">
                    <div style="grid-column:span 2;text-align:center;padding:22px;color:var(--ug-gray-light);"><span class="ultraguard-spinner" style="display:block;margin:0 auto 10px;"></span><?php esc_html_e( 'Loading modules...', 'ultraguard-security-suite' ); ?></div>
                </div>
            </div>
        </div>

        <!-- Step 3: Settings -->
        <div class="ug-wpane<?php echo esc_attr( $cur_step === 3 ? ' active' : '' ); ?>" id="ug-pane-3">
            <div class="ug-wizard-card-header">
                <div class="ug-step-title"><span class="ug-card-title-icon"><span class="dashicons dashicons-admin-settings"></span></span><?php esc_html_e( 'Recommended Settings', 'ultraguard-security-suite' ); ?></div>
                <p class="ug-step-subtitle" id="ug-pane3-sub"><?php esc_html_e( 'Based on your site profile, here are the recommended settings. Click Apply & Continue to configure them automatically.', 'ultraguard-security-suite' ); ?></p>
            </div>
            <div class="ug-wizard-card-body">
                <div class="ug-ialert ug-ialert-success" id="ug-alert-3"></div>
                <div class="ug-preset-table" id="ug-preset-preview"><div class="ug-preset-row" style="color:var(--ug-gray-light);font-style:italic;"><?php esc_html_e( 'Select a site type on step 1 first.', 'ultraguard-security-suite' ); ?></div></div>
            </div>
        </div>

        <!-- Step 4: Baseline -->
        <div class="ug-wpane<?php echo esc_attr( $cur_step === 4 ? ' active' : '' ); ?>" id="ug-pane-4">
            <div class="ug-wizard-card-header">
                <div class="ug-step-title"><span class="ug-card-title-icon"><span class="dashicons dashicons-database-import"></span></span><?php esc_html_e( 'Setting Up Your Security Baseline', 'ultraguard-security-suite' ); ?></div>
                <p class="ug-step-subtitle"><?php esc_html_e( 'Populating your database with firewall rules, attack signatures, and default configurations.', 'ultraguard-security-suite' ); ?></p>
            </div>
            <div class="ug-wizard-card-body">
                <div class="ug-ialert ug-ialert-success" id="ug-alert-4"></div>
                <div class="ug-baseline-wrap">
                    <div class="ug-prog-meta"><span id="ug-task-label"><?php esc_html_e( 'Ready...', 'ultraguard-security-suite' ); ?></span><span id="ug-task-pct">0%</span></div>
                    <div class="ug-prog-track"><div class="ug-prog-fill" id="ug-prog-fill"></div></div>
                </div>
                <div class="ug-task-list" id="ug-task-list"></div>
            </div>
        </div>

        <!-- Step 5: Licence -->
        <div class="ug-wpane<?php echo esc_attr( $cur_step === 5 ? ' active' : '' ); ?>" id="ug-pane-5">
            <div class="ug-wizard-card-header">
                <div class="ug-step-title"><span class="ug-card-title-icon"><span class="dashicons dashicons-admin-network"></span></span><?php esc_html_e( 'Activate Your Licence', 'ultraguard-security-suite' ); ?></div>
                <p class="ug-step-subtitle"><?php esc_html_e( 'Enter your licence key to unlock Pro features and receive real-time security updates.', 'ultraguard-security-suite' ); ?></p>
            </div>
            <div class="ug-wizard-card-body">
                <div class="ug-upgrade-hero">
                    <span class="ug-pill ug-pill-primary" style="margin-bottom:10px;"><?php esc_html_e( 'PRO', 'ultraguard-security-suite' ); ?></span>
                    <h3><?php esc_html_e( 'Upgrade to UltraGuard Pro', 'ultraguard-security-suite' ); ?></h3>
                    <p><?php esc_html_e( 'Get real-time threat intelligence, priority support, and instant security updates the moment new threats are discovered.', 'ultraguard-security-suite' ); ?></p>
                    <div class="ug-upgrade-feats">
                        <div class="ug-upgrade-feat"><?php esc_html_e( 'Real-time update feed', 'ultraguard-security-suite' ); ?></div>
                        <div class="ug-upgrade-feat"><?php esc_html_e( 'Advanced firewall rules', 'ultraguard-security-suite' ); ?></div>
                        <div class="ug-upgrade-feat"><?php esc_html_e( 'Priority support', 'ultraguard-security-suite' ); ?></div>
                        <div class="ug-upgrade-feat"><?php esc_html_e( 'Virtual patching', 'ultraguard-security-suite' ); ?></div>
                        <div class="ug-upgrade-feat"><?php esc_html_e( 'Malware auto-removal', 'ultraguard-security-suite' ); ?></div>
                        <div class="ug-upgrade-feat"><?php esc_html_e( 'Unlimited sites', 'ultraguard-security-suite' ); ?></div>
                    </div>
                </div>
                <div class="ug-ialert ug-ialert-error"   id="ug-alert-5"></div>
                <div class="ug-ialert ug-ialert-success" id="ug-alert-5s"></div>
                <div class="ultraguard-field-wrapper">
                    <label class="ultraguard-field-label" for="ug-license-key"><span class="dashicons dashicons-admin-network"></span> <?php esc_html_e( 'Licence Key', 'ultraguard-security-suite' ); ?></label>
                    <input type="text" id="ug-license-key" class="ultraguard-field" placeholder="UGPRO-XXXX-XXXX-XXXX-XXXX">
                </div>
                <div class="ug-delay-warning" id="ug-delay-warning">
                    <strong><?php esc_html_e( 'Important:', 'ultraguard-security-suite' ); ?></strong>
                    <?php esc_html_e( 'Without a Pro licence, security definition updates are delivered within 24 hours. Pro users receive them instantly — including zero-day signatures within minutes of publication.', 'ultraguard-security-suite' ); ?>
                </div>
            </div>
        </div>

        <!-- Done -->
        <div class="ug-wpane" id="ug-pane-done">
            <div class="ug-wizard-card-body">
                <div class="ug-done-pane">
                    <div class="ug-done-icon">&#10003;</div>
                    <h2><?php esc_html_e( "You're All Set!", 'ultraguard-security-suite' ); ?></h2>
                    <p><?php esc_html_e( 'UltraGuard Pro is configured and protecting your site.', 'ultraguard-security-suite' ); ?><br><?php esc_html_e( 'Redirecting you to the security dashboard...', 'ultraguard-security-suite' ); ?></p>
                </div>
            </div>
        </div>

        <!-- Footer buttons -->
        <div class="ug-wizard-card-footer" id="ug-wizard-footer">
            <div style="display:flex;align-items:center;gap:12px;">
                <button type="button" class="ultraguard-button ultraguard-button-secondary" id="ug-btn-back" style="display:none;"><span class="dashicons dashicons-arrow-left-alt"></span> <?php esc_html_e( 'Back', 'ultraguard-security-suite' ); ?></button>
                <button type="button" class="ug-ghost" id="ug-btn-dismiss"><?php esc_html_e( 'Skip setup wizard', 'ultraguard-security-suite' ); ?></button>
            </div>
            <div style="display:flex;align-items:center;gap:10px;">
                <button type="button" class="ultraguard-button ultraguard-button-secondary" id="ug-btn-skip" style="display:none;"><?php esc_html_e( 'Skip this step', 'ultraguard-security-suite' ); ?></button>
                <button type="button" class="ultraguard-button ultraguard-button-primary ultraguard-button-large" id="ug-btn-next"><?php esc_html_e( 'Get Started', 'ultraguard-security-suite' ); ?> <span class="dashicons dashicons-arrow-right-alt"></span></button>
            </div>
        </div>

    </div><!-- /.ug-wizard-card -->
</div><!-- /.ug-wizard-wrap -->
</div><!-- /.wrap.ultraguard-framework -->
<script type="application/json" id="ug-wz-cfg"><?php echo wp_json_encode([
            'ajaxurl'    => self_admin_url('admin-ajax.php'),
    'nonce'      => $nonce,
    'adminEmail' => get_option('admin_email',''),
    'siteType'   => get_option('ultraguard_onboarding_site_type',''),
    'step'       => $cur_step,
    'dashUrl'    => admin_url('admin.php?page=dashboard'),
]); ?></script>
<?php
    }

    // -------------------------------------------------------------------------
    private function render_step_bar( int $cur ): void {
        $steps = [
            1 => __( 'Profile',  'ultraguard-security-suite' ),
            2 => __( 'Modules',  'ultraguard-security-suite' ),
            3 => __( 'Settings', 'ultraguard-security-suite' ),
            4 => __( 'Baseline', 'ultraguard-security-suite' ),
            5 => __( 'Licence',  'ultraguard-security-suite' ),
        ];
        $i = 0;
        foreach ( $steps as $n => $label ) {
            $cls = $n < $cur ? 'done' : ( $n === $cur ? 'active' : '' );
            if ( $i > 0 ) {
                echo '<div class="ug-wstep-line' . ( $n <= $cur ? ' done' : '' ) . '"></div>';
            }
            printf(
                '<div class="ug-wstep %s" data-step="%d"><div class="ug-wstep-dot">%s</div><span class="ug-wstep-label">%s</span></div>',
                esc_attr( $cls ),
                absint( $n ),
                esc_html( $n < $cur ? "\u{2713}" : (string) $n ),
                esc_html( $label )
            );
            $i++;
        }
    }

    // -------------------------------------------------------------------------
    // JavaScript - ASCII-only source, special chars via JS unicode escapes
    // -------------------------------------------------------------------------
    private function output_scripts(): void { ?>
<script id="ug-wizard-js">
(function(){
'use strict';
var cfg=JSON.parse(document.getElementById('ug-wz-cfg').textContent);
var DASH=cfg.dashUrl;
var step=cfg.step||1,siteType=cfg.siteType||'',modulesLoaded=false,baselineStarted=false,baselineDone=false;
function $(id){return document.getElementById(id);}
function $$(s){return document.querySelectorAll(s);}
document.addEventListener('DOMContentLoaded',function(){goTo(step);bind();});

function goTo(n){
    step=n;
    $$('.ug-wpane').forEach(function(p){p.classList.remove('active');});
    var pane=$('ug-pane-'+n);if(pane)pane.classList.add('active');
    $$('.ug-wstep').forEach(function(item){
        var sn=+item.dataset.step;
        item.classList.remove('active','done');
        if(sn<n)item.classList.add('done');
        else if(sn===n)item.classList.add('active');
        item.querySelector('.ug-wstep-dot').textContent=sn<n?'\u2713':sn;
    });
    $$('.ug-wstep-line').forEach(function(l,i){l.classList.toggle('done',i<n-1);});
    $('ug-btn-back').style.display=(n>1&&n<=5)?'':'none';
    $('ug-btn-skip').style.display=(n===5)?'':'none';
    setLbl(n);
    if(n===2&&!modulesLoaded)loadModules();
    if(n===3)renderPreset();
    if(n===4&&!baselineStarted)startBaseline();
}
function setLbl(n){
    var b=$('ug-btn-next');
    var lbl={1:'Continue',2:'Continue',3:'Apply & Continue',4:'Continue',5:'Activate Licence'};
    b.innerHTML=(lbl[n]||'Continue')+' <span class="dashicons dashicons-arrow-right-alt"></span>';
    b.disabled=false;
}
function bind(){
    $('ug-btn-next').addEventListener('click',handleNext);
    $('ug-btn-back').addEventListener('click',function(){if(step>1)goTo(step-1);});
    $('ug-btn-skip').addEventListener('click',handleSkip);
    $('ug-btn-dismiss').addEventListener('click',handleDismiss);
    $$('.ug-site-card').forEach(function(c){
        c.addEventListener('click',function(){
            $$('.ug-site-card').forEach(function(x){x.classList.remove('selected');});
            this.classList.add('selected');
            siteType=this.dataset.type;
        });
    });
    if(siteType){
        var s=document.querySelector('.ug-site-card[data-type="'+siteType+'"]');
        if(s)s.classList.add('selected');
    }
}

function handleNext(){
    clearA(step);
    var btn=$('ug-btn-next');
    btn.disabled=true;
    btn.innerHTML='<span class="ug-spin"></span>';
    var p;
    if(step===1)      p=saveProfile().then(function(){goTo(2);});
    else if(step===2) p=Promise.resolve().then(function(){goTo(3);});
    else if(step===3) p=applyPreset().then(function(){goTo(4);});
    else if(step===4){
        if(baselineDone){goTo(5);setLbl(step);return;}
        btn.innerHTML='Waiting...';return;
    }
    else if(step===5) p=activateLicence().then(function(){return doComplete();});
    else return;
    p.catch(function(e){showA(step,e.message||'An error occurred.','error');setLbl(step);});
}

function handleSkip(){
    if(step===5){
        $('ug-delay-warning').style.display='';
        req('ultraguard_onboarding_save_license',{skipped:1}).then(function(){return doComplete();}).catch(function(){});
    }
}
function handleDismiss(){
    if(!confirm('<?php echo esc_js( __( 'Skip the setup wizard? You can run it again by resetting the onboarding option.', 'ultraguard-security-suite' ) ); ?>'))return;
    req('ultraguard_onboarding_dismiss',{}).then(function(){location.href=DASH;}).catch(function(){location.href=DASH;});
}

function saveProfile(){
    var email=$('ug-admin-email').value.trim();
    if(!siteType)return Promise.reject(new Error('<?php echo esc_js( __( 'Please select a site type before continuing.', 'ultraguard-security-suite' ) ); ?>'));
    if(!email||email.indexOf('@')<0)return Promise.reject(new Error('<?php echo esc_js( __( 'Please enter a valid admin e-mail address.', 'ultraguard-security-suite' ) ); ?>'));
    return req('ultraguard_onboarding_save_profile',{admin_email:email,site_type:siteType}).then(function(r){if(!r.success)throw new Error(r.data&&r.data.message?r.data.message:'Failed.');});
}

function loadModules(){
    modulesLoaded=true;
    var grid=$('ug-module-grid');
    req('ultraguard_onboarding_get_state',{}).then(function(r){
        if(!r.success){grid.innerHTML='<p style="color:var(--ug-error);font-size:13px;">Failed to load modules.</p>';return;}
        var mods=r.data.modules||[];
        if(!mods.length){grid.innerHTML='<p style="color:var(--ug-gray);font-size:13px;">No configurable modules found.</p>';return;}
        grid.innerHTML=mods.map(function(m){
            var locked=!m.license_ok;
            return '<div class="ug-mod-card'+(m.is_active?' is-active':'')+(locked?' is-locked':'')+'">'+
                '<div class="ug-mod-icon"><span class="dashicons '+esc(m.icon||'dashicons-admin-plugins')+'"></span></div>'+
                '<div class="ug-mod-body"><div class="ug-mod-name">'+esc(m.name)+(locked?' <span class="ug-pro-badge">PRO</span>':'')+'</div>'+
                '<div class="ug-mod-desc">'+esc(m.description)+'</div></div>'+
                '<label class="ug-toggle"><input type="checkbox" class="ug-mod-toggle" data-id="'+esc(m.id)+'"'+(m.is_active?' checked':'')+(locked?' disabled':'')+'>'+
                '<span class="ug-toggle-track"></span></label></div>';
        }).join('');
        grid.querySelectorAll('.ug-mod-toggle').forEach(function(inp){
            inp.addEventListener('change',function(){
                var id=this.dataset.id,on=this.checked,self=this;
                self.disabled=true;
                req('ultraguard_onboarding_toggle_module',{module_id:id,activate:on?1:0}).then(function(rr){
                    if(!rr.success){self.checked=!on;showA(2,rr.data&&rr.data.message?rr.data.message:'Toggle failed.','error');}
                    else self.closest('.ug-mod-card').classList.toggle('is-active',on);
                }).catch(function(){self.checked=!on;}).then(function(){self.disabled=false;});
            });
        });
    }).catch(function(){grid.innerHTML='<p style="color:var(--ug-error);">Failed to load modules.</p>';});
}

var PL={firewall_enabled:'Firewall',firewall_mode:'Firewall mode',login_limiter_enabled:'Login limiter',max_login_attempts:'Max attempts',lockout_duration:'Lockout (secs)',two_factor_auth:'2FA',strong_password_enforcement:'Strong passwords',ssl_enforcement:'Enforce SSL',hide_wp_version:'Hide WP version',disable_xmlrpc:'Disable XML-RPC',security_headers:'Security headers',content_security_policy:'CSP header',block_tor_users:'Block Tor',block_proxy_users:'Block proxies',rate_limiting_enabled:'Rate limiting',rate_limit_requests:'Rate limit (req/h)',database_security:'DB security',log_admin_actions:'Log admin actions',log_file_changes:'Log file changes',is_email_notifications:'Email notifications',critical_threat_notification:'Critical alerts',auto_cleanup:'Auto cleanup',backup_before_actions:'Backup before actions'};
var PR={blog:{firewall_enabled:true,firewall_mode:'active',login_limiter_enabled:true,max_login_attempts:5,lockout_duration:1800,two_factor_auth:false,strong_password_enforcement:true,hide_wp_version:true,disable_xmlrpc:true,security_headers:true,is_email_notifications:true,critical_threat_notification:true,auto_cleanup:true},ecommerce:{firewall_enabled:true,firewall_mode:'active',login_limiter_enabled:true,max_login_attempts:3,lockout_duration:3600,two_factor_auth:true,strong_password_enforcement:true,ssl_enforcement:true,hide_wp_version:true,disable_xmlrpc:true,security_headers:true,content_security_policy:true,block_tor_users:true,block_proxy_users:true,rate_limiting_enabled:true,rate_limit_requests:60,database_security:true,is_email_notifications:true,critical_threat_notification:true,auto_cleanup:true,backup_before_actions:true},agency:{firewall_enabled:true,firewall_mode:'active',login_limiter_enabled:true,max_login_attempts:4,lockout_duration:2700,two_factor_auth:true,strong_password_enforcement:true,hide_wp_version:true,disable_xmlrpc:true,security_headers:true,log_admin_actions:true,log_file_changes:true,is_email_notifications:true,critical_threat_notification:true,auto_cleanup:true,backup_before_actions:true},custom:{firewall_enabled:true,firewall_mode:'learning',login_limiter_enabled:true,hide_wp_version:true,security_headers:true,is_email_notifications:true}};
var TN={blog:'Blog / Content',ecommerce:'E-commerce',agency:'Agency / Business',custom:'Custom'};

function renderPreset(){
    if(!siteType||!PR[siteType])return;
    $('ug-pane3-sub').innerHTML='Based on your <strong>'+esc(TN[siteType]||siteType)+'</strong> profile. Click <strong>Apply &amp; Continue</strong> to configure automatically.';
    $('ug-preset-preview').innerHTML=Object.keys(PR[siteType]).map(function(k){
        var v=PR[siteType][k],l=PL[k]||k,isOn=v===true||v==='active',isOff=v===false;
        var cls=isOn?'ug-preset-on':isOff?'ug-preset-off':'ug-preset-val';
        var d=isOn?'\u2713 Enabled':isOff?'\u2717 Disabled':esc(String(v));
        return '<div class="ug-preset-row"><span class="ug-preset-key">'+esc(l)+'</span><span class="'+cls+'">'+d+'</span></div>';
    }).join('');
}
function applyPreset(){
    return req('ultraguard_onboarding_apply_preset',{site_type:siteType||'custom'}).then(function(r){
        if(!r.success)throw new Error(r.data&&r.data.message?r.data.message:'Failed.');
        showA(3,r.data.message,'success');
    });
}

var TL=[
    '<?php echo esc_js( __( 'Applying default settings...', 'ultraguard-security-suite' ) ); ?>',
    '<?php echo esc_js( __( 'Seeding firewall rules...', 'ultraguard-security-suite' ) ); ?>',
    '<?php echo esc_js( __( 'Seeding attack pattern signatures...', 'ultraguard-security-suite' ) ); ?>',
    '<?php echo esc_js( __( 'Configuring login protection...', 'ultraguard-security-suite' ) ); ?>',
    '<?php echo esc_js( __( 'Setting up security headers...', 'ultraguard-security-suite' ) ); ?>',
    '<?php echo esc_js( __( 'Initialising audit log...', 'ultraguard-security-suite' ) ); ?>',
    '<?php echo esc_js( __( 'Configuring notification channels...', 'ultraguard-security-suite' ) ); ?>',
    '<?php echo esc_js( __( 'Finalising database tables...', 'ultraguard-security-suite' ) ); ?>'
];
function startBaseline(){
    baselineStarted=true;baselineDone=false;
    $('ug-task-list').innerHTML=TL.map(function(l,i){
        return '<div class="ug-task-row pending" id="ugt-'+i+'"><div class="ug-task-dot">o</div><span>'+esc(l)+'</span></div>';
    }).join('');
    setP(0,TL.length,TL[0]);
    $('ug-btn-next').disabled=true;
    runTask(0);
}
function runTask(i){
    var total=TL.length;
    if(i>=total){
        setP(total,total,'<?php echo esc_js( __( 'Complete!', 'ultraguard-security-suite' ) ); ?>');
        baselineDone=true;
        var b=$('ug-btn-next');
        b.disabled=false;
        b.innerHTML='<?php echo esc_js( __( 'Continue', 'ultraguard-security-suite' ) ); ?> <span class="dashicons dashicons-arrow-right-alt"></span>';
        showA(4,'<?php echo esc_js( __( 'Security baseline setup complete.', 'ultraguard-security-suite' ) ); ?>','success');
        return;
    }
    var row=$('ugt-'+i);
    if(row){row.className='ug-task-row running';row.querySelector('.ug-task-dot').textContent='*';}
    setP(i,total,TL[i]);
    req('ultraguard_onboarding_seed_baseline',{task_index:i}).then(function(){
        if(row){row.className='ug-task-row done';row.querySelector('.ug-task-dot').textContent='\u2713';}
        setTimeout(function(){runTask(i+1);},260);
    }).catch(function(e){
        if(row){row.className='ug-task-row failed';row.querySelector('.ug-task-dot').textContent='!';}
        showA(4,'<?php echo esc_js( __( 'A task failed - you can continue anyway.', 'ultraguard-security-suite' ) ); ?>','error');
        baselineDone=true;
        var b=$('ug-btn-next');
        b.disabled=false;
        b.innerHTML='<?php echo esc_js( __( 'Continue anyway', 'ultraguard-security-suite' ) ); ?> <span class="dashicons dashicons-arrow-right-alt"></span>';
    });
}
function setP(done,total,label){
    var pct=total>0?Math.round(done/total*100):0;
    $('ug-prog-fill').style.width=pct+'%';
    $('ug-task-pct').textContent=pct+'%';
    $('ug-task-label').textContent=label;
}

function activateLicence(){
    var key=$('ug-license-key').value.trim();
    if(!key)return Promise.reject(new Error('<?php echo esc_js( __( 'Please enter a licence key or use "Skip this step".', 'ultraguard-security-suite' ) ); ?>'));
    return req('ultraguard_onboarding_save_license',{license_key:key,skipped:0}).then(function(r){
        if(!r.success)throw new Error(r.data&&r.data.message?r.data.message:'Failed.');
        showA(5,r.data.message,'success','s');
    });
}
function doComplete(){
    return req('ultraguard_onboarding_complete',{}).then(function(r){
        if(r.success){
            goTo('done');
            $('ug-wizard-footer').style.display='none';
            setTimeout(function(){location.href=(r.data&&r.data.redirect_url)||DASH;},2200);
        }
    });
}

function req(action,data){
    var params={action:action,nonce:cfg.nonce};
    Object.keys(data).forEach(function(k){params[k]=data[k];});
    var body=new URLSearchParams(params);
    return fetch(cfg.ajaxurl,{method:'POST',body:body}).then(function(r){return r.json();}).then(function(res){
        if(!res.success&&res.data&&res.data.message)throw new Error(res.data.message);
        return res;
    });
}
function showA(s,msg,type,sfx){
    var el=$('ug-alert-'+s+(sfx||''));
    if(!el)return;
    el.textContent=msg;
    el.className='ug-ialert ug-ialert-'+(type==='error'?'error':type==='success'?'success':'info');
    el.style.display='';
}
function clearA(s){
    ['','s'].forEach(function(sfx){var el=$('ug-alert-'+s+sfx);if(el){el.style.display='none';el.textContent='';}});
}
function esc(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
}());
</script>
<?php
    }
}
