// CSS
var styles = `
  .modal {
    position: fixed; 
    left: 0; 
    top: 0; 
    width: 100%; 
    height: 100%; 
    background-color: rgba(0, 0, 0, 0.5); 
    opacity: 0; 
    visibility: hidden; 
    transform: scale(1.1); 
    transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s; 
    z-index: 5;
    font-family: Arial;
  }

  .modal-content {
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%); 
    background-color: white; 
    padding: 1rem; 
    width: 24rem; 
    border-radius: 0.2rem; 
  }

  .modal-content h3 {
    font-size: 24px;
    margin-top: 20px;
    line-height: 0px;
  }

  .modal-content p {
    font-size: 15px;
  }

  .modal-content hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eeeeee;
  }

  .modal-content input {
    width: 100%;
    padding: 10px;
    margin-top: 20px;
    border: 1px #ccc solid;
    border-radius: 3px;
  }

  #modal-submit {
    background-color: #4B4;
    color: #fff;
    font-weight: bold;
    padding: 15px;
  }

  .close-button {
    float: right; 
    width: 1.5rem; 
    line-height: 1.5rem; 
    text-align: center; 
    cursor: pointer; 
    border-radius: 0.25rem; 
    background-color: #FFF;
  }

  .small-message, .action-close {
    font-size: 12px;
    opacity: 0.7;
  }

  .action-close {
    text-align: center;
    margin-top: 15px;
  }

  .action-close a {
    background-color: #DDF0DD;
    border-radius: 3px;
    padding: 15px;
    text-decoration: none;
    color: black;
  }

  .show-modal {
    opacity: 1; 
    visibility: visible; 
    transform: scale(1.0); 
    transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s; 
  }

  @media (min-width: 767px) {
    .modal-content {
      padding: 2rem;
      width: 32rem;
    }
  }
`

var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.appendChild(styleSheet)

// JS
window.addEventListener('load', function () {
  var notificationText = "Notify me";   
  var outOfStockButtons = document.getElementsByClassName("w-commerce-commerceaddtocartoutofstock");
  for( let i = 0; i < outOfStockButtons.length; i++) {
    if (outOfStockButtons[i].style.display != "none") {
      var outOfStockParentElement = outOfStockButtons[i].parentNode;
      var form = outOfStockParentElement.firstChild
      var skuId = form.getAttribute("data-commerce-sku-id")
      var productId = form.getAttribute("data-commerce-product-id")
      var productName = form.parentElement.parentElement.getElementsByClassName('pricing-link-header')[0].text
      var formInput = form.querySelectorAll("input")
      var AddToCartButtonClone = formInput[formInput.length - 1].cloneNode(true);
      AddToCartButtonClone.value = notificationText;
      AddToCartButtonClone.classList.add("trigger");
      AddToCartButtonClone.setAttribute("sku-id", skuId)
      AddToCartButtonClone.setAttribute("product-id", productId)
      AddToCartButtonClone.setAttribute("product-name", productName)
      outOfStockButtons[i].style.display = "none";
      outOfStockParentElement.prepend(AddToCartButtonClone);
    } 
  }
  
  var triggers = document.getElementsByClassName("trigger")
  
  var div = document.createElement("div");
  div.className = "modal";
  div.innerHTML = `
      <div class="modal-content">
        <button class="close-button">×</button>
        <h3>NOTIFY ME WHEN AVAILABLE</h3>
        <p>We'll notify you when this product is back in stock.</p>
        <hr />
        <p class="product-name"></p>
        <hr />
        <input type="text" name="email" value="" placeholder="E-mail address" id="modal-email" />
        <p class="email-validation"></p>
        <input type="hidden" name="sku-id" value="" />
        <input type="hidden" name="product-id" value="" />
        <input type="button" value="Notify me when available" id="modal-submit" />
        <p class="action-close"></p>
        <p class="small-message">We don't share your information with others.</p>
      </div>
    `;
  document.body.prepend(div);
  
  var modal = document.querySelector(".modal");
  var modalContent = document.querySelector(".modal-content");
  var payloadButton = modalContent.querySelector('input[type="button"]');
  var closeButton = document.querySelector(".close-button");
  
  function toggleModal() {
      modal.classList.toggle("show-modal");
      modalContent.querySelector('input[name=product-id]').value = "";
      modalContent.querySelector('input[name=sku-id]').value = "";
      modalContent.querySelector('input[name=email]').value = "";
      document.querySelector(".product-name").innerText = "" ;
      document.querySelector(".action-close").innerHTML = "" ;
      document.querySelector(".email-validation").innerText = "" ;
  
      var productId = event.target.getAttribute("product-id")
      var productName = event.target.getAttribute("product-name");
      var skuId = event.target.getAttribute("sku-id");
      
      document.querySelector(".product-name").innerText = productName ;
      modalContent.querySelector('input[name=product-id]').value = productId;
      modalContent.querySelector('input[name=sku-id]').value = skuId;
  }
  
  function windowOnClick(event) {
      if (event.target === modal) {
          toggleModal();
      }
  }
  
  function sendPayload() {
    productId = modalContent.querySelector('input[name=product-id]').value;
    skuId = modalContent.querySelector('input[name=sku-id]').value;
    emailAddress = modalContent.querySelector('input[name=email]').value;
    var is_valid_email = function(email) { return /^.+@.+\..+$/.test(email); }
  
    if (is_valid_email(emailAddress)) {
      if (document.querySelector(".email-validation").innerText != "") {
        document.querySelector(".email-validation").innerText = "This e-mail address is valid!" ;
      }
      
      const xhr = new XMLHttpRequest();
  
      xhr.onload = () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          modalContent.children[1].innerText = "Thanks";
          var closeElement = document.querySelector(".action-close")
          closeElement.innerHTML = "<a href='#'>Your notification has been registered. Close</a>" ;
          closeElement.addEventListener("click", toggleModal);
        }
      };
  
      const payload = {
        "productId": productId,
        "skuId": skuId,
        "emailAddress": emailAddress
      };
      
      var url = 'https://webhook.site/95dcda72-fe5b-4443-a94c-b19a89bf6e4e'
      xhr.open("POST", url);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.send(JSON.stringify(payload));
    } else {
      document.querySelector(".email-validation").innerText = "E-mail address is not valid" ;
    }
  }
  
  
  for ( let i = 0; i < triggers.length; i++ ) {
    triggers[i].addEventListener("click", toggleModal);
  }
  
  closeButton.addEventListener("click", toggleModal);
  window.addEventListener("click", windowOnClick);
  payloadButton.addEventListener("click", sendPayload);    
});
