/**
 * Table of contents
 * -----------------------------------
 * 01.CURRENT TIME
 * 02.OPEN BUTTON
 * 03.CHECK AVAILABILITY
 * 04.GET WEEK DAY
 * 05.MULTI USER AVAILABILITY
 * 06.MULTI USER SEARCH
 * 07.BUTTONS AVAILABILITY
 * 08.SINGLE CHAT AVAILABILITY
 * DARK VERSION
 * -----------------------------------
 */

"use strict";
let ctd = document.querySelectorAll(".ctd");
let ctdMulti = document.querySelectorAll(".ctd-multi");
let ctdBubble = document.querySelectorAll(".ctd-bubble");
let currentTime = document.querySelector(".current-time");
let ctdUserAvailability = document.querySelectorAll(".ctdUserAvailability");
let ctdSendMessage = document.querySelector(".ctd__send-message");
let ctdMultiPopupContent = document.querySelector(
  ".ctd-multi__popup--content"
);
let user = document.querySelector(".user");

/******************** 01.CURRENT TIME  ********************/

let today = new Date();
if (currentTime !== null) {
  let time =
    today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  currentTime.innerText = time;
}
/******************** 02.OPEN BUTTON  ********************/
const openChatBtn = () => {
  ctd.forEach((item) => {
    item.classList?.toggle("ctd-show");
  });
  ctdMulti.forEach((item) => {
    item.classList?.toggle("ctd-show");
  });
};
ctdBubble.forEach((item) => {
  item.addEventListener("click", openChatBtn);
});

/******************** 03.CHECK AVAILABILITY  ********************/
function is_available(available, now) {
  let is_available = false;
  let almost_available = false;
  for (let key in available) {
    if (available.hasOwnProperty(key)) {
      if (get_day_of_week(key) == now.day()) {
        let timeRange = available[key].split("-");
        let start = moment.tz(timeRange[0], "HH:mm", now.tz());  // Apply the same timezone
        let end = moment.tz(timeRange[1], "HH:mm", now.tz());

        // Align start/end to the same date as `now`
        start.year(now.year()).month(now.month()).date(now.date());
        end.year(now.year()).month(now.month()).date(now.date());

        if (now.isBetween(start, end)) {
          is_available = true;
        } else if (now.isBefore(start)) {
          almost_available = true;
        }        
      }
    }
  }
  return { is_available: is_available, almost_available: almost_available };
}

/******************** 04.GET WEEK DAY  ********************/
function get_day_of_week(name) {
  name = name.toLowerCase();
  if (name == "sunday") {
    return 0;
  } else if (name == "monday") {
    return 1;
  } else if (name == "tuesday") {
    return 2;
  } else if (name == "wednesday") {
    return 3;
  } else if (name == "thursday") {
    return 4;
  } else if (name == "friday") {
    return 5;
  } else if (name == "saturday") {
    return 6;
  }
}

/******************** 05.MULTI USER AVAILABILITY  ********************/
const searchInfo = ctdMultiPopupContent?.getAttribute("data-search");
const isGrid = document
  .querySelector(".ctd-multi")
  ?.classList.contains("ctd-grid");

if (ctdUserAvailability !== undefined) {
  if (searchInfo === "true") {
    ctdMultiPopupContent.classList.add("ctd-search");
  }
  if (ctdUserAvailability.length > 3 && !isGrid) {
    ctdMultiPopupContent.classList.add("ctd-scroll");
  }
  if (ctdUserAvailability.length > 4 && isGrid) {
    ctdMultiPopupContent.classList.add("ctd-scroll");
  }
  ctdUserAvailability.forEach((item) => {
    const availableTimes = item.getAttribute("data-useravailability");
    const timezone = item.getAttribute("data-timezone");
    let now = timezone ? moment().tz(timezone) : moment();
    let available = is_available(JSON.parse(availableTimes), now);
    let dataNumbers = item.getAttribute("data-number");
    if (available.is_available && dataNumbers !== "") {
      let a = item.appendChild(document.createElement("a"));
      a.href = `tel:${dataNumbers}`;
    }
    if (available.is_available || availableTimes == null) {
      ctdUserAvailability.forEach((item) => {
        const availableTime = item.getAttribute("data-useravailability");
        if (availableTime === availableTimes) {
          item.classList.add("avatar-active");
          item.classList.remove("avatar-inactive");
        }
      });
    } else {
      ctdUserAvailability.forEach((item) => {
        const availableTime = item.getAttribute("data-useravailability");
        if (availableTime === availableTimes) {
          item.classList.add("avatar-inactive");
          item.setAttribute("disabled", "");
          item.classList.remove("avatar-active");
        }
      });
    }
  });
}
/******************** 06.MULTI USER SEARCH  ********************/
function searchUser() {
  var searchKeyword, i, txtValue;
  let input = document.getElementById("search-input");
  let filter = input.value.toUpperCase();
  let multiUser = document.getElementById("multi-user");
  let user = multiUser.getElementsByClassName("user");

  for (i = 0; i < user.length; i++) {
    searchKeyword = user[i].getElementsByClassName("user__info--name")[0];
    txtValue = searchKeyword.textContent || searchKeyword.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      user[i].style.display = "";
    } else {
      user[i].style.display = "none";
    }
  }
}

/******************** 07.BUTTONS AVAILABILITY  ********************/
let ctdButtons = document.querySelectorAll(".ctdButtons");
if (ctdButtons !== undefined) {
  ctdButtons.forEach((item) => {
    const availableTimes = item.getAttribute("data-btnavailablety");
    const timezone = item.getAttribute("data-timezone");
    let now = timezone ? moment().tz(timezone) : moment();
    let available = is_available(JSON.parse(availableTimes), now);

    if (available.is_available) {
      ctdButtons.forEach((item) => {
        const availableTime = item.getAttribute("data-btnavailablety");
        if (availableTime === availableTimes) {
          item.classList.add("avatar-active");
          item.classList.remove("avatar-inactive");
        }
      });
    } else {
      ctdButtons.forEach((item) => {
        const availableTime = item.getAttribute("data-btnavailablety");
        if (availableTime === availableTimes) {
          item.classList.add("avatar-inactive");
          item.classList.remove("avatar-active");
        }
      });
    }
  });
}

/******************** 08.SINGLE CHAT AVAILABILITY  ********************/
const chatAvailability = document.querySelector(".chat-availability");

if (chatAvailability) {
  const chatAvailableTime = chatAvailability.getAttribute("data-availability");
  const timezone = chatAvailability.getAttribute("data-timezone");
  let dataNumbers = chatAvailability.getAttribute("data-ctdNumber");
  if (chatAvailableTime !== undefined) {
    let now = timezone ? moment().tz(timezone) : moment();
    let available = is_available(JSON.parse(chatAvailableTime), now);

    if ((available.is_available || chatAvailableTime == null) && dataNumbers !== "") {
      chatAvailability.classList.add("avatar-active");
      let a = ctdSendMessage.appendChild(document.createElement("a"));
      a.href = `tel:${dataNumbers}`;
    } else {
      chatAvailability.classList.add("avatar-inactive");
      chatAvailability.setAttribute("disabled", "");
      chatAvailability.classList.remove("avatar-active");
    }
  }
}
