<?php
/**
 * UpgradeManager — Central registry for Pro feature hints and contextual upgrade nudges.
 *
 * PHILOSOPHY
 * ─────────────────────────────────────────────────────────────────────────────
 * UltraGuard never hard-blocks a free user from seeing or learning about a
 * feature. Instead it:
 *   1. Shows the feature fully to pro users.
 *   2. Shows free users a live preview of the feature UI (with a gentle nudge).
 *   3. Places contextual hint banners only where they add genuine value.
 *   4. Provides one beautiful dedicated upgrade page they can reach at any time.
 *
 * WHAT THIS CLASS DOES
 * ─────────────────────────────────────────────────────────────────────────────
 *   • Provides static feature registry — what's free vs what's pro and why.
 *   • Provides render helpers for:
 *       - Contextual inline hints (small, non-blocking notice inside a card)
 *       - Feature teaser cards (shown instead of locked UI)
 *       - Pro badge overlays on settings fields
 *       - AJAX error responses that redirect to the upgrade page
 *   • Provides helper for the "soft gate" pattern in AJAX handlers:
 *       Free users can READ everything. They get a nudge on WRITE/DESTRUCTIVE
 *       actions (run a full scan, restore quarantine, etc.) instead of a wall.
 *
 * @package UltraguardPro\support
 * @since   6.7.0
 */

namespace UltraguardPro\support;

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

final class UpgradeManager {

    /** URL of the dedicated upgrade page inside the plugin. */
    public const UPGRADE_PAGE_URL_PATTERN = 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=upgrade-manager';

    /** External website URL — pricing/subscription decided later. */
    public const EXTERNAL_UPGRADE_URL = 'https://ultraguard.net/pricing';

    /** Static billing/account management URL used when the license server does not provide one. */
    public const BILLING_PORTAL_URL = 'https://ultraguard.net/awesome-login/';

    /** Static support URL used across upgrade/license screens. */
    public const SUPPORT_URL = 'https://ultraguard.net/contact';

    // ── Feature registry ──────────────────────────────────────────────────────

