const desktopSubMenu1Container = document.querySelector(
  "#desktop-sub-menu-1-container"
);
const mobileSubMenu1Container = document.querySelector(
  "#mobile-sub-menu1-container"
);

const desktopSubMenu2Container = document.querySelector(
  "#desktop-sub-menu-2-container"
);
const mobileSubMenu2Container = document.querySelector(
  "#mobile-sub-menu2-container"
);

let mobileScreen = false;

if (window.innerWidth <= 600) {
  mobileScreen = true;

  if(desktopSubMenu1Container.innerHTML != "") {
    mobileSubMenu1Container.innerHTML = desktopSubMenu1Container.innerHTML;
    desktopSubMenu1Container.innerHTML = "";
  }
      
  if(desktopSubMenu2Container.innerHTML != "") {
    mobileSubMenu2Container.innerHTML = desktopSubMenu2Container.innerHTML;
    desktopSubMenu2Container.innerHTML = "";
  }

} else {
  mobileScreen = false;

  if(mobileSubMenu1Container.innerHTML != "") {
    desktopSubMenu1Container.innerHTML = mobileSubMenu1Container.innerHTML;
    mobileSubMenu1Container.innerHTML = "";
  }

  if(mobileSubMenu2Container.innerHTML != "") {
    desktopSubMenu2Container.innerHTML = mobileSubMenu2Container.innerHTML;
    mobileSubMenu2Container.innerHTML = "";
  }
}

window.addEventListener("resize", function (event) {
  console.log('resize');

  if (window.innerWidth <= 600) {
    mobileScreen = true;

    if(desktopSubMenu1Container.innerHTML != "") {
      mobileSubMenu1Container.innerHTML = desktopSubMenu1Container.innerHTML;
      desktopSubMenu1Container.innerHTML = "";
    }
      
    if(desktopSubMenu2Container.innerHTML != "") {
      mobileSubMenu2Container.innerHTML = desktopSubMenu2Container.innerHTML;
      desktopSubMenu2Container.innerHTML = "";
    }
    
  } else {
    mobileScreen = false;

    if(mobileSubMenu1Container.innerHTML != "") {
      desktopSubMenu1Container.innerHTML = mobileSubMenu1Container.innerHTML;
      mobileSubMenu1Container.innerHTML = "";
    }

    if(mobileSubMenu2Container.innerHTML != "") {
      desktopSubMenu2Container.innerHTML = mobileSubMenu2Container.innerHTML;
      mobileSubMenu2Container.innerHTML = "";
    }
    
  }

  // hide the menus when resizing the window
  let subMenu1 = document.querySelector(".sub-menu-1");
  subMenu1.classList.remove("mobile-sub-menu-1-open");
  subMenu1.classList.remove("desktop-sub-menu-1-open");

  let subMenu2 = document.querySelector(".sub-menu-2");
  subMenu2.classList.remove("mobile-sub-menu-2-open");
  subMenu2.classList.remove("desktop-sub-menu-2-open");

  console.log("mobileScreen:", mobileScreen);
});

const specialOffersHovered = (event) => {
  console.log("specialOffersHovered");
  console.log("eventType:", event.type);
  
  let subMenu1 = document.querySelector(".sub-menu-1");

  if(mobileScreen && event.type == 'click') {
    subMenu1.classList.toggle("mobile-sub-menu-1-open");
    document.getElementById('special-offers').classList.toggle('menu-link-selected');
  }

  if(!mobileScreen) {
    subMenu1.classList.toggle("desktop-sub-menu-1-open");
    document.getElementById('special-offers').classList.toggle('menu-link-selected');
  }

  let subMenu2 = document.querySelector(".sub-menu-2");
  subMenu2.classList.remove("mobile-sub-menu-2-open");
  subMenu2.classList.remove("desktop-sub-menu-2-open");
  document.getElementById('quick-find').classList.remove('menu-link-selected');
      
  console.log("--------------------");
  
};

