<?php
/**
 * Form Renderer class file
 *
 * This file contains the FormRenderer class which handles the rendering of all
 * form field types including text inputs, selects, checkboxes, radios, toggles,
 * and specialized fields like color pickers, date pickers, and password strength meters.
 * It implements caching mechanisms for performance optimization and provides
 * secure output escaping.
 *
 * @package    UltraguardPro\view
 * @author     Vikas Bhardwaj <support@ultraguard.net>
 * @copyright  2024 UltraguardPro
 * @license    GPL-2.0-or-later
 * @version    1.0.0
 * @link       https://ultraguardpro.com/docs/form-renderer
 */

namespace UltraguardPro\view;

defined( 'ABSPATH' ) || exit;

use UltraguardPro\core\CacheManager;

/**
 * Form Renderer
 *
 * Handles rendering of all form field types with proper CSS classes, default values,
 * and secure output escaping. Implements singleton pattern with caching for performance
 * optimization on frequently accessed configurations and resources.
 *
 * This class extends BaseRenderer and provides static methods for rendering specific
 * field types. It includes comprehensive field validation, accessibility features,
 * and support for modern form elements like gradient pickers, icon selectors,
 * and password strength meters.
 *
 * @package    UltraguardPro\view
 * @author     Vikas Bhardwaj
 * @version    1.0.0
 * @since      1.0.0
 * @see        \UltraguardPro\view\BaseRenderer
 * @see        \UltraguardPro\view\RenderEngine
 * @see        \UltraguardPro\view\DataLoader
 *
 * @example
 * // Render a text input field
 * echo FormRenderer::render_text([
 *     'name' => 'username',
 *     'label' => 'Username',
 *     'placeholder' => 'Enter username'
 * ], $context);
 *
 * @example
 * // Render a select dropdown
 * echo FormRenderer::render_select([
 *     'name' => 'country',
 *     'label' => 'Country',
 *     'options' => ['us' => 'USA', 'uk' => 'UK', 'ca' => 'Canada']
 * ], $context);
 */
class FormRenderer extends BaseRenderer {

    /**
     * Singleton instance
     *
     * @var self|null
     * @access private
     * @static
     */
    private static $instance = null;

    /**
     * Cached default configurations
     *
     * Stores default configuration arrays for each field type to avoid
     * repeated array creation and improve performance.
     *
     * @var array
     * @access private
     * @static
     */
    private static $default_configs = array();

    /**
     * Cached icon sets
     *
     * Caches icon definitions for icon selector fields to reduce
     * repetitive processing and database queries.
     *
     * @var array
     * @access private
     * @static
     */
    private static $cached_icon_sets = array();

    /**
     * Cached field IDs to prevent regeneration
     *
     * Stores generated field IDs to ensure consistency and avoid
     * duplicate ID generation during form rendering.
     *
     * @var array
     * @access private
     * @static
     */
    private static $field_id_cache = array();

    /**
     * Get singleton instance
     *
     * Returns the singleton instance of FormRenderer. Creates a new instance
     * if one doesn't exist. Ensures only one instance exists for performance.
     *
     * @return self  Singleton instance of FormRenderer
     * @access public
     * @static
     *
     * @example
     * $renderer = FormRenderer::get_instance();
     */
    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Render text input
     *
     * Renders a standard text input field with proper attributes, validation,
     * and accessibility features. Supports all common text input attributes.
     *
     * @param  array  $scheme   Text input configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML text input field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_text([
     *     'name' => 'first_name',
     *     'label' => 'First Name',
     *     'placeholder' => 'Enter your first name',
     *     'required' => true,
     *     'maxlength' => 50
     * ], $context);
     */
    public static function render_text( $scheme, $context ) {
        return self::get_instance()->render_input_field( $scheme, $context, 'text' );
    }