    /**
     * Full registry of every pro-only feature.
     *
     * Keys are stable feature identifiers used by hint helpers.
     * Each entry has:
     *   label       — short name shown in badges
     *   headline    — one-sentence value proposition
     *   description — 1–2 sentences: what they get and why it matters
     *   icon        — dashicons class
     *   benefits    — up to 4 bullet points (strings)
     *   module      — which module owns this feature
     *
     * @return array<string, array>
     */
    public static function features(): array {
        static $features = null;
        if ( $features !== null ) { return $features; }

        $features = [

            // ── File Checker ──────────────────────────────────────────────────
            'file_integrity_scan' => [
                'label'       => __( 'File Integrity Scanner', 'ultraguard-security-suite' ),
                'headline'    => __( 'Know the instant any file on your site changes.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro scans every file in your WordPress install and alerts you the moment something is added, modified, or deleted — so you catch hackers before they do damage.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-search',
                'module'      => 'filechecker',
                'benefits'    => [
                    __( 'Detects malware injected into PHP, JS and HTML files', 'ultraguard-security-suite' ),
                    __( 'Verifies WordPress core files against official checksums', 'ultraguard-security-suite' ),
                    __( 'Scheduled automatic scans — daily, weekly, or on upgrade', 'ultraguard-security-suite' ),
                    __( 'Quarantine suspicious files with one click', 'ultraguard-security-suite' ),
                ],
            ],
            'file_quarantine' => [
                'label'       => __( 'File Quarantine', 'ultraguard-security-suite' ),
                'headline'    => __( 'Isolate infected files without deleting them.', 'ultraguard-security-suite' ),
                'description' => __( 'Move suspicious files to a protected quarantine directory so they can\'t execute while you review them. Restore with one click if it\'s a false positive.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-lock',
                'module'      => 'filechecker',
                'benefits'    => [
                    __( 'Safe isolation — file moved, not deleted', 'ultraguard-security-suite' ),
                    __( 'One-click restore if it\'s a false positive', 'ultraguard-security-suite' ),
                    __( 'Complete audit trail of every quarantine event', 'ultraguard-security-suite' ),
                ],
            ],
            'file_restore' => [
                'label'       => __( 'File Restore', 'ultraguard-security-suite' ),
                'headline'    => __( 'Restore any file from quarantine in seconds.', 'ultraguard-security-suite' ),
                'description' => __( 'Review quarantined files and restore them to their original location when safe, with a full audit trail of who restored what and why.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-image-rotate',
                'module'      => 'filechecker',
                'benefits'    => [
                    __( 'Restore from quarantine with a reason note', 'ultraguard-security-suite' ),
                    __( 'Admin audit trail: user, timestamp, reason', 'ultraguard-security-suite' ),
                    __( 'Permanently delete files you\'re sure are malicious', 'ultraguard-security-suite' ),
                ],
            ],
            'baseline_reset' => [
                'label'       => __( 'Baseline Reset', 'ultraguard-security-suite' ),
                'headline'    => __( 'Set a new trusted file baseline after an update.', 'ultraguard-security-suite' ),
                'description' => __( 'After a legitimate update or deploy, tell UltraGuard "this is the new normal" so future scans compare against your updated files, not the old ones.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-image-rotate',
                'module'      => 'filechecker',
                'benefits'    => [
                    __( 'Zero false positives after intentional updates', 'ultraguard-security-suite' ),
                    __( 'Mark individual files or the entire install as trusted', 'ultraguard-security-suite' ),
                    __( 'Keeps the changelog of every baseline change', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Notifications ─────────────────────────────────────────────────
            'notification_rules' => [
                'label'       => __( 'Notification Rules', 'ultraguard-security-suite' ),
                'headline'    => __( 'Get alerted on the threats that matter to you.', 'ultraguard-security-suite' ),
                'description' => __( 'Create custom notification rules: choose the event type, severity threshold, channel (email, Slack, webhook), and a cooldown period. Never miss a real threat.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-bell',
                'module'      => 'notifications',
                'benefits'    => [
                    __( 'Email, Slack, and webhook delivery channels', 'ultraguard-security-suite' ),
                    __( 'Per-event severity thresholds — only alert when it matters', 'ultraguard-security-suite' ),
                    __( 'Cooldown periods to prevent alert fatigue', 'ultraguard-security-suite' ),
                    __( 'Wildcard rules — catch any event type with one rule', 'ultraguard-security-suite' ),
                ],
            ],
            'notification_channels' => [
                'label'       => __( 'Notification Channels', 'ultraguard-security-suite' ),
                'headline'    => __( 'Send alerts to Slack, webhooks, or any endpoint.', 'ultraguard-security-suite' ),
                'description' => __( 'Save reusable delivery destinations — a Slack workspace, a PagerDuty webhook, a team email alias — and use them across multiple notification rules.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-share',
                'module'      => 'notifications',
                'benefits'    => [
                    __( 'Named, reusable channel configurations', 'ultraguard-security-suite' ),
                    __( 'Test any channel with one click before saving', 'ultraguard-security-suite' ),
                    __( 'HMAC-signed webhook payloads for secure delivery', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Server Intelligence ───────────────────────────────────────────
            'intelligence_sync' => [
                'label'       => __( 'Real-Time Intelligence', 'ultraguard-security-suite' ),
                'headline'    => __( 'Get threat updates the moment they\'re published.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro users receive new malware signatures, threat IP lists, firewall rules, and vulnerability DB entries immediately. Free users receive the same updates within 24 hours.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-cloud',
                'module'      => 'server_intelligence',
                'benefits'    => [
                    __( 'Zero-day threat signatures — no delay', 'ultraguard-security-suite' ),
                    __( 'Global threat IP blacklist updated hourly', 'ultraguard-security-suite' ),
                    __( 'Cloud firewall rules pushed instantly', 'ultraguard-security-suite' ),
                    __( 'Push events always real-time on both tiers', 'ultraguard-security-suite' ),
                ],
            ],
            'ip_intelligence' => [
                'label'       => __( 'IP Intelligence Feed', 'ultraguard-security-suite' ),
                'headline'    => __( 'Check and sync malicious IP reputation before attackers reach your site.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro connects your site to AbuseIPDB, Spamhaus, and UltraGuard network intelligence so you can block hostile IPs faster and investigate reputation live from the dashboard.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-shield-alt',
                'module'      => 'ip_intelligence',
                'benefits'    => [
                    __( 'Live IP reputation lookups from the dashboard', 'ultraguard-security-suite' ),
                    __( 'Automatic sync from cloud threat feeds', 'ultraguard-security-suite' ),
                    __( 'High-confidence IP auto-blocking workflows', 'ultraguard-security-suite' ),
                ],
            ],
            'reputation_monitor' => [
                'label'       => __( 'Blacklist & Reputation Monitor', 'ultraguard-security-suite' ),
                'headline'    => __( 'Know when your domain or IP appears on public blacklists.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro monitors major reputation sources and alerts you when your site is flagged, helping you respond before customers and search engines are affected.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-search',
                'module'      => 'reputation_monitor',
                'benefits'    => [
                    __( 'Automated blacklist checks across multiple sources', 'ultraguard-security-suite' ),
                    __( 'History tracking for status changes over time', 'ultraguard-security-suite' ),
                    __( 'Immediate alerting when your site reputation drops', 'ultraguard-security-suite' ),
                ],
            ],
            'uptime_monitor' => [
                'label'       => __( 'Uptime & SSL Monitor', 'ultraguard-security-suite' ),
                'headline'    => __( 'Track site uptime and certificate health from one security dashboard.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro performs recurring uptime and SSL checks so you know when the site goes down, slows down, or approaches certificate expiry.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-clock',
                'module'      => 'uptime_monitor',
                'benefits'    => [
                    __( 'Scheduled uptime checks throughout the day', 'ultraguard-security-suite' ),
                    __( 'SSL expiry monitoring and alerts', 'ultraguard-security-suite' ),
                    __( 'Incident history and response-time charts', 'ultraguard-security-suite' ),
                ],
            ],
            'compliance_reports' => [
                'label'       => __( 'Compliance Reports', 'ultraguard-security-suite' ),
                'headline'    => __( 'Generate audit-ready security evidence in shareable reports.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro builds HTML and PDF compliance reports using data from across UltraGuard so you can show what protections are active and what incidents were handled.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-media-document',
                'module'      => 'compliance_reports',
                'benefits'    => [
                    __( 'Generate GDPR, PCI-DSS, and security audit reports', 'ultraguard-security-suite' ),
                    __( 'Collect evidence from multiple UltraGuard modules', 'ultraguard-security-suite' ),
                    __( 'Email and archive reports for compliance workflows', 'ultraguard-security-suite' ),
                ],
            ],
            'woo_security' => [
                'label'       => __( 'WooCommerce Security Mode', 'ultraguard-security-suite' ),
                'headline'    => __( 'Protect checkout flows with WooCommerce-specific security controls.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro adds skimmer scanning, checkout honeypots, CSP hardening, and security headers designed specifically for WooCommerce storefronts.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-cart',
                'module'      => 'woo_security',
                'benefits'    => [
                    __( 'Skimmer detection for checkout JavaScript files', 'ultraguard-security-suite' ),
                    __( 'Checkout honeypot protection against bot orders', 'ultraguard-security-suite' ),
                    __( 'PCI-conscious headers and CSP on sensitive store pages', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Upload-module feature ─────────────────────────────────────────
            'module_upload' => [
                'label'       => __( 'Third-Party Module Upload', 'ultraguard-security-suite' ),
                'headline'    => __( 'Extend UltraGuard with custom security modules.', 'ultraguard-security-suite' ),
                'description' => __( 'Upload ZIP modules built by third parties or your own development team to add custom security checks, integrations, or reports to your UltraGuard install.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-upload',
                'module'      => 'modules',
                'benefits'    => [
                    __( 'Upload any module as a ZIP file', 'ultraguard-security-suite' ),
                    __( 'Automatic schema creation and lifecycle management', 'ultraguard-security-suite' ),
                    __( 'Full module API with DB tables, AJAX, and admin pages', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Vulnerability Scanner ─────────────────────────────────────────
            'vulnerability_scan' => [
                'label'       => __( 'CVE Vulnerability Scan', 'ultraguard-security-suite' ),
                'headline'    => __( 'Know exactly which of your plugins, themes, and core files have known exploits.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro runs automated daily scans against the WPScan and Patchstack CVE databases, assigns CVSS severity scores to every finding, and emails you when a critical vulnerability is discovered.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-shield-alt',
                'module'      => 'vulnerability',
                'benefits'    => [
                    __( 'Checks every installed plugin, theme, and WordPress core', 'ultraguard-security-suite' ),
                    __( 'CVSS 3.x scoring — Critical / High / Medium / Low', 'ultraguard-security-suite' ),
                    __( 'Daily automatic scans via WP-Cron', 'ultraguard-security-suite' ),
                    __( 'Email alerts when critical CVEs are discovered', 'ultraguard-security-suite' ),
                ],
            ],
            'virtual_patching' => [
                'label'       => __( 'Virtual Patching', 'ultraguard-security-suite' ),
                'headline'    => __( 'Block exploit attempts before an official fix ships.', 'ultraguard-security-suite' ),
                'description' => __( 'When a CVE has no patch yet, UltraGuard Pro instantly generates a WAF rule that intercepts known attack patterns targeting that vulnerability. The rule removes itself automatically once you install the official update.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-shield',
                'module'      => 'vulnerability',
                'benefits'    => [
                    __( 'Zero-day protection — WAF rule active within seconds', 'ultraguard-security-suite' ),
                    __( 'Auto-removes when the component is updated', 'ultraguard-security-suite' ),
                    __( 'No manual configuration — one-click or fully automatic', 'ultraguard-security-suite' ),
                    __( 'Full audit trail of every patch applied and removed', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Database Scanner ──────────────────────────────────────────────
            'database_scan' => [
                'label'       => __( 'Database Scanner', 'ultraguard-security-suite' ),
                'headline'    => __( 'Find malware that hides inside your WordPress database, not just your files.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro scans every post, option, and user record for SEO spam links, pharma hack patterns, eval() injections, hidden iframes, and base64 payloads — then removes them with one click.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-database',
                'module'      => 'database_scanner',
                'benefits'    => [
                    __( 'Detects SEO spam, pharma hacks, and hidden links in posts', 'ultraguard-security-suite' ),
                    __( 'Finds eval() and base64 payloads injected into options', 'ultraguard-security-suite' ),
                    __( 'One-click injection removal with before/after preview', 'ultraguard-security-suite' ),
                    __( 'Scheduled daily scan — runs automatically via WP-Cron', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Scheduled Antivirus ───────────────────────────────────────────
            'scheduled_av_scan' => [
                'label'       => __( 'Scheduled Antivirus Scans', 'ultraguard-security-suite' ),
                'headline'    => __( 'Malware waits — your scanner shouldn\'t. A hack discovered six days late costs six days of damage.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro runs automatic antivirus scans daily, weekly, or on every plugin update — so new infections are caught within hours, not when a visitor happens to notice something wrong.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-clock',
                'module'      => 'antivirus',
                'benefits'    => [
                    __( 'Automatic scheduled scans — daily, weekly, or on update', 'ultraguard-security-suite' ),
                    __( 'Email alert the moment a threat is discovered', 'ultraguard-security-suite' ),
                    __( 'No 48-hour cooldown — scan whenever you need to', 'ultraguard-security-suite' ),
                    __( 'Full scan history with trend charts', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Antivirus Scan History ────────────────────────────────────────
            'av_scan_history' => [
                'label'       => __( 'Antivirus Scan History & Export', 'ultraguard-security-suite' ),
                'headline'    => __( 'Without scan history, you can\'t prove when your site was last clean — or when it wasn\'t.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro stores the full history of every scan run, every file checked, and every threat found. Export for audits, insurance claims, or client reporting.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-backup',
                'module'      => 'antivirus',
                'benefits'    => [
                    __( 'Complete scan run history with timestamps', 'ultraguard-security-suite' ),
                    __( 'Trend chart — see if threats are increasing over time', 'ultraguard-security-suite' ),
                    __( 'CSV export for client reports and insurance claims', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Audit Log Extended Retention ──────────────────────────────────
            'audit_log_retention' => [
                'label'       => __( 'Extended Audit Log Retention', 'ultraguard-security-suite' ),
                'headline'    => __( 'Most breaches are discovered weeks after they happen — but your free log only goes back 7 days.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro keeps 90 days of every admin action, login, file edit, and security event. When something goes wrong — and eventually it will — you will have the full picture.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-backup',
                'module'      => 'audit_log',
                'benefits'    => [
                    __( '90-day audit log retention vs 7-day on free plan', 'ultraguard-security-suite' ),
                    __( 'Full history export to CSV for compliance audits', 'ultraguard-security-suite' ),
                    __( 'Never lose evidence when you need it most', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Traffic Monitor Full History ──────────────────────────────────
            'traffic_history' => [
                'label'       => __( 'Full Traffic History & Export', 'ultraguard-security-suite' ),
                'headline'    => __( 'Attackers don\'t stop after 200 requests — but your free traffic log does.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro stores your complete traffic history so you can investigate attack patterns, prove clean traffic to CDNs, and export logs for incident response reports.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-chart-area',
                'module'      => 'traffic_monitor',
                'benefits'    => [
                    __( 'Unlimited traffic log history (vs last 200 requests free)', 'ultraguard-security-suite' ),
                    __( 'Full date-range filtering across all stored requests', 'ultraguard-security-suite' ),
                    __( 'CSV export for incident response and compliance', 'ultraguard-security-suite' ),
                ],
            ],

            // ── Slack & Webhook Notifications ─────────────────────────────────
            'slack_notifications' => [
                'label'       => __( 'Slack & Webhook Notifications', 'ultraguard-security-suite' ),
                'headline'    => __( 'Email is too slow when your site is under attack — real-time alerts go to where your team already is.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro delivers security alerts to Slack, Discord, or any webhook endpoint. Set cooldown periods to prevent alert fatigue and get only the notifications that matter.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-share',
                'module'      => 'notifications',
                'benefits'    => [
                    __( 'Slack, Discord, and generic webhook delivery', 'ultraguard-security-suite' ),
                    __( 'Configurable cooldown periods — no alert storms', 'ultraguard-security-suite' ),
                    __( 'HMAC-signed payloads for secure webhook delivery', 'ultraguard-security-suite' ),
                    __( 'Test any channel with one click before going live', 'ultraguard-security-suite' ),
                ],
            ],

            // ── 2FA for All Users ─────────────────────────────────────────────
            'all_users_2fa' => [
                'label'       => __( '2FA for All Users + Enforcement', 'ultraguard-security-suite' ),
                'headline'    => __( 'One compromised editor account can take down your site — protect every role, not just the admin.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro enables Two-Factor Authentication for every user account with role-based enforcement, grace periods, and passkeys. Free plan covers the admin account only.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-admin-users',
                'module'      => 'authenticator',
                'benefits'    => [
                    __( '2FA for every user role — editors, authors, shop managers', 'ultraguard-security-suite' ),
                    __( 'Enforce 2FA by role with configurable grace periods', 'ultraguard-security-suite' ),
                    __( 'Passkeys (WebAuthn) for passwordless login', 'ultraguard-security-suite' ),
                    __( 'Backup codes with bcrypt-secure storage', 'ultraguard-security-suite' ),
                ],
            ],

            // ── API Security ──────────────────────────────────────────────────
            'api_security' => [
                'label'       => __( 'REST API & XML-RPC Security', 'ultraguard-security-suite' ),
                'headline'    => __( 'Your REST API is a wide-open door that attackers use to bypass the login form entirely.', 'ultraguard-security-suite' ),
                'description' => __( 'Pro locks down the WordPress REST API and XML-RPC with rate limiting, authentication requirements, endpoint whitelisting, and complete request logging.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-rest-api',
                'module'      => 'api_security',
                'benefits'    => [
                    __( 'Require authentication for all REST API endpoints', 'ultraguard-security-suite' ),
                    __( 'Disable XML-RPC entirely or whitelist specific methods', 'ultraguard-security-suite' ),
                    __( 'Per-endpoint rate limiting and IP blocking', 'ultraguard-security-suite' ),
                    __( 'Full API request log with threat classification', 'ultraguard-security-suite' ),
                ],
            ],
        ];

        return $features;
    }

    /**
     * Get a single feature definition by key, or null if unknown.
     *
     * @param  string $feature_key
     * @return array|null
     */
    public static function feature( string $feature_key ): ?array {
        return self::features()[ $feature_key ] ?? null;
    }

    // ── Render helpers ────────────────────────────────────────────────────────

    /**
     * Build a small contextual inline hint — shown inside a card or settings section.
     *
     * Returns an `alert-box` scheme component (works inside card 'data' arrays).
     * Returns an empty array if the user is Pro (nothing to show).
     *
     * @param  string $feature_key  Key from self::features()
     * @param  string $context      Optional extra sentence for this specific location
     * @return array  alert-box component or []
     */
    public static function inline_hint( string $feature_key, string $context = '' ): array {
        if ( ! self::should_show_nudge() ) { return []; }

        $feature = self::feature( $feature_key );
        if ( ! $feature ) { return []; }

        $upgrade_url = self::upgrade_page_url();
        $message     = $feature['headline'];
        if ( $context ) {
            $message .= ' ' . $context;
        }

        return [
            'type'       => 'alert-box',
            'alert_type' => 'info',
            'title'      => sprintf(
                /* translators: %s: feature label */
                __( '✨ %s — Pro Feature', 'ultraguard-security-suite' ),
                $feature['label']
            ),
            'message'    => $message,
            'actions'    => [
                [
                    'type'         => 'button',
                    'text'         => __( 'See What\'s Included in Pro →', 'ultraguard-security-suite' ),
                    'button_style' => 'secondary',
                    'url'          => $upgrade_url,
                ],
            ],
        ];
    }

    /**
     * Build a "teaser card" — a full card component showing what the feature does
     * and a friendly CTA. Used where free users see a locked module section.
     *
     * @param  string $feature_key
     * @return array  card component
     */
    public static function teaser_card( string $feature_key ): array {
        if ( ! self::should_show_nudge() ) {
            return [];
        }

        $feature     = self::feature( $feature_key );
        $upgrade_url = self::upgrade_page_url();

        if ( ! $feature ) {
            return [
                'type'  => 'card',
                'title' => __( 'Pro Feature', 'ultraguard-security-suite' ),
                'data'  => [
                    [
                        'type'       => 'alert-box',
                        'alert_type' => 'info',
                        'title'      => __( 'Upgrade to Pro to unlock this feature.', 'ultraguard-security-suite' ),
                        'message'    => '',
                    ],
                ],
            ];
        }

        $benefit_items = array_map( fn( $b ) => [
            'icon' => 'dashicons-yes-alt',
            'text' => $b,
        ], $feature['benefits'] ?? [] );

        return [
            'type'  => 'card',
            'title' => sprintf( '✨ %s', $feature['label'] ),
            'icon'  => $feature['icon'] ?? 'dashicons-lock',
            'data'  => [
                [
                    'type'       => 'alert-box',
                    'alert_type' => 'info',
                    'title'      => $feature['headline'],
                    'message'    => $feature['description'],
                ],
                [
                    'type'  => 'list',
                    'items' => $benefit_items,
                ],
                [
                    'type'         => 'button',
                    'text'         => __( 'Compare Free vs Pro →', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                    'url'          => $upgrade_url,
                ],
            ],
        ];
    }

    /**
     * Build a "soft gate" AJAX JSON response for write actions on free accounts.
     *
     * Instead of "you can't do this", explains what they'd get with Pro and links
     * to the upgrade page. Suitable for calling in AJAX handlers before wp_die().
     *
     * @param  string $feature_key
     * @param  string $action_description  e.g. "run a full file scan"
     */
    public static function soft_gate_response( string $feature_key, string $action_description = '' ): void {
        $feature     = self::feature( $feature_key );
        $upgrade_url = self_admin_url( self::UPGRADE_PAGE_URL_PATTERN );

        $headline = $feature
            ? $feature['headline']
            : __( 'This action is available to Pro users.', 'ultraguard-security-suite' );

        $msg = $action_description
            ? sprintf(
                /* translators: 1: action e.g. "run a full scan", 2: headline */
                __( 'To %1$s, you\'ll need UltraGuard Pro. %2$s', 'ultraguard-security-suite' ),
                $action_description,
                $headline
              )
            : $headline;

        AjaxResponseBuilder::make()
            ->error( $msg, 'upgrade_required' )
            ->addData( 'upgrade_url', $upgrade_url )
            ->addData( 'feature', $feature_key )
            ->addNotification( $msg, 'warning', 7000 )
            ->addNotification( __( 'Upgrade to Pro to unlock this action and the related dashboard tools.', 'ultraguard-security-suite' ), 'info', 7000 )
            ->send( 200 );
    }

    /**
     * Return the in-plugin upgrade page URL.
     *
     * @return string
     */
    public static function upgrade_page_url(): string {
        return self_admin_url( self::UPGRADE_PAGE_URL_PATTERN );
    }

    public static function external_upgrade_url(): string {
        $url = (string) get_option( 'upgrade_manager_external_upgrade_url', self::EXTERNAL_UPGRADE_URL );
        return (string) apply_filters( 'ultraguard_external_upgrade_url', $url ?: self::EXTERNAL_UPGRADE_URL );
    }

    public static function billing_portal_url(): string {
        $url = (string) get_option( 'upgrade_manager_billing_portal_url', self::BILLING_PORTAL_URL );
        return (string) apply_filters( 'ultraguard_billing_portal_url', $url ?: self::BILLING_PORTAL_URL );
    }

    public static function support_url(): string {
        $url = (string) get_option( 'upgrade_manager_support_url', self::SUPPORT_URL );
        return (string) apply_filters( 'ultraguard_support_url', $url ?: self::SUPPORT_URL );
    }

    /**
     * Return whether the current user should see pro nudges.
     * (i.e. they are not already on Pro)
     *
     * @return bool
     */
    public static function should_show_nudge(): bool {
        return ! LicenseInfo::instance()->isPro()
            && (bool) get_option( 'upgrade_manager_show_inline_nudges', true );
    }
}