const quickFindHovered = (event) => {
  console.log("quickFindHovered");
  console.log("eventType:", event.type);

  let subMenu2 = document.querySelector(".sub-menu-2");

  if(mobileScreen && event.type == 'click') {
    subMenu2.classList.toggle("mobile-sub-menu-2-open");
    document.getElementById('quick-find').classList.toggle('menu-link-selected');
  }

  if(!mobileScreen) {
    subMenu2.classList.toggle("desktop-sub-menu-2-open");
    document.getElementById('quick-find').classList.toggle('menu-link-selected');
  }

  let subMenu1 = document.querySelector(".sub-menu-1");
  subMenu1.classList.remove("mobile-sub-menu-1-open");
  subMenu1.classList.remove("desktop-sub-menu-1-open");
  document.getElementById('special-offers').classList.remove('menu-link-selected');
      
  console.log("--------------------");
};


const closeIcon = document.querySelector(".close-icon");
const menuIcon = document.querySelector(".menu-icon");
const menuContainer = document.querySelector(".menu-container");
const body = document.querySelector("body");

menuIcon.addEventListener("click", () => {
  menuContainer.classList.toggle("menu-container-open");
  body.classList.toggle("body-menu-open");
  //alert('window.innerWidth:' + window.innerWidth);
});

closeIcon.addEventListener("click", () => {
  menuContainer.classList.toggle("menu-container-open");
  body.classList.toggle("body-menu-open");
});

const toggleCategories = () => {
  const categoriesMenu = document.getElementById("categories-menu");

  categoriesMenu.classList.toggle("categories-menu-open");
};

const toggleTopTags = () => {
  const toptagsMenu = document.getElementById("top-tags-menu");

  toptagsMenu.classList.toggle("top-tags-menu-open");
};

const toggleQuickAccess = () => {
  const quickAccessMenu = document.getElementById("quick-access-menu");

  quickAccessMenu.classList.toggle("quick-access-menu-open");
};

/*
 * back to top action
 */
function scrollToTopSmooth() {
  window.scrollTo({
    top: 0, // Scrolls to the very top of the page
    behavior: "smooth", // Enables the smooth scrolling animation
  });
}

// Example usage: Attach this function to a button click event
const backToTopButton = document.querySelector(".back-to-top-button"); // Assuming you have a button with this ID

if (backToTopButton) {
  backToTopButton.addEventListener("click", scrollToTopSmooth);
}


/**
 * 
 */
const toggleBasket = () => {
  const basketPanel = document.querySelector('.basket-panel');

  basketPanel.classList.toggle('basket-panel-open');

  if(basketPanel.classList.contains('basket-panel-open')) {
    displayCartProducts();
  }
}


/**
 * Account management
 */
async function loginUser(form, event) { 
  event.preventDefault();

  const formAction = "login-user";
  console.log('formAction: ', formAction);

  const username = form.username.value;
  const password = form.password.value;

  url = "../wp-json/api/v1/user-account";

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-type" : "application/json"
      },
      body: JSON.stringify({
        formAction: formAction,
        username: username,
        password: password
      })
    });
    const data_response = await response.json(); 
    console.log('data_response:', data_response);
    console.log('message:', data_response.message);

    const loginSuccess = document.querySelector('.login-success');
    const loginError = document.querySelector('.login-error');
    loginSuccess.style.display = 'none';
    loginError.style.display = 'none';

    const accountLink = document.querySelector('.account-link');
    accountLink.style.display = 'none';

    if(data_response.login) {
      loginSuccess.style.display = 'block';
      loginSuccess.innerHTML = data_response.message;
      accountLink.style.display = 'block';
    } else {
      loginError.style.display = 'block';
      loginError.innerHTML = data_response.message;
    }

    
  } catch(error) {
    console.log('Fetch error: ', error);
  }
}

