    let currentIndex = 0;
        var container = document.getElementById('container');
        var boxCount = 10;
        var visibleBoxCount = 3;
         var xhr = new XMLHttpRequest();
  var booster_counter = 0;
  var booster_cuee_slider = 0;
  
 
    // Get the order ID from the URL
   
   if(Shopify.checkout ){
       
       console.log("Order Data:\n" + JSON.stringify(Shopify.checkout, null, 2) );
   }
 
  function play_with_samples(){
      
   
      
      const fullscreenButton = document.getElementById('fullscreenButton');

   
            // Create the iframeContainer dynamically
            const iframeContainer = document.createElement('div');
            iframeContainer.style.position = 'fixed';
            iframeContainer.style.top = '0';
            iframeContainer.style.left = '0';
            iframeContainer.style.width = '100%';
            iframeContainer.style.height = '100%';
            iframeContainer.style.backgroundColor = 'white'; // Optional background color
            iframeContainer.style.zIndex = '9999';

            // Add the iframeContainer to the document body
            document.body.appendChild(iframeContainer);

            // Enter full-screen mode
           /* if (iframeContainer.requestFullscreen) {
                iframeContainer.requestFullscreen();
            } else if (iframeContainer.mozRequestFullScreen) {
                iframeContainer.mozRequestFullScreen();
            } else if (iframeContainer.webkitRequestFullscreen) {
                iframeContainer.webkitRequestFullscreen();
            } else if (iframeContainer.msRequestFullscreen) {
                iframeContainer.msRequestFullscreen();
            }
*/
            // Create the iframe element
            const iframe = document.createElement('iframe');
            console.log("added samples",added_samples);
             
     const savedData = localStorage.getItem('samples_samplio'); 
        
        // Check if data exists in Local Storage
        if (savedData !== null) {
            // Parse the saved data (assuming it's JSON)
            cart_added_booster_json = JSON.parse(savedData);
        added_samples = cart_added_booster_json.id;
            // Log the parsed data to the console
            console.log('Saved data 2:', savedData);
        } else {
            console.log('No data found in Local Storage for the specified key.');
        }
 
            iframe.src = '   https://samplio.shopbooster.co/frontend/widgets/selection.php?shop='+Shopify.shop+'&ids='+added_samples;
            iframe.width = '100%';
            iframe.height = '100%';
            iframe.style.border = 'none';

            // Append the iframe to the container
            iframeContainer.appendChild(iframe);
             window.addEventListener('message', (event) => {
                 var EEE = event.data+"";
                if (event.data === 'booster_hideIframe') {
                    // Hide the iframeContainer when a 'hideIframe' message is received
                    if (iframeContainer) {
                        iframeContainer.style.display = 'none';
                    }
                }else if (EEE.startsWith('booster_ids')) {
                    if (iframeContainer) {
                        iframeContainer.style.display = 'none';
                    }
                    idsString = EEE.substring('booster_ids'.length); //strings received from iframe
                    
                    
                    const samplesData = {
            id: idsString 
        };
        
        // Convert userData object to a string using JSON.stringify
        const samples_defined = JSON.stringify(samplesData);
        
        try {
                localStorage.setItem('samples_samplio', samples_defined);
                  console.log(' Samplio:localStorage' , samples_defined);
            } catch (error) {
                console.error('Error removing data from LocalStorage:', error);
                
            }
                    
                    
                    
                    //alert(idsString);
                   available_ids=  document.getElementById('booster_p_ids').value; // all ids user selected
                   
                   
                   //alert( available_ids);
                   in_cart_currently
                  //added_samples = idsString;
                  tttoss = "0";
                  if(idsString!=''){
                      var idsArray = idsString.split(',');
  var inCartArray = in_cart_currently.split(',');

  // Use the filter method to get IDs that are in idsString but not in in_cart_currently
  var resultArray = idsArray.filter(function(id) {
    return !inCartArray.includes(id);
  });

  // Join the resulting array into a comma-separated string
  var new_string = resultArray.join(',');
 
                    addToCart(new_string);
                  }
                    var availableIDsArray = available_ids.split(',');
  var idsArray = idsString.split(',');

  // Use the filter method to get IDs that are in available_ids but not in idsString
  var resultArray = availableIDsArray.filter(function(id) {
    return !idsArray.includes(id);
  });

  // Join the resulting array into a comma-separated string
  var resultString = resultArray.join(',');
  
  var resultArray = resultString.split(',');
  var inCartArray = in_cart_currently.split(',');

  // Use the filter method to get common IDs
 commonIDs = resultArray.filter(function(id) {
    return inCartArray.includes(id);
  });

   resultStringx = commonIDs.join(',');

  if(commonIDs!="" && tttoss == "0"){
      
                    removeFromCart(resultStringx);
  }
                    
                  }
            });
            
         
   
  }
  var tttoss = "0";
