// DESCRIPTION: Handles repeat field add/remove/reindex functionality for WPUF frontend forms.

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, $instance);
            });

            $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);
            // Update z-index for all instances
            updateZIndex($container);
        });
    }

    // Add repeat instance
    function addRepeatInstance($container, fieldName, maxRepeats, $clickedInstance) {
        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 clicked instance (more efficient - we already have it)
                // Note: We clone with the wrapper intact, then clean up only the cloned instance
                // This preserves the source field's state and wrapper
                var $newInstance = $clickedInstance.clone(true, true);
        var clickedIndex = parseInt($clickedInstance.attr('data-instance')) || 0;
        var newIndex = clickedIndex + 1;

        // 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('.hasDatepicker').removeClass('hasDatepicker');

        // Properly clean up intlTelInput wrappers in cloned instance - unwrap the input from its container
        $newInstance.find('input.wpuf_telephone').each(function() {
            var $input = $(this);
            var $wrapper = $input.closest('.iti, .iti--allow-dropdown, .iti--separate-dial-code');

            // If input is wrapped, unwrap it to get back to the raw input
            if ($wrapper.length && $wrapper[0] !== $input[0]) {
                // Move input out of wrapper and remove wrapper
                $input.detach();
                $wrapper.replaceWith($input);
            }

            // Remove any intlTelInput-related classes and data
            $input.removeClass('iti wpuf-initialized');
            $input.removeAttr('data-intl-tel-input-id');
            $input.removeData('intlTelInput');
        });

        // 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);
            }
        });

        // Insert the new instance after the clicked instance (works for both rows and blocks)
        $clickedInstance.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);
        updateZIndex($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);
            // Update z-index for all instances
            updateZIndex($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 z-index for all instances (first row gets highest z-index)
    function updateZIndex($container) {
        var $instances = $container.find('.wpuf-repeat-instance');
        var totalInstances = $instances.length;

        $instances.each(function(index) {
            var $instance = $(this);
            var zIndex = totalInstances - index;
            $instance.css('z-index', zIndex);
        });
    }

    // 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');

                // Add button: show on all instances
                if ($addButton.length) {
                    $addButton.show();
                }
                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 on all instances
                $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();
    });

});
