jQuery(document).ready(function($) {
    $('.wdpop_core-data-wrapper').each(function() {
        var $wrapper = $(this);
        var lastId   = parseInt($wrapper.data('last-group')) || 0;

        // Step 1: Ensure existing items have IDs
        const updateExisting = false;
        if(updateExisting){
            $wrapper.find('.wdpop_core-cloneable-item').each(function() {
                var $item = $(this);
                var $idField = $item.find('input[name*="__group_id"]');
                
                if ($idField.length && !$idField.val()) {
                    lastId++;
                    $idField.val(lastId);
                } else if ($idField.length) {
                    var existing = parseInt($idField.val());
                    
                    if (!isNaN(existing) && existing > lastId) {
                        lastId = existing;
                    }
                }
            });
        }
        
        // Handle shortcode display for existing items
        $itemsHere = $wrapper.find('.wdpop_core-cloneable-item');
        $itemsHere.each(function() {
            var $item = $(this);
            var $idField = $item.find('input[name*="__group_id"]').val();
            var shortcode = $item.find('.wdpop_core-shortcode-contnet');
            let contentNow = shortcode.text();
            contentNow = contentNow?.replace("id__here", $idField);
            shortcode.text(contentNow);
        });
        
        // Step 2 & 3: Assign new IDs on Add or Clone
        const addCloneSelector = '.wdpop_core-cloneable-add, .wdpop_core-cloneable-clone';
        $wrapper.closest('.wdpop_core-field').on('click', addCloneSelector, function(e) {
            setTimeout(function() {
                var $newItem   = $wrapper.find('.wdpop_core-cloneable-item').last();
                var $idField   = $newItem.find('input[name*="__group_id"]');
                var shortcode  = $newItem.find('.wdpop_core-shortcode-contnet');

                if ($idField.length) {
                    lastId++;
                    $idField.val(lastId);

                    let contentNow = shortcode.text();
                    contentNow = contentNow?.replace("id__here", lastId);
                    shortcode.text(contentNow);
                }
            }, 100);
        });

        
        
        

    });
});