async function registerUser(form) {
  const formAction = "register-user";
  console.log('formAction', formAction);

  const userName = form.username.value;
  const firstName = form.first_name.value;
  const lastName = form.last_name.value;
  const password = form.password.value;
  const confirmPassword = form.confirm_password.value;

  const url = "../wp-json/api/v1/user-account";

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-type" : "application/json"
      },
      body: JSON.stringify({
        formAction: formAction,
        userName: userName,
        firstName: firstName,
        lastName: lastName,
        password: password,
        confirmPassword: confirmPassword
      })
    });

    const response_data = await response.json();
    console.log('response_data: ', response_data);

    const registerSuccess = document.querySelector('.register-success');
    const registerError = document.querySelector('.register-error');
    registerSuccess.style.display = 'none';
    registerError.style.display = 'none';

    if(response_data.register) {
      registerSuccess.style.display = 'block';
      registerSuccess.innerHTML = response_data.message;
    } else {
      registerError.style.display = 'block';
      registerError.innerHTML = response_data.message; 
    }


  } catch (error) {
    console.log('Fetch error: ', error);
  }
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function accountDetails () {
  const url = '../account-details/';
  
  const accountDetailsContainer = document.querySelector('.account-details');
  accountDetailsContainer.innerHTML = "Loading...";
  await sleep(1000); 

  try {
    const response = await fetch(url, {
      method: "GET"
    });

    const response_data = await response.text();

    accountDetailsContainer.innerHTML = response_data;

  } catch(error) {
    console.log('Fetch error: ', error);
  }
}

async function accountOrders () {
  const url = '../account-orders/';
  
  const accountDetailsContainer = document.querySelector('.account-details');
  accountDetailsContainer.innerHTML = "Loading...";
  await sleep(1000); 

  try {
    const response = await fetch(url, {
      method: "GET"
    });

    const response_data = await response.text();

    accountDetailsContainer.innerHTML = response_data;

    const orderTotalArray = document.querySelectorAll('.order-total');
    console.log('orderTotalArray:', orderTotalArray);

    orderTotalArray.forEach(orderTotal => {
      let orderTotalId = orderTotal.id;
      orderTotalId = orderTotalId.replace('order-total-', '');
      console.log('orderTotalId', orderTotalId);
      const orderTotalContainer = document.getElementById('total-' + orderTotalId);
      orderTotalContainer.innerHTML = '$' + orderTotal.value;
    });

  } catch(error) {
    console.log('Fetch error: ', error);
  }
}

async function saveUserInfos(form, event) {
  event.preventDefault();
  const formAction = "save-user-infos";
  console.log('formAction: ', formAction);

  const userName = form.username.value;
  const firstName = form.first_name.value;
  const lastName = form.last_name.value;

  const url = "../wp-json/api/v1/user-account";

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-type" : "application/json"
      },
      body: JSON.stringify({
        formAction: formAction,
        userName: userName,
        firstName: firstName,
        lastName: lastName
      })
    });

    const response_data = await response.json();
    console.log("response_data: ", response_data);

    const saveUserInfosSuccess = document.querySelector('.save-user-infos-success');
    const saveUserInfosError = document.querySelector('.save-user-infos-error');
    saveUserInfosSuccess.style.display = 'none';
    saveUserInfosError.style.display = 'none';

    if(response_data.update) {
      saveUserInfosSuccess.style.display = 'block';
      saveUserInfosSuccess.innerHTML = response_data.message;
    } else {
      saveUserInfosError.style.display = 'block';
      saveUserInfosError.innerHTML = response_data.message; 
    }

  } catch(error) {
    console.log('Fetch error: ', error);
  }
}

async function changeUserPassword(form, event) {
  event.preventDefault();
  const formAction = "change-user-password";
  console.log('formAction: ', formAction);

  const userName = form.username.value;
  const currentPassword = form.current_password.value;
  const newPassword = form.new_password.value;
  const confirmPassword = form.confirm_password.value;

  const url = "../wp-json/api/v1/user-account";

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-type" : "application/json"
      },
      body: JSON.stringify({
        formAction: formAction,
        userName: userName,
        currentPassword: currentPassword,
        newPassword: newPassword,
        confirmPassword: confirmPassword
      })
    });

    const response_data = await response.json();
    console.log("response_data: ", response_data);

    const changeUserPasswordSuccess = document.querySelector('.change-user-password-success');
    const changeUserPasswordError = document.querySelector('.change-user-password-error');
    changeUserPasswordSuccess.style.display = 'none';
    changeUserPasswordError.style.display = 'none';

    if(response_data.update) {
      changeUserPasswordSuccess.style.display = 'block';
      changeUserPasswordSuccess.innerHTML = response_data.message;
    } else {
      changeUserPasswordError.style.display = 'block';
      changeUserPasswordError.innerHTML = response_data.message; 
    }

  } catch(error) {
    console.log('Fetch error: ', error);
  }
}