    /**
     * Render textarea
     *
     * Renders a multi-line textarea field with configurable rows, columns,
     * and rich text support. Includes proper escaping for textarea content.
     *
     * @param  array  $scheme   Textarea configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML textarea field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_textarea([
     *     'name' => 'description',
     *     'label' => 'Description',
     *     'rows' => 5,
     *     'cols' => 40,
     *     'placeholder' => 'Enter a description',
     *     'maxlength' => 500
     * ], $context);
     */
    public static function render_textarea( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['textarea'] ) ) {
            self::$default_configs['textarea'] = array(
                'name' => '',
                'id' => '',
                'rows' => 5,
                'cols' => 50,
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'placeholder' => '',
                'disabled' => false,
                'readonly' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'maxlength' => '',
                'pattern' => '',
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['textarea'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_textarea_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_textarea_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );
        $attributes = $instance->get_field_attributes( $scheme );

        $attributes .= sprintf( ' rows="%d" cols="%d"',
            absint( $scheme['rows'] ),
            absint( $scheme['cols'] )
        );

        $content = sprintf(
            '<textarea %s>%s</textarea>',
            $attributes,
            $instance->escape( $value, 'textarea' )
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render select dropdown
     *
     * Renders a select dropdown field with options, support for multiple selection,
     * and placeholder option. Properly handles selected values for both single
     * and multiple select scenarios.
     *
     * @param  array  $scheme   Select configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML select field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_select([
     *     'name' => 'colors',
     *     'label' => 'Favorite Colors',
     *     'options' => ['red' => 'Red', 'blue' => 'Blue', 'green' => 'Green'],
     *     'multiple' => true,
     *     'placeholder' => 'Select colors'
     * ], $context);
     */
    public static function render_select( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['select'] ) ) {
            self::$default_configs['select'] = array(
                'name' => '',
                'id' => '',
                'options' => array(),
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'placeholder' => '',
                'disabled' => false,
                'readonly' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'multiple' => false,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['select'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_select_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_select_scheme', $scheme, $context );
        }

        $value      = $instance->get_field_value( $scheme, $context );
        $attributes = $instance->get_field_attributes( $scheme );

        // Handle multiple select — also emit a size so browsers don't collapse to 1 row.
        if ( $scheme['multiple'] ) {
            $attributes .= ' multiple';
            $scheme['name'] .= '[]';
            // Use an explicit 'size' from the scheme, or default to 5 visible rows.
            $select_size = isset( $scheme['size'] ) && is_numeric( $scheme['size'] )
                ? (int) $scheme['size']
                : 5;
            $attributes .= sprintf( ' size="%d"', $select_size );
        }

        $options_html = '';

        // Add placeholder option if provided
        if ( ! empty( $scheme['placeholder'] ) ) {
            $options_html .= sprintf(
                '<option value="">%s</option>',
                $instance->escape( $scheme['placeholder'] )
            );
        }

        // Support two option array formats:
        //   A) Flat associative:  [ 'val' => 'Label', ... ]           (most common)
        //   B) Indexed objects:   [ ['value' => 'val', 'label' => 'Label'], ... ]
        foreach ( $scheme['options'] as $option_key => $option_item ) {
            if ( is_array( $option_item ) ) {
                // Format B — indexed array of ['value', 'label'] pairs.
                $option_value = (string) ( $option_item['value'] ?? $option_key );
                $option_label = (string) ( $option_item['label'] ?? $option_value );
            } else {
                // Format A — standard flat associative.
                $option_value = (string) $option_key;
                $option_label = (string) $option_item;
            }

            $selected = '';
            if ( $scheme['multiple'] ) {
                $selected = is_array( $value ) && in_array( $option_value, $value, true ) ? 'selected' : '';
            } else {
                $selected = selected( $value, $option_value, false );
            }
            $options_html .= sprintf(
                '<option value="%s" %s>%s</option>',
                $instance->escape( $option_value, 'attribute' ),
                $selected,
                $instance->escape( $option_label )
            );
        }

        $content = sprintf(
            '<select %s>%s</select>',
            $attributes,
            $options_html
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render radio buttons
     *
     * Renders a group of radio buttons with options for inline or stacked layout.
     * Includes proper accessibility attributes and keyboard navigation support.
     *
     * @param  array  $scheme   Radio button configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML radio button group
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_radio([
     *     'name' => 'notification',
     *     'label' => 'Notification Preference',
     *     'options' => ['email' => 'Email', 'sms' => 'SMS', 'push' => 'Push'],
     *     'inline' => true,
     *     'required' => true
     * ], $context);
     */
    public static function render_radio( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['radio'] ) ) {
            self::$default_configs['radio'] = array(
                'name' => '',
                'id' => '',
                'options' => array(),
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'inline' => false,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['radio'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_radio_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_radio_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        $radios_html = '';
        $wrapper_class = $scheme['inline'] ? 'ultraguard-radio-inline' : 'ultraguard-radio-list';
        $disabled_attr = ! empty( $scheme['disabled'] ) ? ' disabled' : '';

        // Support both flat ['val'=>'Label'] and indexed [['value'=>'val','label'=>'Label']] formats.
        foreach ( $scheme['options'] as $option_key => $option_item ) {
            if ( is_array( $option_item ) ) {
                $option_value = (string) ( $option_item['value'] ?? $option_key );
                $option_label = (string) ( $option_item['label'] ?? $option_value );
            } else {
                $option_value = (string) $option_key;
                $option_label = (string) $option_item;
            }

            $checked  = checked( $value, $option_value, false );
            $radio_id = $scheme['id'] . '-' . sanitize_html_class( $option_value );

            $radios_html .= sprintf(
                '<div class="ultraguard-radio-item">' .
                '<input type="radio" id="%s" name="%s" value="%s" %s%s class="ultraguard-radio">' .
                '<label for="%s" class="ultraguard-radio-label">%s</label>' .
                '</div>',
                esc_attr( $radio_id ),
                $instance->escape( $scheme['name'], 'attribute' ),
                $instance->escape( $option_value, 'attribute' ),
                $checked,
                $disabled_attr,
                esc_attr( $radio_id ),
                $instance->escape( $option_label )
            );
        }

        $content = sprintf( '<div class="%s">%s</div>', $wrapper_class, $radios_html );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render checkboxes
     *
     * Renders checkbox field(s) with support for single checkbox or checkbox groups.
     * Includes proper handling for both single boolean values and array values.
     *
     * @param  array  $scheme   Checkbox configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML checkbox field(s)
     * @access public
     * @static
     *
     * @example
     * // Single checkbox
     * echo FormRenderer::render_checkbox([
     *     'name' => 'agree_terms',
     *     'label' => 'I agree to the terms and conditions',
     *     'checkbox_value' => '1',
     *     'required' => true
     * ], $context);
     *
     * @example
     * // Checkbox group
     * echo FormRenderer::render_checkbox([
     *     'name' => 'interests',
     *     'label' => 'Areas of Interest',
     *     'options' => ['tech' => 'Technology', 'sports' => 'Sports', 'music' => 'Music'],
     *     'inline' => true
     * ], $context);
     */
    public static function render_checkbox( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['checkbox'] ) ) {
            self::$default_configs['checkbox'] = array(
                'name' => '',
                'id' => '',
                'options' => array(),
                'value' => '',
                'default' => '',
                'checkbox_value' => '1',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'inline' => false,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['checkbox'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_checkbox_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_checkbox_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        // Handle single checkbox vs checkbox group
        if ( empty( $scheme['options'] ) ) {
            // Single checkbox
            $checked  = checked( $value, true, false );
            $disabled = ! empty( $scheme['disabled'] ) ? ' disabled' : '';

            $content = sprintf(
                '<div class="ultraguard-checkbox-single">' .
                '<input type="checkbox" id="%s" name="%s" value="%s" %s%s class="ultraguard-checkbox">' .
                '<label for="%s" class="ultraguard-checkbox-label">%s</label>' .
                '</div>',
                esc_attr( $scheme['id'] ),
                $instance->escape( $scheme['name'], 'attribute' ),
                $instance->escape( $scheme['checkbox_value'], 'attribute' ),
                $checked,
                $disabled,
                esc_attr( $scheme['id'] ),
                $instance->escape( $scheme['label'] )
            );
        } else {
            // Checkbox group
            $checkboxes_html = '';
            $wrapper_class = $scheme['inline'] ? 'ultraguard-checkbox-inline' : 'ultraguard-checkbox-list';

            foreach ( $scheme['options'] as $option_value => $option_label ) {
                $checked = is_array( $value ) && in_array( $option_value, $value, true ) ? 'checked' : '';
                $checkbox_id = $scheme['id'] . '-' . sanitize_html_class( $option_value );

                $checkboxes_html .= sprintf(
                    '<div class="ultraguard-checkbox-item">' .
                    '<input type="checkbox" id="%s" name="%s[]" value="%s" %s class="ultraguard-checkbox">' .
                    '<label for="%s" class="ultraguard-checkbox-label">%s</label>' .
                    '</div>',
                    $checkbox_id,
                    $instance->escape( $scheme['name'], 'attribute' ),
                    $instance->escape( $option_value, 'attribute' ),
                    $checked,
                    $checkbox_id,
                    $instance->escape( $option_label )
                );
            }

            $content = sprintf( '<div class="%s">%s</div>', $wrapper_class, $checkboxes_html );
        }

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render toggle switch
     *
     * Renders a modern toggle switch UI element for boolean values. Supports
     * different sizes (small, medium, large) and includes smooth animations.
     *
     * @param  array  $scheme   Toggle switch configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML toggle switch
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_toggle([
     *     'name' => 'enable_feature',
     *     'label' => 'Enable Feature',
     *     'value' => '1',
     *     'size' => 'medium',
     *     'description' => 'Turn this feature on or off'
     * ], $context);
     */
    public static function render_toggle( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['toggle'] ) ) {
            self::$default_configs['toggle'] = array(
                'name' => '',
                'id' => '',
                'value' => '1',
                'default' => false,
                'label' => '',
                'description' => '',
                'disabled' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'size' => 'medium', // small, medium, large
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['toggle'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_toggle_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_toggle_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );
        $checked  = checked( $value, true, false );
        $disabled = ! empty( $scheme['disabled'] ) ? ' disabled' : '';
        $required = ! empty( $scheme['required'] ) ? ' required' : '';

        $size_class = 'ultraguard-toggle-' . sanitize_html_class( $scheme['size'] );

        // The label text is rendered by render_field_wrapper() in the left column.
        // We must NOT also emit it inside the toggle widget — doing so produces a
        // visible duplicate label and breaks the two-column layout alignment.
        $content = sprintf(
            '<label class="ultraguard-toggle %s">' .
            '<input type="checkbox" id="%s" name="%s" value="%s" %s%s%s class="ultraguard-toggle-input">' .
            '<span class="ultraguard-toggle-slider"></span>' .
            '</label>',
            $size_class,
            $instance->escape( $scheme['id'], 'attribute' ),
            $instance->escape( $scheme['name'], 'attribute' ),
            $instance->escape( $scheme['value'], 'attribute' ),
            $checked,
            $disabled,
            $required
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render slider
     *
     * Renders a range slider input with configurable min, max, step values,
     * and optional value display with unit suffix.
     *
     * @param  array  $scheme   Slider configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML slider field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_slider([
     *     'name' => 'volume',
     *     'label' => 'Volume Level',
     *     'min' => 0,
     *     'max' => 100,
     *     'step' => 5,
     *     'value' => 50,
     *     'show_value' => true,
     *     'unit' => '%'
     * ], $context);
     */
    public static function render_slider( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['slider'] ) ) {
            self::$default_configs['slider'] = array(
                'name' => '',
                'id' => '',
                'min' => 0,
                'max' => 100,
                'step' => 1,
                'value' => 0,
                'default' => 0,
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'show_value' => true,
                'unit' => '',
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['slider'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_slider_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_slider_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        $value_display = $scheme['show_value'] ?
            sprintf( '<span class="ultraguard-slider-value">%s%s</span>',
                esc_html( $value ),
                esc_html( $scheme['unit'] )
            ) : '';

        $content = sprintf(
            '<div class="ultraguard-slider-container">' .
            '<input type="range" id="%s" name="%s" value="%s" min="%s" max="%s" step="%s" class="ultraguard-slider">' .
            '%s' .
            '</div>',
            $instance->escape( $scheme['id'], 'attribute' ),
            $instance->escape( $scheme['name'], 'attribute' ),
            $instance->escape( $value, 'attribute' ),
            $instance->escape( $scheme['min'], 'attribute' ),
            $instance->escape( $scheme['max'], 'attribute' ),
            $instance->escape( $scheme['step'], 'attribute' ),
            $value_display
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render color picker
     *
     * Renders a color picker field with optional alpha channel support.
     * Integrates with WordPress color picker for consistent UI.
     *
     * @param  array  $scheme   Color picker configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML color picker field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_color([
     *     'name' => 'primary_color',
     *     'label' => 'Primary Color',
     *     'value' => '#0073aa',
     *     'alpha' => false,
     *     'description' => 'Select the primary color for your theme'
     * ], $context);
     */
    public static function render_color( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['color'] ) ) {
            self::$default_configs['color'] = array(
                'name' => '',
                'id' => '',
                'value' => '#000000',
                'default' => '#000000',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'alpha' => false,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['color'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_color_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_color_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        $alpha_attr = $scheme['alpha'] ? 'data-alpha="true"' : '';

        $content = sprintf(
            '<div class="ultraguard-color-picker">' .
            '<input type="text" id="%s" name="%s" value="%s" class="ultraguard-color-field" %s>' .
            '</div>',
            $instance->escape( $scheme['id'], 'attribute' ),
            $instance->escape( $scheme['name'], 'attribute' ),
            $instance->escape( $value, 'attribute' ),
            $alpha_attr
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render code editor
     *
     * Renders a code editor field with syntax highlighting for various
     * programming languages and themes.
     *
     * @param  array  $scheme   Code editor configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML code editor field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_code_editor([
     *     'name' => 'custom_css',
     *     'label' => 'Custom CSS',
     *     'language' => 'css',
     *     'theme' => 'monokai',
     *     'value' => 'body { background: #fff; }',
     *     'rows' => 10
     * ], $context);
     */
    public static function render_code_editor( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['code_editor'] ) ) {
            self::$default_configs['code_editor'] = array(
                'name' => '',
                'id' => '',
                'language' => 'html',
                'theme' => 'default',
                'rows' => 10,
                'cols' => 80,
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'readonly' => false,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['code_editor'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_code_editor_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_code_editor_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        $content = sprintf(
            '<textarea id="%s" name="%s" class="ultraguard-code-editor" data-language="%s" data-theme="%s" rows="%d" cols="%d" %s>%s</textarea>',
            $instance->escape( $scheme['id'], 'attribute' ),
            $instance->escape( $scheme['name'], 'attribute' ),
            $instance->escape( $scheme['language'], 'attribute' ),
            $instance->escape( $scheme['theme'], 'attribute' ),
            absint( $scheme['rows'] ),
            absint( $scheme['cols'] ),
            $scheme['readonly'] ? 'readonly' : '',
            $instance->escape( $value, 'textarea' )
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render gradient picker
     *
     * Renders a gradient picker field with visual preview and support for
     * linear and radial gradients. Includes live preview of the gradient.
     *
     * @param  array  $scheme   Gradient picker configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML gradient picker field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_gradient([
     *     'name' => 'background_gradient',
     *     'label' => 'Background Gradient',
     *     'type' => 'linear',
     *     'value' => 'linear-gradient(45deg, #ff0000, #0000ff)',
     *     'description' => 'Choose a gradient for the background'
     * ], $context);
     */
    public static function render_gradient( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['gradient'] ) ) {
            self::$default_configs['gradient'] = array(
                'name' => '',
                'id' => '',
                'value' => 'linear-gradient(45deg, #000000, #ffffff)',
                'default' => 'linear-gradient(45deg, #000000, #ffffff)',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'type' => 'linear', // linear, radial
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['gradient'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_gradient_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_gradient_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        $content = sprintf(
            '<div class="ultraguard-gradient-picker" data-type="%s">' .
            '<div class="ultraguard-gradient-preview" style="background: %s;"></div>' .
            '<input type="text" id="%s" name="%s" value="%s" class="ultraguard-gradient-field">' .
            '</div>',
            $instance->escape( $scheme['type'], 'attribute' ),
            $instance->escape( $value, 'css' ),
            $instance->escape( $scheme['id'], 'attribute' ),
            $instance->escape( $scheme['name'], 'attribute' ),
            $instance->escape( $value, 'attribute' )
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render file uploader
     *
     * Renders a file upload field with drag-and-drop support, file preview,
     * and configurable file type restrictions. Includes security nonce.
     *
     * @param  array  $scheme   Upload field configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML file upload field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_upload([
     *     'name' => 'profile_image',
     *     'label' => 'Profile Image',
     *     'file_types' => 'image/*',
     *     'multiple' => false,
     *     'max_file_size' => 2048,
     *     'description' => 'Upload a profile image (max 2MB)'
     * ], $context);
     */
    public static function render_upload( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['upload'] ) ) {
            self::$default_configs['upload'] = array(
                'name' => '',
                'id' => '',
                'multiple' => false,
                'file_types' => '*',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'max_files' => 0,
                'max_file_size' => 0,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['upload'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_upload_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_upload_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        $preview_html = '';
        if ( $value ) {
            $preview_html = $instance->render_file_preview( $value, $scheme );
        }

        // Add nonce for security
        $nonce = wp_create_nonce( 'ultraguard_upload_' . $scheme['name'] );

        $content = sprintf(
            '<div class="ultraguard-uploader">' .
            '<input type="hidden" id="%s" name="%s" value="%s">' .
            '<input type="hidden" class="ultraguard-upload-nonce" value="%s">' .
            '<div class="ultraguard-upload-preview">%s</div>' .
            '<button type="button" class="button ultraguard-upload-button" data-multiple="%s" data-file-types="%s" data-max-files="%s" data-max-size="%s">%s</button>' .
            '<button type="button" class="button ultraguard-remove-button" style="%s">%s</button>' .
            '</div>',
            $instance->escape( $scheme['id'], 'attribute' ),
            $instance->escape( $scheme['name'], 'attribute' ),
            $instance->escape( $value, 'attribute' ),
            $nonce,
            $preview_html,
            $scheme['multiple'] ? 'true' : 'false',
            $instance->escape( $scheme['file_types'], 'attribute' ),
            absint( $scheme['max_files'] ),
            absint( $scheme['max_file_size'] ),
            esc_html__( 'Select File', 'ultraguard-security-suite' ),
            $value ? '' : 'display: none;',
            esc_html__( 'Remove', 'ultraguard-security-suite' )
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render icon selector
     *
     * Renders an icon selector field with searchable grid of icons from
     * various icon sets (Dashicons, Font Awesome, etc.).
     *
     * @param  array  $scheme   Icon selector configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML icon selector field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_icon_selector([
     *     'name' => 'feature_icon',
     *     'label' => 'Feature Icon',
     *     'icon_set' => 'dashicons',
     *     'searchable' => true,
     *     'description' => 'Select an icon for this feature'
     * ], $context);
     */
    public static function render_icon_selector( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['icon_selector'] ) ) {
            self::$default_configs['icon_selector'] = array(
                'name' => '',
                'id' => '',
                'icon_set' => 'dashicons',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'searchable' => true,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['icon_selector'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_icon_selector_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_icon_selector_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );
        $icons = $instance->get_icon_set( $scheme['icon_set'] );

        $icons_html = '';
        foreach ( $icons as $icon_value => $icon_class ) {
            $selected = $value === $icon_value ? ' ultraguard-icon-selected' : '';
            $icons_html .= sprintf(
                '<div class="ultraguard-icon-item%s" data-icon="%s">' .
                '<span class="%s"></span>' .
                '</div>',
                $selected,
                $instance->escape( $icon_value, 'attribute' ),
                esc_attr( $icon_class )
            );
        }

        $search_html = $scheme['searchable'] ?
            '<div class="ultraguard-icon-search"><input type="text" placeholder="' . esc_attr__( 'Search icons...', 'ultraguard-security-suite' ) . '" class="ultraguard-icon-search-input"></div>' : '';

        $content = sprintf(
            '<div class="ultraguard-icon-selector">' .
            '<input type="hidden" id="%s" name="%s" value="%s">' .
            '%s' .
            '<div class="ultraguard-icon-grid">%s</div>' .
            '</div>',
            $instance->escape( $scheme['id'], 'attribute' ),
            $instance->escape( $scheme['name'], 'attribute' ),
            $instance->escape( $value, 'attribute' ),
            $search_html,
            $icons_html
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render page selector
     *
     * Renders a page selector field that populates options from WordPress pages
     * or custom post types. Uses object caching for performance.
     *
     * @param  array  $scheme   Page selector configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML page selector field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_page_selector([
     *     'name' => 'landing_page',
     *     'label' => 'Landing Page',
     *     'post_type' => 'page',
     *     'description' => 'Select the landing page for this campaign'
     * ], $context);
     */
    public static function render_page_selector( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['page_selector'] ) ) {
            self::$default_configs['page_selector'] = array(
                'name' => '',
                'id' => '',
                'post_type' => 'page',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'include_children' => false,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['page_selector'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_page_selector_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_page_selector_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        // Use object cache for better performance than transients
        $cache_key = 'ultraguard_pages_' . md5( serialize( $scheme ) );
        $pages = CacheManager::get_instance()->get( $cache_key, 'asset' );

        if ( false === $pages ) {
            $pages = get_posts( array(
                'post_type'      => sanitize_text_field( $scheme['post_type'] ),
                'post_status'    => 'publish',
                'posts_per_page' => -1,
                'orderby'        => 'title',
                'order'          => 'ASC',
                'suppress_filters' => false,
            ) );
            CacheManager::get_instance()->set( $cache_key, $pages, 'asset' );
        }

        $options = array( '' => esc_html__( 'Select a page', 'ultraguard-security-suite' ) );
        foreach ( $pages as $page ) {
            $options[ $page->ID ] = $page->post_title;
        }

        $scheme['options'] = $options;

        return $instance->render_select( $scheme, $context );
    }

    /**
     * Render rich text editor
     *
     * Renders a WordPress rich text editor (TinyMCE) with configurable
     * toolbar options, media buttons, and quicktags.
     *
     * @param  array  $scheme   Editor configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML rich text editor field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_editor([
     *     'name' => 'content',
     *     'label' => 'Content',
     *     'editor_settings' => [
     *         'media_buttons' => true,
     *         'quicktags' => true,
     *         'textarea_rows' => 15
     *     ],
     *     'description' => 'Enter the main content'
     * ], $context);
     */
    public static function render_editor( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['editor'] ) ) {
            self::$default_configs['editor'] = array(
                'name' => '',
                'id' => '',
                'value' => '',
                'default' => '',
                'editor_settings' => array(),
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'media_buttons' => true,
                'quicktags' => true,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['editor'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_editor_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_editor_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );
        $editor_id = $scheme['id'];

        // Set default editor settings
        $default_settings = array(
            'textarea_name' => $scheme['name'],
            'editor_class' => 'ultraguard-rich-editor',
            'media_buttons' => $scheme['media_buttons'],
            'quicktags' => $scheme['quicktags'],
            'textarea_rows' => 10,
        );

        $editor_settings = wp_parse_args( $scheme['editor_settings'], $default_settings );

        ob_start();
        wp_editor( $value, $editor_id, $editor_settings );
        $editor_content = ob_get_clean();

        $output = $instance->render_field_wrapper( $editor_content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render date picker
     *
     * Renders a date picker field with configurable date format, min/max dates,
     * and locale support. Integrates with jQuery UI datepicker.
     *
     * @param  array  $scheme   Date picker configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML date picker field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_date_picker([
     *     'name' => 'birth_date',
     *     'label' => 'Birth Date',
     *     'format' => 'Y-m-d',
     *     'min_date' => '1900-01-01',
     *     'max_date' => 'today',
     *     'placeholder' => 'YYYY-MM-DD'
     * ], $context);
     */
    public static function render_date_picker( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['date_picker'] ) ) {
            self::$default_configs['date_picker'] = array(
                'name' => '',
                'id' => '',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'placeholder' => '',
                'disabled' => false,
                'readonly' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'format' => 'Y-m-d',
                'min_date' => '',
                'max_date' => '',
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['date_picker'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_date_picker_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_date_picker_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );
        $attributes = $instance->get_field_attributes( $scheme );

        $additional_attrs = array();
        if ( ! empty( $scheme['min_date'] ) ) {
            $additional_attrs[] = sprintf( 'data-min-date="%s"', $instance->escape( $scheme['min_date'], 'attribute' ) );
        }
        if ( ! empty( $scheme['max_date'] ) ) {
            $additional_attrs[] = sprintf( 'data-max-date="%s"', $instance->escape( $scheme['max_date'], 'attribute' ) );
        }
        if ( ! empty( $scheme['format'] ) ) {
            $additional_attrs[] = sprintf( 'data-date-format="%s"', $instance->escape( $scheme['format'], 'attribute' ) );
        }

        if ( ! empty( $additional_attrs ) ) {
            $attributes .= ' ' . implode( ' ', $additional_attrs );
        }

        $content = sprintf(
            '<input type="text" value="%s" %s class="ultraguard-date-picker">',
            $instance->escape( $value, 'attribute' ),
            $attributes
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render time picker
     *
     * Renders a time picker field with configurable time format, step intervals,
     * and 12/24 hour support. Integrates with jQuery UI timepicker.
     *
     * @param  array  $scheme   Time picker configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML time picker field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_time_picker([
     *     'name' => 'appointment_time',
     *     'label' => 'Appointment Time',
     *     'format' => 'H:i',
     *     'step' => 15,
     *     'placeholder' => 'HH:MM'
     * ], $context);
     */
    public static function render_time_picker( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['time_picker'] ) ) {
            self::$default_configs['time_picker'] = array(
                'name' => '',
                'id' => '',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'placeholder' => '',
                'disabled' => false,
                'readonly' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'format' => 'H:i',
                'step' => 30,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['time_picker'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_time_picker_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_time_picker_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );
        $attributes = $instance->get_field_attributes( $scheme );

        $additional_attrs = array();
        if ( ! empty( $scheme['format'] ) ) {
            $additional_attrs[] = sprintf( 'data-time-format="%s"', $instance->escape( $scheme['format'], 'attribute' ) );
        }
        if ( ! empty( $scheme['step'] ) ) {
            $additional_attrs[] = sprintf( 'data-step="%s"', $instance->escape( $scheme['step'], 'attribute' ) );
        }

        if ( ! empty( $additional_attrs ) ) {
            $attributes .= ' ' . implode( ' ', $additional_attrs );
        }

        $content = sprintf(
            '<input type="text" value="%s" %s class="ultraguard-time-picker">',
            $instance->escape( $value, 'attribute' ),
            $attributes
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render number input
     *
     * Renders a number input field with min, max, step constraints and
     * optional unit suffix display.
     *
     * @param  array  $scheme   Number input configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML number input field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_number([
     *     'name' => 'quantity',
     *     'label' => 'Quantity',
     *     'min' => 1,
     *     'max' => 100,
     *     'step' => 1,
     *     'value' => 10,
     *     'unit' => 'items',
     *     'description' => 'Enter quantity between 1 and 100'
     * ], $context);
     */
    public static function render_number( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['number'] ) ) {
            self::$default_configs['number'] = array(
                'name' => '',
                'id' => '',
                'min' => '',
                'max' => '',
                'step' => '',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'placeholder' => '',
                'disabled' => false,
                'readonly' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'unit' => '',
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['number'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_number_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_number_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );
        $attributes = $instance->get_field_attributes( $scheme );

        // Add number-specific attributes
        $additional_attrs = array();

        if ( $scheme['min'] !== '' ) {
            $additional_attrs[] = sprintf( 'min="%s"', $instance->escape( $scheme['min'], 'attribute' ) );
        }

        if ( $scheme['max'] !== '' ) {
            $additional_attrs[] = sprintf( 'max="%s"', $instance->escape( $scheme['max'], 'attribute' ) );
        }

        if ( $scheme['step'] !== '' ) {
            $additional_attrs[] = sprintf( 'step="%s"', $instance->escape( $scheme['step'], 'attribute' ) );
        }

        if ( ! empty( $additional_attrs ) ) {
            $attributes .= ' ' . implode( ' ', $additional_attrs );
        }

        $unit_html = ! empty( $scheme['unit'] ) ?
            sprintf( '<span class="ultraguard-number-unit">%s</span>', $instance->escape( $scheme['unit'] ) ) : '';

        $content = sprintf(
            '<div class="ultraguard-number-input-wrapper">' .
            '<input type="number" value="%s" %s>%s' .
            '</div>',
            $instance->escape( $value, 'attribute' ),
            $attributes,
            $unit_html
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render repeater field
     *
     * Renders a repeater field that allows dynamic addition/removal of rows
     * with configurable sub-fields. Supports sortable rows and min/max limits.
     *
     * @param  array  $scheme   Repeater configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML repeater field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_repeater([
     *     'name' => 'team_members',
     *     'label' => 'Team Members',
     *     'fields' => [
     *         ['type' => 'text', 'name' => 'name', 'label' => 'Name'],
     *         ['type' => 'text', 'name' => 'role', 'label' => 'Role']
     *     ],
     *     'min_rows' => 1,
     *     'max_rows' => 10,
     *     'sortable' => true
     * ], $context);
     */
    public static function render_repeater( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['repeater'] ) ) {
            self::$default_configs['repeater'] = array(
                'name' => '',
                'id' => '',
                'fields' => array(),
                'min_rows' => 0,
                'max_rows' => 0,
                'value' => array(),
                'default' => array(),
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'sortable' => true,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['repeater'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_repeater_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_repeater_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        if ( ! is_array( $value ) ) {
            $value = array();
        }

        // Ensure minimum rows
        while ( count( $value ) < $scheme['min_rows'] ) {
            $value[] = array();
        }

        $rows_html = '';
        $row_index = 0;

        foreach ( $value as $row_data ) {
            $rows_html .= $instance->render_repeater_row( $row_data, $scheme['fields'], $row_index, $context );
            $row_index++;
        }

        $sortable_class = $scheme['sortable'] ? 'ultraguard-repeater-sortable' : '';

        $content = sprintf(
            '<div class="ultraguard-repeater %s" data-min-rows="%s" data-max-rows="%s">' .
            '<div class="ultraguard-repeater-rows">%s</div>' .
            '<button type="button" class="button ultraguard-repeater-add" %s>%s</button>' .
            '</div>',
            $sortable_class,
            absint( $scheme['min_rows'] ),
            absint( $scheme['max_rows'] ),
            $rows_html,
            $scheme['max_rows'] && count( $value ) >= $scheme['max_rows'] ? 'disabled' : '',
            esc_html__( 'Add Row', 'ultraguard-security-suite' )
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render IP address input
     *
     * Renders an IP address input field with validation for IPv4/IPv6 addresses
     * and optional CIDR range notation support.
     *
     * @param  array  $scheme   IP address input configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML IP address input field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_ip_address([
     *     'name' => 'allowed_ip',
     *     'label' => 'Allowed IP Address',
     *     'version' => 'both',
     *     'allow_range' => true,
     *     'validate' => true,
     *     'placeholder' => '192.168.1.1 or 192.168.1.0/24'
     * ], $context);
     */
    public static function render_ip_address( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['ip_address'] ) ) {
            self::$default_configs['ip_address'] = array(
                'name' => '',
                'id' => '',
                'allow_range' => false,
                'version' => 'both',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'placeholder' => '',
                'disabled' => false,
                'readonly' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'validate' => true,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['ip_address'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_ip_address_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_ip_address_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );
        $attributes = $instance->get_field_attributes( $scheme );

        $placeholder = $scheme['allow_range'] ?
            esc_attr__( 'e.g., 192.168.1.1 or 192.168.1.0/24', 'ultraguard-security-suite' ) :
            esc_attr__( 'e.g., 192.168.1.1', 'ultraguard-security-suite' );

        $help_text = '';
        if ( 'both' === $scheme['version'] ) {
            $help_text = esc_html__( 'Supports IPv4 and IPv6 addresses', 'ultraguard-security-suite' );
        } elseif ( '6' === $scheme['version'] ) {
            $help_text = esc_html__( 'IPv6 address format', 'ultraguard-security-suite' );
        } else {
            $help_text = esc_html__( 'IPv4 address format', 'ultraguard-security-suite' );
        }

        if ( $scheme['allow_range'] ) {
            $help_text .= '. ' . esc_html__( 'CIDR notation supported for ranges', 'ultraguard-security-suite' );
        }

        $content = sprintf(
            '<input type="text" value="%s" %s placeholder="%s" data-ip-version="%s" data-allow-range="%s" data-validate="%s">' .
            '<div class="ultraguard-ip-help">%s</div>',
            $instance->escape( $value, 'attribute' ),
            $attributes,
            $placeholder,
            $scheme['version'],
            $scheme['allow_range'] ? 'true' : 'false',
            $scheme['validate'] ? 'true' : 'false',
            $instance->escape( $help_text )
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render severity level selector
     *
     * Renders a severity level selector with visual indicators (colors, icons)
     * for different severity levels (critical, high, medium, low, info).
     *
     * @param  array  $scheme   Severity selector configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML severity selector field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_severity_selector([
     *     'name' => 'issue_severity',
     *     'label' => 'Issue Severity',
     *     'allow_multiple' => false,
     *     'default_severity' => 'medium',
     *     'show_colors' => true,
     *     'description' => 'Select the severity level'
     * ], $context);
     */
    public static function render_severity_selector( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['severity_selector'] ) ) {
            self::$default_configs['severity_selector'] = array(
                'name' => '',
                'id' => '',
                'allow_multiple' => false,
                'default_severity' => 'medium',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'show_colors' => true,
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['severity_selector'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_severity_selector_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_severity_selector_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        $severity_levels = array(
            'critical' => array(
                'label' => esc_html__( 'Critical', 'ultraguard-security-suite' ),
                'color' => '#dc2626',
                'icon' => 'dashicons-warning',
            ),
            'high' => array(
                'label' => esc_html__( 'High', 'ultraguard-security-suite' ),
                'color' => '#ea580c',
                'icon' => 'dashicons-flag',
            ),
            'medium' => array(
                'label' => esc_html__( 'Medium', 'ultraguard-security-suite' ),
                'color' => '#d97706',
                'icon' => 'dashicons-info',
            ),
            'low' => array(
                'label' => esc_html__( 'Low', 'ultraguard-security-suite' ),
                'color' => '#65a30d',
                'icon' => 'dashicons-editor-help',
            ),
            'info' => array(
                'label' => esc_html__( 'Info', 'ultraguard-security-suite' ),
                'color' => '#2563eb',
                'icon' => 'dashicons-admin-comments',
            ),
        );

        // Allow filtering severity levels
        if ( has_filter( 'ultraguard_severity_levels' ) ) {
            $severity_levels = apply_filters( 'ultraguard_severity_levels', $severity_levels, $scheme, $context );
        }

        $severities_html = '';
        foreach ( $severity_levels as $severity => $config ) {
            $is_selected = $scheme['allow_multiple'] ?
                ( is_array( $value ) && in_array( $severity, $value, true ) ) :
                ( $value === $severity );

            $selected_class = $is_selected ? ' ultraguard-severity-selected' : '';
            $color_style = $scheme['show_colors'] ? sprintf( 'style="background-color: %s;"', esc_attr( $config['color'] ) ) : '';

            $severities_html .= sprintf(
                '<div class="ultraguard-severity-option ultraguard-severity-%s%s" data-severity="%s">' .
                '<span class="ultraguard-severity-color" %s></span>' .
                '<span class="dashicons %s"></span>' .
                '<span class="ultraguard-severity-label">%s</span>' .
                '</div>',
                sanitize_html_class( $severity ),
                $selected_class,
                $instance->escape( $severity, 'attribute' ),
                $color_style,
                esc_attr( $config['icon'] ),
                $instance->escape( $config['label'] )
            );
        }

        $hidden_input = $scheme['allow_multiple'] ?
            sprintf( '<input type="hidden" id="%s" name="%s" value="%s">',
                $instance->escape( $scheme['id'], 'attribute' ),
                $instance->escape( $scheme['name'], 'attribute' ),
                is_array( $value ) ? implode( ',', $value ) : $value
            ) :
            sprintf( '<input type="hidden" id="%s" name="%s" value="%s">',
                $instance->escape( $scheme['id'], 'attribute' ),
                $instance->escape( $scheme['name'], 'attribute' ),
                $instance->escape( $value, 'attribute' )
            );

        $content = sprintf(
            '<div class="ultraguard-severity-selector" data-multiple="%s">%s%s</div>',
            $scheme['allow_multiple'] ? 'true' : 'false',
            $hidden_input,
            $severities_html
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render password strength meter
     *
     * Renders a password input field with real-time strength meter,
     * requirement validation, and optional password generation.
     *
     * @param  array  $scheme   Password strength configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML password strength field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_password_strength([
     *     'name' => 'user_password',
     *     'label' => 'Password',
     *     'min_strength' => 'medium',
     *     'allow_generate' => true,
     *     'requirements' => [
     *         'length' => 8,
     *         'uppercase' => true,
     *         'numbers' => true,
     *         'symbols' => true
     *     ],
     *     'confirm_field' => 'confirm_password'
     * ], $context);
     */
    public static function render_password_strength( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['password_strength'] ) ) {
            self::$default_configs['password_strength'] = array(
                'name' => '',
                'id' => '',
                'min_strength' => 'medium',
                'allow_generate' => false,
                'requirements' => array(
                    'length' => 8,
                    'uppercase' => true,
                    'numbers' => true,
                    'symbols' => true,
                ),
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'placeholder' => '',
                'disabled' => false,
                'readonly' => false,
                'required' => false,
                'class' => '',
                'field_class' => '',
                'confirm_field' => '',
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['password_strength'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_password_strength_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_password_strength_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );
        $attributes = $instance->get_field_attributes( $scheme );

        $generate_button = '';
        if ( $scheme['allow_generate'] ) {
            $generate_button = sprintf(
                '<button type="button" class="button ultraguard-generate-password" title="%s">' .
                '<span class="dashicons dashicons-update"></span>' .
                '</button>',
                esc_attr__( 'Generate strong password', 'ultraguard-security-suite' )
            );
        }

        $toggle_button = sprintf(
            '<button type="button" class="ultraguard-password-toggle" title="%s">' .
            '<span class="dashicons dashicons-visibility"></span>' .
            '</button>',
            esc_attr__( 'Show/hide password', 'ultraguard-security-suite' )
        );

        $strength_meter = sprintf(
            '<div class="ultraguard-password-strength-meter">' .
            '<div class="ultraguard-strength-bar">' .
            '<div class="ultraguard-strength-fill"></div>' .
            '</div>' .
            '<div class="ultraguard-strength-text"></div>' .
            '</div>'
        );

        $requirements_html = '';
        if ( ! empty( $scheme['requirements'] ) ) {
            $requirements_html .= '<div class="ultraguard-password-requirements">';
            foreach ( $scheme['requirements'] as $requirement => $config ) {
                $label = $instance->get_requirement_label( $requirement, $config );
                $requirements_html .= sprintf(
                    '<div class="ultraguard-requirement" data-requirement="%s">' .
                    '<span class="ultraguard-requirement-icon"></span>' .
                    '<span class="ultraguard-requirement-text">%s</span>' .
                    '</div>',
                    $requirement,
                    $label
                );
            }
            $requirements_html .= '</div>';
        }

        $confirm_field_html = '';
        if ( ! empty( $scheme['confirm_field'] ) ) {
            $confirm_field_html = sprintf(
                '<div class="ultraguard-password-confirm">' .
                '<input type="password" placeholder="%s" class="ultraguard-password-confirm-input" data-original-field="%s">' .
                '</div>',
                esc_attr__( 'Confirm password', 'ultraguard-security-suite' ),
                $instance->escape( $scheme['id'], 'attribute' )
            );
        }

        $content = sprintf(
            '<div class="ultraguard-password-field">' .
            '<div class="ultraguard-password-input-wrapper">' .
            '<input type="password" value="%s" %s class="ultraguard-password-input" data-min-strength="%s">' .
            '%s%s' .
            '</div>' .
            '%s' .
            '%s' .
            '%s' .
            '</div>',
            $instance->escape( $value, 'attribute' ),
            $attributes,
            $scheme['min_strength'],
            $toggle_button,
            $generate_button,
            $strength_meter,
            $requirements_html,
            $confirm_field_html
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render tag input field
     *
     * Renders a tag input field that allows adding/removing tags with
     * autocomplete support and configurable delimiters.
     *
     * @param  array  $scheme   Tag input configuration scheme
     * @param  array  $context  Context data for field value resolution
     * @return string           Rendered HTML tag input field
     * @access public
     * @static
     *
     * @example
     * echo FormRenderer::render_tag_input([
     *     'name' => 'tags',
     *     'label' => 'Tags',
     *     'max_tags' => 10,
     *     'allow_custom' => true,
     *     'autocomplete_source' => '/api/tags',
     *     'delimiter' => ',',
     *     'description' => 'Add tags separated by commas'
     * ], $context);
     */
    public static function render_tag_input( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme = $instance->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['tag_input'] ) ) {
            self::$default_configs['tag_input'] = array(
                'name' => '',
                'id' => '',
                'max_tags' => 0,
                'allow_custom' => true,
                'autocomplete_source' => '',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'disabled' => false,
                'class' => '',
                'field_class' => '',
                'delimiter' => ',',
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['tag_input'];
        $defaults['id'] = $instance->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_tag_input_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_tag_input_scheme', $scheme, $context );
        }

        $value = $instance->get_field_value( $scheme, $context );

        // Convert value to array of tags
        $tags = array();
        if ( is_string( $value ) ) {
            $tags = array_filter( array_map( 'trim', explode( $scheme['delimiter'], $value ) ) );
        } elseif ( is_array( $value ) ) {
            $tags = array_filter( array_map( 'trim', $value ) );
        }

        $hidden_input = sprintf(
            '<input type="hidden" id="%s" name="%s" value="%s">',
            $instance->escape( $scheme['id'], 'attribute' ),
            $instance->escape( $scheme['name'], 'attribute' ),
            $instance->escape( implode( $scheme['delimiter'], $tags ), 'attribute' )
        );

        $tags_html = '';
        foreach ( $tags as $tag ) {
            $tags_html .= sprintf(
                '<span class="ultraguard-tag">' .
                '%s' .
                '<button type="button" class="ultraguard-tag-remove" data-tag="%s">&times;</button>' .
                '</span>',
                $instance->escape( $tag ),
                $instance->escape( $tag, 'attribute' )
            );
        }

        $max_tags_attr = $scheme['max_tags'] > 0 ? sprintf( 'data-max-tags="%d"', absint( $scheme['max_tags'] ) ) : '';
        $autocomplete_attr = $scheme['autocomplete_source'] ? sprintf( 'data-autocomplete-source="%s"', esc_attr( $scheme['autocomplete_source'] ) ) : '';

        $content = sprintf(
            '<div class="ultraguard-tag-input" %s %s data-allow-custom="%s" data-delimiter="%s">' .
            '%s' .
            '<div class="ultraguard-tags-container">%s</div>' .
            '<input type="text" class="ultraguard-tag-new" placeholder="%s">' .
            '</div>',
            $max_tags_attr,
            $autocomplete_attr,
            $scheme['allow_custom'] ? 'true' : 'false',
            $instance->escape( $scheme['delimiter'], 'attribute' ),
            $hidden_input,
            $tags_html,
            esc_attr__( 'Add a tag...', 'ultraguard-security-suite' )
        );

        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Render input field (generic method)
     *
     * Generic method for rendering input fields of various types (text, email, url, etc.).
     * Handles common attributes and applies filters for extensibility.
     *
     * @param  array   $scheme   Field configuration scheme
     * @param  array   $context  Context data for field value resolution
     * @param  string  $type     Input type (text, email, url, tel, etc.)
     * @return string            Rendered HTML input field
     * @access protected
     *
     * @example
     * $html = $this->render_input_field($scheme, $context, 'email');
     */
    protected function render_input_field( $scheme, $context, $type = 'text' ) {
        $scheme = $this->before_render( $scheme, $context );

        // Get cached defaults
        if ( ! isset( self::$default_configs['input_field'] ) ) {
            self::$default_configs['input_field'] = array(
                'name' => '',
                'id' => '',
                'value' => '',
                'default' => '',
                'label' => '',
                'description' => '',
                'placeholder' => '',
                'disabled' => false,
                'readonly' => false,
                'required' => false,
                'maxlength' => '',
                'pattern' => '',
                'class' => '',
                'field_class' => '',
                'autocomplete' => '',
            );
        }

        // Secure with wp_parse_args with complete defaults
        $defaults = self::$default_configs['input_field'];
        $defaults['id'] = $this->generate_field_id( $scheme['name'] ?? '' );
        $scheme = wp_parse_args( $scheme, $defaults );

        // Apply filters for extendability
        if ( has_filter( 'ultraguard_input_field_scheme' ) ) {
            $scheme = apply_filters( 'ultraguard_input_field_scheme', $scheme, $context, $type );
        }

        $value = $this->get_field_value( $scheme, $context );
        $attributes = $this->get_field_attributes( $scheme );

        // Add autocomplete if specified
        if ( ! empty( $scheme['autocomplete'] ) ) {
            $attributes .= sprintf( ' autocomplete="%s"', $this->escape( $scheme['autocomplete'], 'attribute' ) );
        }

        $content = sprintf(
            '<input type="%s" value="%s" %s>',
            $type,
            $this->escape( $value, 'attribute' ),
            $attributes
        );

        $output = $this->render_field_wrapper( $content, $scheme, $context );
        $output = $this->after_render( $output, $scheme, $context );

        return $output;
    }

    /**
     * Get field value
     *
     * Determines the field value based on priority: explicit value > source > default.
     * Integrates with DataLoader for dynamic value resolution.
     *
     * @param  array  $scheme   Field configuration scheme
     * @param  array  $context  Context data for value resolution
     * @return mixed            Field value
     * @access protected
     */
    protected function get_field_value( $scheme, $context ) {
        // Priority: value > source > default
        if ( isset( $scheme['value'] ) && $scheme['value'] !== '' ) {
            return $scheme['value'];
        }

        if ( isset( $scheme['source'] ) ) {
            $data_loader = DataLoader::get_instance();
            return $data_loader->load( $scheme['source'], $context );
        }

        return isset( $scheme['default'] ) ? $scheme['default'] : '';
    }

    /**
     * Get field attributes
     *
     * Generates HTML attributes string for a field based on scheme configuration.
     * Includes ID, name, placeholder, disabled, readonly, required, maxlength,
     * pattern, and class attributes.
     *
     * @param  array  $scheme  Field configuration scheme
     * @return string          HTML attributes string
     * @access protected
     */
    protected function get_field_attributes( $scheme ) {
        $attributes = array();

        // Ensure ID is set (with caching)
        $field_id = isset( $scheme['id'] ) && $scheme['id'] ? $scheme['id'] : $this->generate_field_id( $scheme['name'] ?? '' );

        $attributes[] = sprintf( 'id="%s"', $this->escape( $field_id, 'attribute' ) );
        $attributes[] = sprintf( 'name="%s"', $this->escape( $scheme['name'], 'attribute' ) );

        if ( isset( $scheme['placeholder'] ) && $scheme['placeholder'] !== '' ) {
            $attributes[] = sprintf( 'placeholder="%s"', $this->escape( $scheme['placeholder'], 'attribute' ) );
        }

        if ( isset( $scheme['disabled'] ) && $scheme['disabled'] ) {
            $attributes[] = 'disabled';
        }

        if ( isset( $scheme['readonly'] ) && $scheme['readonly'] ) {
            $attributes[] = 'readonly';
        }

        if ( isset( $scheme['required'] ) && $scheme['required'] ) {
            $attributes[] = 'required';
        }

        if ( isset( $scheme['maxlength'] ) && $scheme['maxlength'] !== '' ) {
            $attributes[] = sprintf( 'maxlength="%s"', $this->escape( $scheme['maxlength'], 'attribute' ) );
        }

        if ( isset( $scheme['pattern'] ) && $scheme['pattern'] !== '' ) {
            $attributes[] = sprintf( 'pattern="%s"', $this->escape( $scheme['pattern'], 'attribute' ) );
        }

        $class = 'ultraguard-field';
        if ( isset( $scheme['class'] ) && $scheme['class'] !== '' ) {
            $class .= ' ' . $scheme['class'];
        }
        $attributes[] = sprintf( 'class="%s"', $this->escape( $class, 'attribute' ) );

        if ( has_filter( 'ultraguard_field_attributes' ) ) {
            $attributes = apply_filters( 'ultraguard_field_attributes', $attributes, $scheme );
        }

        return implode( ' ', $attributes );
    }

    /**
     * Render field wrapper with two-column layout
     *
     * Wraps field content in a consistent two-column layout with label,
     * field input, and help text. Applies filters for custom wrapper HTML.
     *
     * @param  string  $content  Field content HTML
     * @param  array   $scheme   Field configuration scheme
     * @param  array   $context  Context data
     * @return string            Wrapped field HTML
     * @access protected
     */
    protected function render_field_wrapper( $content, $scheme, $context ) {
        $label_html = '';

        // Ensure ID is set for label
        $field_id = isset( $scheme['id'] ) && $scheme['id'] ? $scheme['id'] : $this->generate_field_id( $scheme['name'] ?? '' );

        if ( isset( $scheme['label'] ) && $scheme['label'] !== '' ) {
            $required_mark = isset( $scheme['required'] ) && $scheme['required'] ? ' <span class="ultraguard-required">*</span>' : '';

            $label_html = sprintf(
                '<label for="%s" class="ultraguard-field-label">%s%s</label>',
                $this->escape( $field_id, 'attribute' ),
                $this->escape( $scheme['label'] ),
                $required_mark
            );
        }

        $help_html = '';
        if ( isset( $scheme['description'] ) && $scheme['description'] !== '' ) {
            $help_html = sprintf(
                '<p class="ultraguard-field-help">%s</p>',
                $this->escape( $scheme['description'] )
            );
        }

        $field_classes = array( 'ultraguard-field-wrapper', 'ultraguard-two-column' );
        if ( isset( $scheme['field_class'] ) && $scheme['field_class'] !== '' ) {
            $field_classes[] = $scheme['field_class'];
        }

        $wrapper_html = sprintf(
            '<div class="%s">' .
            '<div class="ultraguard-field-label-column">%s</div>' .
            '<div class="ultraguard-field-input-column">%s%s</div>' .
            '</div>',
            implode( ' ', $field_classes ),
            $label_html,
            $content,
            $help_html
        );

        if ( has_filter( 'ultraguard_field_wrapper' ) ) {
            $wrapper_html = apply_filters( 'ultraguard_field_wrapper', $wrapper_html, $scheme, $context );
        }

        return $wrapper_html;
    }

    /**
     * Render file preview with caching for attachment URLs
     *
     * Generates file preview HTML for uploaded files, with caching for
     * attachment URLs to improve performance.
     *
     * @param  mixed  $value   File value (URL or attachment ID)
     * @param  array  $scheme  Upload field configuration scheme
     * @return string          File preview HTML
     * @access protected
     */
    protected function render_file_preview( $value, $scheme ) {
        if ( empty( $value ) ) {
            return '';
        }

        $cache_key = 'ultraguard_file_preview_' . md5( serialize( array( $value, $scheme['name'] ) ) );
        $cached = CacheManager::get_instance()->get( $cache_key, 'render' );

        if ( false !== $cached ) {
            return $cached;
        }

        $file_url = '';
        $file_name = '';

        if ( is_numeric( $value ) ) {
            $file_url = wp_get_attachment_url( $value );
            $file_name = get_the_title( $value );
        } else {
            $file_url = $value;
            $file_name = basename( $value );
        }

        if ( empty( $file_url ) ) {
            CacheManager::get_instance()->set( $cache_key, '', 'render' );
            return '';
        }

        $file_ext = pathinfo( $file_name, PATHINFO_EXTENSION );
        $image_extensions = array( 'jpg', 'jpeg', 'png', 'gif', 'webp' );

        $preview_html = '';
        if ( in_array( strtolower( $file_ext ), $image_extensions, true ) ) {
            $preview_html = sprintf(
                '<div class="ultraguard-file-preview ultraguard-image-preview">' .
                '<img src="%s" alt="%s" loading="lazy">' .
                '</div>',
                esc_url( $file_url ),
                esc_attr( $file_name )
            );
        } else {
            $preview_html = sprintf(
                '<div class="ultraguard-file-preview ultraguard-file-info">' .
                '<span class="dashicons dashicons-media-document"></span>' .
                '<span class="ultraguard-file-name">%s</span>' .
                '</div>',
                esc_html( $file_name )
            );
        }

        CacheManager::get_instance()->set( $cache_key, $preview_html, 'render' );

        return $preview_html;
    }

    /**
     * Get icon set with caching
     *
     * Retrieves icon definitions for a specific icon set with caching
     * for performance. Supports Dashicons and custom icon sets via filters.
     *
     * @param  string  $icon_set  Icon set name (dashicons, fontawesome, etc.)
     * @return array              Icon set array [value => css_class]
     * @access protected
     */
    protected function get_icon_set( $icon_set ) {
        // Check cache first
        if ( isset( self::$cached_icon_sets[ $icon_set ] ) ) {
            return self::$cached_icon_sets[ $icon_set ];
        }

        $icons = array();

        switch ( $icon_set ) {
            case 'dashicons':
                $icons = array(
                    'dashicons-admin-site'    => 'dashicons dashicons-admin-site',
                    'dashicons-dashboard'     => 'dashicons dashicons-dashboard',
                    'dashicons-admin-post'    => 'dashicons dashicons-admin-post',
                    'dashicons-admin-media'   => 'dashicons dashicons-admin-media',
                    'dashicons-admin-page'    => 'dashicons dashicons-admin-page',
                    'dashicons-admin-comments' => 'dashicons dashicons-admin-comments',
                    'dashicons-admin-appearance' => 'dashicons dashicons-admin-appearance',
                    'dashicons-admin-plugins' => 'dashicons dashicons-admin-plugins',
                    'dashicons-admin-users'   => 'dashicons dashicons-admin-users',
                    'dashicons-admin-tools'   => 'dashicons dashicons-admin-tools',
                    'dashicons-admin-settings' => 'dashicons dashicons-admin-settings',
                    'dashicons-shield'        => 'dashicons dashicons-shield',
                    'dashicons-shield-alt'    => 'dashicons dashicons-shield-alt',
                    'dashicons-lock'          => 'dashicons dashicons-lock',
                    'dashicons-yes'           => 'dashicons dashicons-yes',
                    'dashicons-no'            => 'dashicons dashicons-no',
                    'dashicons-warning'       => 'dashicons dashicons-warning',
                );
                break;

            default:
                if ( has_filter( 'ultraguard_icon_set_' . $icon_set ) ) {
                    $icons = apply_filters( 'ultraguard_icon_set_' . $icon_set, array() );
                }
                break;
        }

        // Cache the result
        self::$cached_icon_sets[ $icon_set ] = $icons;

        return $icons;
    }

    /**
     * Render repeater row with optimized field rendering
     *
     * Renders a single row for a repeater field with all configured sub-fields.
     * Uses RenderEngine for field rendering and includes sort handle and remove button.
     *
     * @param  array  $row_data   Row data values
     * @param  array  $fields     Field configurations for the row
     * @param  int    $row_index  Row index/number
     * @param  array  $context    Context data
     * @return string             Rendered repeater row HTML
     * @access protected
     */
    protected function render_repeater_row( $row_data, $fields, $row_index, $context ) {
        $fields_html = '';

        if ( empty( $fields ) || ! is_array( $fields ) ) {
            return '';
        }

        // Get render engine instance once
        static $render_engine = null;
        if ( null === $render_engine ) {
            $render_engine = RenderEngine::get_instance();
        }

        foreach ( $fields as $field_scheme ) {
            if ( ! is_array( $field_scheme ) ) {
                continue;
            }

            $field_name = $field_scheme['name'] ?? '';
            if ( empty( $field_name ) ) {
                continue;
            }

            $field_id = ( $field_scheme['id'] ?? '' ) . '_' . $row_index;
            $field_name_full = ( $field_scheme['name'] ?? '' ) . '[' . $row_index . ']';

            // Set current value
            $field_value = isset( $row_data[ $field_name ] ) ? $row_data[ $field_name ] : '';
            $field_scheme['value'] = $field_value;
            $field_scheme['id'] = $field_id;
            $field_scheme['name'] = $field_name_full;

            $fields_html .= $render_engine->render( $field_scheme, $context );
        }

        $sort_handle = ''; // Note: $scheme is not available in this method in original code
        // Assuming sortable is true by default or should be passed differently
        // For now, we'll add it conditionally

        return sprintf(
            '<div class="ultraguard-repeater-row">' .
            '%s' .
            '<div class="ultraguard-repeater-row-fields">%s</div>' .
            '<button type="button" class="button ultraguard-repeater-remove">%s</button>' .
            '</div>',
            $sort_handle,
            $fields_html,
            esc_html__( 'Remove', 'ultraguard-security-suite' )
        );
    }

    /**
     * Get requirement label for password strength
     *
     * Generates human-readable labels for password strength requirements
     * based on requirement type and configuration.
     *
     * @param  string  $requirement  Requirement type (length, uppercase, etc.)
     * @param  mixed   $config       Requirement configuration value
     * @return string                Human-readable requirement label
     * @access protected
     */
    protected function get_requirement_label( $requirement, $config ) {
        static $requirement_labels = null;

        if ( null === $requirement_labels ) {
            $requirement_labels = array(
                'length' => function( $config ) {
                    return sprintf(
                        /* translators: %d: number */
                        _n( 'At least %d character', 'At least %d characters', $config, 'ultraguard-security-suite' ),
                        absint( $config )
                    );
                },
                'uppercase' => function() {
                    return esc_html__( 'Contains uppercase letter', 'ultraguard-security-suite' );
                },
                'numbers' => function() {
                    return esc_html__( 'Contains number', 'ultraguard-security-suite' );
                },
                'symbols' => function() {
                    return esc_html__( 'Contains symbol', 'ultraguard-security-suite' );
                },
                'lowercase' => function() {
                    return esc_html__( 'Contains lowercase letter', 'ultraguard-security-suite' );
                },
                'default' => function( $requirement ) {
                    return ucfirst( $requirement );
                }
            );
        }

        if ( isset( $requirement_labels[ $requirement ] ) ) {
            return $requirement_labels[ $requirement ]( $config );
        }

        return $requirement_labels['default']( $requirement );
    }

    /**
     * Escape output based on context with minimal function calls
     *
     * Escapes output for different contexts (HTML, attribute, textarea, etc.)
     * using appropriate WordPress escaping functions.
     *
     * @param  mixed   $value    Value to escape
     * @param  string  $context  Escape context (html, attribute, textarea, url, css, js)
     * @return string            Escaped value
     * @access protected
     */
    protected function escape( $value, $context = 'html' ) {
        if ( null === $value ) {
            return '';
        }

        switch ( $context ) {
            case 'attribute':
                return esc_attr( $value );
            case 'textarea':
                return esc_textarea( $value );
            case 'url':
                return esc_url( $value );
            case 'css':
                return esc_attr( $value ); // For CSS contexts, use esc_attr
            case 'js':
                return esc_js( $value );
            case 'html':
            default:
                return esc_html( $value );
        }
    }

    /**
     * Clear all caches (useful for testing/debugging)
     *
     * Clears all internal caches including default configurations,
     * icon sets, and field ID cache. Useful during development and testing.
     *
     * @return void
     * @access public
     * @static
     */
    public static function clear_caches() {
        self::$default_configs = array();
        self::$cached_icon_sets = array();
        self::$field_id_cache = array();
    }

    /**
     * Render cron-builder field
     * Human-friendly WordPress cron schedule selector.
     */
    public static function render_cron_builder( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme   = $instance->before_render( $scheme, $context );

        $scheme = wp_parse_args( $scheme, [
            'name'        => '',
            'value'       => 'daily',
            'label'       => '',
            'description' => '',
            'id'          => 'ultraguard-cron-' . uniqid(),
            'required'    => false,
            'disabled'    => false,
            'options'     => [],
        ] );

        $default_schedules = [
            'hourly'     => __( 'Every Hour', 'ultraguard-security-suite' ),
            'twicedaily' => __( 'Twice Daily', 'ultraguard-security-suite' ),
            'daily'      => __( 'Daily', 'ultraguard-security-suite' ),
            'weekly'     => __( 'Weekly', 'ultraguard-security-suite' ),
        ];
        $schedules = ! empty( $scheme['options'] ) ? $scheme['options'] : $default_schedules;

        $options_html = '';
        foreach ( $schedules as $val => $lbl ) {
            $options_html .= sprintf(
                '<option value="%s"%s>%s</option>',
                esc_attr( $val ),
                selected( $scheme['value'], $val, false ),
                esc_html( $lbl )
            );
        }

        $label_html = $scheme['label']
            ? '<label for="' . esc_attr( $scheme['id'] ) . '" class="ultraguard-form-label">' . esc_html( $scheme['label'] ) . '</label>'
            : '';
        $desc_html = $scheme['description']
            ? '<p class="ultraguard-field-description">' . esc_html( $scheme['description'] ) . '</p>'
            : '';

        return sprintf(
            '<div class="ultraguard-field-wrapper ultraguard-cron-builder">%s'
            . '<select name="%s" id="%s" class="ultraguard-field"%s%s>%s</select>%s</div>',
            $label_html,
            esc_attr( $scheme['name'] ), esc_attr( $scheme['id'] ),
            $scheme['disabled'] ? ' disabled' : '',
            $scheme['required'] ? ' required' : '',
            $options_html, $desc_html
        );
    }

    /**
     * Render multi-step-toggle field
     * Segmented control with 3+ discrete steps (replaces radio groups).
     */
    public static function render_multi_step_toggle( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme   = $instance->before_render( $scheme, $context );

        $scheme = wp_parse_args( $scheme, [
            'name'        => '',
            'value'       => '',
            'label'       => '',
            'description' => '',
            'id'          => 'ultraguard-mst-' . uniqid(),
            'options'     => [],
            'disabled'    => false,
        ] );

        $options = is_array( $scheme['options'] ) ? $scheme['options'] : [];
        $buttons = '';
        foreach ( $options as $val => $lbl ) {
            $active = ( (string) $scheme['value'] === (string) $val ) ? ' ultraguard-mst-active' : '';
            $buttons .= sprintf(
                '<button type="button" class="ultraguard-mst-btn%s" data-value="%s" data-name="%s"%s>%s</button>',
                $active, esc_attr( $val ), esc_attr( $scheme['name'] ),
                $scheme['disabled'] ? ' disabled' : '',
                esc_html( is_array( $lbl ) ? ( $lbl['label'] ?? $val ) : $lbl )
            );
        }

        $label_html = $scheme['label']
            ? '<label class="ultraguard-form-label">' . esc_html( $scheme['label'] ) . '</label>'
            : '';
        $desc_html = $scheme['description']
            ? '<p class="ultraguard-field-description">' . esc_html( $scheme['description'] ) . '</p>'
            : '';

        return sprintf(
            '<div class="ultraguard-field-wrapper ultraguard-multi-step-toggle">%s'
            . '<input type="hidden" name="%s" id="%s" value="%s">'
            . '<div class="ultraguard-mst-group" style="display:inline-flex;border:2px solid var(--ug-border,#e2e8f0);border-radius:var(--ug-radius-md,8px);overflow:hidden;">%s</div>'
            . '%s</div>',
            $label_html,
            esc_attr( $scheme['name'] ), esc_attr( $scheme['id'] ), esc_attr( $scheme['value'] ),
            $buttons, $desc_html
        );
    }

    /**
     * Render duration-picker field
     * Number + unit selector for time durations (minutes, hours, days).
     */
    public static function render_duration_picker( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme   = $instance->before_render( $scheme, $context );

        $scheme = wp_parse_args( $scheme, [
            'name'        => '',
            'value'       => 60,
            'unit'        => 'minutes',
            'label'       => '',
            'description' => '',
            'id'          => 'ultraguard-duration-' . uniqid(),
            'min'         => 1,
            'max'         => 99999,
            'disabled'    => false,
            'units'       => [],
        ] );

        $default_units = [
            'seconds' => __( 'Seconds', 'ultraguard-security-suite' ),
            'minutes' => __( 'Minutes', 'ultraguard-security-suite' ),
            'hours'   => __( 'Hours', 'ultraguard-security-suite' ),
            'days'    => __( 'Days', 'ultraguard-security-suite' ),
        ];
        $units = ! empty( $scheme['units'] ) ? $scheme['units'] : $default_units;

        $unit_options = '';
        foreach ( $units as $val => $lbl ) {
            $unit_options .= sprintf(
                '<option value="%s"%s>%s</option>',
                esc_attr( $val ), selected( $scheme['unit'], $val, false ), esc_html( $lbl )
            );
        }

        $label_html = $scheme['label']
            ? '<label for="' . esc_attr( $scheme['id'] ) . '" class="ultraguard-form-label">' . esc_html( $scheme['label'] ) . '</label>'
            : '';
        $desc_html = $scheme['description']
            ? '<p class="ultraguard-field-description">' . esc_html( $scheme['description'] ) . '</p>'
            : '';
        $disabled = $scheme['disabled'] ? ' disabled' : '';

        return sprintf(
            '<div class="ultraguard-field-wrapper ultraguard-duration-picker">%s'
            . '<div style="display:flex;gap:8px;align-items:center;">'
            . '<input type="number" name="%s" id="%s" value="%d" min="%d" max="%d" class="ultraguard-field" style="width:100px;"%s>'
            . '<select name="%s_unit" class="ultraguard-field" style="width:auto;"%s>%s</select>'
            . '</div>%s</div>',
            $label_html,
            esc_attr( $scheme['name'] ), esc_attr( $scheme['id'] ),
            absint( $scheme['value'] ), absint( $scheme['min'] ), absint( $scheme['max'] ), $disabled,
            esc_attr( $scheme['name'] ), $disabled, $unit_options,
            $desc_html
        );
    }

    /**
     * Render json-editor field
     * Textarea-based JSON editor with syntax validation hint.
     */
    public static function render_json_editor( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme   = $instance->before_render( $scheme, $context );

        $scheme = wp_parse_args( $scheme, [
            'name'        => '',
            'value'       => '',
            'label'       => '',
            'description' => '',
            'id'          => 'ultraguard-json-' . uniqid(),
            'rows'        => 10,
            'disabled'    => false,
            'required'    => false,
            'placeholder' => '{}',
        ] );

        $value = is_array( $scheme['value'] ) || is_object( $scheme['value'] )
            ? wp_json_encode( $scheme['value'], JSON_PRETTY_PRINT )
            : (string) $scheme['value'];

        $label_html = $scheme['label']
            ? '<label for="' . esc_attr( $scheme['id'] ) . '" class="ultraguard-form-label">' . esc_html( $scheme['label'] ) . '</label>'
            : '';
        $desc_html = $scheme['description']
            ? '<p class="ultraguard-field-description">' . esc_html( $scheme['description'] ) . '</p>'
            : '';

        return sprintf(
            '<div class="ultraguard-field-wrapper ultraguard-json-editor">%s'
            . '<textarea name="%s" id="%s" rows="%d" class="ultraguard-field" style="font-family:monospace;font-size:13px;" placeholder="%s"%s%s>%s</textarea>'
            . '%s</div>',
            $label_html,
            esc_attr( $scheme['name'] ), esc_attr( $scheme['id'] ),
            absint( $scheme['rows'] ),
            esc_attr( $scheme['placeholder'] ),
            $scheme['disabled'] ? ' disabled' : '',
            $scheme['required'] ? ' required' : '',
            esc_textarea( $value ),
            $desc_html
        );
    }

    /**
     * Render country-selector field.
     *
     * A multi-select <select> pre-populated from the bundled ISO 3166-1 country
     * codes JSON file (assets/json/country-codes.json), falling back to WooCommerce
     * or a minimal hard-coded list.
     *
     * Alignment fix: the field content is now passed through render_field_wrapper()
     * exactly like render_select() and every other form field, so it sits correctly
     * in the two-column label / input layout.
     */
    public static function render_country_selector( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme   = $instance->before_render( $scheme, $context );

        $scheme = wp_parse_args( $scheme, [
            'name'        => '',
            'value'       => [],
            'default'     => [],
            'label'       => '',
            'description' => '',
            'id'          => 'ultraguard-country-' . uniqid(),
            'multiple'    => true,
            'size'        => 8,
            'disabled'    => false,
            'required'    => false,
            'countries'   => [],
            'field_class' => 'ultraguard-country-selector',
        ] );

        // Resolve value through the standard helper so 'default' behaves identically
        // to every other field type (before_render already normalises value/default).
        $value = $instance->get_field_value( $scheme, $context );

        // ── Build country list ──────────────────────────────────────────────────────
        // Priority: explicit 'countries' key -> bundled JSON -> WooCommerce -> fallback.
        if ( ! empty( $scheme['countries'] ) ) {
            $countries = $scheme['countries'];
        } else {
            $json_path = defined( 'ULTRAGUARD_PRO_DIR' )
                ? trailingslashit( ULTRAGUARD_PRO_DIR ) . 'assets/json/country-codes.json'
                : '';

            if ( $json_path && file_exists( $json_path ) ) {
                $raw_json  = json_decode( file_get_contents( $json_path ), true ); // phpcs:ignore
                $countries = [];
                foreach ( $raw_json['countries'] ?? [] as $entry ) {
                    $countries[ (string) $entry['code'] ] = (string) $entry['name'];
                }
            } elseif ( function_exists( 'WC' ) && class_exists( 'WC_Countries' ) ) {
                $countries = ( new \WC_Countries() )->get_countries();
            } else {
                $countries = [
                    'US' => 'United States', 'GB' => 'United Kingdom', 'CA' => 'Canada',
                    'AU' => 'Australia',     'IN' => 'India',          'DE' => 'Germany',
                    'FR' => 'France',        'JP' => 'Japan',          'CN' => 'China',
                    'BR' => 'Brazil',
                ];
            }
        }

        // ── Normalise selected values ─────────────────────────────────────────────────
        $selected_arr = is_array( $value ) ? $value : array_filter( [ $value ] );

        // ── Build <option> HTML ─────────────────────────────────────────────────────────
        $options_html = '';
        foreach ( $countries as $code => $name ) {
            $sel           = in_array( (string) $code, $selected_arr, true ) ? ' selected' : '';
            $options_html .= sprintf(
                '<option value="%s"%s>%s</option>',
                esc_attr( $code ),
                $sel,
                esc_html( $name )
            );
        }

        // ── Build the <select> element ──────────────────────────────────────────────────
        $name_attr = esc_attr( $scheme['name'] ) . '[]';   // always array-style name
        $size_val  = max( 1, (int) $scheme['size'] );

        $content = sprintf(
            '<select name="%s" id="%s" class="ultraguard-field ultraguard-country-select" multiple size="%d"%s%s>%s</select>',
            $name_attr,
            esc_attr( $scheme['id'] ),
            $size_val,
            $scheme['disabled'] ? ' disabled' : '',
            $scheme['required'] ? ' required' : '',
            $options_html
        );

        // ── Wrap via render_field_wrapper() ─────────────────────────────────────────────
        // Identical call chain to render_select() → consistent two-column alignment.
        $output = $instance->render_field_wrapper( $content, $scheme, $context );
        $output = $instance->after_render( $output, $scheme, $context );

        return $output;
    }
    /**
     * Render schedule-picker field
     * Day-of-week + time-of-day compound selector for recurring schedules.
     */
    public static function render_schedule_picker( $scheme, $context ) {
        $instance = self::get_instance();
        $scheme   = $instance->before_render( $scheme, $context );

        $scheme = wp_parse_args( $scheme, [
            'name'        => '',
            'day_value'   => 'monday',
            'time_value'  => '02:00',
            'label'       => '',
            'description' => '',
            'id'          => 'ultraguard-sched-' . uniqid(),
            'disabled'    => false,
        ] );

        $days = [
            'monday'    => __( 'Monday', 'ultraguard-security-suite' ),
            'tuesday'   => __( 'Tuesday', 'ultraguard-security-suite' ),
            'wednesday' => __( 'Wednesday', 'ultraguard-security-suite' ),
            'thursday'  => __( 'Thursday', 'ultraguard-security-suite' ),
            'friday'    => __( 'Friday', 'ultraguard-security-suite' ),
            'saturday'  => __( 'Saturday', 'ultraguard-security-suite' ),
            'sunday'    => __( 'Sunday', 'ultraguard-security-suite' ),
        ];

        $day_options = '';
        foreach ( $days as $val => $lbl ) {
            $day_options .= sprintf(
                '<option value="%s"%s>%s</option>',
                esc_attr( $val ), selected( $scheme['day_value'], $val, false ), esc_html( $lbl )
            );
        }

        $label_html = $scheme['label']
            ? '<label class="ultraguard-form-label">' . esc_html( $scheme['label'] ) . '</label>'
            : '';
        $desc_html = $scheme['description']
            ? '<p class="ultraguard-field-description">' . esc_html( $scheme['description'] ) . '</p>'
            : '';
        $disabled = $scheme['disabled'] ? ' disabled' : '';
        $base_name = esc_attr( $scheme['name'] );

        return sprintf(
            '<div class="ultraguard-field-wrapper ultraguard-schedule-picker">%s'
            . '<div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">'
            . '<select name="%s[day]" class="ultraguard-field" style="width:auto;"%s>%s</select>'
            . '<span style="color:#64748b;">%s</span>'
            . '<input type="time" name="%s[time]" value="%s" class="ultraguard-field" style="width:auto;"%s>'
            . '</div>%s</div>',
            $label_html,
            $base_name, $disabled, $day_options,
            esc_html__( 'at', 'ultraguard-security-suite' ),
            $base_name, esc_attr( $scheme['time_value'] ), $disabled,
            $desc_html
        );
    }

}