var salesIQFieldsArray = [
  { formFieldName: "Email", formFieldType: 9, salesIQFieldName: "Email" },
];

function obtenerValoresFormulario() {
  const formulario = document.getElementById('contacto');
  const inputs = formulario.getElementsByTagName('input');
  const valores = {};

  for (let input of inputs) {
    if (input.type !== 'submit') {
      valores[input.name] = input.value;
    }
  }

  return valores;
}

// Enviar los valores del formulario a través de dataLayer
function enviarValoresDataLayer() {
  const valoresFormulario = obtenerValoresFormulario();
  gtag('event', 'lead_submit', {...valoresFormulario});
}

function zf_validateandsubmitdata() {
  const visitorinfo = {};
  enviarValoresDataLayer();

  var elements = document.getElementById("form").elements;
  for (var elmIdx = 0; elmIdx < elements.length; elmIdx++) {
    var inpElem = elements[elmIdx];
    var fieldLinkName = inpElem.getAttribute("name");
    var fieldType = inpElem.getAttribute("fieldType");
    if (
      fieldType === "1" ||
      fieldType === "7" ||
      fieldType === "9" ||
      fieldType === "11"
    ) {
      for (var idx = 0; idx < salesIQFieldsArray.length; idx++) {
        var salesIQObj = salesIQFieldsArray[idx];
        var zfFieldName = salesIQObj.formFieldName;
        var salesIQFieldName = salesIQObj.salesIQFieldName;
        if (fieldType === "1") {
          if (fieldLinkName === zfFieldName) {
            var salesIQValue = inpElem.value;
            if (salesIQFieldName === "Phone") {
              visitorinfo.contactnumber = salesIQValue;
            }
            if (salesIQFieldName === "Name") {
              visitorinfo.name = salesIQValue;
            }
          }
        }
        if (fieldType === "7") {
          var zfFldCompLinkName = salesIQObj.fieldCompLinkName;
          if (fieldLinkName === zfFldCompLinkName) {
            var salesIQValue = inpElem.value;
            visitorinfo.name = salesIQValue;
          }
        }
        if (fieldType === "9") {
          if (fieldLinkName === zfFieldName) {
            var salesIQValue = inpElem.value;
            visitorinfo.email = salesIQValue;
          }
        }
        if (fieldType === "11") {
          fieldLinkName = inpElem.getAttribute("compname");
          if (fieldLinkName === zfFieldName) {
            var phoneFormat = inpElem.getAttribute("phoneFormat");
            var salesIQValue = "";
            if (phoneFormat === "1") {
              salesIQValue = document.getElementById(
                "international_" + fieldLinkName + "_countrycode"
              ).value;
              var isCodeEnabled = inpElem.getAttribute("isCountryCodeEnabled");
              if (
                isCodeEnabled === "true" &&
                salesIQValue != null &&
                salesIQValue != ""
              ) {
                salesIQValue =
                  document.getElementById(
                    "international_" + fieldLinkName + "_countrycodeval"
                  ).value + salesIQValue;
              }
            } else if (phoneFormat === "2") {
              var countryCode = document.getElementById(
                fieldLinkName + "_countrycode"
              ).value;
              var first = document.getElementById(
                fieldLinkName + "_first"
              ).value;
              var last = document.getElementById(
                fieldLinkName + "_second"
              ).value;
              salesIQValue = countryCode + first + last;
            }
            visitorinfo.contactnumber = salesIQValue;
          }
        }
      }
    }
  }
  parent.postMessage(
    JSON.stringify({ type: "zoho.salesiq.apimessage", visitor: visitorinfo }),
    "*"
  ); // No I18N
}

function watchAnimations() {
  const elements = document.querySelectorAll(".animate__animated");
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const el = entry.target;
          const animatedClasses = el.dataset.animated.split(" ") || [];
          const delay = el.dataset.animationDelay || "2s";

          el.style.setProperty("--animate-duration", delay);
          animatedClasses.forEach((cls) => el.classList.add(cls));
          el.classList.add("load");
          observer.unobserve(el);
        }
      });
    },
    {
      threshold: 0.1,
    }
  );

  elements.forEach((el) => observer.observe(el));
}

window.addEventListener("scroll", () => {
  if (window.scrollY > 200) {
    document.querySelector(".footerblack").classList.add("show");
  } else {
    document.querySelector(".footerblack").classList.remove("show");
  }
});