function selectAccountLink(element) {
  const linksArray = document.querySelectorAll('.account-link');

  linksArray.forEach(link => {
    link.classList.remove('account-link-selected');
  });
  
  element.classList.add('account-link-selected');
}

async function logoutUser() {
  const formAction = "logout-user";
  console.log('formAction: ', formAction);

  const url = "../wp-json/api/v1/user-account";

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-type" : "application/json"
      },
      body: JSON.stringify({
        formAction, formAction
      })
    });

    const response_data = await response.json();
    console.log('response_data:', response_data);

    if(response_data.logout) {
      document.location.href = ".";
    }
  } catch(error) {
    console.log('Fetch error: ', error);
  }
}


/** 
 * Cart management
 */

async function displayCartProducts() {
  let url = './basket/';

  if(page == "index.php") {
    url = './basket/';
  } else {
    url = '../basket/';
  }

  try {
    const response = await fetch(url, {
      method: "GET"
    });

    const response_data = await response.text();

    const basketPanel = document.querySelector('.basket-panel');
    basketPanel.innerHTML = response_data ;

    document.getElementById('basket_cart_count').innerHTML = document.getElementById('cart_count').value;

  } catch(error) {
    console.log('Fetch error: ', error);
  }
}

async function addProductToCart(productId) {

  const username = document.getElementById('username').value;

  let url = "./wp-json/api/v1/add-product-to-cart/";
  if(page == "index.php") {
    url = "./wp-json/api/v1/add-product-to-cart/";
  } else {
    url = "../wp-json/api/v1/add-product-to-cart/";
  }

  const addToCartButtonText = document.getElementById('add-to-cart-text-' + productId);
  addToCartButtonText.innerHTML = "Adding...";
  await sleep(1000);

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        username: username,
        productId: productId
      })
    });

    const response_data = await response.json();
    console.log('response_data: ', response_data);

    if(response_data.add_product) {
      addToCartButtonText.innerHTML = "Added!";
      document.getElementById('basket_cart_count').innerHTML = response_data.count;
    } else {
      if(response_data.error = "Already added!") 
        addToCartButtonText.innerHTML = "Already added!";
      else addToCartButtonText.innerHTML = "Add to cart";
    }

  } catch (error) {
    console.log('Fetch error: ', error);
  }
}

async function removeProductFromBasket(productId) {

  const username = document.getElementById('username').value;

  let url = "./wp-json/api/v1/remove-product-from-cart/";

  if(page == "index.php") {
    url = "./wp-json/api/v1/remove-product-from-cart/";
  } else {
    url = "../wp-json/api/v1/remove-product-from-cart/";
  }

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        username: username,
        productId: productId
      })
    });

    const response_data = await response.json();
    console.log('response_data: ', response_data);

    if(response_data.remove_product) {
      displayCartProducts();
    }

  } catch (error) {
    console.log('Fetch error: ', error);
  }
}

async function removeProductFromCart(productId) {

  let url = "./wp-json/api/v1/remove-product-from-cart/";

  if(page == "index.php") {
    url = "./wp-json/api/v1/remove-product-from-cart/";
  } else {
    url = "../wp-json/api/v1/remove-product-from-cart/";
  }

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        productId: productId
      })
    });

    const response_data = await response.json();
    console.log('response_data: ', response_data);
    
    if(response_data.remove_product) {
      document.location.href = "./cart/";
    }

  } catch (error) {
    console.log('Fetch error: ', error);
  }
}