var resultStringx = "";
  var commonIDs = "";
var added_samples = '';
var total_samples = 0;

var cart_added_booster= "";
var in_cart_currently = "";
var refsamp = "0";
function refresh_samples(){
   // localStorage.removeItem('samples_samplio');
     //localStorage.setItem('samples_samplio', null);
     total_samples=0;
     console.log('Samples updated');
     
      
    const savedData = localStorage.getItem('samples_samplio'); 
                console.log(savedData);
                // Check if data exists in Local Storage
                if (savedData !== null && savedData!='') {
                    // Parse the saved data (assuming it's JSON)
                    cart_added_booster_json = JSON.parse(savedData);
                cart_added_booster_cart = cart_added_booster_json.id;
                    // Log the parsed data to the console
                    console.log('Saved data control:', savedData);
                    
                    
                    if(cart_added_booster_cart!=""  ){
            
                         start_samples(cart_added_booster_cart);
                            console.log('Samples updated 2 -');
                         return 1;
                            console.log('Samples updated---');
                     } 
                } else {
                    console.log('No data found in Local Storage for the specified key.');
                }
                
              console.log('Samples updatedXX-');  
                
             
            in_cart_currently = "";
            added_samples = "";
          fetch('/cart.js')
            .then(response => response.json())
            .then(cart => {
                cart_added_booster="";
                total_samples=0;
              // Check if the cart is not empty
              if (cart.item_count > 0) {
                  console.log('Removed');
                 let elementsxx = document.querySelectorAll('.samplio_samples');
                
                // Loop through each element and set its display property to "none"
                elementsxx.forEach(elementxx => {
                    elementxx.style.display = 'block';
                });
                // Clear any existing product list
               /* cart.items.forEach(function(item) {
                     total_samples++;
               cart_added_booster=cart_added_booster+""+item.id+",";
                });*/
        var boosterBoxes = document.querySelectorAll('.booster_box');
        
        // Loop through each element and set inner HTML to an empty string
        boosterBoxes.forEach(function(boosterBox) {
          boosterBox.innerHTML = '+';
        });
         
        // Loop through the selected elements
        boosterBoxes.forEach(function (element) {
            
          // Check if the element has the class "booster_box_selected"
          if (element.classList.contains('booster_box_selected')) {
            // Remove the class "booster_box_selected" if it exists
            element.classList.remove('booster_box_selected');
          }
        });
        //start_samples(cart_added_booster);
                // Iterate through each item in the cart and display product details
               cart.items.forEach(function(item) {
                   if (in_cart_currently.indexOf(item.id) === -1) {
                   in_cart_currently += item.id+",";
                   }
                   var iddddd= document.getElementById('booster_p_ids').value;
                    
                   
                   var idsArray = iddddd.split(',');
        
          // Convert item.id to a string for comparison
          var itemIdStr = item.id.toString();
        
         //alert(idsArray);
                   
                   if(idsArray.includes(itemIdStr) && itemIdStr!=""){
                     total_samples++;
                   //alert("--->"+total_samples);
                  if (added_samples.indexOf(item.id) === -1) {
          // Add the ID to added_samples
          added_samples += item.id + ",";
        }
        
        var elementsxxxx = document.getElementsByClassName("booster_container");
        
        // Get the number of elements with the class "exampleClass"
        var numberOfElementsdddxxx = elementsxxxx.length;
        
        for (var ixxx = 0; ixxx < numberOfElementsdddxxx; ixxx++) {
                 document.querySelector('#booster_container-'+ixxx+' .booster_box:nth-child('+total_samples+')').innerHTML = '<img src="'+item.image+'" alt="'+item.id+'"  style="max-width: 100%;max-height: 100%;">';
         var selectedElement = document.querySelector('#booster_container-'+ixxx+' .booster_box:nth-child(' + total_samples + ')');
        
        if (selectedElement) {
          selectedElement.classList.add('booster_box_selected');
        }
        }
         var real_sampelee = document.getElementById('booster_max_samples').value;
        
        var cddddd = document.querySelectorAll('.div_translate_select_progress');
        
        // Loop through each element and set inner HTML to an empty string
        cddddd.forEach(function(cddddd) {
            //alert("xxx");
          cddddd.innerHTML = document.getElementById('translate_select_progress').value.replaceAll( "[chosen]",total_samples).replaceAll("[total]",real_sampelee);
        });
        var bxxx = document.querySelectorAll('.div_translate_selection_footer_title');
        
        // Loop through each element and set inner HTML to an empty string
        bxxx.forEach(function(bxxx) {
            //alert(document.getElementById('translate_selection_footer_title').value);
          bxxx.innerHTML = document.getElementById('translate_selection_footer_title').value.replaceAll( "[chosen]",total_samples).replaceAll("[total]",real_sampelee);
        });
        
        
          console.log('added_samples:', added_samples);
                     console.log('total_samples:', total_samples);
                     console.log('in_cart_currently:', in_cart_currently);
                   }else{
                       
                     
                       
                   }
                   
                    var real_sampelee = document.getElementById('booster_max_samples').value;
        
        var cddddd = document.querySelectorAll('.div_translate_select_progress');
        
        // Loop through each element and set inner HTML to an empty string
        cddddd.forEach(function(cddddd) {
            //alert("xxx");
          cddddd.innerHTML = document.getElementById('translate_select_progress').value.replaceAll( "[chosen]",total_samples).replaceAll("[total]",real_sampelee);
        });
        var bxxx = document.querySelectorAll('.div_translate_selection_footer_title');
        
        // Loop through each element and set inner HTML to an empty string
        bxxx.forEach(function(bxxx) {
            //alert(document.getElementById('translate_selection_footer_title').value);
          bxxx.innerHTML = document.getElementById('translate_selection_footer_title').value.replaceAll( "[chosen]",total_samples).replaceAll("[total]",real_sampelee);
        });
                   
                   
                   
                });
              } else {
                // Display a message if the cart is empty
                 console.log('Removed');
                 let elementsxx = document.querySelectorAll('.samplio_samples');
                
                // Loop through each element and set its display property to "none"
                elementsxx.forEach(elementxx => {
                    elementxx.style.display = 'none';
                });
              }
            })
            .catch(error => {
              console.error('Error fetching cart data:', error);
            });
          
         
         
         
 
 
 
 
 
  
}

