var currentPageNumber = 1; // initialization before all functions
var dataAvailable = true;

$(function () {
  get_product_list(null, currentPageNumber);
  $(window).scroll(async function () {
    if (dataAvailable == true) {
      if (
        $(window).scrollTop() + 105 >=
        $(document).height() - $(window).height()
      ) {
        currentPageNumber++;
        await get_product_list(null, currentPageNumber);
      }
    }
  });
});

const storedPixelId = sessionStorage.getItem("facebook_pixel_id");

// Facebook Pixel script
!(function (f, b, e, v, n, t, s) {
  if (f.fbq) return;
  n = f.fbq = function () {
    n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
  };
  if (!f._fbq) f._fbq = n;
  n.push = n;
  n.loaded = !0;
  n.version = "2.0";
  n.queue = [];
  t = b.createElement(e);
  t.async = !0;
  t.src = v;
  s = b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t, s);
})(window, document, "script", "../connect.facebook.net/en_US/fbevents.js");
fbq("init", storedPixelId); // Your Pixel ID
fbq("track", "PageView"); // Track the PageView event

async function get_product_list(data, currentPageNumber) {
  if (data && data != null && data.status == true) {
    var productData = data.data;
    var html = "";
    var i = 1;
    productData.forEach(function (value) {
      if (i % 2 != 0) {
        html += `<tr>`;
      }
      const randomRating = (Math.random() * (5 - 3) + 3).toFixed(1);
      const randomRatingNumber =
        Math.floor(Math.random() * (2000 - 1600 + 1)) + 1600;

      const filledStars = Math.floor(randomRating);
      const halfStar = randomRating - filledStars >= 0.5 ? 1 : 0;
      const emptyStars = 5 - (filledStars + halfStar);

      let starsHtml = "";

      // Add filled stars
      for (let j = 0; j < filledStars; j++) {
        starsHtml += `<i class='fa fa-star' style='font-size:18px;color:#008C00'></i>`;
      }

      // Add half star if applicable
      if (halfStar) {
        starsHtml += `<i class='fa fa-star-half-o' style='font-size:18px;color:#008C00'></i>`;
      }

      // Add empty stars
      for (let j = 0; j < emptyStars; j++) {
        starsHtml += `<i class='fa fa-star-o' style='font-size:18px;color:#008C00'></i>`;
      }

      let imgUrl = value.img1; // Assuming `value.img1` contains the image URL

      // Dynamically generate a set of image sizes based on the original image
      let imgSrcset = `${imgUrl.replace("1400x", "500x")} 500w, 
                             ${imgUrl.replace("1400x", "800x")} 800w, 
                             ${imgUrl} 1400w`;

      html += `<td class="Cs7ycL TcKeCe">
                         <a href="product-details/${
                           value.md5_id
                         }&q=${randomRatingNumber}">
                            <div class="_2enssu">
                                <div style="position:relative;min-height:171.5px;min-width:141px">
                                    <div class="_3LXIRu">
                                        <div class="_2GaeWJ" style="width: 171.5px; height: 176px;">
                                          <picture>
                            <source srcset="${imgUrl.replace(
                              "1400x",
                              "500x"
                            )}" type="image/webp">
                                               <img   
                        class="_2puWtW _3a3qyb"   
                        src="${imgUrl}"   
                        alt="Product Image"   
                        srcset="${imgSrcset}"   
                        sizes="(max-width: 600px) 500px, (max-width: 1000px) 800px, 1400px"   
                        width="1400"   
                        height="800"> 
                        </picture>
                                        </div>
                                    </div>
                                </div>
                                <div class="_24B_AU _3SexMn" style='color:#0F1111;'>${
                                  value.name
                                }</div>
                                
                                <div class="_24B_AU _1AQnZC" style='margin:5px 0px'>
                                    <svg width="16" height="16" viewBox="0 0 12 12" fill="none" style='margin-top:-4px;'>
                                    <path d="M6.73461 1V8.46236L9.5535 5.63352L10.5876 6.65767L5.99384 11.2415L1.41003 6.65767L2.42424 5.63352L5.25307 8.46236V1H6.73461Z" fill="#008C00">
                                    </path></svg> 
                                    
                                    <span style='font-size: 14px;
                                    margin-left:-4px;
                                        line-height: 20px;
                                        font-weight:600;
                                        letter-spacing: -0.01px;
                                        color: rgb(0, 140, 0);'>${
                                          100 -
                                          (
                                            (value.selling_price * 100) /
                                            value.mrp
                                          ).toFixed(0)
                                        }%</span>
                                    <span class="mrp" style="font-family: 'CustomFont', Arial, sans-serif;font-size:14px;">₹${
                                      value.mrp
                                    }</span>
                                    <b class="selling-price" style='color:#212529; font-size: 15px; line-height: 20px; letter-spacing: -0.01px; margin-bottom: 2px;'>₹${
                                      value.selling_price
                                    }</b>
                                </div>
                                <div style="border-radius: 2px; overflow: hidden; padding: 2px 10px; display: flex; justify-content: space-between; align-items: center;">  
                                     <p style="float: left; background-color: #c7ffd3; font-size: 12px; color: rgb(38, 165, 65); font-weight: 600; padding: 2px 6px; margin: 0; margin-right: 10px;">  
                                         Hot Deal  
                                      </p>  
                                 <div class="m_trusted" style="float: right;">  
                                      <img src= "https://rukminim2.flixcart.com/www/120/32/promos/25/06/2024/71af54bd-9160-41ff-81cc-c55e534dedeb.png?q=60" alt="Trusted Icon" style="height: 20px;">  
                                  </div>  
                                  </div>
                                   <div style='margin-top:8px;'>
                                    <div style='display: flex; align-items: center;'>
                                        ${starsHtml}&nbsp;<span style="font-size:13px!important;color:gray!important">${randomRatingNumber}<span> Ratings </span> &nbsp; </span>
                                    </div>
                                    
                                </div>
                                 
                               
                                <div style='color:#26A541;font-size: 13px;text-align:center;padding-top:5px'>Free Delivery</div>
                               
                            </div>
                  </a>
                    </td>`;
      if (i % 2 == 0) {
        html += `</tr>`;
      }
      i++;
    });
    if (currentPageNumber == 1) {
      $("#home_page_product").html(html);
    } else {
      $("#home_page_product").append(html);
    }
    $("#home_page_product .scaling-circle").remove();
    return false;
  } else if (data && data != null && data.status == false) {
    if (currentPageNumber == 1) {
      $("#home_page_product").html(
        "<h1 class='no-data-found'>" + data.message + "</h1>"
      );
    }
    $("#home_page_product .scaling-circle").remove();
    dataAvailable = false;
    return false;
  } else if (!data) {
    $("#home_page_product").append(getLoader());
    var length = 10;
    var start = (currentPageNumber - 1) * length;
    var req_data = {
      op: "get_products",
      page: currentPageNumber,
      start: start,
      length: length,
    };
    doAPICall(req_data, function (res) {
      get_product_list(res, currentPageNumber);
    });
  }
  return false;
}

// Function to track pixel event and redirect user
function trackPixelAndRedirect(md5_id) {
  // Track the AddToCart event
  fbq("track", "AddToCart", {
    content_ids: [md5_id],
    content_type: "product",
    value: 0, // You can add a dynamic price if you want
    currency: "INR",
  });

  // Delay the redirect slightly to ensure the pixel event is sent
  setTimeout(function () {
    window.location.href =
      ("product-details/" + encodeURIComponent(md5_id)) &
      ("q=" + randomRatingNumber);
  }, 500); // 500ms delay before redirecting
}