(() => {
  const handlers = document.querySelectorAll(".gallery");
  const $gallery = document.getElementById("uiGallery");
  const $closer = document.getElementById("galleryCloseButton");
  const gallerySlider = document.querySelector(".gallery-slider");
  const $next = $gallery.querySelector("#nextBtn");
  const $prev = $gallery.querySelector("#prevBtn");

  watchAnimations();

  $closer.addEventListener("click", function () {
    $gallery.classList.remove("show");
    document.body.style.overflow = "initial";
    gallerySlider.innerHTML = "";
  });

  handlers.forEach((handler) => {
    handler.addEventListener("click", async function () {
      console.log("entro");
      const typeGallery = this.dataset.gallery || null;

      if (typeGallery) {
        const response = await fetch(`./${typeGallery}.json?v=2.0`);
        const gallery = await response.json();
        createGallery(gallery.images);
      }
    });
  });

  async function createGallery(images) {
    const renderGallery = await renderSlide(images);

    if (renderGallery) {
      gallerySlider.style.marginLeft = `0`;
      $gallery.classList.add("show");
      document.body.style.overflow = "hidden";
      initSliderEvents();
    }
  }

  function initSliderEvents() {
    const pictures = $gallery.querySelectorAll("picture");

    $gallery.querySelector("picture").classList.add("active");

    let count = 0;
    const limit = pictures.length;

    $next.addEventListener("click", function () {
      count = count - 1 > 0 ? count - 1 : 0;
      updateGallery(pictures, count);
    });
    $prev.addEventListener("click", function () {
      count = count + 1 < limit ? count + 1 : limit - 1;
      updateGallery(pictures, count);
    });

    if (pictures.length > 1) {
      $next.style.display = "none";
      $prev.style.display = "inline-flex";
    } else {
      $next.style.display = "none";
      $prev.style.display = "none";
    }
  }

  function updateGallery(pictures, index) {
    pictures.forEach((picture) => {
      if (+picture.dataset.index === +index) {
        picture.classList.add("active");
      } else {
        picture.classList.remove("active");
      }

      gallerySlider.style.marginLeft = `-${index}00%`;

      index === 0 && ($next.style.display = "none");
      index !== 0 && ($next.style.display = "inline-flex");
      index === pictures.length - 1 && ($prev.style.display = "none");
      index !== pictures.length - 1 && ($prev.style.display = "inline-flex");
    });
  }

  async function renderSlide(images) {
    return new Promise((resolve, reject) => {
      const limit = images.length;

      let elements = "";
      images.forEach((image, index) => {
        elements += `
            <picture data-index=${index} class="flex items:center justify:center">
                <img loading="lazy" src="${image}" width=1 height=1 alt="preview image">
            </picture>
          `;
      });

      gallerySlider.innerHTML = elements;
      gallerySlider.style.minWidth = `${limit}00%`;

      setTimeout(() => {
        resolve(true);
      }, 1000);
    });
  }

  // popup

  const closePop = document.getElementById("closePop");
  const popup247 = document.querySelector(".aviso-nom247");
  closePop.addEventListener(
    "click",
    function () {
      popup247.classList.add("hide");
    },
    true
  );

  window.addEventListener("scroll", function () {
    let headerHeight = document.querySelector(".home").offsetHeight;
    let footerblack = document.querySelector(".footerblack");

    if (window.pageYOffset > headerHeight) {
      footerblack.style.display = "block";
    } else {
      footerblack.style.display = "none";
    }
  });

  window.addEventListener("scroll", function () {
    let button = document.querySelector(".whatsapp-button");
    let scrollPosition =
      window.pageYOffset || document.documentElement.scrollTop;

    if (scrollPosition > 250) {
      button.style.opacity = "1";
    } else {
      button.style.opacity = "0";
    }
  });

  function scrollToContact() {
    const contactoSection = document.getElementById("prefooter");
    contactoSection.scrollIntoView({
      behavior: "smooth",
    });
  }

  const houses = document.querySelectorAll(".house");
  let currentHouse = 0;

  function showHouse(n) {
    houses[currentHouse].classList.remove("active");
    const prevHouse = currentHouse;
    currentHouse = (n + houses.length) % houses.length;

    if (n > 0) {
      houses[currentHouse].classList.add("active");
    } else {
      houses[currentHouse].classList.add("active", "prev");
    }

    houses[prevHouse].classList.remove("prev");
  }

  document.querySelector(".arrow-left").addEventListener("click", () => {
    showHouse(currentHouse - 1);
  });
  document.querySelector(".arrow-left-mobile").addEventListener("click", () => {
    showHouse(currentHouse - 1);
  });

  document.querySelector(".arrow-right").addEventListener("click", () => {
    showHouse(currentHouse + 1);
  });
  document
    .querySelector(".arrow-right-mobile")
    .addEventListener("click", () => {
      showHouse(currentHouse + 1);
    });

  function scrollToElement(element) {
    const el = document.querySelector(element);
    window.scrollTo({
      behavior: "smooth",
      top: el.offsetTop,
    });
  }

  document.querySelectorAll('a[href^="#"]').forEach((link) => {
    link.addEventListener("click", (event) => {
      event.preventDefault();
      const target = link.getAttribute("href");
      scrollToElement(target);
    });
  });

  function toggleMenu() {
    const menu = document.getElementById("menu");
    const menuIcon = document.getElementById("menuIcon");

    menu.classList.toggle("nav__links-container");
    menuIcon.classList.toggle("active");
    menuIcon.src = menuIcon.classList.contains("active")
      ? "./assets/icons/close-menu.svg"
      : "./assets/icons/menu.svg";
  }
})();