let intervalIdrefresh_samples = setInterval(refresh_samples, 2000);
// Function to add multiple items to the Shopify cart from a comma-separated string
function addToCart(idsStringxx) {
    
     const savedData = localStorage.getItem('samples_samplio'); 
        
        // Check if data exists in Local Storage
        if (savedData !== null) {
            // Parse the saved data (assuming it's JSON)
            cart_added_booster_json = JSON.parse(savedData);
        cart_added_booster_cart = cart_added_booster_json.id;
            // Log the parsed data to the console
            console.log('Saved data control:', savedData);
            
            
            if(cart_added_booster_cart!=""  ){
        
                 start_samples(cart_added_booster_cart);
                 return 1;
             } 
        } else {
            console.log('No data found in Local Storage for the specified key.');
        }
    
    
    if(idsStringxx!=''){
         tttoss = "1";
         console.log('Removed');
         let elementsxx = document.querySelectorAll('.samplio_samples');
        
        // Loop through each element and set its display property to "none"
        elementsxx.forEach(elementxx => {
            elementxx.style.display = 'block';
        });
    //alert('added to cart');
  // Split the comma-separated string into an array of product variant IDs
  var productVariantIds = idsStringxx.split(',');

  // Create an array of JSON objects for each item
  var cartItems = productVariantIds.map(productVariantId => ({
    quantity: 1, // Set the quantity for each item (adjust as needed)
    id: Number(productVariantId.trim()) // Trim any leading/trailing spaces
  }));
var filteredCartItems = cartItems.filter(item => item.id !== 0);
  // Send a POST request to the Shopify cart endpoint
  fetch('/cart/add.js', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body:  JSON.stringify({ items: filteredCartItems })
  })
  .then(response => response.json())
  .then(data => {
    // Handle the response data here if needed
    console.log('Items added to cart:', data);
    //alert("added"+idsStringxx);
    if(commonIDs!=""  ){
      
                    removeFromCart(resultStringx);
  }
  if(data.status!='404'){
    refresh_samples();
    
  }else{
        const samplesData = {
            id: idsStringxx 
        };
        
        // Convert userData object to a string using JSON.stringify
        const samples_defined = JSON.stringify(samplesData);
        
        try {
                localStorage.setItem('samples_samplio', samples_defined);
                  console.log(' Samplio:localStorage' , samples_defined);
            } catch (error) {
                console.error('Error removing data from LocalStorage:', error);
                
            }
        
        
              
              console.log(' 404 error', samples_defined);
              const savedData = localStorage.getItem('samples_samplio'); 
        
        // Check if data exists in Local Storage
        if (savedData !== null) {
            // Parse the saved data (assuming it's JSON)
            const parsedData = JSON.parse(savedData);
        start_samples(idsStringxx);
            // Log the parsed data to the console
            console.log('Saved data 1:', parsedData);
        } else {
            console.log('No data found in Local Storage for the specified key.');
        }
        
        
  }
    
    
  })
  .catch(error => {
    console.error('Error adding items to cart:', error);
  });


}
}

 
function removeFromCart(idsStringww) {
    console.log("vvv"+idsStringww);
    
     const savedData = localStorage.getItem('samples_samplio'); 
        
        // Check if data exists in Local Storage
        if (savedData !== null) {
            console.log("vvv"+idsStringww);
        }
    
  if(idsStringww!=''){
  // Split the comma-separated string into an array of IDs
 
 // Replace with your comma-separated variant IDs
var idsArray = idsStringww.split(',');

var itemsToRemove = {};

idsArray.forEach(function(id) {
  // Add each variant ID to itemsToRemove with a quantity of 0 for removal
  itemsToRemove[id] = 0;
});
  
  // Loop through the array and remove each item from the cart
 
  

  // Send a POST request to the Shopify cart endpoint
 fetch('/cart/update.js', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ updates: itemsToRemove })
  })
   .then(function(response) {
    // Check the response status and handle it accordingly
    if (response.ok) {
      console.log('Items removed from the cart.');
       refresh_samples();
    } else {
      console.error('Failed to remove items from the cart.');
    }
  })
  .catch(function(error) {
    console.error('Error:', error);
  });
    // Make an AJAX POST request to remove the item from the cart
    
  }
}

  
 function slideLeft(ii) {
            currentIndex = Math.max(0, currentIndex - 1);
            if(booster_cuee_slider>0){
            booster_cuee_slider--;
            }
            updateSliderPosition(ii);
            
        }

        function slideRight(ii) {
            currentIndex = Math.min(boxCount - visibleBoxCount, currentIndex + 1);
            if(booster_cuee_slider<booster_counter-3){
            booster_cuee_slider++;
            }
            updateSliderPosition(ii);
        }

        function updateSliderPosition(ii=0) {
            const container = document.getElementById('booster_container-'+ii);
            const transformValue = `translateX(-${currentIndex * (100 / visibleBoxCount)}%)`;
            container.style.transform = transformValue;
            updateArrows_booster(ii);
            //alert(booster_cuee_slider+"  /  "+booster_counter);
        }
  
 function updateArrows_booster(ii){ 
     if(booster_cuee_slider==0){
    document.getElementById('booster_left-arrow-'+ii).style.display="none";
     }else{
            document.getElementById('booster_left-arrow-'+ii).style.display="block";
     }
    
     
     
      if(booster_cuee_slider>=booster_counter-3){
      document.getElementById('booster_right-arrow-'+ii).style.display="none"; 
     }else{
        document.getElementById('booster_right-arrow-'+ii).style.display="block";  
     }
     
     if(booster_counter<=3){
      document.getElementById('booster_right-arrow-'+ii).style.display="none"; 
     }
     
     
     
     
 }
  
 
 
 function start_samples(cart_added_booster=""){
    
if(cart_added_booster==""){
     const savedData = localStorage.getItem('samples_samplio'); 
        
        // Check if data exists in Local Storage
        if (savedData !== null) {
            // Parse the saved data (assuming it's JSON)
            cart_added_booster_json = JSON.parse(savedData);
        cart_added_booster = cart_added_booster_json.id;
            // Log the parsed data to the console
            console.log('Saved data 3:', savedData);
        } else {
            console.log('No data found in Local Storage for the specified key.');
        }
 }
xhr.open('GET', '//samplio.shopbooster.co/frontend/widgets/widget.php?shop='+Shopify.shop+"&ids="+cart_added_booster, true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    
 
    var booster_elementsArray = Array.from(document.getElementsByClassName('samplio_samples'));
         
        for (var i = 0; i < booster_elementsArray.length; i++) {
          // Access and manipulate the inner HTML of each element
          //alert("memmememe");
           console.log("elemets:",booster_elementsArray.length);
          booster_elementsArray[i].innerHTML = xhr.responseText.replaceAll("[INDICATOR]",i);
           
           booster_counter = document.getElementById('booster_counter-0').value;    
            boxCount = booster_counter;
            
            
            updateArrows_booster(i);
            
            
        
        }
         if (typeof savedData !== 'undefined' && savedData == null) {
            refresh_samples();
        
        } 
         
 
  
  }
};
xhr.send();

}
if(document.getElementsByClassName('samplio_samples')[0]){


 const savedData = localStorage.getItem('samples_samplio'); 
        
        // Check if data exists in Local Storage
        if (savedData !== null) {
            // Parse the saved data (assuming it's JSON)
            cart_added_booster_json = JSON.parse(savedData);
        cart_added_booster_cart = cart_added_booster_json.id;
            // Log the parsed data to the console
            console.log('Saved data control:', savedData);
            
            
            if(cart_added_booster_cart!="" && refsamp == "0"){
         refsamp  = "1" ;
                 start_samples(cart_added_booster_cart);
           
             } 
        } else {
            start_samples();
            console.log('No data found in Local Storage for the specified key.');
        }
}

