<?php

namespace WeDevs\Wpuf\Pro\Fields;

use WeDevs\Wpuf\Fields\Form_Field_Post_Trait;

/**
 * Repeat Field Class
 *
 * @since 3.1.0
 **/
class Field_Repeat extends Pro_Field_Contract {

    use Form_Field_Post_Trait;

    public function __construct() {
        $this->name       = __( 'Repeat Field', 'wpuf-pro' );
        $this->input_type = 'repeat_field';
        $this->icon       = 'rectangle-stack';
    }

    /**
     * Render the Repeat field in the frontend
     *
     * @since 4.1.9   Simplified repeat field rendering
     *
     * @param array  $field_settings
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     *
     * @return void
     */
    public function render( $field_settings, $form_id, $type = 'post', $post_id = null ) {
        $inner_fields = ! empty( $field_settings['inner_fields'] ) ? $field_settings['inner_fields'] : [];
        $max_repeats  = ! empty( $field_settings['max_repeats'] ) ? $field_settings['max_repeats'] : - 1;
        $field_name   = ! empty( $field_settings['name'] ) ? $field_settings['name'] : '';
        $id           = ! empty( $field_settings['id'] ) ? $field_settings['id'] : 0;
        $input_type   = 'repeat_field';
        $values       = [];
        $class_names  = ! empty( $field_settings['css'] ) ? ' ' . $field_settings['css'] : '';
        $class_names  .= ' wpuf_' . $input_type . '_' . $id . '_' . esc_attr( $form_id );

        // Get the display option - default to 'blocks' for backward compatibility
        $display_option = ! empty( $field_settings['repeat_display'] ) ? $field_settings['repeat_display'] : 'blocks';
        $class_names .= ' wpuf-repeat-display-' . esc_attr( $display_option );

        if ( isset( $post_id ) && $post_id != '0' ) {
            if ( $this->is_meta( $field_settings ) ) {
                $values = $this->get_meta( $post_id, $field_settings['name'], $type );
            }
        } else {
            $values = $field_settings['default'];
        }

        ?>
        <div class="wpuf-fields wpuf-repeat-container <?php echo esc_attr( $class_names ); ?>" data-field-name="<?php echo esc_attr( $field_name ); ?>"
             data-max-repeats="<?php echo esc_attr( $max_repeats ); ?>" data-display-option="<?php echo esc_attr( $display_option ); ?>">
             <?php
             if( !empty($field_settings['label'])) {
                ?>
                <p style="margin: 0 0 0 10px;"><?php echo esc_html( $field_settings['label'] ); ?></p>
                <hr style="margin-left: 10px;">
                <?php
             }
             ?>
            <?php
            // Choose rendering method based on display option
            if ( 'rows' === $display_option ) {
                $this->render_repeat_instances_rows( $inner_fields, $values, $form_id, $type, $post_id, $field_name, 1 );
            } else {
                // Default to blocks rendering for backward compatibility
                $this->render_repeat_instances_wrapped( $inner_fields, $values, $form_id, $type, $post_id, $field_name, 1 );
            }
            ?>

            <?php $this->help_text( $field_settings ); ?>
        </div>

        <?php
        // Add JavaScript for repeat field functionality (blocks display)
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            // Initialize repeat field functionality
            function initRepeatFields() {
                var $containers = $('.wpuf-repeat-container');
                $containers.each(function() {
                    var $container = $(this);
                    var fieldName = $container.data('field-name');
                    var maxRepeats = parseInt($container.data('max-repeats')) || -1;

                    // Remove existing event handlers to prevent duplicates
                    $container.off('click.repeat');

                    // Add button click handlers
                    $container.on('click.repeat', '.wpuf-add-repeat', function(e) {
                        e.preventDefault();
                        var $instance = $(this).closest('.wpuf-repeat-instance');
                        var instanceIndex = $instance.attr('data-instance');
                        addRepeatInstance($container, fieldName, maxRepeats);
                    });

                    $container.on('click.repeat', '.wpuf-remove-repeat', function(e) {
                        e.preventDefault();
                        var $instance = $(this).closest('.wpuf-repeat-instance');
                        removeRepeatInstance($instance, $container);
                    });

                    // Initialize button visibility
                    updateRepeatButtons($container);
                });
            }

            // Add repeat instance
            function addRepeatInstance($container, fieldName, maxRepeats) {
                var $instances = $container.find('.wpuf-repeat-instance');
                var currentCount = $instances.length;
                var displayOption = $container.data('display-option') || 'blocks';

                // Check max repeats limit
                if (maxRepeats > 0 && currentCount >= maxRepeats) {
                    return;
                }

                // Clone the last instance
                var $lastInstance = $instances.last();
                var $newInstance = $lastInstance.clone();
                var newIndex = currentCount;

                // Update the data-instance attribute
                $newInstance.attr('data-instance', newIndex);

                // Clear all input values in the new instance
                $newInstance.find('input, textarea, select').each(function() {
                    var $input = $(this);
                    if ($input.is(':checkbox') || $input.is(':radio')) {
                        $input.prop('checked', false);
                    } else {
                        $input.val('');
                    }
                });

                // Remove initialization classes from cloned fields so they can be re-initialized
                $newInstance.find('.wpuf-initialized').removeClass('wpuf-initialized');
                $newInstance.find('.iti').removeClass('iti');
                $newInstance.find('.hasDatepicker').removeClass('hasDatepicker');

                // Update field names and IDs to use the new index
                $newInstance.find('[name], [id], [for]').each(function() {
                    var $element = $(this);
                    var originalName = $element.attr('name');
                    var originalId = $element.attr('id');
                    var originalFor = $element.attr('for');

                    if (originalName && originalName.includes('[')) {
                        var newName = originalName.replace(/\[\d+\]/, '[' + newIndex + ']');
                        $element.attr('name', newName);
                    }
                    if (originalId && originalId.includes('[')) {
                        var newId = originalId.replace(/\[\d+\]/, '[' + newIndex + ']');
                        $element.attr('id', newId);
                    }
                    if (originalFor && originalFor.includes('[')) {
                        var newFor = originalFor.replace(/\[\d+\]/, '[' + newIndex + ']');
                        $element.attr('for', newFor);
                    }
                });

                // Add the new instance based on display mode
                if (displayOption === 'rows') {
                    // For rows display, append to tbody
                    $container.find('tbody').append($newInstance);
                } else {
                    // For blocks display, append after the last instance
                    $lastInstance.after($newInstance);
                }

                // Add smooth animation for new instance
                $newInstance.addClass('wpuf-adding');
                setTimeout(function() {
                    $newInstance.removeClass('wpuf-adding');
                }, 10);

                // Reindex all instances
                reindexInstances($container, fieldName);
                updateRepeatButtons($container);

                // Re-initialize fields in the new instance with a delay to ensure DOM is ready
                setTimeout(function() {
                    if (typeof WPUF_Field_Initializer !== 'undefined') {
                        WPUF_Field_Initializer.init();
                    }
                }, 100);
            }

            // Remove repeat instance
            function removeRepeatInstance($instance, $container) {
                var fieldName = $container.data('field-name');
                var instanceIndex = $instance.attr('data-instance');

                // Add smooth animation for removal
                $instance.addClass('wpuf-removing');
                
                setTimeout(function() {
                    $instance.remove();
                    reindexInstances($container, fieldName);
                    updateRepeatButtons($container);
                }, 300); // Match the CSS transition duration
            }

            // Reindex all instances
            function reindexInstances($container, fieldName) {
                $container.find('.wpuf-repeat-instance').each(function(index) {
                    var $instance = $(this);
                    $instance.attr('data-instance', index);

                    // Update field names and IDs
                    $instance.find('[name], [id], [for]').each(function() {
                        var $element = $(this);
                        var originalName = $element.attr('name');
                        var originalId = $element.attr('id');
                        var originalFor = $element.attr('for');

                        if (originalName && originalName.includes('[')) {
                            var newName = originalName.replace(/\[\d+\]/, '[' + index + ']');
                            $element.attr('name', newName);
                        }
                        if (originalId && originalId.includes('[')) {
                            var newId = originalId.replace(/\[\d+\]/, '[' + index + ']');
                            $element.attr('id', newId);
                        }
                        if (originalFor && originalFor.includes('[')) {
                            var newFor = originalFor.replace(/\[\d+\]/, '[' + index + ']');
                            $element.attr('for', newFor);
                        }
                    });
                });
            }

            // Update button visibility
            function updateRepeatButtons($container) {
                var $instances = $container.find('.wpuf-repeat-instance');
                var count = $instances.length;
                var displayOption = $container.data('display-option') || 'blocks';

                $instances.each(function(i) {
                    var $instance = $(this);
                    var $controls = $instance.find('.wpuf-repeat-controls');
                    var isLast = i === count - 1;
                    var isOnlyInstance = count === 1;

                    if (displayOption === 'rows') {
                        // For rows display, buttons are already rendered in PHP, just show/hide them
                        var $addButton = $controls.find('.wpuf-add-repeat');
                        var $removeButton = $controls.find('.wpuf-remove-repeat');

                        if ($addButton.length) {
                            $addButton.toggle(isLast);
                        }
                        if ($removeButton.length) {
                            $removeButton.toggle(!isOnlyInstance);
                        }
                    } else {
                        // For blocks display, dynamically create buttons
                        $controls.empty();

                        // Create and add buttons based on logic
                        var addButtonHtml = '<button type="button" class="wpuf-add-repeat" data-instance="' + i + '">+</button>';
                        var removeButtonHtml = '<button type="button" class="wpuf-remove-repeat" data-instance="' + i + '">−</button>';

                        // Add button: show only on last instance
                        if (isLast) {
                            $controls.append(addButtonHtml);
                        }

                        // Remove button: show on all instances EXCEPT when there's only 1 instance
                        if (!isOnlyInstance) {
                            $controls.append(removeButtonHtml);
                        }
                    }
                });
            }

            // Initialize on page load
            initRepeatFields();

            // Re-initialize when new content is added (for dynamic forms)
            $(document).on('wpuf-form-loaded', function() {
                initRepeatFields();
            });

        });
        </script>

        <!-- JavaScript for repeat fields is handled by the main admin script in Posting.php -->
        <style>
            .wpuf-fields.wpuf-repeat-container li {
                margin-bottom: 0 !important;
                padding-bottom: 0 !important;
            }
            .wpuf-repeat-instance li {
                margin-bottom: 0 !important;
            }
            .wpuf-repeat-controls {
                margin-left: 5px;
                margin-top: 10px;
            }
            .wpuf-repeat-controls:last-child {
                margin-bottom: 1rem;
            }
            .wpuf-repeat-controls button {
                border: 1px solid #ccc !important;
                background: #fff;
                padding: 2px 8px;
                margin-left: 5px;
                border-radius: 3px;
                cursor: pointer;
                font-size: 1rem;
                line-height: 1.4;
                transition: all 0.2s ease;
            }
            .wpuf-repeat-controls button:hover {
                background: #f0f0f0;
                cursor: pointer;
                transform: translateY(-1px);
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }

            /* Smooth transition effects for repeat instances */
            .wpuf-repeat-instance {
                transition: all 0.3s ease;
                opacity: 1;
                transform: translateY(0);
            }

            .wpuf-repeat-instance.wpuf-adding {
                opacity: 0;
                transform: translateY(-10px);
            }

            .wpuf-repeat-instance.wpuf-removing {
                opacity: 0;
                transform: translateY(-10px);
                max-height: 0;
                overflow: hidden;
                margin: 0;
                padding: 0;
            }

            /* Smooth transitions for buttons */
            .wpuf-repeat-controls button {
                transition: all 0.2s ease;
            }

            .wpuf-repeat-controls button:active {
                transform: translateY(1px);
            }

            /* Styles for rows display mode */
            .wpuf-repeat-display-rows .wpuf-repeat-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 15px;
                border: none;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-table th,
            .wpuf-repeat-display-rows .wpuf-repeat-table td {
                border: none;
                padding: 0;
                text-align: left;
                vertical-align: top;
                background: transparent;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-table th {
                background: transparent;
                font-weight: bold;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-table .wpuf-label {
                display: none !important; /* Hide individual field labels in row mode */
            }

            .wpuf-repeat-display-rows .wpuf-fields input[type="text"] {
                vertical-align: top !important;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-controls {
                margin: 0;
                text-align: center;
                vertical-align: middle;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-controls button {
                margin: 0 2px;
                padding: 4px 8px;
                min-width: 24px;
                height: 24px;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                vertical-align: middle;
                transition: all 0.2s ease;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-instance {
                display: table-row;
                transition: all 0.3s ease;
                opacity: 1;
                transform: translateY(0);
            }

            .wpuf-repeat-display-rows .wpuf-repeat-instance.wpuf-adding {
                opacity: 0;
                transform: translateY(-10px);
            }

            .wpuf-repeat-display-rows .wpuf-repeat-instance.wpuf-removing {
                opacity: 0;
                transform: translateY(-10px);
                transition: all 0.3s ease;
            }

            /* Enhanced transitions for rows display */
            .wpuf-repeat-display-rows .wpuf-repeat-table tbody tr {
                transition: all 0.3s ease;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-table tbody tr.wpuf-adding {
                opacity: 0;
                transform: translateY(-10px);
            }

            .wpuf-repeat-display-rows .wpuf-repeat-table tbody tr.wpuf-removing {
                opacity: 0;
                transform: translateY(-10px);
                max-height: 0;
                overflow: hidden;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-table td li {
                padding-top: 0 !important;
                padding-left: 0 !important;
                margin: 0 !important;
                border: none !important;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-table td .wpuf-fields {
                margin: 0 !important;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-table td .wpuf-fields input,
            .wpuf-repeat-display-rows .wpuf-repeat-table td .wpuf-fields textarea,
            .wpuf-repeat-display-rows .wpuf-repeat-table td .wpuf-fields select {
                width: 100%;
                margin: 0 !important;
                transition: all 0.2s ease;
            }

            .wpuf-repeat-display-rows .wpuf-repeat-table td .wpuf-fields input:focus,
            .wpuf-repeat-display-rows .wpuf-repeat-table td .wpuf-fields textarea:focus,
            .wpuf-repeat-display-rows .wpuf-repeat-table td .wpuf-fields select:focus {
                border-color: #007cba;
                box-shadow: 0 0 0 1px #007cba;
            }
        </style>
        <?php
    }

    /**
     * Render the Repeat field in admin metabox
     *
     * @since 4.1.9
     *
     * @param array  $field_settings
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     *
     * @return void
     */
    public function render_admin_metabox( $field_settings, $form_id, $type = 'post', $post_id = null ) {
        $inner_fields = ! empty( $field_settings['inner_fields'] ) ? $field_settings['inner_fields'] : [];
        $max_repeats  = ! empty( $field_settings['max_repeats'] ) ? $field_settings['max_repeats'] : - 1;
        $field_name   = ! empty( $field_settings['name'] ) ? $field_settings['name'] : '';
        $id           = ! empty( $field_settings['id'] ) ? $field_settings['id'] : 0;
        $input_type   = 'repeat_field';
        $values       = [];
        $class_names  = ! empty( $field_settings['css'] ) ? ' ' . $field_settings['css'] : '';
        $class_names  .= ' wpuf_' . $input_type . '_' . $id . '_' . esc_attr( $form_id );

        if ( isset( $post_id ) && $post_id != '0' ) {
            if ( $this->is_meta( $field_settings ) ) {
                $values = $this->get_meta( $post_id, $field_settings['name'], $type );
            }
        } else {
            $values = $field_settings['default'];
        }

        // Output a single table row for the repeat field and all its instances
        ob_start();
        ?>
        <tr class="wpuf-el <?php echo esc_attr( $field_name ); ?> field-size-large" data-label="<?php echo esc_attr( $field_settings['label'] ); ?>">
            <th><strong><?php echo esc_html( $field_settings['label'] ); ?></strong></th>
            <td>
                <div class="wpuf-fields wpuf-repeat-container <?php echo esc_attr( $class_names ); ?>" data-field-name="<?php echo esc_attr( $field_name ); ?>" data-max-repeats="<?php echo esc_attr( $max_repeats ); ?>">
                    <?php $this->render_repeat_instances_admin_inline( $inner_fields, $values, $form_id, $type, $post_id, $field_name, 1 ); ?>
                </div>
                <?php $this->help_text( $field_settings ); ?>
            </td>
        </tr>
        <style>
            .ui-datepicker-calendar {
                background: #fff;
            }
        </style>
        <?php
        $output = ob_get_clean();
        echo $output;
    }

    // New method: render repeat instances as inline inputs for admin metabox
    private function render_repeat_instances_admin_inline( $fields, $values, $form_id, $type = 'post', $post_id = null, $field_name = '', $min_instances = 1 ) {
        if ( ! $fields ) {
            return;
        }


        $fields = apply_filters( 'wpuf_render_fields', $fields, $form_id );
        // Ensure $values is a flat array of instances, not nested/appended
        if ( empty( $values ) || ! is_array( $values ) ) {
            $values = [];
        }
        // If no values provided, create at least min_instances empty instances
        $instance_count = max(count($values), $min_instances);
        $normalized_values = [];
        for ( $i = 0; $i < $instance_count; $i++ ) {
            $instance = [];
            foreach ( $fields as $field ) {
                $instance[ $field['name'] ] = isset($values[$i][$field['name']]) ? $values[$i][$field['name']] : '';
            }
            $normalized_values[] = $instance;
        }
        foreach ( $normalized_values as $instance_index => $instance_values ) {
            echo '<div class="wpuf-repeat-instance" data-instance="' . esc_attr( $instance_index ) . '">';
            foreach ( $fields as $field ) {
                if ( ! $field_object = wpuf()->fields->field_exists( $field['template'] ) ) {
                    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                        echo wp_kses_post( '<h4 style="color: red;"><em>' . $field['template'] . '</em> field not found.</h4>' );
                    }
                    continue;
                }
                if ( wpuf()->fields->check_field_visibility( $field ) ) {
                    if ( is_object( $field_object ) ) {
                        $field_value = isset( $instance_values[ $field['name'] ] ) ? $instance_values[ $field['name'] ] : '';
                        $field_with_value = $field;

                        // Set the appropriate property based on field type
                        if ( in_array( $field['template'], [ 'dropdown_field', 'radio_field', 'checkbox_field', 'multiple_select' ] ) ) {
                            $field_with_value['selected'] = $field_value;
                        } elseif ( $field['template'] === 'country_list_field' ) {
                            // For country list fields, set the country_list.name property
                            if ( ! isset( $field_with_value['country_list'] ) ) {
                                $field_with_value['country_list'] = [];
                            }
                            $field_with_value['country_list']['name'] = $field_value;
                        } else {
                            $field_with_value['default'] = $field_value;
                        }

                        $original_name = $field_with_value['name'];
                        if ( ! empty( $field_name ) ) {
                            $field_with_value['name'] = $field_name . '[' . $instance_index . '][' . $original_name . ']';
                        }
                        // Render label and input inline

                        ob_start();
                        ?>
                            <div style="margin-bottom:8px">
                                <label style="display:block;font-weight:600;margin-bottom:2px"><?php echo esc_html( $field_with_value['label'] ); ?></label>
                                <?php
                                    $field_object->render( $field_with_value, $form_id, $type, null );
                                ?>
                            </div>
                        <?php
                        $input_html = ob_get_clean();
                        // Remove any <tr>...</tr> wrappers if present
                        $input_html = preg_replace('/<tr[^>]*>|<\/tr>/i', '', $input_html);
                        $input_html = preg_replace('/<th[^>]*>.*?<\/th>/is', '', $input_html);
                        $input_html = preg_replace('/<td[^>]*>|<\/td>/i', '', $input_html);

                        echo $input_html;
                    }
                }
            }

            // Add placeholder for buttons - JavaScript will add the actual buttons
            echo '<div class="wpuf-repeat-controls"></div>';
            echo '</div>'; // Close wpuf-repeat-instance
        }
    }

    /**
     * Render repeat instances with proper wrapper structure for frontend
     *
     * @param array  $fields
     * @param array  $values
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     * @param string $field_name
     * @param int    $min_instances
     *
     * @return void
     */
    private function render_repeat_instances_wrapped( $fields, $values, $form_id, $type = 'post', $post_id = null, $field_name = '', $min_instances = 1 ) {
        if ( ! $fields ) {
            return;
        }

        $fields = apply_filters( 'wpuf_render_fields', $fields, $form_id );

        // If no values provided, create at least min_instances empty instances
        if ( empty( $values ) ) {
            $values = [];
            for ( $i = 0; $i < $min_instances; $i++ ) {
                $empty_instance = [];
                foreach ( $fields as $field ) {
                    $empty_instance[ $field['name'] ] = '';
                }
                $values[] = $empty_instance;
            }
        }

        // Normalize values to match field names
        $normalized_values = $this->normalize_values_for_fields( $fields, $values );

        // Loop through each instance
        foreach ( $normalized_values as $instance_index => $instance_values ) {
            echo '<div class="wpuf-repeat-instance" data-instance="' . esc_attr( $instance_index ) . '">';

            // Render each field with its corresponding value
            foreach ( $fields as $field ) {
                if ( ! $field_object = wpuf()->fields->field_exists( $field['template'] ) ) {
                    if ( defined( 'WP_DEBUG' && WP_DEBUG ) ) {
                        echo wp_kses_post( '<h4 style="color: red;"><em>' . $field['template'] . '</em> field not found.</h4>' );
                    }
                    continue;
                }

                if ( wpuf()->fields->check_field_visibility( $field ) ) {
                    if ( is_object( $field_object ) ) {
                        // Get the value for this specific field in this instance
                        $field_value = isset( $instance_values[ $field['name'] ] ) ? $instance_values[ $field['name'] ] : '';

                        // Create a copy of the field settings and set the value
                        $field_with_value = $field;

                        // Set the appropriate property based on field type
                        if ( in_array( $field['template'], [ 'dropdown_field', 'radio_field', 'checkbox_field', 'multiple_select' ] ) ) {
                            $field_with_value['selected'] = $field_value;
                        } elseif ( $field['template'] === 'country_list_field' ) {
                            // For country list fields, set the country_list.name property
                            if ( ! isset( $field_with_value['country_list'] ) ) {
                                $field_with_value['country_list'] = [];
                            }
                            $field_with_value['country_list']['name'] = $field_value;
                        } else {
                            $field_with_value['default'] = $field_value;
                        }

                        // Modify the field name to be indexed for repeat field structure
                        // Format: repeat_field_name[instance_index][inner_field_name]
                        $original_name = $field_with_value['name'];
                        if ( ! empty( $field_name ) ) {
                            $field_with_value['name'] = $field_name . '[' . $instance_index . '][' . $original_name . ']';
                        }

                        // Force post_id to null so that the field uses the default value
                        $render_post_id = null;

                        // Render the field with the current value
                        $field_object->render( $field_with_value, $form_id, $type, $render_post_id );
                        $field_object->conditional_logic( $field_with_value, $form_id );
                    }
                }
            }

            // Add repeat controls
            // Add placeholder for buttons - JavaScript will add the actual buttons
            echo '<div class="wpuf-repeat-controls"></div>';
            echo '</div>'; // Close wpuf-repeat-instance
        }
    }

    /**
     * Render repeat instances with or without values
     *
     * @param array  $fields
     * @param array  $values
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     * @param string $field_name
     * @param int    $min_instances
     *
     * @return void
     */
    private function render_repeat_instances( $fields, $values, $form_id, $type = 'post', $post_id = null, $field_name = '', $min_instances = 1 ) {
        if ( ! $fields ) {
            return;
        }

        $fields = apply_filters( 'wpuf_render_fields', $fields, $form_id );

        // If no values provided, create at least min_instances empty instances
        if ( empty( $values ) ) {
            $values = [];
            for ( $i = 0; $i < $min_instances; $i++ ) {
                $empty_instance = [];
                foreach ( $fields as $field ) {
                    $empty_instance[ $field['name'] ] = '';
                }
                $values[] = $empty_instance;
            }
        }

        // Normalize values to match field names
        $normalized_values = $this->normalize_values_for_fields( $fields, $values );

        // Loop through each instance
        foreach ( $normalized_values as $instance_index => $instance_values ) {
            // Render each field with its corresponding value
            foreach ( $fields as $field ) {
                if ( ! $field_object = wpuf()->fields->field_exists( $field['template'] ) ) {
                    if ( defined( 'WP_DEBUG' && WP_DEBUG ) ) {
                        echo wp_kses_post( '<h4 style="color: red;"><em>' . $field['template'] . '</em> field not found.</h4>' );
                    }
                    continue;
                }

                if ( wpuf()->fields->check_field_visibility( $field ) ) {
                    if ( is_object( $field_object ) ) {
                        // Get the value for this specific field in this instance
                        $field_value = isset( $instance_values[ $field['name'] ] ) ? $instance_values[ $field['name'] ] : '';

                        // Create a copy of the field settings and set the value
                        $field_with_value = $field;

                        // Set the appropriate property based on field type
                        if ( in_array( $field['template'], [ 'dropdown_field', 'radio_field', 'checkbox_field', 'multiple_select' ] ) ) {
                            $field_with_value['selected'] = $field_value;
                        } elseif ( $field['template'] === 'country_list_field' ) {
                            // For country list fields, set the country_list.name property
                            if ( ! isset( $field_with_value['country_list'] ) ) {
                                $field_with_value['country_list'] = [];
                            }
                            $field_with_value['country_list']['name'] = $field_value;
                        } else {
                            $field_with_value['default'] = $field_value;
                        }

                        // Modify the field name to be indexed for repeat field structure
                        // Format: repeat_field_name[instance_index][inner_field_name]
                        $original_name = $field_with_value['name'];
                        if ( ! empty( $field_name ) ) {
                            $field_with_value['name'] = $field_name . '[' . $instance_index . '][' . $original_name . ']';
                        }

                        // Force post_id to null so that the field uses the default value
                        $render_post_id = null;

                        // Render the field with the current value
                        $field_object->render( $field_with_value, $form_id, $type, $render_post_id );
                        $field_object->conditional_logic( $field_with_value, $form_id );
                    }
                }
            }

            // Add repeat controls
            // Add placeholder for buttons - JavaScript will add the actual buttons
            echo '<div class="wpuf-repeat-controls"></div>';
        }
    }

    /**
     * Normalize values array to match field names
     *
     * @param array $fields
     * @param array $values
     *
     * @return array
     */
    private function normalize_values_for_fields( $fields, $values ) {
        $normalized_values = [];

        // Create a mapping of field templates to field names
        $template_to_name = [];
        foreach ( $fields as $field ) {
            $template_to_name[ $field['template'] ] = $field['name'];
        }

        // Normalize each instance
        foreach ( $values as $instance_index => $instance_values ) {
            $normalized_instance = [];

            foreach ( $instance_values as $key => $value ) {
                // Try to find the correct field name by matching template or name
                $found_field_name = null;

                // First, try exact name match
                foreach ( $fields as $field ) {
                    if ( $field['name'] === $key ) {
                        $found_field_name = $field['name'];
                        break;
                    }
                }

                // If not found, try to match by template type
                if ( ! $found_field_name ) {
                    // Extract template type from the key (e.g., 'text_3357845579' -> 'text_field')
                    $key_parts = explode( '_', $key );
                    if ( count( $key_parts ) >= 2 ) {
                        $template_type = $key_parts[0] . '_field';

                        // Look for matching template
                        foreach ( $fields as $field ) {
                            if ( $field['template'] === $template_type ) {
                                $found_field_name = $field['name'];
                                break;
                            }
                        }
                    }
                }

                // If still not found, use the original key
                if ( ! $found_field_name ) {
                    $found_field_name = $key;
                }

                $normalized_instance[ $found_field_name ] = $value;
            }

            $normalized_values[ $instance_index ] = $normalized_instance;
        }

        return $normalized_values;
    }

    /**
     * It's not a full width block
     *
     * @return bool
     */
    public function is_full_width() {
        return true;
    }

    /**
     * Get field options setting
     *
     * @return array
     */
    public function get_options_settings() {
        $default_options = $this->get_default_option_settings( true, [ 'read_only', 'show_icon', 'field_icon', 'icon_position' ] );

        $settings = [
            [
                'name'      => 'repeat_display',
                'title'     => __( 'Display', 'wpuf-pro' ),
                'type'      => 'radio',
                'section'   => 'basic',
                'priority'  => 10,
                'default'   => 'blocks',
                'options'   => [
                    'blocks' => __( 'Blocks', 'wpuf-pro' ),
                    'rows'   => __( 'Rows', 'wpuf-pro' ),
                ],
                'help_text' => __( 'Choose how the repeat fields should be displayed', 'wpuf-pro' ),
            ],
            [
                'name'      => 'max_repeats',
                'title'     => __( 'Maximum Repeats', 'wpuf-pro' ),
                'type'      => 'text',
                'variation' => 'number',
                'section'   => 'advanced',
                'priority'  => 23,
                'default'   => -1,
                'help_text' => __( 'Maximum number of repeatable instances (-1 for unlimited)', 'wpuf-pro' ),
            ],
        ];

        $all_settings = array_merge( $default_options, $settings );

        /**
         * Filter: 'wpuf_repeat_field_option_settings' - Allows filtering of all the repeat field settings.
         *
         * @param array $all_settings The current settings array
         */
        return apply_filters( 'wpuf_repeat_field_option_settings', $all_settings );
    }

    /**
     * Get the field props
     *
     * @return array
     */
    public function get_field_props() {
        $defaults     = $this->default_attributes();

        $props = [
            'input_type'       => 'repeat',
            'is_meta'          => 'yes',
            'width'            => 'large',
            'size'             => '40',
            'id'               => 0,
            'is_new'           => true,
            'show_in_post'     => 'yes',
            'repeat_display'   => 'blocks',
            'hide_field_label' => 'no',
            'max_repeats'      => - 1,
            'inner_fields'     => [],
        ];

        $all_props = array_merge( $defaults, $props );

        /**
         * Filter: 'wpuf_repeat_field_props' - Allows filtering of all the repeat field props.
         *
         * @param array $all_props The current props array
         */
        return apply_filters( 'wpuf_repeat_field_props', $all_props );
    }

    /**
     * Prepare entry
     *
     * @param $field
     *
     * @return mixed
     */
    public function prepare_entry( $field ) {
        $entry_value = [];


        // Process repeat field data with indexed field names
        if ( isset( $_POST[$field['name']] ) && is_array( $_POST[$field['name']] ) ) {
            foreach ( $_POST[$field['name']] as $instance_index => $instance_data ) {
                if ( is_array( $instance_data ) ) {
                    $instance_meta = [];
                    foreach ( $instance_data as $field_name => $field_value ) {
                        // Handle different field types
                        if ( is_array( $field_value ) ) {
                            // For fields like checkboxes that can have multiple values
                            $instance_meta[$field_name] = array_map( function( $item ) { return strip_shortcodes( sanitize_text_field( $item ) ); }, $field_value );
                        } else {
                            $instance_meta[$field_name] = strip_shortcodes( sanitize_text_field( $field_value ) );
                        }
                    }
                    $entry_value[] = $instance_meta;
                }
            }
        }
        return $entry_value;
    }

    /**
     * Render repeat instances in rows format (table-like display)
     *
     * @param array  $fields
     * @param array  $values
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     * @param string $field_name
     * @param int    $min_instances
     */
    private function render_repeat_instances_rows( $fields, $values, $form_id, $type = 'post', $post_id = null, $field_name = '', $min_instances = 1 ) {
        if ( ! $fields ) {
            return;
        }

        $fields = apply_filters( 'wpuf_render_fields', $fields, $form_id );

        // If no values provided, create at least min_instances empty instances
        if ( empty( $values ) ) {
            $values = [];
            for ( $i = 0; $i < $min_instances; $i++ ) {
                $empty_instance = [];
                foreach ( $fields as $field ) {
                    $empty_instance[ $field['name'] ] = '';
                }
                $values[] = $empty_instance;
            }
        }

        // Normalize values to match field names
        $normalized_values = $this->normalize_values_for_fields( $fields, $values );

        echo '<table class="wpuf-repeat-table" style="padding-left: 10px;">';

        // Render table header
        echo '<thead><tr>';
        foreach ( $fields as $field ) {
            echo '<th style="text-align: left">' . esc_html( $field['label'] ) . '</th>';
        }
        echo '<th></th>';
        echo '</tr></thead>';

        echo '<tbody>';

        // Loop through each instance
        foreach ( $normalized_values as $instance_index => $instance_values ) {
            echo '<tr class="wpuf-repeat-instance" data-instance="' . esc_attr( $instance_index ) . '">';

            // Render each field as a table cell
            foreach ( $fields as $field ) {
                echo '<td>';

                if ( ! $field_object = wpuf()->fields->field_exists( $field['template'] ) ) {
                    echo '</td>';
                    continue;
                }

                if ( wpuf()->fields->check_field_visibility( $field ) ) {
                    if ( is_object( $field_object ) ) {
                        // Get the value for this specific field in this instance
                        $field_value = isset( $instance_values[ $field['name'] ] ) ? $instance_values[ $field['name'] ] : '';

                        // Create a copy of the field settings and set the value
                        $field_with_value = $field;

                        // Set the appropriate property based on field type
                        if ( in_array( $field['template'], [ 'dropdown_field', 'radio_field', 'checkbox_field', 'multiple_select' ] ) ) {
                            $field_with_value['selected'] = $field_value;
                        } elseif ( $field['template'] === 'country_list_field' ) {
                            // For country list fields, set the country_list.name property
                            if ( ! isset( $field_with_value['country_list'] ) ) {
                                $field_with_value['country_list'] = [];
                            }
                            $field_with_value['country_list']['name'] = $field_value;
                        } else {
                            $field_with_value['default'] = $field_value;
                        }

                        // Modify the field name to be indexed for repeat field structure
                        // Format: repeat_field_name[instance_index][inner_field_name]
                        $field_with_value['name'] = $field_name . '[' . $instance_index . '][' . $field['name'] . ']';
                        $field_with_value['id'] = $field['id'] . '_' . $instance_index;

                        // Force post_id to null so that the field uses the pre-processed value
                        $render_post_id = null;

                        // Render the field
                        $field_object->render( $field_with_value, $form_id, $type, $render_post_id );
                    }
                }

                echo '</td>';
            }

            // Actions column
            echo '<td>';
            echo '<div class="wpuf-repeat-controls">';
            // Show add button only on the last instance, remove button on all instances (except when there's only 1)
            $is_last_instance = ($instance_index === count($normalized_values) - 1);
            $is_only_instance = (count($normalized_values) === 1);
            echo '<button type="button" class="wpuf-add-repeat" style="' . ($is_last_instance ? '' : 'display: none;') . '">+</button>';
            echo '<button type="button" class="wpuf-remove-repeat" style="' . ($is_only_instance ? 'display: none;' : '') . '">−</button>';
            echo '</div>';
            echo '</td>';

            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }
}
