$(document).ready(function () {
  const initFilterState = window.location.search;
  function handleCloseModalFilter() {
    const queryParams = new Proxy(new URLSearchParams(window.location.search), {
      get: (searchParams, prop) => searchParams.get(prop),
    });
    let newUrl =
      window.location.origin + window.location.pathname + initFilterState;
    if (window.location.pathname.indexOf("/tenant") !== -1) {
      newUrl = updateQueryStringParameter(
        newUrl,
        "alphabet",
        queryParams.alphabet
      );
    }
    history.pushState(null, null, newUrl);
    getFiltersAPI();
    $("body").css("overflow", "");
  }
  $(".modal").on("hide.bs.modal", handleCloseModalFilter);
  let urlPath = "";
  let callAPIGetDataByFilter;
  if (window.location.pathname.indexOf("/our-properties") !== -1) {
    urlPath = "/restapi/cdl/filter/building/";
    callAPIGetDataByFilter = () => getOurPropertiesAPI();
  } else if (window.location.pathname.indexOf("/happenings") !== -1) {
    urlPath = "/restapi/cdl/filter/happening/";
    callAPIGetDataByFilter = () => getHappeningsAPI();
  } else if (window.location.pathname.indexOf("/tenant") !== -1) {
    urlPath = "/restapi/cdl/filter/tenant/";
    callAPIGetDataByFilter = () => getTenantsAPI();
  }

  const filterBtn = document.getElementById("applyFilters");
  filterBtn.addEventListener("click", () => {
    callAPIGetDataByFilter();
    window.location.reload();
  });

  const clearFilterBtn = document.getElementById("clearFilter");
  clearFilterBtn.addEventListener("click", () => {
    const listCheckBox = document.querySelectorAll(
      ".modal-body--category-list input[type='checkbox']"
    );
    listCheckBox.forEach((item) => {
      item.classList.remove("selected");
    });
    let newUrl = window.location.origin + window.location.pathname;
    history.pushState(null, null, newUrl);
    callAPIGetDataByFilter();
    window.location.reload();
  });

  function handleResultGetFiltersAPI(result) {
    for (const key in result) {
      const queryParamsDecoded = customGetQueryParams(key);
      const filterTitle = document.getElementById(key);
      if (result[key].length === 0 && filterTitle) {
        filterTitle.parentElement.remove();
        continue;
      }
      if (filterTitle) {
        filterTitle.parentElement.lastElementChild.innerHTML = "";
      }
      const listFilter = document.createElement("ul");
      listFilter.classList.add("d-flex", "p-t-28");
      const filterOption = document.createElement("li");
      const inputCheck = document.createElement("input"),
        labelOption = document.createElement("label");
      inputCheck.setAttribute("type", "checkbox");
      inputCheck.setAttribute("value", "");
      if (
        queryParamsDecoded &&
        queryParamsDecoded.split(",").length === result[key].length
      ) {
        inputCheck.classList.add("selected");
      }
      labelOption.innerHTML = "Select All";
      inputCheck.classList.add("m-t-4");
      filterOption.classList.add("align-items-start");
      filterOption.appendChild(inputCheck);
      filterOption.appendChild(labelOption);
      listFilter.appendChild(filterOption);
      const defaultListLimit =
        result[key].length <= 14 ? result[key].length : 14;
      for (let index = 0; index < defaultListLimit; index++) {
        const item = result[key][index];
        const filterOption = document.createElement("li");
        const inputCheck = document.createElement("input"),
          labelOption = document.createElement("label");
        inputCheck.setAttribute("type", "checkbox");
        inputCheck.setAttribute("value", "");
        inputCheck.setAttribute("id", item);
        inputCheck.classList.add("m-t-4");
        if (
          queryParamsDecoded &&
          queryParamsDecoded
            .split(",")
            .indexOf(fixedEncodeURIComponent(item)) !== -1
        ) {
          inputCheck.classList.add("selected");
        }
        labelOption.innerHTML = item;
        filterOption.classList.add("align-items-start");
        filterOption.appendChild(inputCheck);
        filterOption.appendChild(labelOption);
        listFilter.appendChild(filterOption);
      }
      const showFilterSpanWrapper = document.createElement("div");
      if (result[key].length > 14) {
        const showFilterSpan = document.createElement("span"),
          showFilterSvg = document.createElementNS(
            "http://www.w3.org/2000/svg",
            "svg"
          ),
          showFilterPath = document.createElementNS(
            "http://www.w3.org/2000/svg",
            "path"
          );
        showFilterSpanWrapper.classList.add(
          "show-filter-wrapper",
          "d-flex",
          "justify-content-center"
        );
        showFilterSpan.classList.add("show-filter-text");
        showFilterSpan.innerHTML = "Show All";

        function handleShowFilter() {
          if (showFilterSpan.innerHTML === "Show All") {
            showFilterSpan.innerHTML = "Show Less";
            showFilterPath.setAttribute("d", "M3 10.5L8 5.5L13 10.5");
            $(".expand-option" + key).removeClass("d-none");
          } else {
            showFilterSpan.innerHTML = "Show All";
            showFilterPath.setAttribute("d", "M13 6.5L8 11.5L3 6.5");
            $(".expand-option" + key).addClass("d-none");
          }
        }
        showFilterSpan.addEventListener("click", handleShowFilter);
        showFilterSvg.addEventListener("click", handleShowFilter);
        showFilterSvg.setAttribute("width", "16");
        showFilterSvg.setAttribute("height", "17");
        showFilterSvg.setAttribute("viewBox", "0 0 16 17");
        showFilterSvg.setAttribute("fill", "none");
        showFilterPath.setAttribute("d", "M13 6.5L8 11.5L3 6.5");
        showFilterPath.setAttribute("stroke", "#2B4AB0");
        showFilterPath.setAttribute("stroke-width", "2");
        showFilterPath.setAttribute("stroke-linecap", "round");
        showFilterPath.setAttribute("stroke-linejoin", "round");
        showFilterSvg.appendChild(showFilterPath);
        showFilterSpanWrapper.appendChild(showFilterSpan);
        showFilterSpanWrapper.appendChild(showFilterSvg);
        for (let index = 14; index < result[key].length; index++) {
          const item = result[key][index],
            filterOption = document.createElement("li"),
            inputCheck = document.createElement("input"),
            labelOption = document.createElement("label");
          filterOption.classList.add("expand-option" + key, "d-none");
          filterOption.classList.add("align-items-start");
          inputCheck.setAttribute("type", "checkbox");
          inputCheck.setAttribute("value", "");
          inputCheck.setAttribute("id", item);
          inputCheck.classList.add("m-t-4");
          if (
            queryParamsDecoded &&
            queryParamsDecoded
              .split(",")
              .indexOf(fixedEncodeURIComponent(item)) !== -1
          ) {
            inputCheck.classList.add("selected");
          }
          labelOption.innerHTML = item;
          filterOption.appendChild(inputCheck);
          filterOption.appendChild(labelOption);
          listFilter.appendChild(filterOption);
        }
      }
      if (filterTitle) {
        filterTitle?.nextElementSibling.appendChild(listFilter);
        result[key].length > 14 &&
          filterTitle.nextElementSibling.appendChild(showFilterSpanWrapper);
      }
    }

    const filterCategories = document.querySelectorAll(
      ".modal-body--category-list ul"
    );
    filterCategories.forEach((filterCategory) => {
      const listFilters = filterCategory.children;
      for (let idx = 0; idx < listFilters.length; idx++) {
        let handleClickCheckFilter = (e) => {
          e.preventDefault();
          const idFilter =
            listFilters[idx].parentElement.parentElement.previousElementSibling
              .id;
          const checkBox = listFilters[idx].firstElementChild;
          if (checkBox.classList.contains("selected")) {
            checkBox.classList.remove("selected");
            listFilters[0].firstElementChild.classList.remove("selected");
            const paramsArray = customGetQueryParams(idFilter).split(",");
            const newParamArr = paramsArray.filter((item) => {
              return (
                decodeURIComponent(item) !==
                listFilters[idx].lastElementChild.innerText
              );
            });
            history.pushState(
              null,
              null,
              window.location.href.replace(
                `${idFilter}=${paramsArray.toString()}`,
                `${idFilter}=${newParamArr.toString()}`
              )
            );
          } else {
            checkBox.classList.add("selected");
            const paramsArray = customGetQueryParams(idFilter)
              ? customGetQueryParams(idFilter).split(",")
              : [];
            paramsArray.push(
              fixedEncodeURIComponent(
                listFilters[idx].lastElementChild.innerText
              )
            );
            history.pushState(
              null,
              null,
              updateQueryStringParameter(
                window.location.href,
                idFilter,
                paramsArray.toString()
              )
            );
            if (paramsArray.length === listFilters.length - 1) {
              listFilters[0].firstElementChild.classList.add("selected");
            }
          }
        };
        if (idx === 0) {
          handleClickCheckFilter = (e) => {
            e.preventDefault();
            const idFilter =
              listFilters[idx].parentElement.parentElement
                .previousElementSibling.id;
            let listQueryParam = [];
            for (let i = 0; i < listFilters.length; i++) {
              if (i > 0) {
                listQueryParam.push(
                  fixedEncodeURIComponent(
                    listFilters[i].lastElementChild.innerText
                  )
                );
              }
              if (i !== idx) {
                listFilters[i].firstElementChild.classList.remove("selected");
              }
            }
            const checkBox = listFilters[idx].firstElementChild;
            if (checkBox.classList.contains("selected")) {
              checkBox.classList.remove("selected");
              history.pushState(
                null,
                null,
                removeURLParameter(window.location.href, idFilter)
              );
            } else {
              for (let i = 0; i < listFilters.length; i++) {
                listFilters[i].firstElementChild.classList.add("selected");
              }
              history.pushState(
                null,
                null,
                updateQueryStringParameter(
                  window.location.href,
                  idFilter,
                  listQueryParam.toString()
                )
              );
            }
          };
        }
        listFilters[idx].firstElementChild.addEventListener(
          "click",
          handleClickCheckFilter
        );
        listFilters[idx].lastElementChild.addEventListener(
          "click",
          handleClickCheckFilter
        );
      }
    });
  }
  function getFiltersAPI() {
    const filterLabels = document.querySelectorAll(
      ".modal-body--category-heading"
    );
    let listFilterLabel = [];
    const queryParams = new Proxy(new URLSearchParams(window.location.search), {
      get: (searchParams, prop) => searchParams.get(prop),
    });
    for (var i = 0; i < filterLabels.length; i++) {
      listFilterLabel.push(filterLabels[i].id);
      if(!!queryParams[filterLabels[i].id]){
        document.querySelector(".filter-icon").parentElement.classList.add("filtered");
      }
    }
    const url = window.location.origin + urlPath + listFilterLabel.toString();
    // const url =
      //   "https://citydevelopmentslimited-dev.sitefinity.cloud/" +
    //   urlPath +
    //   listFilterLabel.toString();
    $.ajax({
      url,
      type: "GET",
      contentType: "application/json",
      dataType: "json",
      success: function (result) {
        handleResultGetFiltersAPI(result.value);
      },
    });
  }
  getFiltersAPI();

  $("button[data-target='#filterModal']").click(function () {
    $("body").css("overflow", "hidden");
  });
});

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!',()*_.~]/g, function (c) {
    return "%" + c.charCodeAt(0).toString(16).toUpperCase();
  });
}

function customGetQueryParams(key) {
  const indexOfKeyParam = window.location.search.indexOf(`&${key}=`)
    ? window.location.search.indexOf(`&${key}=`) 
    : window.location.search.indexOf(`?${key}=`)
  if (indexOfKeyParam === -1) return ""
  const newStr = window.location.search.substring(indexOfKeyParam + key.length + 2),
    result =
      newStr.indexOf("&") !== -1
        ? newStr.substring(0, newStr.indexOf("&"))
        : newStr;
  return result;
}

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf("?") !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, "$1" + key + "=" + value + "$2");
  } else {
    return uri + separator + key + "=" + value;
  }
}

function removeURLParameter(url, parameter) {
  var urlparts = url.split("?");
  if (urlparts.length >= 2) {
    var prefix = encodeURIComponent(parameter) + "=";
    var pars = urlparts[1].split(/[&;]/g);
    for (var i = pars.length; i-- > 0; ) {
      if (pars[i].lastIndexOf(prefix, 0) !== -1) {
        pars.splice(i, 1);
      }
    }
    return urlparts[0] + (pars.length > 0 ? "?" + pars.join("&") : "");
  }
  return url;
}
