window.onload = () => {
  // Open Element
  const btnsDataOpen = document.querySelectorAll("[data-compare-kav-open]");

  if (btnsDataOpen) {
    btnsDataOpen.forEach((btnDataOpen) => {
      btnDataOpen.addEventListener("click", () => {
        const { compareKavOpen, compareKavScrollbar } = btnDataOpen.dataset;
        const content = document.querySelector(compareKavOpen);

        if (content) {
          content.classList.add("open");

          if (compareKavScrollbar) {
            document.documentElement.classList.add(
              "compare-kav-overflow-hidden"
            );
          }
        }
      });
    });
  }

  // Close Element
  const btnsDataClose = document.querySelectorAll("[data-compare-kav-close]");

  if (btnsDataClose) {
    btnsDataClose.forEach((btnDataClose) => {
      btnDataClose.addEventListener("click", () => {
        const { compareKavClose } = btnDataClose.dataset;
        const content = document.querySelector(compareKavClose);

        if (content) {
          content.classList.remove("open");

          document.documentElement.classList.remove(
            "compare-kav-overflow-hidden"
          );
        }
      });
    });
  }

  // Set Width Label
  const allLabels = document.querySelectorAll(
    ".compare-kav__compares__item .label"
  );
  const containerElement = document.querySelector(".compare-kav__container");

  // Check if elements exist before accessing properties
  if (!containerElement || !allLabels.length) {
    return;
  }

  const containerWidth = containerElement.clientWidth - 24;
  const labelWidth = allLabels[0].clientWidth;

  const setWidthcompares = () => {
    if (allLabels.length) {
      allLabels.forEach((label) => {
        const nodes = Array.prototype.slice.call(
          label.closest("#compares").children
        );
        const parent = label.parentElement.parentElement;
        const indexParent = nodes.indexOf(parent);

        if (indexParent) {
          if (nodes.length - 2 === indexParent) {
            label.style.setProperty("--w", labelWidth + labelWidth + "px");
          } else {
            label.style.setProperty(
              "--w",
              containerWidth - labelWidth * indexParent + "px"
            );
          }
        } else {
          label.style.setProperty("--w", containerWidth + "px");
        }
      });
    }
  };

  setWidthcompares();

  // Set Height Box Add Compare
  const setHeightBoxAddCompare = () => {
    const boxProduct = document.querySelector(
      ".compare-kav__compares__item__product"
    );
    const boxAddProduct = document.querySelector(
      ".compare-kav__compares__add__product .box-add"
    );

    if (boxProduct && boxAddProduct) {
      boxAddProduct.style.height = boxProduct.clientHeight + "px";
      boxAddProduct.style.paddingTop = 0;
    }
  };

  setHeightBoxAddCompare();

  window.onresize = () => {
    setWidthcompares();
    setHeightBoxAddCompare();
  };
};
