document.addEventListener("DOMContentLoaded", function () {
  const navLinks = document.querySelectorAll(".nav-link");
  navLinks.forEach((link) => {
    link.addEventListener("click", function () {
      navLinks.forEach((nav) => nav.classList.remove("active"));
      this.classList.add("active");
    });
  });
});
async function fetchNews(selectedLang) {
  axios
    .get("https://api.sanabel-altatweer.com/news")
    .then(function (response) {
      const isSmallScreen = window.innerWidth < 991;
      if (isSmallScreen) {
        createSliderSmallScreen(response, selectedLang);
      } else {
        createSliderLargeScreen(response, selectedLang);
      }
    })
    .catch(function (error) {
      console.log(error);
    });
}
async function fetchOffers(selectedLang) {
  axios
    .get("https://api.sanabel-altatweer.com/offers")
    .then(function (response) {
      const isSmallScreen = window.innerWidth < 991;
      if (isSmallScreen) {
        createSliderSmallScreenOffer(response, selectedLang);
      } else {
        createSliderLargeScreenOffer(response, selectedLang);
      }
    })
    .catch(function (error) {
      console.log(error);
    });
}
async function fetchPartners(selectedLang) {
  axios
    .get("https://api.sanabel-altatweer.com/partner")
    .then(function (response) {
      const isSmallScreen = window.innerWidth < 991;
      if (isSmallScreen) {
        createSliderSmallScreenPartners(response);
      } else {
        createSliderLargeScreenPartners(response);
      }
    })
    .catch(function (error) {
      console.log(error);
    });
}
function createSliderLargeScreen(response, selectedLang) {
  const carouselContent = document.getElementById("carousel-content");

  let carouselItem = document.createElement("div");
  carouselItem.className = "carousel-item active";

  let newsRow = document.createElement("div");
  newsRow.className = "row row-news justify-content-center";

  let count = 0;
  const filteredNews = response.data.filter(
    (news) => news.lang === selectedLang
  );
  if (filteredNews.length <= 3) {
    const nextBtn = document.getElementById("news-next-btn");
    const prevBtn = document.getElementById("news-prev-btn");
    nextBtn.remove();
    prevBtn.remove();
  }
  if (!Array.isArray(filteredNews)) {
    filteredNews = [filteredNews];
  }
  console.log("filternews", filteredNews);
  filteredNews.map((news, index) => {
    // Create the card elements
    const colMdDiv = document.createElement("div");
    colMdDiv.className = "col-md-4";

    const cardDiv = document.createElement("div");
    cardDiv.className = "card";

    const cardImg = document.createElement("img");
    cardImg.className = "card-img-top";
    cardImg.alt = "News Picture";
    cardImg.src = `${news.image.replace("http:", "http://")}`;

    const cardBody = document.createElement("div");
    cardBody.className = "card-body text-center";

    const cardTitle = document.createElement("h5");
    cardTitle.className = "card-title";
    cardTitle.innerHTML = truncate(news.title,36);

    const cardText = document.createElement("p");
    cardText.className = "card-text";
    cardText.innerHTML = truncate(htmlToText(news.description.article), 60);

    const readMoreButton = document.createElement("button");
    readMoreButton.className = "btn rounded-pill w-100";
    if (news.lang === "AR") {
      readMoreButton.innerHTML = "اقرأ المزيد";
    }
    if (news.lang === "ENG") {
      readMoreButton.innerHTML = "Read More";
      readMoreButton.style = "color: white;";
    }
    readMoreButton.onclick = function () {
      if (news.lang === "AR") {
        const newsString = JSON.stringify(news);
        goToArticleAr(newsString);
      }
      if (news.lang === "ENG") {
        const newsString = JSON.stringify(news);
        goToArticleEn(newsString);
      }
    };

    // Append card elements
    cardBody.appendChild(cardTitle);
    cardBody.appendChild(cardText);
    cardBody.appendChild(readMoreButton);
    cardDiv.appendChild(cardImg);
    cardDiv.appendChild(cardBody);
    colMdDiv.appendChild(cardDiv);
    newsRow.appendChild(colMdDiv);

    count++;

    // If 3 news cards are added to the current carousel item or it's the last news item
    if (count === 3 || index === filteredNews.length - 1) {
      carouselItem.appendChild(newsRow);
      carouselContent.appendChild(carouselItem);

      // Reset count and create new carousel item and row for the next set of news
      count = 0;

      if (index !== filteredNews.length - 1) {
        carouselItem = document.createElement("div");
        carouselItem.className = "carousel-item";

        newsRow = document.createElement("div");
        newsRow.className = "row row-news justify-content-center";
      }
    }
  });
}
function createSliderSmallScreen(response, selectedLang) {
  const carouselContent = document.getElementById("carousel-content");
  let count = 0;
  const filteredNews = response.data.filter(
    (news) => news.lang === selectedLang
  );
  if (filteredNews.length <= 1) {
    const nextBtn = document.getElementById("news-next-btn");
    const prevBtn = document.getElementById("news-prev-btn");
    nextBtn.remove();
    prevBtn.remove();
  }
  response.data
    .filter((news) => news.lang === selectedLang)
    .map((news, index) => {
      let carouselItem = document.createElement("div");
      if (index === 0) {
        carouselItem.className = "carousel-item active";
      } else {
        carouselItem.className = "carousel-item";
      }

      let newsRow = document.createElement("div");
      newsRow.className = "row row-news justify-content-center";
      // Create the card elements
      const colMdDiv = document.createElement("div");
      colMdDiv.className = "col-md-4";

      const cardDiv = document.createElement("div");
      cardDiv.className = "card";

      const cardImg = document.createElement("img");
      cardImg.className = "card-img-top";
      cardImg.src = `${news.image.replace("http:", "http://")}`;

      const cardBody = document.createElement("div");
      cardBody.className = "card-body text-center";

      const cardTitle = document.createElement("h5");
      cardTitle.className = "card-title";
      cardTitle.innerHTML = truncate(news.title,25);

      const cardText = document.createElement("p");
      cardText.className = "card-text";
      cardText.innerHTML = truncate(htmlToText(news.description.article), 60);

      const readMoreButton = document.createElement("button");
      readMoreButton.className = "btn rounded-pill w-100";
      if (news.lang === "AR") {
        readMoreButton.innerHTML = "اقرأ المزيد";
      }
      if (news.lang === "ENG") {
        readMoreButton.innerHTML = "Read More";
        readMoreButton.style = "color: white;";
      }
      readMoreButton.onclick = function () {
        if (news.lang === "AR") {
          const newsString = JSON.stringify(news);
          goToArticleAr(newsString);
        }
        if (news.lang === "ENG") {
          const newsString = JSON.stringify(news);
          goToArticleEn(newsString);
        }
      };
      cardBody.appendChild(cardTitle);
      cardBody.appendChild(cardText);
      cardBody.appendChild(readMoreButton);
      cardDiv.appendChild(cardImg);
      cardDiv.appendChild(cardBody);
      colMdDiv.appendChild(cardDiv);
      newsRow.appendChild(colMdDiv);
      carouselItem.appendChild(newsRow);
      carouselContent.appendChild(carouselItem);
    });
}
function createSliderLargeScreenOffer(response, selectedLang) {
  const carouselContent = document.getElementById("carousel-content-offers");

  let carouselItem = document.createElement("div");
  carouselItem.className = "carousel-item active";

  let newsRow = document.createElement("div");
  newsRow.className = "row row-news justify-content-center";

  let count = 0;
  console.log(response);
  const filteredNews = response.data.filter(
    (news) => news.lang === selectedLang
  );
  if (filteredNews.length <= 3) {
    const nextBtn = document.getElementById("offers-next-btn");
    const prevBtn = document.getElementById("offers-prev-btn");
    nextBtn.remove();
    prevBtn.remove();
  }
  console.log(filteredNews);
  response.data
    .filter((news) => news.lang === selectedLang)
    .map((news, index) => {
      // Create the card elements
      const colMdDiv = document.createElement("div");
      colMdDiv.className = "col-md-4";

      const cardDiv = document.createElement("div");
      cardDiv.className = "card";

      const cardImg = document.createElement("img");
      cardImg.className = "card-img-top";
      cardImg.src = `${news.image.replace("http:", "http://")}`;

      const cardBody = document.createElement("div");
      cardBody.className = "card-body text-center";

      const cardTitle = document.createElement("h5");
      cardTitle.className = "card-title";
      cardTitle.innerHTML = truncate(news.title,36);

      const cardText = document.createElement("p");
      cardText.className = "card-text";
      cardText.innerHTML = truncate(htmlToText(news.description.article), 60);

      const readMoreButton = document.createElement("button");
      readMoreButton.className = "btn rounded-pill w-100";
      if (news.lang === "AR") {
        readMoreButton.innerHTML = "اقرأ المزيد";
      }
      if (news.lang === "ENG") {
        readMoreButton.innerHTML = "Read More";
        readMoreButton.style = "color: white;";
      }
      readMoreButton.onclick = function () {
        if (news.lang === "AR") {
          const newsString = JSON.stringify(news);
          goToArticleAr(newsString);
        }
        if (news.lang === "ENG") {
          const newsString = JSON.stringify(news);
          goToArticleEn(newsString);
        }
      };

      // Append card elements
      cardBody.appendChild(cardTitle);
      cardBody.appendChild(cardText);
      cardBody.appendChild(readMoreButton);
      cardDiv.appendChild(cardImg);
      cardDiv.appendChild(cardBody);
      colMdDiv.appendChild(cardDiv);
      newsRow.appendChild(colMdDiv);
      console.log(newsRow);
      count++;
      // If 3 news cards are added to the current carousel item or it's the last news item
      if (count === 3 || index === filteredNews.length - 1) {
        carouselItem.appendChild(newsRow);
        carouselContent.appendChild(carouselItem);

        // Reset count and create new carousel item and row for the next set of news
        count = 0;

        if (index !== filteredNews.length - 1) {
          carouselItem = document.createElement("div");
          carouselItem.className = "carousel-item";

          newsRow = document.createElement("div");
          newsRow.className = "row row-news justify-content-center";
        }
      }
    });
}
function createSliderSmallScreenOffer(response, selectedLang) {
  const carouselContent = document.getElementById("carousel-content-offers");
  let count = 0;
  const filteredNews = response.data.filter(
    (news) => news.lang === selectedLang
  );
  if (filteredNews.length <= 1) {
    const nextBtn = document.getElementById("offers-next-btn");
    const prevBtn = document.getElementById("offers-prev-btn");
    nextBtn.remove();
    prevBtn.remove();
  }
  filteredNews.map((news, index) => {
    let carouselItem = document.createElement("div");
    if (index === 0) {
      carouselItem.className = "carousel-item active";
    } else {
      carouselItem.className = "carousel-item";
    }

    let newsRow = document.createElement("div");
    newsRow.className = "row row-news justify-content-center";
    // Create the card elements
    const colMdDiv = document.createElement("div");
    colMdDiv.className = "col-md-4";

    const cardDiv = document.createElement("div");
    cardDiv.className = "card";

    const cardImg = document.createElement("img");
    cardImg.className = "card-img-top";
    cardImg.src = `${news.image.replace("http:", "http://")}`;

    const cardBody = document.createElement("div");
    cardBody.className = "card-body text-center";

    const cardTitle = document.createElement("h5");
    cardTitle.className = "card-title";
    cardTitle.innerHTML = truncate(news.title,25)

    const cardText = document.createElement("p");
    cardText.className = "card-text";
    cardText.innerHTML = truncate(htmlToText(news.description.article), 60);

    const readMoreButton = document.createElement("button");
    readMoreButton.className = "btn rounded-pill w-100";
    if (news.lang === "AR") {
      readMoreButton.innerHTML = "اقرأ المزيد";
    }
    if (news.lang === "ENG") {
      readMoreButton.innerHTML = "Read More";
      readMoreButton.style = "color: white;";
    }
    readMoreButton.onclick = function () {
      if (news.lang === "AR") {
        const newsString = JSON.stringify(news);
        goToArticleAr(newsString);
      }
      if (news.lang === "ENG") {
        const newsString = JSON.stringify(news);
        goToArticleEn(newsString);
      }
    };
    cardBody.appendChild(cardTitle);
    cardBody.appendChild(cardText);
    cardBody.appendChild(readMoreButton);
    cardDiv.appendChild(cardImg);
    cardDiv.appendChild(cardBody);
    colMdDiv.appendChild(cardDiv);
    newsRow.appendChild(colMdDiv);
    carouselItem.appendChild(newsRow);
    carouselContent.appendChild(carouselItem);
  });
}
function createSliderLargeScreenPartners(response) {
  // Select the carousel content container
  const carouselContentPartners = document.getElementById(
    "carousel-content-partners"
  );

  let slide;
  let active = true;
  if (response.data.length <= 4) {
    const nextBtn = document.getElementById("partners-next-btn");
    const prevBtn = document.getElementById("partners-prev-btn");
    nextBtn.remove();
    prevBtn.remove();
  }
  // Loop over the partner data
  response.data.forEach((partner, index) => {
    // Create a new slide for each 4 logos
    if (index % 4 === 0) {
      slide = document.createElement("div");
      slide.classList.add("carousel-item");

      // Set the first slide as active
      if (active) {
        slide.classList.add("active");
        active = false;
      }

      const row = document.createElement("div");
      row.classList.add("images-row");
      slide.appendChild(row);
      carouselContentPartners.appendChild(slide);
    }

    // Create the column div for the logos
    const col = document.createElement("div");
    col.classList.add("images-row");
    const logoLink = document.createElement("a");
    logoLink.href = partner.link;
    const logoImg = document.createElement("img");
    logoImg.classList.add("logo-img");
    logoImg.src = `${partner.image.replace("http:", "http://")}`;
    logoImg.alt = partner.name;

    logoLink.appendChild(logoImg);
    col.appendChild(logoLink);

    // Append the column to the current slide
    slide.querySelector(".images-row").appendChild(logoLink);
  });
}
function createSliderSmallScreenPartners(response) {
  const carouselContentPartners = document.getElementById(
    "carousel-content-partners"
  );

  let active = true;

  // Loop over the partner data
  response.data.forEach((partner) => {
    // Create a new carousel-item for each logo
    const slide = document.createElement("div");
    slide.classList.add("carousel-item");

    // Set the first slide as active
    if (active) {
      slide.classList.add("active");
      active = false;
    }

    const row = document.createElement("div");
    row.classList.add("row", "justify-content-center");
    row.style = "display: flex; flex-direction: row; justify-content: center;";
    slide.appendChild(row);

    // Create the image element for the logo
    const logoImg = document.createElement("img");
    logoImg.classList.add("logo-img");
    logoImg.src = `${partner.image.replace("http:", "http://")}`;
    logoImg.alt = partner.name;

    // Optionally wrap the image in a link
    const logoLink = document.createElement("a");
    logoLink.href = partner.link;
    logoLink.appendChild(logoImg);
    row.appendChild(logoImg);

    // Append the slide to the carousel content
    carouselContentPartners.appendChild(slide);
  });
}
function sendContactMessage(lang) {
  const contactName = document.getElementById("contactName");
  const contactPhone = document.getElementById("contactPhone");
  const contactEmail = document.getElementById("contactEmail");
  const contactMessage = document.getElementById("contactMessage");

  const contactNameValue = contactName.value;
  const contactPhoneValue = contactPhone.value;
  const contactMessageValue = contactMessage.value;
  const contactEmailValue = contactEmail.value;

  axios
    .post("https://api.sanabel-altatweer.com/customer", {
      name: contactNameValue,
      phone: contactPhoneValue,
      email: contactEmailValue,
      message: contactMessageValue,
    })
    .then(function () {
      if (lang === "AR") {
        Swal.fire({
          icon: "success",
          title: "تم ارسال الأستفسار.",
          text: "شكرا لتواصلكم معنا!",
          confirmButtonColor: "#db792e",
        }).then((result) => {
          if (result.isConfirmed) {
            location.reload();
          }
        });
      }
      if (lang === "ENG") {
        Swal.fire({
          icon: "success",
          title: "Your inquiry has been sent.",
          text: "Thank you for contacting us!",
          confirmButtonColor: "#db792e",
        }).then((result) => {
          if (result.isConfirmed) {
            location.reload();
          }
        });
      }
    })
    .catch(function (error) {
      console.log(error);
      if (lang === "AR") {
        Swal.fire({
          icon: "error",
          title: "حدث خطأ",
          text: "حدث خطأ ما, من فضلك حاول مرة اخرى",
          confirmButtonColor: "#db792e",
        });
      }
      if (lang === "ENG") {
        Swal.fire({
          icon: "error",
          title: "An Error has occurred!",
          text: "Please Try again later.",
          confirmButtonColor: "#db792e",
        });
      }
    });
}
function htmlToText(html) {
  // Create a temporary DOM element to parse the HTML
  const tempElement = document.createElement("div");

  // Set the HTML content
  tempElement.innerHTML = html;

  // Return the text content (removes HTML tags)
  return tempElement.textContent || tempElement.innerText || "";
}
function goToArticleAr(item) {
  localStorage.setItem("news", item);
  window.location.href = "/html/mainArticleAr.html";
}
function goToArticleEn(item) {
  localStorage.setItem("news", item);
  window.location.href = "/html/mainArticleEn.html";
}
function truncate(string, number) {
  if (string.length > number) {
    var newstring = string.slice(0, number);
    newstring += "...";
    return newstring;
  } else {
    return string;
  }
}
