<?php
/**
 * LoginLimiterSettingsPage — Login Limiter full settings page.
 *
 * Tabs:
 *   Brute Force    — lockout thresholds, progressive lockout, admin notification
 *   Two-Factor     — 2FA method, expiry, role requirements
 *   Sessions       — single session, timeout, activity tracking
 *   Advanced       — CAPTCHA, log retention, custom login slug
 *   Hidden Login   — custom secret path and legacy URL handling
 *   Danger Zone    — destructive reset / clear actions
 *
 * @package UltraguardPro\modules\loginlimiter\pages
 */

namespace UltraguardPro\modules\loginlimiter\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;

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

class LoginLimiterSettingsPage extends BasePage {

    protected string $ajax_nonce_action = 'ultraguard_admin_nonce';

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_captcha_test_assets' ] );
    }

    public function get_scheme( $context ): array {
        $s     = fn( string $k, $d = '' ) => $this->get_setting( $k, $d );
        $nonce = $this->create_nonce( 'ultraguard_admin_nonce' );

        $is_enabled = (bool) $s( 'loginlimiter_enabled', true );

        return apply_filters( 'ultraguard_loginlimiter_settings_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-login-limiter-settings',
            'page_slug' => 'login-limiter-settings',
            'class'     => 'ultraguard-login-limiter-settings-page',

            'header' => [
                'title'    => __( 'Login Limiter Settings', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Configure brute-force protection, two-factor authentication and session management.', 'ultraguard-security-suite' ),
                'badge'    => [
                    'text'       => $is_enabled ? __( 'Protection Active', 'ultraguard-security-suite' ) : __( 'Protection Disabled', 'ultraguard-security-suite' ),
                    'badge_type' => $is_enabled ? 'success' : 'danger',
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Test Protection',  'ultraguard-security-suite' ), 'ultraguard_ll_test_protection', [], 'secondary', 'dashicons-yes'        ),
                    $this->create_ajax_button( __( 'Security Audit',   'ultraguard-security-suite' ), 'ultraguard_ll_security_audit',  [], 'secondary', 'dashicons-chart-pie'  ),
                    $this->create_ajax_button( __( 'Export Audit Log', 'ultraguard-security-suite' ), 'ultraguard_ll_export_audit',    [], 'secondary', 'dashicons-download'   ),
                    $this->create_url_button(  __( 'View Dashboard',   'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=login-limiter' ), 'secondary', 'dashicons-admin-users' ),
                ],
            ],

            'data' => [ [
                'type' => 'tabs',
                'id'   => 'loginlimiter-settings-tabs',
                'tabs' => [

                    // ── Tab 1: Brute Force ───────────────────────────────
                    [
                        'id'    => 'brute-force',
                        'title' => __( 'Brute Force', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-shield',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'responsive' => [ 'md' => 12, 'lg' => 12 ], 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Brute Force Protection', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-shield',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_enabled',             'label' => __( 'Enable Login Limiting',      'ultraguard-security-suite' ), 'description' => __( 'Activate brute-force protection for the login page.',          'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_enabled', true ) ],
                                        [ 'type' => 'number', 'name' => 'loginlimiter_max_attempts',        'label' => __( 'Max Failed Attempts',         'ultraguard-security-suite' ), 'description' => __( 'Number of failures before an IP is locked out.',              'ultraguard-security-suite' ), 'min' => 1, 'max' => 20,   'default' => (int) $s( 'loginlimiter_max_attempts', 5 ) ],
                                        [ 'type' => 'number', 'name' => 'loginlimiter_lockout_duration',    'label' => __( 'Lockout Duration (minutes)',   'ultraguard-security-suite' ), 'description' => __( 'How long the lockout lasts.',                                  'ultraguard-security-suite' ), 'min' => 1, 'max' => 1440, 'default' => (int) $s( 'loginlimiter_lockout_duration', 30 ) ],
                                        [ 'type' => 'number', 'name' => 'loginlimiter_attempt_window',      'label' => __( 'Attempt Window (minutes)',     'ultraguard-security-suite' ), 'description' => __( 'Time window for counting failures.',                           'ultraguard-security-suite' ), 'min' => 1, 'max' => 1440, 'default' => (int) $s( 'loginlimiter_attempt_window', 60 ) ],
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_progressive_lockout', 'label' => __( 'Progressive Lockout',         'ultraguard-security-suite' ), 'description' => __( 'Double the lockout duration with each repeat offence (max 8×).',  'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_progressive_lockout', false ) ],
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_notify_admin',        'label' => __( 'Email Admin on Lockout',      'ultraguard-security-suite' ), 'description' => __( 'Send an email alert when a lockout is triggered.',              'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_notify_admin', true ) ],
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_hide_errors',         'label' => __( 'Hide Login Error Details',    'ultraguard-security-suite' ), 'description' => __( 'Show a generic error instead of specific username/password hints.','ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_hide_errors', true ) ],
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_clear_lockout_on_success', 'label' => __( 'Clear Lockout on Success','ultraguard-security-suite' ), 'description' => __( 'Auto-release an IP lockout when the correct credentials are used.', 'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_clear_lockout_on_success', false ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 2: Two-Factor ────────────────────────────────
                    [
                        'id'    => 'two-factor',
                        'title' => __( 'Two-Factor', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-smartphone',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Two-Factor Authentication', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-smartphone',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_two_factor_enabled', 'label' => __( 'Enable 2FA',               'ultraguard-security-suite' ), 'description' => __( 'Require a second factor at login.',                         'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_two_factor_enabled', false ) ],
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_2fa_required_admin', 'label' => __( '2FA Required for Admins',  'ultraguard-security-suite' ), 'description' => __( 'Force administrators to use 2FA.',                         'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_2fa_required_admin', false ) ],
                                        [
                                            'type'    => 'select',
                                            'name'    => 'loginlimiter_2fa_method',
                                            'label'   => __( '2FA Method', 'ultraguard-security-suite' ),
                                            'options' => [ 'email' => __( 'Email Code', 'ultraguard-security-suite' ), 'totp' => __( 'Authenticator App (TOTP)', 'ultraguard-security-suite' ), 'sms' => __( 'SMS', 'ultraguard-security-suite' ) ],
                                            'default' => $s( 'loginlimiter_2fa_method', 'email' ),
                                        ],
                                        [ 'type' => 'number', 'name' => 'loginlimiter_2fa_code_expiry', 'label' => __( 'Code Expiry (minutes)', 'ultraguard-security-suite' ), 'min' => 1, 'max' => 30, 'default' => (int) $s( 'loginlimiter_2fa_code_expiry', 10 ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 3: Sessions ──────────────────────────────────
                    [
                        'id'    => 'sessions',
                        'title' => __( 'Sessions', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-admin-users',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Session Management', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-admin-users',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_single_session',  'label' => __( 'Single Session Only',       'ultraguard-security-suite' ), 'description' => __( 'Prevent users from logging in from multiple devices simultaneously.', 'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_single_session', false ) ],
                                        [ 'type' => 'number', 'name' => 'loginlimiter_session_timeout', 'label' => __( 'Session Timeout (minutes)',  'ultraguard-security-suite' ), 'description' => __( 'Auto-logout after inactivity (0 = disabled).',                         'ultraguard-security-suite' ), 'min' => 0, 'max' => 43200, 'default' => (int) $s( 'loginlimiter_session_timeout', 0 ) ],
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_track_activity',  'label' => __( 'Track User Activity',       'ultraguard-security-suite' ), 'description' => __( 'Log login/logout events per user.',                                     'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_track_activity', true ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 4: Advanced ──────────────────────────────────
                    [
                        'id'    => 'advanced',
                        'title' => __( 'Advanced', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-admin-generic',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'CAPTCHA & Advanced', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-admin-generic',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'loginlimiter_captcha_enabled', 'label' => __( 'Enable CAPTCHA',              'ultraguard-security-suite' ), 'description' => __( 'Show a CAPTCHA challenge on the login form.',                       'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_captcha_enabled', false ) ],
                                        [ 'type' => 'number', 'name' => 'loginlimiter_captcha_after',   'label' => __( 'CAPTCHA After (attempts)',    'ultraguard-security-suite' ), 'description' => __( 'Show CAPTCHA after this many failures (0 = always).',                'ultraguard-security-suite' ), 'min' => 0, 'max' => 10, 'default' => (int) $s( 'loginlimiter_captcha_after', 3 ) ],
                                        [ 'type' => 'number', 'name' => 'loginlimiter_log_retention',   'label' => __( 'Log Retention (days)',        'ultraguard-security-suite' ), 'description' => __( 'Auto-prune login attempt logs older than this many days.',            'ultraguard-security-suite' ), 'min' => 1, 'max' => 365, 'default' => (int) $s( 'loginlimiter_log_retention', 30 ) ],
                                        [ 'type' => 'text',   'name' => 'loginlimiter_custom_login_slug','label' => __( 'Custom Login URL Slug',      'ultraguard-security-suite' ), 'description' => __( 'Optional: rename the login URL (e.g. "secure-login"). Leave empty to use /wp-login.php.', 'ultraguard-security-suite' ), 'placeholder' => 'secure-login', 'default' => $s( 'loginlimiter_custom_login_slug', '' ) ],
                                    ],
                                ] ],
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'CAPTCHA Configuration', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-shield',
                                    'data'  => [
                                        [
                                            'type'    => 'select',
                                            'name'    => 'loginlimiter_captcha_provider',
                                            'label'   => __( 'Provider', 'ultraguard-security-suite' ),
                                            'options' => [
                                                'turnstile'    => __( 'Cloudflare Turnstile', 'ultraguard-security-suite' ),
                                                'recaptcha_v2' => __( 'Google reCAPTCHA v2', 'ultraguard-security-suite' ),
                                                'recaptcha_v3' => __( 'Google reCAPTCHA v3', 'ultraguard-security-suite' ),
                                            ],
                                            'default' => $s( 'loginlimiter_captcha_provider', 'turnstile' ),
                                        ],
                                        [ 'type' => 'text', 'name' => 'loginlimiter_turnstile_site_key',   'label' => __( 'Turnstile Site Key', 'ultraguard-security-suite' ),   'default' => $s( 'loginlimiter_turnstile_site_key', '' ) ],
                                        [ 'type' => 'text', 'name' => 'loginlimiter_turnstile_secret_key', 'label' => __( 'Turnstile Secret Key', 'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_turnstile_secret_key', '' ) ],
                                        [ 'type' => 'text', 'name' => 'loginlimiter_recaptcha_site_key',   'label' => __( 'reCAPTCHA Site Key', 'ultraguard-security-suite' ),   'default' => $s( 'loginlimiter_recaptcha_site_key', '' ) ],
                                        [ 'type' => 'text', 'name' => 'loginlimiter_recaptcha_secret_key', 'label' => __( 'reCAPTCHA Secret Key', 'ultraguard-security-suite' ), 'default' => $s( 'loginlimiter_recaptcha_secret_key', '' ) ],
                                        [ 'type' => 'number', 'name' => 'loginlimiter_recaptcha_v3_min_score', 'label' => __( 'reCAPTCHA v3 Minimum Score', 'ultraguard-security-suite' ), 'min' => 0.1, 'max' => 1.0, 'step' => 0.1, 'default' => (float) $s( 'loginlimiter_recaptcha_v3_min_score', 0.5 ) ],
                                        [
                                            'type'              => 'html',
                                            'allow_unsafe_html' => true,
                                            'content'           => $this->build_captcha_configuration_html( [
                                                'provider'              => (string) $s( 'loginlimiter_captcha_provider', 'turnstile' ),
                                                'turnstile_site_key'    => (string) $s( 'loginlimiter_turnstile_site_key', '' ),
                                                'recaptcha_site_key'    => (string) $s( 'loginlimiter_recaptcha_site_key', '' ),
                                            ] ),
                                        ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 5: Hidden Login ──────────────────────────────
                    [
                        'id'    => 'hidden-login',
                        'title' => __( 'Hidden Login', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-admin-links',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Login URL Protection', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-admin-links',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'login_protect_enabled', 'label' => __( 'Enable Hidden Login Protection', 'ultraguard-security-suite' ), 'description' => __( 'Hide wp-login.php behind a custom secret path.', 'ultraguard-security-suite' ), 'default' => (bool) $this->plugin->settings->get_option( 'login_protect_enabled', true ) ],
                                        [ 'type' => 'text', 'name' => 'login_protect_custom_path', 'label' => __( 'Custom login path slug', 'ultraguard-security-suite' ), 'description' => __( 'Use only letters, numbers, and dashes. Minimum 6 characters.', 'ultraguard-security-suite' ), 'placeholder' => 'access-f7g3k9', 'default' => (string) $this->plugin->settings->get_option( 'login_protect_custom_path', '' ) ],
                                        [ 'type' => 'select', 'name' => 'login_protect_original_action', 'label' => __( 'Original URL Action', 'ultraguard-security-suite' ), 'description' => __( 'Choose what happens when someone visits wp-login.php directly.', 'ultraguard-security-suite' ), 'default' => (string) $this->plugin->settings->get_option( 'login_protect_original_action', '404' ), 'options' => [
                                            [ 'value' => '404', 'label' => __( '404 Not Found', 'ultraguard-security-suite' ) ],
                                            [ 'value' => 'redirect_home', 'label' => __( 'Redirect to home', 'ultraguard-security-suite' ) ],
                                            [ 'value' => 'redirect_custom', 'label' => __( 'Redirect to custom URL', 'ultraguard-security-suite' ) ],
                                        ] ],
                                        [ 'type' => 'text', 'name' => 'login_protect_custom_redirect_url', 'label' => __( 'Custom redirect URL', 'ultraguard-security-suite' ), 'description' => __( 'Only used when Original URL Action is set to custom redirect.', 'ultraguard-security-suite' ), 'default' => (string) $this->plugin->settings->get_option( 'login_protect_custom_redirect_url', '' ) ],
                                        [ 'type' => 'toggle', 'name' => 'login_protect_log_attempts', 'label' => __( 'Log legacy login URL hits', 'ultraguard-security-suite' ), 'description' => __( 'Store blocked requests to the old login URL for review.', 'ultraguard-security-suite' ), 'default' => (bool) $this->plugin->settings->get_option( 'login_protect_log_attempts', true ) ],
                                        [ 'type' => 'toggle', 'name' => 'login_protect_auto_block', 'label' => __( 'Auto-block repeated hits', 'ultraguard-security-suite' ), 'description' => __( 'Send repeat offenders to the firewall block action.', 'ultraguard-security-suite' ), 'default' => (bool) $this->plugin->settings->get_option( 'login_protect_auto_block', false ) ],
                                        [ 'type' => 'number', 'name' => 'login_protect_auto_block_threshold', 'label' => __( 'Auto-block threshold per hour', 'ultraguard-security-suite' ), 'min' => 1, 'max' => 100, 'default' => (int) $this->plugin->settings->get_option( 'login_protect_auto_block_threshold', 5 ) ],
                                        [ 'type' => 'toggle', 'name' => 'login_protect_notify_admin', 'label' => __( 'Notify admin on legacy login hits', 'ultraguard-security-suite' ), 'description' => __( 'Send an email when someone probes the old login URL.', 'ultraguard-security-suite' ), 'default' => (bool) $this->plugin->settings->get_option( 'login_protect_notify_admin', false ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 6: Danger Zone ───────────────────────────────
                    [
                        'id'    => 'danger-zone',
                        'title' => __( 'Danger Zone', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-warning',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Danger Zone', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-warning',
                                    'class' => 'ug-danger-card',
                                    'data'  => [
                                        [
                                            'type'       => 'alert-box',
                                            'alert_type' => 'warning',
                                            'icon'       => 'dashicons-warning',
                                            'message'    => __( 'These actions are destructive and cannot be undone.', 'ultraguard-security-suite' ),
                                        ],
                                        [
                                            'type'      => 'button-group',
                                            'alignment' => 'left',
                                            'buttons'   => [
                                                $this->create_ajax_button(
                                                    __( 'Reset Login Stats', 'ultraguard-security-suite' ),
                                                    'ultraguard_ll_reset_stats', [], 'secondary', 'dashicons-undo',
                                                    __( 'Clear all login attempt statistics?', 'ultraguard-security-suite' )
                                                ),
                                                $this->create_ajax_button(
                                                    __( 'Clear All Lockouts', 'ultraguard-security-suite' ),
                                                    'ultraguard_ll_clear_lockouts', [], 'warning', 'dashicons-unlock',
                                                    __( 'Release all active lockouts?', 'ultraguard-security-suite' )
                                                ),
                                            ],
                                        ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                ],
            ] ],

            'form' => [
                'enable'     => true,
                'id'         => 'loginlimiter-settings-form',
                'ajax'       => true,
                'action'     => 'ultraguard_ll_save_settings',
                'nonce'      => $nonce,
                'submit'     => [
                    'text'         => __( 'Save Login Limiter Settings', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                ],
            ],
        ], $context );
    }

    /**
     * Build the HTML block used for CAPTCHA provider help and inline testing.
     *
     * @param array<string,string> $data
     */
    private function build_captcha_configuration_html( array $data ): string {
        $provider           = $data['provider'] ?? 'turnstile';
        $turnstile_site_key = $data['turnstile_site_key'] ?? '';
        $recaptcha_site_key = $data['recaptcha_site_key'] ?? '';

        $turnstile_test = $turnstile_site_key !== ''
            ? '<div class="cf-turnstile" data-sitekey="' . esc_attr( $turnstile_site_key ) . '"></div>'
            : '<p>' . esc_html__( 'Enter a Turnstile site key above to test the widget.', 'ultraguard-security-suite' ) . '</p>';

        $recaptcha_test = $recaptcha_site_key !== ''
            ? '<div class="g-recaptcha" data-sitekey="' . esc_attr( $recaptcha_site_key ) . '"></div>'
            : '<p>' . esc_html__( 'Enter a reCAPTCHA site key above to test the widget.', 'ultraguard-security-suite' ) . '</p>';

        $turnstile_style = 'turnstile' === $provider ? '' : 'display:none;';
        $recaptcha_style = 'turnstile' === $provider ? 'display:none;' : '';

        return
            '<div class="ultraguard-captcha-config-help">'
            . '<p><a href="https://developers.cloudflare.com/turnstile/get-started/" target="_blank" rel="noopener noreferrer">'
            . esc_html__( 'Get Cloudflare Turnstile keys', 'ultraguard-security-suite' )
            . '</a> | <a href="https://www.google.com/recaptcha/admin/create" target="_blank" rel="noopener noreferrer">'
            . esc_html__( 'Get Google reCAPTCHA keys', 'ultraguard-security-suite' )
            . '</a></p>'
            . '<p><button type="button" class="button" id="ultraguard-test-captcha">'
            . esc_html__( 'Test CAPTCHA', 'ultraguard-security-suite' )
            . '</button></p>'
            . '<p class="description">'
            . esc_html__( 'The test widget uses your saved site key and loads only on this settings page.', 'ultraguard-security-suite' )
            . '</p>'
            . '<div id="ultraguard-captcha-test-wrap" style="display:none;margin-top:12px;">'
            . '<div id="ultraguard-captcha-turnstile-test" style="' . esc_attr( $turnstile_style ) . '">' . $turnstile_test . '</div>'
            . '<div id="ultraguard-captcha-recaptcha-test" style="' . esc_attr( $recaptcha_style ) . '">' . $recaptcha_test . '</div>'
            . '</div>'
            . '</div>';
    }

    /**
     * Load CAPTCHA test assets only on the Login Limiter settings screen.
     */
    public function enqueue_captcha_test_assets(): void {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only screen detection for conditional asset loading.
        $page    = sanitize_key( wp_unslash( $_GET['page'] ?? '' ) );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only screen detection for conditional asset loading.
        $ug_page = sanitize_key( wp_unslash( $_GET['ug_page'] ?? '' ) );

        if ( 'ultraguard-security-suite-dashboard' !== $page || 'login-limiter-settings' !== $ug_page ) {
            return;
        }

        wp_enqueue_script(
            'ultraguard-captcha-loader',
            ULTRAGUARD_PRO_URL . 'assets/js/ultraguard-captcha-loader.js',
            [],
            ULTRAGUARD_PRO_VERSION,
            true
        );

        wp_add_inline_script(
            'ultraguard-captcha-loader',
            'window.ultraguardCaptchaConfigs = window.ultraguardCaptchaConfigs || [];'
            . 'window.ultraguardCaptchaConfigs.push(' . wp_json_encode(
                [
                    'provider' => 'turnstile',
                    'siteKey'  => (string) $this->plugin->settings->get_option( 'loginlimiter_turnstile_site_key', '' ),
                    'context'  => 'admin-test',
                ]
            ) . ');'
            . 'window.ultraguardCaptchaConfigs.push(' . wp_json_encode(
                [
                    'provider' => 'recaptcha_v2',
                    'siteKey'  => (string) $this->plugin->settings->get_option( 'loginlimiter_recaptcha_site_key', '' ),
                    'context'  => 'admin-test',
                ]
            ) . ');',
            'before'
        );

        wp_add_inline_script(
            'ultraguard-captcha-loader',
            <<<'JS'
(function () {
    function updateCaptchaPreview() {
        var providerField = document.querySelector('[name="loginlimiter_captcha_provider"]');
        var turnstileWrap = document.getElementById('ultraguard-captcha-turnstile-test');
        var recaptchaWrap = document.getElementById('ultraguard-captcha-recaptcha-test');
        var provider = providerField ? providerField.value : 'turnstile';

        if (turnstileWrap) {
            turnstileWrap.style.display = provider === 'turnstile' ? '' : 'none';
        }

        if (recaptchaWrap) {
            recaptchaWrap.style.display = provider === 'turnstile' ? 'none' : '';
        }
    }

    document.addEventListener('click', function (event) {
        if (event.target && event.target.id === 'ultraguard-test-captcha') {
            var wrap = document.getElementById('ultraguard-captcha-test-wrap');
            if (wrap) {
                wrap.style.display = 'block';
            }
            updateCaptchaPreview();
        }
    });

    document.addEventListener('change', function (event) {
        if (event.target && event.target.name === 'loginlimiter_captcha_provider') {
            updateCaptchaPreview();
        }
    });

    document.addEventListener('DOMContentLoaded', updateCaptchaPreview);
})();
JS
        );
    }
}