// Start observing changes in the entire document


// Function to create elements with class "samplio_samples"
function checkIfDivIsEmptyAndStart() {
    
    const sampleDivs = document.querySelectorAll('.samplio_samples');

    sampleDivs.forEach(div => {
        if (!div.hasChildNodes()) {
            // The div is empty, call the "start" function
            const savedData = localStorage.getItem('samples_samplio'); 
        
        // Check if data exists in Local Storage
        if (savedData !== null) {
            // Parse the saved data (assuming it's JSON)
            cart_added_booster_json = JSON.parse(savedData);
        cart_added_booster = cart_added_booster_json.id;
            // Log the parsed data to the console
            console.log('Saved data - non:', savedData);
        } else {
            console.log('No data found in Local Storage for the specified key.');
            
        }
        start_samples();
        }
    });
    
    
    
}

// Function to be called when the div is empty
function start() {
    console.log('The div with class "samplio_samples" is empty. Starting...');
    // Add your logic here to start something when the div is empty
}


// Call createSampleElements to create the elements initially
//createSampleElements();








// Array of places where the code will be inserted
const insertionPoints = [
    { selector: 'form.cart__drawer-form[method="post"][data-location="header"] .cart__scrollable', position: "prepend" } 
];

// The HTML code to be inserted
const htmlCode = '<div class="samplio_samples"></div>';

// Function to insert the HTML code
function insertHtmlCode(insertionPoints, htmlCode) {
    insertionPoints.forEach(point => {
        const element = document.querySelector(point.selector);

        if (element && !element.querySelector('.samplio_samples')) {
            switch (point.position) {
                case "before":
                    element.insertAdjacentHTML('beforebegin', htmlCode);
                    break;
                case "after":
                    element.insertAdjacentHTML('afterend', htmlCode);
                    break;
                case "append":
                    element.insertAdjacentHTML('beforeend', htmlCode);
                    break;
                case "prepend":
                    element.insertAdjacentHTML('afterbegin', htmlCode);
                    break;
                
                    
                default:
                    console.warn(`Unknown position: ${point.position}`);
            }
        }
    });
    // Call the check function periodically
setInterval(checkIfDivIsEmptyAndStart, 3000);
}

// Call the function to insert the HTML code
insertHtmlCode(insertionPoints, htmlCode);

