/*Assign Events Open Service Details*/
let btns = document.querySelectorAll(".services .button")
if (btns.length > 0) {
  btns.forEach((v) => v.addEventListener('click', openService))
  document.querySelector(".modal .close").addEventListener('click', closeModal);
}

/*Assign Events Open Pricing Details*/
btns = document.querySelectorAll(".btnprices");
  getPriceHeight();
if (btns.length > 0) {
  btns.forEach((v) => v.addEventListener('click', openPriceTable))
}


/*Assign EventHandler: Submit Form */
let btn = document.getElementById("submitForm");
if (btn) {
  btn.addEventListener("click", sendForm);
}

/*Assign EventHandler: Regenerate Captcha */
btn = document.getElementById("regenerate");
if (btn) {
  btn.addEventListener("click", (() => document.getElementById("keyimg").src = "php/captcha.php"));
}

/*Assing EventHandler: toggle responsive nav menu*/
btn = document.getElementById("navtoggler");
if (btn) {
  btn.addEventListener("click", () => document.querySelector(".topmenu").classList.toggle('expanded'));
}

btn = document.querySelector(".menuitems");
if (btn) {
  btn.addEventListener("click", () => document.querySelector(".topmenu").classList.toggle('expanded'));
}

/*Init animation on scroll*/
if (typeof (AOS) != "undefined") {
  AOS.init({
    duration: 1000,
    disable: window.innerWidth < 575
  })
}
/*Init active internal link on scroll*/
scrollSpy();


/*Define and set locations map*/
/*Here you can set the coordinates of your shop
pos:[latitude, longitude], text:"text in popup marker"
*/
if (document.querySelector(".gmaps") && typeof (L) != "undefined") {
  const locations = [{
      pos: [40.760505656958166, -73.98522987442576],
      text: "Headquarter"
    },
    {
      pos: [40.75309443074146, -73.86656895852735],
      text: "NorthCorona"
    },
    {
      pos: [40.81373813144561, -73.93551361675354],
      text: "Weehawken"
    },
    {
      pos: [40.806604626275856, -73.95547754558885],
      text: "Harlem"
    },
  ]
  initMap("map", locations)
  initMap("minimap", [locations[0]])
}
/*Functions*/
function getPriceHeight() {
  let tables = document.querySelectorAll(".pricetable");
  tables.forEach((v) => {
    v.realHeight = window.getComputedStyle(v).height;
    v.style.setProperty("height", "0px");
    v.classList.remove('init');
  });
}

function openService(event) {
  let serviceId = event.currentTarget.dataset.target;
  let service = document.getElementById(serviceId);
  openModal(service.innerHTML);
}

function openModal(content) {
  let modal = document.querySelector(".modal");
  modal.querySelector(".content .txt").innerHTML = content;
  modal.style.top = (window.scrollY) + 'px'
  modal.style.display = "block";
  modal.style.opacity = "0";
  document.body.style.paddingRight = `${window.innerWidth - document.documentElement.clientWidth}px`;
  document.body.style.overflow = "hidden";
  setTimeout(() => modal.style.opacity = "1", 10)
}

function closeModal(event) {
  let modal = document.querySelector(".modal");
  document.body.style.removeProperty("overflow");
  document.body.style.removeProperty("padding-right");
  modal.style.opacity = "0";
  let transition = parseFloat(getComputedStyle(modal).transitionDuration) * 1000
  setTimeout(() => modal.style.display = "none", transition)
}

function openPriceTable(event) {
  let activeBtn = event.currentTarget;
  let category = activeBtn.dataset.target;
  let table = document.getElementById(category);
  let oldButton = document.querySelector(".btnprices.active");
  if (oldButton) {
    oldButton.classList.remove("active");
    let oldTable = document.getElementById(oldButton.dataset.target)
    oldTable.classList.remove("active");
    oldTable.style.setProperty("height", "0px");
  }
  if (oldButton != activeBtn) {
    activeBtn.classList.add("active");
    table.classList.add("active");
    table.style.setProperty("height", table.realHeight);
  }
}
/*Send contact form*/
function sendForm() {
  event.preventDefault();
  let form = event.currentTarget.form;
  if (form.checkValidity()) {
    const formData = new FormData(form);
    fetch('php/sendmail.php', {
        method: 'POST',
        body: formData
      })
      .then(response => response.json())
      .then(result => {
        let message = "";
        if (result.code.toLowerCase() === "ok") {
          message = '<div style="padding: 0 2rem 2rem 2rem">';
          message += '<header><h5>Thank You for Reaching Out!</h5></header>'
          message += '<p style="margin: 10px 0">We have received your message and will respond as soon as possible.';
          message += '<br>If your matter is urgent, please contact us at 1-123-456-7890<p>';
          message += '<p>Warm regards<h6>Clean Car</h6></p></div>';
          openModal(message);
        } else {
          if (result.code === "captcha") {
            message = '<div style="padding: 0 2rem 2rem 2rem">';
            message += '<header><h5>Form Sending Error</h5></header>'
            message += '<p style="margin: 10px 0">You have to write the security code<p>';
            message += '<p><b>Clean Wash Team is working for you<b></p></div>';
            openModal(message);
            document.getElementById("keyimg").src = "php/captcha.php";
          } else {
            result.errors.forEach((v) => console.log(v));
          }
        }
      })
      .catch(error => {
        alert('Sending Data Error');
      });
  } else {
    form.reportValidity();
  }
}


//Scroll Spy
//Active links when scolling teh page
function scrollSpy() {
  let sections = [];
  const navLinks = document.querySelectorAll('.menuitems li a');
  navLinks.forEach(
    item => sections.push(document.querySelector(item.getAttribute('href')))
  );

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const id = entry.target.getAttribute('id');
        navLinks.forEach(link => {
          link.classList.remove('activelnk');
          if (link.getAttribute('href') === `#${id}`) {
            link.classList.add('activelnk');
          }
        });
      }
    });
  }, {
    threshold: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7],
    rootMargin: '0% 0px -60% 0px'
  });

  sections.forEach(section => {
    if (section) {
      observer.observe(section);
    }
  });
}

//OpenStreetMap using leaflet library
//https://www.openstreetmap.org/
//https://leafletjs.com/
//idmap: id attribute of map containerin HTML
//locations array of objects {pos[lat,lng], popuptext]

function initMap(idmap, locations) {
  if (document.getElementById(idmap) == null) {
    return
  }
  const map = L.map(idmap).setView(locations[0].pos, 11);
  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  const LeafIcon = L.Icon.extend({
    options: {
      iconSize: [54, 44],
      iconAnchor: [22, 22],
      popupAnchor: [-3, -6]
    }
  });

  const icon = new LeafIcon({
    iconUrl: 'images/cleancar_fav.png'
  });
  locations.forEach((location) => {
    let text = location.text + getRouteLnk(location);
    let marker = L.marker(location.pos, {
      icon: icon
    }).bindPopup(text).addTo(map);
    map.on('zoomend', function () {
      marker.setLatLng(marker.getLatLng());
    });
  });
}

function getRouteLnk(location) {
  let route = `https://www.google.com/maps/dir/?api=1&destination=${location.pos[0]},${location.pos[1]}`;
  return `<br><a href="${route}">Go here</a>`;
}
