// Go to top
document.addEventListener('click', function(event) {
  if (event.target.matches('.back-to-top')) {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
    event.preventDefault();
  }
});

// Header locations
let headerLocations = [];
const getHeaderLocations = () => {
  document.querySelectorAll('.switcher-nav li a').forEach(link => {
    const location = link.getAttribute('href');
    const text = link.textContent;
    headerLocations.push({ location, text });
  });
};

const registerCarouselActions = () => {
  // Carousel actions
  document.querySelectorAll('.control.next').forEach(nextControl => {
    nextControl.addEventListener('click', function(event) {
      const activeStage = this.parentElement.querySelector('.stage.active');
      if (activeStage) {
        activeStage.classList.remove('active');
        const nextStage = activeStage.nextElementSibling;
        if (nextStage && nextStage.classList.contains('stage')) {
          nextStage.classList.add('active');
        } else {
          this.parentElement.querySelector('.stage').classList.add('active');
        }
      }
    });
  });

  // Loop background slides when clicking backward
  document.querySelectorAll('.control.previous').forEach(prevControl => {
    prevControl.addEventListener('click', function(event) {
      const activeStage = this.parentElement.querySelector('.stage.active');
      if (activeStage) {
        activeStage.classList.remove('active');
        const prevStage = activeStage.previousElementSibling;
        if (prevStage && prevStage.classList.contains('stage')) {
          prevStage.classList.add('active');
        } else {
          this.parentElement.querySelector('.stage:last-child').classList.add('active');
        }
      }
    });
  });
};

window.addEventListener('load', () => {
  document.body.classList.remove('preload');
  getHeaderLocations();
  registerCarouselActions();
});

// Load URL depending on parameter
const getUrlParameter = (name) => {
  const params = new URLSearchParams(window.location.search);
  return params.get(name);
};

// Header actions
document.querySelectorAll('.header .main-nav-item.menu-container').forEach(menuItem => {
  menuItem.addEventListener('click', event => {
    event.preventDefault();
    document.body.classList.toggle('nav-active');
    menuItem.setAttribute('aria-expanded', menuItem.getAttribute('aria-expanded') === 'false' ? 'true' : 'false');
  });
});

document.querySelectorAll('.header .main-nav-item.search-icon').forEach(searchItem => {
  searchItem.addEventListener('click', event => {
    event.preventDefault();
    document.body.classList.toggle('search-active');
  });
});

// Page dropdowns
document.querySelectorAll('.page-dropdowns select').forEach(select => {
  select.addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    const label = selectedOption.text;
    const link = selectedOption.dataset.link;
    this.previousElementSibling.textContent = label;
    window.location.href = link;
  });
});

document.querySelectorAll('.community-switcher').forEach(switcher => {
  switcher.addEventListener('click', (e) => {
    if (e.target.id !== 'header-search') {
      document.body.classList.toggle('switcher-active');
    }
  });
});

document.querySelectorAll('.subnav-toggle').forEach(toggle => {
  toggle.addEventListener('click', () => {
    document.body.classList.toggle('subnav-active');
  });
});

if(document.querySelector('#header-search')) {
  document.querySelector('#header-search').addEventListener('input', function() {
    const search = this.value;
    if (search.length > 0) {
      document.querySelectorAll('.switcher-nav li').forEach((item, index) => index > 0 && item.remove());
      const results = headerLocations.filter(location => location.text.toLowerCase().includes(search.toLowerCase()));
      const switcherNav = document.querySelector('.switcher-nav');
      if (results.length > 0) {
        results.forEach(result => {
          switcherNav.insertAdjacentHTML('beforeend', `<li><a href="${result.location}" class="nav-link">${result.text}</a></li>`);
        });
      } else {
        switcherNav.insertAdjacentHTML('beforeend', `<li><a href="#" class="nav-link">No results found</a></li>`);
      }
    } else {
      document.querySelectorAll('.switcher-nav li').forEach((item, index) => index > 0 && item.remove());
      const switcherNav = document.querySelector('.switcher-nav');
      headerLocations.forEach(location => {
        switcherNav.insertAdjacentHTML('beforeend', `<li><a href="${location.location}" class="nav-link">${location.text}</a></li>`);
      });
    }
  });
}

if(document.querySelector('#blocker-banner .close')) {
  document.querySelector('#blocker-banner .close').addEventListener('click', () => {
    document.querySelector('#blocker-banner').style.display = 'none';
  });
}

// Log interaction
document.querySelectorAll('.interaction-tracker').forEach(tracker => {
  tracker.addEventListener('click', async () => {
    const endpoint = 'https://us-central1-kube-ownlocal.cloudfunctions.net/dir-track-interactions';
    const data = tracker.dataset;
    await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });
  });
});

// Notify lead
document.querySelectorAll('.lead-tracker').forEach(tracker => {
  tracker.addEventListener('click', async () => {
    const data = tracker.dataset;
    fetch("/interactions/leads_notification", {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      }
    })
  });
});

function lazyLoadImages(type) {
  setTimeout(() => {
    const carousel = document.querySelector(`#carousel${type}`);
    const stage = carousel.querySelector(".stage.active");
    let lazies;
    if (type === "offers") {
      lazies = stage.querySelectorAll("iframe");
    } else {
      lazies = stage.querySelectorAll(".image");
    }
    lazies.forEach(lazy => {
      if (type === "offers") {
        if (!lazy.hasAttribute('src')) {
          lazy.setAttribute("src", lazy.dataset.src);
          lazy.removeAttribute("data-src");
        }
      } else {
        if (!lazy.hasAttribute('style')) {
          lazy.setAttribute("style", lazy.dataset.style);
          lazy.removeAttribute("data-style");
        }
      }
    });
  }, 100);
}

function loadEntities(path, type) {
  setTimeout(() => {
    const carousel = document.querySelector(`#carousel${type}`);
    const lastStage = carousel.querySelector(".stage:last-child");
    if (lastStage.classList.contains("active")) {
      const total = carousel.querySelectorAll("li").length;
      fetch(`${path}?type=${type}&offset=${total}`)
        .then(response => response.text())
        .then(data => {
          carousel.insertAdjacentHTML('beforeend', data);
        });
    }
  }, 100);
}
;