async function addQuantity(productId) {
  const username = document.getElementById('username').value;
  const orderId = document.getElementById('order_id').value;

  let url = "../wp-json/api/v1/add-product-quantity-in-cart/";

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        username: username,
        orderId: orderId,
        productId: productId
      })
    });

    const response_data = await response.json();
    console.log('response_data: ', response_data);

    const quantityInput = document.getElementById('quantity-input-' + productId);

    const productPrice = document.getElementById('product-price-' + productId);
    const productSubtotal = document.getElementById('product-subtotal-' + productId);
    
    if(response_data.add_quantity) {
      quantityInput.value = response_data.quantity;
      let subTotal = productPrice.innerHTML * response_data.quantity;
      productSubtotal.innerHTML = subTotal;
      updateCartTotal();
    }

  } catch (error) {
    console.log('Fetch error: ', error);
  }
}

async function reduceQuantity(productId) {
  const username = document.getElementById('username').value;
  const orderId = document.getElementById('order_id').value;

  let url = "../wp-json/api/v1/reduce-product-quantity-in-cart/";

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        username: username,
        orderId: orderId,
        productId: productId
      })
    });

    const response_data = await response.json();
    console.log('response_data: ', response_data);

    const quantityInput = document.getElementById('quantity-input-' + productId);

    const productPrice = document.getElementById('product-price-' + productId);
    const productSubtotal = document.getElementById('product-subtotal-' + productId);
    
    if(response_data.reduce_quantity) {
      quantityInput.value = response_data.quantity;
      let subTotal = productPrice.innerHTML * response_data.quantity;
      productSubtotal.innerHTML = subTotal;
      updateCartTotal();
    }

  } catch (error) {
    console.log('Fetch error: ', error);
  }
}

function updateCartTotal() { 
  const subtotalArray = document.querySelectorAll('.product-subtotal');
  let subTotals = "";
  let total = 0;
  let i=0;
  subtotalArray.forEach(subtotal => {
    subTotals += '$' + subtotal.innerHTML;
    i++;
    if(i < subtotalArray.length) subTotals += ' + ';
    total += (Number) (subtotal.innerHTML);
  });

  const cartSubtotals = document.getElementById('cart-subtotals');
  const cartTotal = document.getElementById('cart-total');

  cartSubtotals.innerHTML = subTotals;
  cartTotal.innerHTML = total;
}

window.addEventListener('scroll', () => {
  const navBar = document.querySelector('nav');
  const navBarOffset = navBar.offsetTop;

  if(window.scrollY > navBarOffset) {
    navBar.classList.add('nav-fixed');
  } else {
    navBar.classList.remove('nav-fixed');
  }
});

/**
 * Wishlist management
 */
async function removeProductFromWishlist(productId) {
  
  const username = document.getElementById('username').value;

  let url = "./wp-json/api/v1/remove-product-from-wishlist/";
  if(page == "index.php") {
    url = "./wp-json/api/v1/remove-product-from-wishlist/";
  } else {
    url = "../wp-json/api/v1/remove-product-from-wishlist/";
  }

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        username: username,
        productId: productId
      })
    });

    const response_data = await response.json();
    console.log('response_data: ', response_data);

    const heartEnabledIcon = document.getElementById('heart-enabled-' + productId);
    const heartDisabledIcon = document.getElementById('heart-disabled-' + productId);

    if(response_data.remove_product) {
      if(page == "index.php") {
        heartDisabledIcon.classList.add('heart-disabled-displayed');
        heartEnabledIcon.classList.remove('heart-enabled-displayed');
      } else {
        document.location.href = "./wishlist/";
      }
      
    }

  } catch (error) {
    console.log('Fetch error: ', error);
  }
}

async function addProductToWishlist(productId) {
  const username = document.getElementById('username').value;

  let url = "./wp-json/api/v1/add-product-to-wishlist";

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        username: username,
        productId: productId
      })
    });

    const response_data = await response.json();
    console.log('response_data: ', response_data);

    const heartEnabledIcon = document.getElementById('heart-enabled-' + productId);
    const heartDisabledIcon = document.getElementById('heart-disabled-' + productId);

    if(response_data.add_product) {
      heartEnabledIcon.classList.add('heart-enabled-displayed');
      heartDisabledIcon.classList.remove('heart-disabled-displayed');
    }

  } catch (error) {
    console.log('Fetch error: ', error);
  }
}
