let sliderData;
const sliderContainer = document.querySelector(".lp-01-teacher-mask");

const teacherUrl =
  "https://services.shvasa.com/api/counselling/consultant/teacher";

// To get all teachers data
const fetchDetails = async function (url) {
  try {
    const response = await fetch(url, {
      method: "GET",
    });
    const data = await response.json();
    sliderData = data.body;
    console.log(data);
    return data;
  } catch (error) {
    console.error("There is some error while fetching slider data", error);
    throw error;
  }
};

// To create a single filter array
const constructArray = function () {
  const dataWithCertification = sliderData.filter(
    (data) => data?.certification.length > 0
  );
  const dataWithoutCertification = sliderData.filter(
    (data) => data?.certification.length === 0
  );
  return dataWithCertification.concat(dataWithoutCertification);
};

// Function returns filtered array
const generateSingleArray = async function () {
  await fetchDetails(teacherUrl);
  const mergedArray = constructArray();
  return mergedArray;
};

// Initialize Webflow slider after adding slides
const initializeWebflowSlider = function () {
  Webflow.require("slider").redraw();
};

const forEachArray = async function (array) {
  array.forEach((data, i, arr) => {
    if (data?.name === "Jiraiya Sensei") return;
    const expertise = data.style[0].toLowerCase();
    const expertiseArr = expertise.split("_");
    //console.log(expertiseArr);
    const expertiseStr = expertiseArr
      .map((word) => {
        //const firstLetter = word.at(0);
        //const firstLetterCap = firstLetter.toUpperCase();
        const updatedWord = word.replace(word.at(0), word.at(0).toUpperCase());
        return updatedWord;
      })
      .join(" ");
    console.log("%c output", "color:red; font-weight:bold ", expertiseStr);

    const html = `<div class="lp-01-teacher-slide w-slide" aria-label="${
      i + 1
    } of ${arr.length}" role="group"
    style="transform: translateX(0px); opacity: 1; transition: transform 500ms ease 0s;">
    <div class="lp-01-teacher-slider-components-wrapper">
        <div class="lp-teacher-slider-image-wrapper"><img
                src=${data?.imageURL?.thumbNailImages}
                loading="lazy" alt="" class="lp-teacher-slider-image"></div>
        <div class="lp-teachers-text-wrapper">
            <div class="lp-01-teacher-name-designation-wrapper">
                    <div class="lp-01-teacher-name-wrapper">
                    <div class="text-1">${data?.name}</div>
                    <div class="lp-01-para-1">${
                      data?.certification[0] || ""
                    }</div>
                </div>
            </div>
            <div class="lp-01-teacher-rating-2">
                <div class="students-coached">8 Years of experience</div><img
                    src="https://assets-global.website-files.com/60e7f6b5ecd3ae8e0c125cd7/6596dd631273477ad5595a25_%E2%AD%90.webp"
                    loading="lazy" alt="" class="lp-01-teacher-rating-star">
                <div>${data.avgRating} stars</div>
            </div>
            <div class="lp-01-teacher-slide-speciality-text-wrappper">
                <div class="students-coached">8 Years of experience</div>
                <div>${expertiseStr}</div>
            </div>
            <div class="lp-01-teacher-slide-bottom-text-wrappper">
                <div class="students-coached">8 Years of experience</div>
                <div>${data.yearsOfExp} Years of experience</div>
            </div>
        </div>
    </div>
</div>`;
    sliderContainer.insertAdjacentHTML("afterbegin", html);
  });
};

const generateSlides = async () => {
  try {
    // Clear the container before inserting new content
    sliderContainer.innerHTML = "";
    const mergedArray = await generateSingleArray();
    await forEachArray(mergedArray);
    // Set a timeout to ensure that the slides are added before initializing the slider
    setTimeout(initializeWebflowSlider, 1000);
  } catch (error) {
    console.error("Error in getting result:", error);
  }
};

generateSlides();

// Target element you want to observe
const targetElement = document.getElementById('teacher-slides');

// Options for the Intersection Observer
const options = {
  root: null, // Use the viewport as the root
  rootMargin: '0px', // No margin
  threshold: 0.5, // Trigger when 50% of the element is visible
};

// Callback function to be executed when the intersection changes
const callback = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // Your code to be triggered when the section is about to be in view
      console.log('Section is about to be in view');
      window.dispatchEvent(new Event("resize"));
      
      // Remove the observer if you only want to trigger it once
      //observer.unobserve(entry.target);
    }
  });
};

// Create an Intersection Observer with the callback and options
const observer = new IntersectionObserver(callback, options);

// Start observing the target element
observer.observe(targetElement);