<?php
/**
 * VulnerabilityDashboard — Overview page for the Vulnerability Scanner.
 *
 * FREE USER PHILOSOPHY: Show everything. Free users see the full UI, real stat
 * cards, and the scan-status panel. A single contextual inline_hint() nudge
 * explains what's unlocked with Pro. The Run Scan button is visible but the
 * AJAX handler returns a soft_gate_response() instead of a hard 403.
 *
 * @package UltraguardPro\modules\vulnerability\pages
 */

namespace UltraguardPro\modules\vulnerability\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;
use UltraguardPro\support\LicenseInfo;
use UltraguardPro\support\UpgradeManager;

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

class VulnerabilityDashboard extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->ajax_nonce_action = 'ultraguard_admin_nonce';
    }

    public function get_scheme( $context ): array {
        $is_pro = LicenseInfo::instance()->isPro();
        $preview_mode = $this->is_soft_gated_module_preview( 'vulnerability' );
        $nonce  = $this->create_nonce( 'ultraguard_admin_nonce' );

        $table = $this->plugin->modules->get_db_tables()->get_table( 'vulnerability_results' );

        if ( $preview_mode ) {
            $summary = [
                'total'           => 12,
                'open'            => 8,
                'critical'        => 2,
                'high'            => 3,
                'medium'          => 2,
                'low'             => 1,
                'virtual_patched' => 2,
            ];
        } else {
            $summary = $table ? $table->get_summary() : [
                'total' => 0, 'open' => 0, 'critical' => 0,
                'high' => 0, 'medium' => 0, 'low' => 0, 'virtual_patched' => 0,
            ];
        }

        // ── Chart data ────────────────────────────────────────────────────────
        // CVE severity breakdown as doughnut
        $severity_chart = [
            'labels' => [ __( 'Critical', 'ultraguard-security-suite' ), __( 'High', 'ultraguard-security-suite' ), __( 'Medium', 'ultraguard-security-suite' ), __( 'Low', 'ultraguard-security-suite' ) ],
            'data'   => [
                (int) $summary['critical'],
                (int) $summary['high'],
                (int) $summary['medium'],
                (int) $summary['low'],
            ],
            'colors' => [ '#dc2626', '#f97316', '#eab308', '#22c55e' ],
        ];

        // CVEs detected per day over last 30 days
        $cve_trend = $preview_mode
            ? [ 'labels' => [ 'Week 1', 'Week 2', 'Week 3', 'Week 4' ], 'data' => [ 3, 5, 4, 6 ] ]
            : ( $table
                ? $table->get_chart_data( 'created_at', 'id', 'day', [], 30 )
                : [ 'labels' => [], 'data' => [] ] );

        // CVEs grouped by component type (plugin / theme / core)
        $component_type_chart = $preview_mode
            ? [ 'labels' => [ 'Plugins', 'Themes', 'Core' ], 'data' => [ 6, 1, 1 ], 'colors' => [ '#dc2626', '#f97316', '#22c55e' ] ]
            : ( $table
                ? $table->get_pie_chart_data( 'component_type', 'id', 'COUNT', [ 'status' => 'open' ], 6 )
                : [ 'labels' => [], 'data' => [], 'colors' => [] ] );

        $scan_status = get_transient( 'ultraguard_vuln_scan_status' ) ?: [
            'status' => 'idle', 'progress' => 0, 'scan_id' => '',
        ];
        $last_scan = $preview_mode ? gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS ) : $this->plugin->settings->get_option( 'vulnerability_last_scan', '' );
        $settings  = $this->plugin->settings->get_module_settings( 'vulnerability' );

        // Stale-check on page render
        $is_running = in_array( $scan_status['status'] ?? '', [ 'running', 'queued' ], true );
        if ( $is_running ) {
            $started = isset( $scan_status['started'] ) ? strtotime( $scan_status['started'] ) : 0;
            $elapsed = $started ? ( time() - $started ) : 9999;
            if ( ( $elapsed > 600 && (int) ( $scan_status['progress'] ?? 0 ) <= 5 ) || $elapsed > 1200 ) {
                $is_running = false;
            }
        }

        // Top urgent CVEs (empty for free users with no scan history)
        $urgent_items = $preview_mode
            ? $this->preview_urgent_items()
            : ( ( $is_pro && $table )
                ? $table->get_by( [ 'status' => 'open', 'severity' => 'critical' ], 5, 'cvss_score', 'DESC' )
                : [] );

        $urgent_rows = array_map( function ( $r ) {
            $r = (array) $r;
            return [
                'component' => esc_html( $r['component_slug'] ?? '' ),
                'cve'       => esc_html( $r['cve_id'] ?? '—' ),
                'severity'  => [ 'content' => esc_html( ucfirst( $r['severity'] ?? '' ) ), 'class' => 'danger' ],
                'cvss'      => esc_html( number_format( (float) ( $r['cvss_score'] ?? 0 ), 1 ) ),
                'title'     => esc_html( mb_substr( $r['title'] ?? '', 0, 80 ) ),
            ];
        }, $urgent_items );

        // ── Page scheme ────────────────────────────────────────────────────────
        return [
            'type'      => 'page',
            'id'        => 'ultraguard-vulnerability',
            'page_slug' => 'vulnerability-scanner',
            'class'     => 'ultraguard-vulnerability-page ultraguard-page-no-sidebar',
            'header'    => [
                'title'    => __( 'Vulnerability Scanner', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Detect known CVEs across installed plugins, themes, and WordPress core. Apply virtual WAF patches instantly.', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-shield-alt',
                'badge'    => [
                    'text'       => $is_pro
                        /* translators: %d: integer */
                        ? sprintf( __( '%d open', 'ultraguard-security-suite' ), (int) $summary['open'] )
                        : __( 'Pro', 'ultraguard-security-suite' ),
                    'badge_type' => $is_pro
                        ? ( $summary['critical'] > 0 ? 'danger' : ( $summary['open'] > 0 ? 'warning' : 'success' ) )
                        : 'warning',
                ],
                'actions'  => ( $is_pro && ! $is_running ) ? [
                    $this->create_ajax_button(
                        __( 'Run Scan', 'ultraguard-security-suite' ),
                        'ultraguard_vuln_run_scan', [],
                        'primary', 'dashicons-search',
                        __( 'Start a vulnerability scan? This checks all installed plugins, themes, and WordPress core against known CVEs.', 'ultraguard-security-suite' )
                    ),
                ] : [],
            ],

            'form' => $is_pro ? [
                'enable' => true,
                'id'     => 'vulnerability-settings-form',
                'ajax'   => true,
                'action' => 'ultraguard_save_vulnerability_settings',
                'nonce'  => $nonce,
                'submit' => [
                    'text'         => __( 'Save Settings', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                ],
            ] : [ 'enable' => false ],

            'data' => array_values( array_filter( [

                // ── Soft nudge for free users (top of page, non-blocking) ──────
                $preview_mode ? $this->soft_gated_preview_data_notice(
                    __( 'Vulnerability Scanner', 'ultraguard-security-suite' ),
                    __( 'The CVE counts, trend charts, and urgent findings on this screen are sample scan results. Upgrade to run real scans against your installed plugins, themes, and core.', 'ultraguard-security-suite' )
                ) : null,

                UpgradeManager::should_show_nudge()
                    ? UpgradeManager::inline_hint(
                        'vulnerability_scan',
                        __( 'Run your first scan to discover CVEs across all installed plugins, themes, and WordPress core — and see exactly what needs fixing.', 'ultraguard-security-suite' )
                    )
                    : null,

                // ── Scan panel ─────────────────────────────────────────────────
                // ── Scan panel — rendered via RenderEngine ─────────────────────
                $this->build_vuln_scan_panel_scheme( $scan_status, $is_running, $is_pro, $nonce, $last_scan ),

                // ── Stat cards (always visible, zeros for free) ────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total',           'ultraguard-security-suite' ), 'value' => $summary['total'],           'icon' => 'dashicons-visibility', 'class' => 'info' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Open',            'ultraguard-security-suite' ), 'value' => $summary['open'],            'icon' => 'dashicons-warning',    'class' => $summary['open']     > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Critical',        'ultraguard-security-suite' ), 'value' => $summary['critical'],        'icon' => 'dashicons-dismiss',    'class' => $summary['critical']  > 0 ? 'danger'  : 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'High',            'ultraguard-security-suite' ), 'value' => $summary['high'],            'icon' => 'dashicons-flag',       'class' => $summary['high']      > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Med / Low',       'ultraguard-security-suite' ), 'value' => $summary['medium'] + $summary['low'], 'icon' => 'dashicons-info', 'class' => 'secondary' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Virtual Patched', 'ultraguard-security-suite' ), 'value' => $summary['virtual_patched'], 'icon' => 'dashicons-shield',     'class' => 'success' ] ],
                    ],
                ],

                // ── Virtual patching teaser for free users ─────────────────────
                UpgradeManager::should_show_nudge()
                    ? UpgradeManager::teaser_card( 'virtual_patching' )
                    : null,

                // ── Charts: Severity doughnut (4) + CVE trend line (8) ─────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'CVE Severity Breakdown', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-pie',
                                'data'  => array_sum( $severity_chart['data'] ) === 0 ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'Run a scan to see severity data.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'doughnut',
                                        'height'         => '240px',
                                        'labels'         => $severity_chart['labels'],
                                        'datasets'       => [
                                            [
                                                'data'            => $severity_chart['data'],
                                                'backgroundColor' => $severity_chart['colors'],
                                                'borderWidth'     => 2,
                                            ],
                                        ],
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 8,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'CVEs Detected — Last 30 Days', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-line',
                                'data'  => empty( $cve_trend['data'] ) ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'No scan history yet. Run a scan to begin tracking CVEs over time.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'line',
                                        'height'         => '240px',
                                        'labels'         => $cve_trend['labels'],
                                        'datasets'       => [
                                            [
                                                'label'           => __( 'CVEs Found', 'ultraguard-security-suite' ),
                                                'data'            => $cve_trend['data'],
                                                'borderColor'     => '#f97316',
                                                'backgroundColor' => 'rgba(249,115,22,0.12)',
                                                'fill'            => true,
                                                'tension'         => 0.4,
                                                'pointRadius'     => 3,
                                            ],
                                        ],
                                        'x_axis_title'   => __( 'Date', 'ultraguard-security-suite' ),
                                        'y_axis_title'   => __( 'CVEs', 'ultraguard-security-suite' ),
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],

                // ── Component type distribution (pro only — needs scan data) ───
                ( $is_pro && ! empty( $component_type_chart['data'] ) ) ? [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 12,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Open CVEs by Component Type', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-bar',
                                'data'  => [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'bar',
                                        'height'         => '200px',
                                        'labels'         => $component_type_chart['labels'],
                                        'datasets'       => [
                                            [
                                                'label'           => __( 'Open CVEs', 'ultraguard-security-suite' ),
                                                'data'            => $component_type_chart['data'],
                                                'backgroundColor' => $component_type_chart['colors'],
                                                'borderWidth'     => 1,
                                            ],
                                        ],
                                        'x_axis_title'   => __( 'Component Type', 'ultraguard-security-suite' ),
                                        'y_axis_title'   => __( 'Count', 'ultraguard-security-suite' ),
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                    ],
                ] : null,
                ( $is_pro && ! empty( $urgent_rows ) ) ? [
                    'type'  => 'card',
                    'title' => __( 'Critical CVEs — Immediate Attention Required', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-dismiss',
                    'data'  => [ [
                        'type'       => 'data-table',
                        'id'         => 'critical-vuln-table',
                        'columns'    => [
                            'component' => [ 'title' => __( 'Component', 'ultraguard-security-suite' ), 'sortable' => true ],
                            'cve'       => [ 'title' => __( 'CVE',       'ultraguard-security-suite' ) ],
                            'severity'  => [ 'title' => __( 'Severity',  'ultraguard-security-suite' ) ],
                            'cvss'      => [ 'title' => __( 'CVSS',      'ultraguard-security-suite' ), 'sortable' => true ],
                            'title'     => [ 'title' => __( 'Title',     'ultraguard-security-suite' ) ],
                        ],
                        'data'        => $urgent_rows,
                        'searchable'  => false,
                        'empty_state' => [ 'title' => __( 'No critical CVEs', 'ultraguard-security-suite' ), 'description' => '' ],
                    ] ],
                ] : null,

                // ── Settings (Pro only — free users see upgrade nudge instead) ──
                $is_pro ? [
                    'type'  => 'card',
                    'title' => __( 'Scanner Settings', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-admin-settings',
                    'data'  => [
                        [
                            'type'        => 'text',
                            'name'        => 'wpscan_api_key',
                            'label'       => __( 'WPScan API Key', 'ultraguard-security-suite' ),
                            'description' => __( 'Free key at wpscan.com — 25 requests/day. Leave blank to use Patchstack fallback only.', 'ultraguard-security-suite' ),
                            'default'     => esc_attr( $settings['wpscan_api_key'] ?? '' ),
                            'placeholder' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                        ],
                        [
                            'type'        => 'toggle',
                            'name'        => 'vulnerability_auto_scan',
                            'label'       => __( 'Daily Automatic Scan', 'ultraguard-security-suite' ),
                            'description' => __( 'Run a full CVE scan every 24 hours automatically via WP-Cron.', 'ultraguard-security-suite' ),
                            'default'     => (bool) ( $settings['vulnerability_auto_scan'] ?? true ),
                        ],
                        [
                            'type'        => 'toggle',
                            'name'        => 'vulnerability_virtual_patch',
                            'label'       => __( 'Auto-Apply Virtual Patches', 'ultraguard-security-suite' ),
                            'description' => __( 'Automatically generate WAF rules for critical/high CVEs when no official fix is available.', 'ultraguard-security-suite' ),
                            'default'     => (bool) ( $settings['vulnerability_virtual_patch'] ?? true ),
                        ],
                        [
                            'type'        => 'toggle',
                            'name'        => 'vulnerability_notify_on_critical',
                            'label'       => __( 'Email on Critical Findings', 'ultraguard-security-suite' ),
                            'description' => __( 'Send an admin email when critical CVEs are discovered during a scan.', 'ultraguard-security-suite' ),
                            'default'     => (bool) ( $settings['vulnerability_notify_on_critical'] ?? true ),
                        ],
                    ],
                ] : null,

            ] ) ),
        ];
    }

    private function preview_urgent_items(): array {
        return [
            [
                'component_slug' => 'woocommerce',
                'cve_id'         => 'CVE-2026-1042',
                'severity'       => 'critical',
                'cvss_score'     => 9.1,
                'title'          => 'Privilege escalation through insecure checkout endpoint',
            ],
            [
                'component_slug' => 'elementor',
                'cve_id'         => 'CVE-2026-1188',
                'severity'       => 'critical',
                'cvss_score'     => 8.7,
                'title'          => 'Stored XSS in template import workflow',
            ],
        ];
    }

    // ── Scan panel scheme ──────────────────────────────────────────────────────

    /**
     * Build the vulnerability scanner status card as a pure RenderEngine scheme.
     *
     * Replaces the former ob_start() / ob_get_clean() HTML template with:
     *   • 'progress'      — WidgetRenderer::render_progress()  (animated bar, pro only)
     *   • 'list'          — WidgetRenderer::render_list()       (plugins/themes/CVE counters)
     *   • 'button-group'  — ActionRenderer                      (Run Scan / Stop / Upgrade)
     *
     * The `last_scan` footer shows the formatted last-scan time from the stored
     * settings option (already a display string supplied by the caller).
     */
    private function build_vuln_scan_panel_scheme(
        array  $scan,
        bool   $running,
        bool   $is_pro,
        string $nonce,
        string $last_scan
    ): array {
        $progress = (int) ( $scan['progress'] ?? 0 );
        $scan_id  = esc_attr( $scan['scan_id'] ?? '' );
        $status   = $scan['status'] ?? 'idle';

        $data = [];

        // ── Status + progress bar ─────────────────────────────────────────────
        $badge_class = $running ? 'ug-scan-badge ug-scan-badge--running' : 'ug-scan-badge ug-scan-badge--idle';
        $badge_text  = $running ? esc_html__( 'Running\xe2\x80\xa6', 'ultraguard-security-suite' ) : esc_html( ucfirst( $status ) );

        $bar_html =
            '<div style="margin-bottom:12px;">'
          . '<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">'
          .   '<span data-rt="vuln-scan-badge" class="' . $badge_class . '">'
          .     '<span class="ug-scan-badge-dot"></span>'
          .   '</span>'
          .   '<span data-rt="vuln-scan-status-text" style="font-weight:600;font-size:13px;">' . $badge_text . '</span>'
          . '</div>'
          . '<div data-rt="vuln-progress-wrap" class="' . ( $running ? '' : 'ultraguard-hidden' ) . '">'
          .   '<div class="ug-scan-progress-bar-track" style="margin-bottom:4px;">'
          .     '<div data-rt="vuln-progress-bar" class="ug-scan-progress-bar-fill" style="width:' . $progress . '%"></div>'
          .   '</div>'
          .   '<div style="display:flex;justify-content:space-between;font-size:12px;color:#64748b;">'
          .     '<span data-rt="vuln-phase">' . esc_html( $scan['phase'] ?? '' ) . '</span>'
          .     '<strong data-rt="vuln-progress-pct">' . $progress . '%</strong>'
          .   '</div>'
          . '</div>'
          // Error box — always in DOM, JS shows/hides
          . '</div>'
          . '<div data-rt="vuln-error-box" class="' . ( $status === 'error' ? '' : 'ultraguard-hidden' ) . '" style="background:#fef2f2;border:1px solid #fecaca;border-radius:6px;padding:8px 12px;margin-bottom:8px;font-size:13px;color:#dc2626;">'
          .   '<span data-rt="vuln-error-msg">' . esc_html( $scan['error'] ?? '' ) . '</span>'
          . '</div>';

        $data[] = [ 'type' => 'html', 'allow_unsafe_html' => true, 'content' => $bar_html ];

        // ── Stats table (pro-only) ────────────────────────────────────────────
        if ( $is_pro ) {
            $threats_found = (int) ( $scan['threats_found'] ?? 0 );

            $table_rows = [
                [ 'dashicons-admin-plugins',    __( 'Plugins Checked', 'ultraguard-security-suite' ), '—',           'vuln-plugins-checked', 'info'    ],
                [ 'dashicons-admin-appearance', __( 'Themes Checked',  'ultraguard-security-suite' ), '—',           'vuln-themes-checked',  'info'    ],
                [ 'dashicons-warning',          __( 'CVEs Found',      'ultraguard-security-suite' ), $threats_found,'vuln-cves-found',      $threats_found > 0 ? 'danger' : 'success' ],
            ];

            $rows_html = '';
            foreach ( $table_rows as [ $icon, $label, $value, $rt, $bt ] ) {
                $badge_val = is_int( $value ) ? number_format_i18n( $value ) : esc_html( (string) $value );
                $rows_html .= '<tr data-rt="' . esc_attr( $rt ) . '">'
                            . '<td style="padding:6px 10px 6px 0;white-space:nowrap;color:#64748b;font-size:13px;width:1%;">'
                            . '<span class="dashicons ' . esc_attr( $icon ) . '" style="font-size:15px;width:15px;height:15px;vertical-align:text-bottom;margin-right:6px;color:#0ea5e9;"></span>'
                            . esc_html( $label ) . '</td>'
                            . '<td style="padding:6px 0;text-align:right;">'
                            . '<span class="ultraguard-badge ultraguard-badge-' . esc_attr( $bt ) . '" style="min-width:40px;display:inline-block;text-align:center;">'
                            . $badge_val . '</span></td></tr>';
            }

            $data[] = [
                'type'             => 'html',
                'allow_unsafe_html'=> true,
                'content'          => '<table style="width:100%;border-collapse:collapse;"><tbody>' . $rows_html . '</tbody></table>',
            ];

            // Complete summary
            if ( $status === 'complete' ) {
                $data[] = [
                    'type'       => 'alert-box',
                    'alert_type' => 'success',
                    'icon'       => 'dashicons-yes-alt',
                    'message'    => sprintf(
                        /* translators: Placeholder values are inserted into this string. */
                        __( 'Scan complete. %d new vulnerabilities found.', 'ultraguard-security-suite' ),
                        (int) ( $scan['threats_found'] ?? 0 )
                    ),
                    'attributes' => [ 'data-rt' => 'vuln-complete-summary' ],
                ];
                $data[] = [
                    'type'             => 'html',
                    'allow_unsafe_html'=> true,
                    'content'          => '<span data-rt="vuln-complete-detail" style="font-size:12px;color:#64748b;">'
                                       . esc_html( (int) ( $scan['threats_found'] ?? 0 ) . ' new vulnerabilities found.' )
                                       . '</span>',
                ];
            }
        }

        // ── Action buttons ────────────────────────────────────────────────────
        $buttons = [];
        if ( $is_pro ) {
            if ( $running ) {
                $buttons[] = [
                    'type'         => 'button',
                    'text'         => __( 'Stop Scan', 'ultraguard-security-suite' ),
                    'button_style' => 'secondary',
                    'icon'         => 'dashicons-no-alt',
                    'id'           => 'ug-vuln-stop-btn',
                    'attributes'   => [ 'data-rt' => 'vuln-stop-btn' ],
                    'ajax'         => [
                        'action' => 'ultraguard_vuln_stop_scan',
                        'nonce'  => $nonce,
                        'data'   => [ 'scan_id' => $scan_id ],
                    ],
                ];
            } else {
                $buttons[] = [
                    'type'         => 'button',
                    'text'         => __( 'Run Scan', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                    'icon'         => 'dashicons-search',
                    'id'           => 'ug-vuln-scan-btn',
                    'attributes'   => [ 'data-rt' => 'vuln-scan-btn' ],
                    'ajax'         => [
                        'action'  => 'ultraguard_vuln_run_scan',
                        'nonce'   => $nonce,
                        'confirm' => __( 'Start a vulnerability scan? This checks all installed plugins, themes, and WordPress core against known CVEs.', 'ultraguard-security-suite' ),
                    ],
                ];
            }
        } else {
            $buttons[] = [
                'type'         => 'button',
                'text'         => __( 'Upgrade to Scan', 'ultraguard-security-suite' ),
                'button_style' => 'secondary',
                'icon'         => 'dashicons-star-filled',
                'url'          => UpgradeManager::upgrade_page_url(),
            ];
        }

        $data[] = [
            'type'      => 'button-group',
            'alignment' => 'left',
            'id'        => 'ug-vuln-scan-actions',
            'buttons'   => $buttons,
        ];

        return [
            'type'       => 'card',
            'id'         => 'ug-vuln-scan-panel',
            'title'      => __( 'Scan Status', 'ultraguard-security-suite' ),
            'icon'       => 'dashicons-search',
            'badge'      => [
                'text'       => $running ? __( 'Running', 'ultraguard-security-suite' ) : ucfirst( $status ),
                'badge_type' => $running ? 'warning' : ( $status === 'error' ? 'danger' : 'info' ),
            ],
            'attributes' => [
                'data-scan-id'    => $scan_id,
                'data-nonce'      => $nonce,
                'data-running'    => $running ? '1' : '0',
                'data-poll-action'=> 'ultraguard_vuln_scan_status',
                'data-stop-action'=> 'ultraguard_vuln_stop_scan',
            ],
            'data'   => $data,
            'footer' => sprintf(
                /* translators: %s: last scan datetime or "Never" */
                __( 'Last scan: %s', 'ultraguard-security-suite' ),
                '<strong>' . ( $last_scan ? esc_html( $last_scan ) : esc_html__( 'Never', 'ultraguard-security-suite' ) ) . '</strong>'
            ),
        ];
    }
}
