(function () {
  "use strict";

  window.simplyin_global_update_checkout_in_progress = 1;
  window.simplyin_global_timer = null;
  var SimplyInTimerValue = 0;

  function isAddCardElement(item) {
    const radio = item.querySelector('input[data-toggle-add-card="true"]');
    return radio !== null;
  }

  function shouldAddCardElementBeSelected(item) {
    if (!isAddCardElement(item)) {
      return false;
    }

    const radio = item.querySelector('input[data-toggle-add-card="true"]');
    if (!radio || !radio.checked) {
      return false;
    }

    const itemId = radio.getAttribute("data-item-id");
    if (!itemId) {
      return false;
    }

    const container = document.getElementById(
      "simplyin-add-card-iframe-container-" + itemId
    );

    if (!container || container.style.display === "none") {
      return false;
    }

    const successMessage = document.getElementById(
      "card-success-message-" + itemId
    );
    const confirmButton = document.getElementById(
      "confirm-card-button-" + itemId
    );

    const isCardTokenized =
      (confirmButton && confirmButton.classList.contains("edit-mode")) ||
      (successMessage && successMessage.style.display === "block");

    return isCardTokenized;
  }

  function expandGroup(groupItem) {
    if (!groupItem) return;
    if (groupItem.dataset.animating === "true") return;

    const wrapper = groupItem.querySelector(".simplyin-inner-group-wrapper");
    if (!wrapper) return;

    collapseAllGroups(groupItem);

    groupItem.dataset.animating = "true";
    wrapper.style.display = "block";
    wrapper.classList.add("active");
    groupItem.classList.add("expanded");

    setTimeout(() => {
      groupItem.dataset.animating = "false";
    }, 300);

    addLoadingState(groupItem, 150);
  }

  function collapseGroup(groupItem) {
    if (!groupItem) return;
    if (groupItem.dataset.animating === "true") return;

    const wrapper = groupItem.querySelector(".simplyin-inner-group-wrapper");
    if (!wrapper) return;

    groupItem.dataset.animating = "true";
    wrapper.classList.remove("active");

    setTimeout(() => {
      wrapper.style.display = "";
      groupItem.dataset.animating = "false";
    }, 300);

    groupItem.classList.remove("expanded");
    groupItem.classList.remove("simplyin-selected-group");

    const groupRadio = groupItem.querySelector(
      "input[name='simplyin-inner-group']"
    );
    if (groupRadio) {
      groupRadio.checked = false;
    }

    groupItem
      .querySelectorAll(".simplyin-payment-option-item.inner-group-item")
      .forEach((item) => {
        if (isAddCardElement(item)) {
          if (!shouldAddCardElementBeSelected(item)) {
            item.classList.remove("selected");
          }
        } else {
          item.classList.remove("selected");
        }
        const radio = item.querySelector("input[type='radio']");
        if (radio && !radio.hasAttribute("data-toggle-add-card")) {
          radio.checked = false;
        }
      });
  }

  function collapseAllGroups(exceptGroup = null) {
    document
      .querySelectorAll(".simplyin-payment-option-group-item")
      .forEach((groupItem) => {
        if (groupItem !== exceptGroup) {
          collapseGroup(groupItem);
        }
      });
  }

  function addLoadingState(element, duration = 200) {
    const wrapper = element.closest(".simplyin-payment-methods-wrapper");
    if (wrapper) {
      wrapper.classList.add("loading");
      setTimeout(() => {
        wrapper.classList.remove("loading");
      }, duration);
    }
  }

  function addCurrentClass(el) {
    if (!el) return;

    let canContinue = false;
    const current_payment_block = el.closest("#payment");

    if (!current_payment_block) return;

    const elements = current_payment_block.querySelectorAll(
      ".simplyin-payment-option-item input[type='radio'][name='simplyin-payment-option']"
    );

    if (elements && elements.length > 0) {
      elements.forEach((element) => {
        if (element && element.checked) {
          const closestItem = element.closest(".simplyin-payment-option-item");

          if (closestItem && closestItem.classList) {
            closestItem.style.transition = "all 0.2s ease";
            closestItem.classList.add("selected");

            const hasToggleAddCard = element.hasAttribute(
              "data-toggle-add-card"
            );
            if (!hasToggleAddCard) {
              canContinue = true;
            }
          }

          const isInnerGroupItem =
            element.classList.contains("inside-inner-group");
          if (isInnerGroupItem) {
            const groupItem = element.closest(
              ".simplyin-payment-option-group-item"
            );
            if (groupItem) {
              const groupRadio = groupItem.querySelector(
                "input[name='simplyin-inner-group']"
              );
              if (groupRadio && !groupRadio.checked) {
                groupRadio.checked = true;
                expandGroup(groupItem);
              }
            }
          } else {
            collapseAllGroups();
          }

          const hasToggleAddCard = element.hasAttribute("data-toggle-add-card");
          if (hasToggleAddCard) {
            const itemId = element.getAttribute("data-item-id");
            if (itemId) {
              const isUserInteraction =
                window.SimplyIn?.last_user_interaction || false;
              const hasSavedCards =
                document.querySelectorAll(".simplyin-saved-card").length > 0;
              const shouldAutoExpand =
                !window.SimplyIn?.is_login ||
                isUserInteraction ||
                !hasSavedCards;

              if (shouldAutoExpand) {
                toggleAddCardIframe(itemId);
              }

              const successMessage = document.getElementById(
                "card-success-message-" + itemId
              );
              if (successMessage && successMessage.style.display === "block") {
                canContinue = true;
              }
            }
          }
        }
      });

      const uncheckedElements = current_payment_block.querySelectorAll(
        ".simplyin-payment-option-item input[type='radio'][name='simplyin-payment-option']"
      );

      if (uncheckedElements) {
        uncheckedElements.forEach((element) => {
          if (element && element.checked === false) {
            const closestItem = element.closest(
              ".simplyin-payment-option-item"
            );
            if (closestItem && closestItem.classList) {
              if (isAddCardElement(closestItem)) {
                if (!shouldAddCardElementBeSelected(closestItem)) {
                  closestItem.style.transition = "all 0.2s ease";
                  closestItem.classList.remove("selected");
                }
              } else {
                closestItem.style.transition = "all 0.2s ease";
                closestItem.classList.remove("selected");
              }
            }
          }
        });
      }
    }

    if (canContinue) {
      const checkedRadio = current_payment_block.querySelector(
        'input[name="simplyin-payment-option"]:checked'
      );

      if (checkedRadio) {
        const paymentId = checkedRadio.value;
        const blikContainer = document.querySelector(
          `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
        );

        if (blikContainer && blikContainer.classList.contains("active")) {
          const inputs = blikContainer.querySelectorAll(
            ".simplyin-blik-digit-input"
          );
          const values = Array.from(inputs).map((input) => input.value);
          const blikCode = values.join("");

          if (/^[0-9]{6}$/.test(blikCode)) {
            window.SimplyinActivateNewOrderButton();
          } else {
            window.SimplyinDeactivateNewOrderButton();
          }
        } else {
          window.SimplyinActivateNewOrderButton();
        }
      } else {
        window.SimplyinActivateNewOrderButton();
      }
    } else {
      const selectedAddCardElement = current_payment_block.querySelector(
        ".simplyin-payment-option-item input[type='radio'][name='simplyin-payment-option'][data-toggle-add-card]:checked"
      );

      if (selectedAddCardElement) {
        window.SimplyinActivateNewOrderButton();
      } else {
        window.SimplyinDeactivateNewOrderButton();
      }
    }
  }

  function isElementInViewport(el) {
    const rect = el.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <=
        (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }

  function handleGroupClick(groupItem) {
    const radio = groupItem.querySelector('input[name="simplyin-inner-group"]');
    if (!radio) return;
    if (groupItem.dataset.animating === "true") return;

    const isExpanded = groupItem.classList.contains("expanded");

    if (!isExpanded) {
      radio.checked = true;

      handleGroupChange();

      collapseAllGroups(groupItem);
      expandGroup(groupItem);
      groupItem.classList.add("simplyin-selected-group");

      document
        .querySelectorAll(
          ".simplyin-payment-option-item:not(.inner-group-item) input[type='radio']"
        )
        .forEach((otherRadio) => {
          if (
            otherRadio.checked &&
            !otherRadio.hasAttribute("data-toggle-add-card")
          ) {
            otherRadio.checked = false;
            const item = otherRadio.closest(".simplyin-payment-option-item");
            if (item) {
              if (isAddCardElement(item)) {
                if (!shouldAddCardElementBeSelected(item)) {
                  item.classList.remove("selected");
                }
              } else {
                item.classList.remove("selected");
              }
            }
          }
        });

      window.SimplyinDeactivateNewOrderButton();
    } else {
      radio.checked = false;
      collapseGroup(groupItem);
      groupItem.classList.remove("simplyin-selected-group");
    }
  }

  function initializeClickableAreas() {
    document
      .querySelectorAll(".simplyin-payment-option-group-item > label")
      .forEach((label) => {
        label.addEventListener("click", function (e) {
          e.preventDefault();
          const groupItem = this.closest(".simplyin-payment-option-group-item");
          if (groupItem) {
            handleGroupClick(groupItem);
          }
        });
      });

    document.querySelectorAll(".simplyin-inner-group-name").forEach((span) => {
      span.addEventListener("click", function (e) {
        e.preventDefault();
        const groupItem = this.closest(".simplyin-payment-option-group-item");
        if (groupItem) {
          handleGroupClick(groupItem);
        }
      });
    });

    document
      .querySelectorAll(".simplyin-payment-option-group-item")
      .forEach((groupItem) => {
        groupItem.addEventListener("click", function (e) {
          const clickedWrapper = e.target.closest(
            ".simplyin-inner-group-wrapper"
          );
          const clickedLabel = e.target.closest("label");
          const clickedName = e.target.closest(".simplyin-inner-group-name");

          if (clickedWrapper) return;
          if (
            e.target.type === "radio" &&
            e.target.name === "simplyin-inner-group"
          )
            return;
          if (clickedLabel || clickedName) return;

          handleGroupClick(this);
        });
      });

    jQuery(document).on(
      "click",
      "label[for='simplyin-gateway-bank-group']",
      function (e) {
        e.preventDefault();
        const groupItem =
          jQuery(this).closest(".simplyin-payment-option-group-item").length > 0
            ? jQuery(this).closest(".simplyin-payment-option-group-item")[0]
            : this.parentElement;
        if (groupItem) {
          handleGroupClick(groupItem);
        }
      }
    );

    document
      .querySelectorAll(".simplyin-payment-option-item.inner-group-item")
      .forEach((item) => {
        item.addEventListener("click", function (e) {
          if (e.target.type === "radio") return;

          if (window.SimplyIn) {
            window.SimplyIn.last_user_interaction = true;
          }

          const radio = this.querySelector('input[type="radio"]');
          if (radio && !radio.checked) {
            radio.checked = true;
            addCurrentClass(radio);
          }

          setTimeout(() => {
            if (window.SimplyIn) {
              window.SimplyIn.last_user_interaction = false;
            }
          }, 100);
        });
      });

    document
      .querySelectorAll(".simplyin-payment-option-item:not(.inner-group-item)")
      .forEach((item) => {
        item.addEventListener("click", function (e) {
          if (e.target.type === "radio") return;

          if (window.SimplyIn) {
            window.SimplyIn.last_user_interaction = true;
          }

          const radio = this.querySelector('input[type="radio"]');
          if (radio && !radio.checked) {
            radio.checked = true;
            addCurrentClass(radio);
          }

          setTimeout(() => {
            if (window.SimplyIn) {
              window.SimplyIn.last_user_interaction = false;
            }
          }, 100);
        });
      });
  }

  function initializeEventHandlers() {
    if (typeof jQuery !== "undefined") {
      jQuery("body").on("update_checkout", function () {
        window.simplyin_global_update_checkout_in_progress = 1;

        const wrapper = document.querySelector(
          ".simplyin-payment-methods-wrapper"
        );
        if (wrapper) {
          wrapper.classList.add("loading");
        }

        setTimeout(() => {
          initializeBlikField();
        }, 200);

        const checkedElements = document.querySelectorAll(
          ".simplyin-payment-methods-wrapper .simplyin-payment-option-item input[type='radio'][name='simplyin-payment-option']:checked"
        );
        const checkedGroups = document.querySelectorAll(
          "input[name='simplyin-inner-group']:checked"
        );

        if (checkedGroups && checkedGroups.length > 0) {
          checkedGroups.forEach((groupRadio) => {
            const checkInterval = setInterval(() => {
              if (window.simplyin_global_update_checkout_in_progress === 0) {
                clearInterval(checkInterval);
                const groupItem = groupRadio.closest(
                  ".simplyin-payment-option-group-item"
                );
                if (groupItem) {
                  expandGroup(groupItem);
                  window.SimplyinActivateNewOrderButton();
                  groupItem.classList.add("simplyin-selected-group");
                }
                if (wrapper) {
                  wrapper.classList.remove("loading");
                }
                setTimeout(() => {
                  initializeBlikField();
                }, 50);
              }
            }, 100);
          });
        } else if (checkedElements && checkedElements.length > 0) {
          checkedElements.forEach((element) => {
            const checkInterval = setInterval(() => {
              if (window.simplyin_global_update_checkout_in_progress === 0) {
                clearInterval(checkInterval);
                if (element && element.checked) {
                  window.SimplyinActivateNewOrderButton();
                }
                if (wrapper) {
                  wrapper.classList.remove("loading");
                }
                setTimeout(() => {
                  initializeBlikField();
                }, 50);
              }
            }, 100);
          });
        } else {
          setTimeout(() => {
            if (wrapper) {
              wrapper.classList.remove("loading");
            }
            initializeBlikField();
          }, 500);
        }
      });

      jQuery("body").on("updated_checkout", function () {
        setTimeout(() => {
          const isSimplyInSelected = jQuery("#payment_method_simplyin").is(
            ":checked"
          );

          const wrapper = document.querySelector(
            ".simplyin-payment-methods-wrapper"
          );

          if (isSimplyInSelected) {
            document
              .querySelectorAll(".simplyin-blik-field-container")
              .forEach((container) => {
                const inputs = container.querySelectorAll(
                  ".simplyin-blik-digit-input"
                );
                clearAllBlikInputs(inputs);
                if (inputs.length > 0) {
                  clearAllBlikErrors(inputs[0]);
                }
              });

            document
              .querySelectorAll("[id^='confirm-card-button-']")
              .forEach((button) => {
                button.classList.remove("edit-mode");
                button.textContent = getTranslations().confirmButton;
                button.disabled = false;

                const itemId = button.id.replace("confirm-card-button-", "");

                if (window.SimplyIn?.is_login) {
                  const cardNameField = document.getElementById("card-name");
                  if (cardNameField) {
                    cardNameField.value = "";
                  }
                }

                forceUnlockCardForm(itemId);
              });

            document
              .querySelectorAll(".simplyin-add-card-iframe")
              .forEach((form) => {
                form.innerHTML = "";
                form.style.display = "none";
              });

            document
              .querySelectorAll("[id^='card-success-message-']")
              .forEach((message) => {
                message.style.display = "none";
              });

            document
              .querySelectorAll("[id^='form-error-']")
              .forEach((error) => {
                error.style.display = "none";
              });

            document
              .querySelectorAll("[id^='simplyin-add-card-iframe-container-']")
              .forEach((container) => {
                container.style.display = "none";
              });

            const hiddenInputs = [
              'input[name="simplyin_ott"]',
              'input[name="simplyin_first_digits"]',
              'input[name="simplyin_last_digits"]',
              'input[name="simplyin_organization"]',
              'input[name="simplyin_card_name"]',
              'input[name="simplyin_card_save_checkbox"]',
            ];

            hiddenInputs.forEach((selector) => {
              const input = document.querySelector(selector);
              if (input) {
                input.value =
                  input.name === "simplyin_card_save_checkbox" ? "false" : "";
              }
            });

            document
              .querySelectorAll('input[name="simplyin-payment-option"]')
              .forEach((radio) => {
                if (!radio.hasAttribute("data-toggle-add-card")) {
                  radio.checked = false;
                }
              });

            document
              .querySelectorAll('input[name="simplyin-inner-group"]')
              .forEach((radio) => {
                radio.checked = false;
              });

            document
              .querySelectorAll(".simplyin-payment-option-item")
              .forEach((item) => {
                if (!isAddCardElement(item)) {
                  item.classList.remove("selected");
                }
              });

            document
              .querySelectorAll(".simplyin-payment-option-group-item")
              .forEach((group) => {
                group.classList.remove("simplyin-selected-group", "expanded");
                const wrapper = group.querySelector(
                  ".simplyin-inner-group-wrapper"
                );
                if (wrapper) {
                  wrapper.classList.remove("active");
                  wrapper.style.display = "";
                }
              });

            window.SimplyinDeactivateNewOrderButton();

            window.simplyInRadioShow();

            setTimeout(() => {
              initializeBlikField();
            }, 200);

            autoSelectAddCardOption();

            const hasSavedCards =
              document.querySelectorAll(".simplyin-saved-card").length > 0;

            if (window.SimplyIn?.is_login && hasSavedCards) {
              document
                .querySelectorAll('input[data-toggle-add-card="true"]')
                .forEach((radio) => {
                  const selectedItem = document.querySelector(
                    "#simplyin-add-card-payment-method"
                  );
                  selectedItem.classList.remove("selected");
                  radio.checked = false;
                  const itemId = radio.getAttribute("data-item-id");
                  if (itemId) {
                    const container = document.getElementById(
                      "simplyin-add-card-iframe-container-" + itemId
                    );
                    if (container) {
                      container.style.display = "none";
                    }
                  }
                });
            }

            if (window.SimplyIn?.is_login) {
              setTimeout(() => {
                window.SimplyIn.showCardSaveCheckbox();
              }, 300);
            }
          } else {
            window.simplyInRadioHide();
          }

          if (wrapper) {
            wrapper.classList.remove("loading");
          }
        }, 100);
      });
    }

    let clickTimeout;
    document.addEventListener("click", function (event) {
      clearTimeout(clickTimeout);
      clickTimeout = setTimeout(() => {
        handleClick(event);
      }, 10);
    });

    function handleClick(event) {
      const target = event.target;
      if (!target) return;

      if (target.name === "simplyin-inner-group") {
        if (target.checked) {
          const groupItem = target.closest(
            ".simplyin-payment-option-group-item"
          );
          if (groupItem) {
            collapseAllGroups(groupItem);
            expandGroup(groupItem);
            groupItem.classList.add("simplyin-selected-group");

            document
              .querySelectorAll(
                ".simplyin-payment-option-item:not(.inner-group-item) input[type='radio']"
              )
              .forEach((radio) => {
                if (
                  radio.checked &&
                  !radio.hasAttribute("data-toggle-add-card")
                ) {
                  radio.checked = false;
                  const item = radio.closest(".simplyin-payment-option-item");
                  if (item && !isAddCardElement(item)) {
                    item.classList.remove("selected");
                  }
                }
              });

            window.SimplyinDeactivateNewOrderButton();
          }
        }
      } else if (target.name === "simplyin-payment-option") {
        if (!target.classList.contains("inside-inner-group")) {
          collapseAllGroups();
          window.SimplyinDeselectGroupedLi();
        }
      } else if (
        target.hasAttribute("class") &&
        target.getAttribute("class") !==
          "simplyin-payment-option-group-in-group"
      ) {
        window.SimplyinDeselectGroupedLi();
      }
    }

    document
      .querySelectorAll(".simplyin-inner-group-wrapper")
      .forEach((wrapper) => {
        wrapper.classList.remove("active");
      });
  }

  window.SimplyinDeactivateNewOrderButton = function () {
    if (typeof jQuery !== "undefined" && jQuery("#place_order").length > 0) {
      const button = jQuery("#place_order")[0];
      button.disabled = true;
      button.style.transition = "opacity 0.2s ease";
      button.style.opacity = "0.6";
    }
  };

  window.SimplyinActivateNewOrderButton = function () {
    if (typeof jQuery !== "undefined" && jQuery("#place_order").length > 0) {
      const button = jQuery("#place_order")[0];
      button.disabled = false;
      button.style.transition = "opacity 0.2s ease";
      button.style.opacity = "1";
    }

    if (!window.SimplyIn) {
      return;
    }

    if (window.SimplyIn.is_login) {
      return;
    }

    window.SimplyIn.validatePhoneNumber();
  };

  window.SimplyinSelectGroupedLi = function () {
    if (typeof jQuery !== "undefined") {
      jQuery(".simplyin-payment-option-group-item").addClass(
        "simplyin-selected-group"
      );
    }
  };

  window.SimplyinDeselectGroupedLi = function () {
    if (typeof jQuery !== "undefined") {
      jQuery(".simplyin-payment-option-group-item").removeClass(
        "simplyin-selected-group"
      );
    }
  };

  window.SimplyinGetSelectedPaymentMethod = function () {
    const checkedRadio = document.querySelector(
      'input[name="simplyin-payment-option"]:checked'
    );
    return checkedRadio ? checkedRadio.value : null;
  };

  window.SimplyinValidateBlikCode = function () {
    const checkedRadio = document.querySelector(
      'input[name="simplyin-payment-option"]:checked'
    );
    if (!checkedRadio) return true;

    const paymentId = checkedRadio.value;
    const container = document.querySelector(
      `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
    );

    if (!container || !container.classList.contains("active")) return true;

    const inputs = container.querySelectorAll(".simplyin-blik-digit-input");
    const values = Array.from(inputs).map((input) => input.value);
    const blikCode = values.join("");

    return /^[0-9]{6}$/.test(blikCode);
  };

  window.SimplyinIsMainPaymentMethodSelected = function () {
    const simplyInRadio = document.querySelector("#payment_method_simplyin");
    return simplyInRadio ? simplyInRadio.checked : false;
  };

  function setupBlikInputEvents(input, inputs, index) {
    if (input.hasAttribute("data-blik-initialized")) return;
    input.setAttribute("data-blik-initialized", "true");

    const keydownHandler = (e) => handleBlikKeydown(e, inputs, index);
    const keypressHandler = (e) => handleBlikKeypress(e);
    const inputHandler = (e) => handleBlikInput(e, inputs, index);
    const focusHandler = (e) => handleBlikFocus(e);
    const blurHandler = (e) => handleBlikBlur(e, inputs);
    const pasteHandler = (e) => handleBlikPaste(e, inputs, index);
    const clickHandler = (e) => handleBlikClick(e);

    input.addEventListener("keydown", keydownHandler);
    input.addEventListener("keypress", keypressHandler);
    input.addEventListener("input", inputHandler);
    input.addEventListener("focus", focusHandler);
    input.addEventListener("blur", blurHandler);
    input.addEventListener("paste", pasteHandler);
    input.addEventListener("click", clickHandler);
    input.addEventListener("contextmenu", (e) => e.preventDefault());
    input.addEventListener("drop", (e) => e.preventDefault());
    input.addEventListener("dragover", (e) => e.preventDefault());
  }

  function initializeBlikField() {
    const blikContainers = document.querySelectorAll(
      ".simplyin-blik-field-container"
    );

    blikContainers.forEach((container) => {
      const inputs = container.querySelectorAll(".simplyin-blik-digit-input");
      inputs.forEach((input, index) => {
        setupBlikInputEvents(input, inputs, index);
      });
    });
  }

  function handleBlikKeypress(event) {
    const key = event.key;
    const isDigit = /^[0-9]$/.test(key);
    const allowedKeys = [
      "Backspace",
      "Delete",
      "Tab",
      "Enter",
      "Escape",
      "ArrowLeft",
      "ArrowRight",
    ];

    if (
      !isDigit &&
      !allowedKeys.includes(key) &&
      !event.ctrlKey &&
      !event.metaKey
    ) {
      event.preventDefault();
      event.stopPropagation();
      return false;
    }
  }

  function handleBlikKeydown(event, inputs, currentIndex) {
    const input = event.target;
    const key = event.key;

    if (key === "Backspace" || key === "Delete") {
      if (input.value === "" && key === "Backspace" && currentIndex > 0) {
        event.preventDefault();
        inputs[currentIndex - 1].focus();
        inputs[currentIndex - 1].value = "";
        inputs[currentIndex - 1].classList.remove("filled", "valid", "error");
        updateBlikValidation(inputs);
      } else if (input.value !== "") {
        input.value = "";
        input.classList.remove("filled", "valid", "error");
        updateBlikValidation(inputs);
        event.preventDefault();
      }
      return;
    }

    if (key === "ArrowLeft" && currentIndex > 0) {
      event.preventDefault();
      inputs[currentIndex - 1].focus();
      return;
    }

    if (key === "ArrowRight" && currentIndex < inputs.length - 1) {
      event.preventDefault();
      inputs[currentIndex + 1].focus();
      return;
    }

    if (/^[0-9]$/.test(key)) {
      event.preventDefault();
      input.value = key;
      input.classList.add("filled");
      input.classList.remove("error");
      input.dataset.keydownHandled = "true";

      updateBlikValidation(inputs);

      if (currentIndex < inputs.length - 1) {
        setTimeout(() => {
          inputs[currentIndex + 1].focus();
          delete input.dataset.keydownHandled;
        }, 5);
      } else {
        delete input.dataset.keydownHandled;
      }
      return;
    }

    const allowedKeys = ["Tab", "Enter", "Escape"];
    if (!allowedKeys.includes(key) && !event.ctrlKey && !event.metaKey) {
      event.preventDefault();
      event.stopPropagation();
    }
  }

  function handleBlikInput(event, inputs, currentIndex) {
    const input = event.target;

    if (input.dataset.keydownHandled === "true") {
      return;
    }

    const paymentId = input.getAttribute("data-payment-id");
    if (paymentId) {
      selectBlikRadioButton(paymentId);
    }

    let value = input.value;
    value = value.replace(/[^0-9]/g, "");

    if (value.length > 1) {
      value = value.charAt(value.length - 1);
    }

    input.value = value;

    if (value !== "") {
      input.classList.add("filled");
      input.classList.remove("error");

      if (currentIndex < inputs.length - 1) {
        setTimeout(() => {
          inputs[currentIndex + 1].focus();
        }, 5);
      }
    } else {
      input.classList.remove("filled", "valid", "error");
    }

    updateBlikValidation(inputs);
  }

  function handleBlikClick(event) {
    const input = event.target;
    const paymentId = input.getAttribute("data-payment-id");
    if (paymentId) {
      selectBlikRadioButton(paymentId);
    }
  }

  function handleBlikFocus(event) {
    const input = event.target;
    const paymentId = input.getAttribute("data-payment-id");

    input.classList.remove("error");
    clearBlikError(input);

    if (paymentId) {
      selectBlikRadioButton(paymentId);
    }

    setTimeout(() => {
      input.select();
    }, 5);
  }

  function handleBlikBlur(event, inputs) {
    setTimeout(() => {
      const container = inputs[0].closest(".simplyin-blik-field-container");
      if (!container.contains(document.activeElement)) {
        validateAllBlikDigits(inputs);
      }
    }, 100);
  }

  function handleBlikPaste(event, inputs, currentIndex) {
    event.preventDefault();

    const paste = (event.clipboardData || window.clipboardData).getData("text");
    const digits = paste.replace(/[^0-9]/g, "").substring(0, 6);

    if (digits.length > 0) {
      clearAllBlikInputs(inputs);

      for (let i = 0; i < Math.min(digits.length, inputs.length); i++) {
        inputs[i].value = digits[i];
        inputs[i].classList.add("filled");
        inputs[i].classList.remove("error");
      }

      const nextIndex = Math.min(digits.length, inputs.length - 1);
      inputs[nextIndex].focus();

      updateBlikValidation(inputs);
    }
  }

  function clearAllBlikInputs(inputs) {
    inputs.forEach((input) => {
      input.value = "";
      input.classList.remove("error", "valid");
    });

    const hiddenInput = document.querySelector(
      'input[name="simplyin_blik_code"]'
    );
    if (hiddenInput) {
      hiddenInput.value = "";
    }

    const checkedRadio = document.querySelector(
      'input[name="simplyin-payment-option"]:checked'
    );
    if (checkedRadio) {
      const paymentId = checkedRadio.value;
      const blikContainer = document.querySelector(
        `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
      );
      if (blikContainer && blikContainer.classList.contains("active")) {
        window.SimplyinDeactivateNewOrderButton();
      }
    }
  }

  function updateBlikValidation(inputs) {
    const values = Array.from(inputs).map((input) => input.value);
    const filledCount = values.filter((v) => /^[0-9]$/.test(v)).length;
    const blikCode = values.join("");

    const hiddenInput = document.querySelector(
      'input[name="simplyin_blik_code"]'
    );
    if (hiddenInput) {
      hiddenInput.value = blikCode;
    }

    if (filledCount === 6) {
      inputs.forEach((input) => {
        if (/^[0-9]$/.test(input.value)) {
          input.classList.remove("error");
          input.classList.add("valid");
        }
      });
      clearAllBlikErrors(inputs[0]);

      window.SimplyinActivateNewOrderButton();
    } else {
      inputs.forEach((input) => {
        if (input.value) {
          input.classList.remove("valid");
        }
      });

      if (filledCount === 0) {
        clearAllBlikErrors(inputs[0]);
      }

      const checkedRadio = document.querySelector(
        'input[name="simplyin-payment-option"]:checked'
      );
      if (checkedRadio) {
        const paymentId = checkedRadio.value;
        const blikContainer = document.querySelector(
          `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
        );
        if (blikContainer && blikContainer.classList.contains("active")) {
          window.SimplyinDeactivateNewOrderButton();
        }
      }
    }
  }

  function validateAllBlikDigits(inputs) {
    const values = Array.from(inputs).map((input) => input.value);
    const validDigits = values.filter((v) => /^[0-9]$/.test(v));

    if (validDigits.length === 0) {
      clearAllBlikErrors(inputs[0]);
      const checkedRadio = document.querySelector(
        'input[name="simplyin-payment-option"]:checked'
      );
      if (checkedRadio) {
        const paymentId = checkedRadio.value;
        const blikContainer = document.querySelector(
          `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
        );
        if (blikContainer && blikContainer.classList.contains("active")) {
          window.SimplyinDeactivateNewOrderButton();
        }
      }
      return true;
    }

    if (validDigits.length === 6) {
      inputs.forEach((input) => {
        if (/^[0-9]$/.test(input.value)) {
          input.classList.remove("error");
          input.classList.add("valid");
        }
      });
      clearAllBlikErrors(inputs[0]);
      window.SimplyinActivateNewOrderButton();
      return true;
    } else {
      inputs.forEach((input) => {
        if (input.value) {
          input.classList.add("error");
          input.classList.remove("valid");
        }
      });
      showAllBlikErrors(inputs[0]);
      window.SimplyinDeactivateNewOrderButton();
      return false;
    }
  }

  function showAllBlikErrors(firstInput) {
    const container = firstInput.closest(".simplyin-blik-input-wrapper");
    const errorElement = container.querySelector(".simplyin-blik-error");

    if (errorElement) {
      errorElement.style.display = "flex";
    }
  }

  function clearAllBlikErrors(firstInput) {
    const container = firstInput.closest(".simplyin-blik-input-wrapper");
    const errorElement = container.querySelector(".simplyin-blik-error");

    if (errorElement) {
      errorElement.style.display = "none";
    }
  }

  function clearBlikError(input) {
    clearAllBlikErrors(input);
  }

  function selectBlikRadioButton(paymentId) {
    const radioButton = document.querySelector(
      `input[name="simplyin-payment-option"][value="${paymentId}"]`
    );

    if (radioButton && !radioButton.checked) {
      radioButton.checked = true;
      radioButton.dispatchEvent(new Event("change", { bubbles: true }));
      addCurrentClass(radioButton);
      validateBlikOnSubmit();
    }
  }

  function toggleBlikField(paymentId, show = true) {
    const container = document.querySelector(
      `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
    );

    if (!container) return;

    if (show) {
      container.classList.add("active");
      const firstInput = container.querySelector(".simplyin-blik-digit-input");
      if (firstInput) {
        setTimeout(() => {
          firstInput.focus();
        }, 350);
      }
    } else {
      const inputs = container.querySelectorAll(".simplyin-blik-digit-input");
      clearAllBlikInputs(inputs);
      if (inputs.length > 0) {
        clearAllBlikErrors(inputs[0]);
      }
    }
  }

  function getBlikCode(paymentId) {
    const container = document.querySelector(
      `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
    );
    if (!container) return "";

    const inputs = container.querySelectorAll(".simplyin-blik-digit-input");
    const code = Array.from(inputs)
      .map((input) => input.value)
      .join("");

    return /^[0-9]{6}$/.test(code) ? code : "";
  }

  function validateBlikOnSubmit() {
    const checkedRadio = document.querySelector(
      'input[name="simplyin-payment-option"]:checked'
    );
    if (!checkedRadio) return true;

    const paymentId = checkedRadio.value;
    const container = document.querySelector(
      `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
    );

    if (!container || !container.classList.contains("active")) return true;

    const inputs = container.querySelectorAll(".simplyin-blik-digit-input");
    const isValid = validateAllBlikDigits(inputs);

    if (!isValid) {
      const firstEmptyInput =
        Array.from(inputs).find((input) => !input.value) || inputs[0];
      firstEmptyInput.focus();
      return false;
    }

    return true;
  }

  function handlePaymentMethodChange() {
    const checkedRadio = document.querySelector(
      'input[name="simplyin-payment-option"]:checked'
    );

    document
      .querySelectorAll(".simplyin-payment-option-item")
      .forEach((item) => {
        if (isAddCardElement(item)) {
          if (!shouldAddCardElementBeSelected(item)) {
            item.classList.remove("selected");
          }
        } else {
          item.classList.remove("selected");
        }
      });

    document
      .querySelectorAll(".simplyin-blik-field-container")
      .forEach((container) => {
        const inputs = container.querySelectorAll(".simplyin-blik-digit-input");
        clearAllBlikInputs(inputs);
        if (inputs.length > 0) {
          clearAllBlikErrors(inputs[0]);
        }
      });

    if (checkedRadio) {
      const selectedItem = checkedRadio.closest(
        ".simplyin-payment-option-item"
      );
      if (selectedItem) {
        selectedItem.classList.add("selected");
      }

      const paymentId = checkedRadio.value;
      const blikContainer = document.querySelector(
        `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
      );

      if (blikContainer) {
        window.SimplyinDeactivateNewOrderButton();
        setTimeout(() => {
          toggleBlikField(paymentId, true);
          initializeBlikField();
        }, 100);
      } else {
        const hasToggleAddCard = checkedRadio.hasAttribute(
          "data-toggle-add-card"
        );

        if (hasToggleAddCard) {
          const itemId = checkedRadio.getAttribute("data-item-id");
          const hasSavedCards =
            document.querySelectorAll(".simplyin-saved-card").length > 0;

          if (itemId) {
            if (window.SimplyIn?.is_login && hasSavedCards) {
              const selectedItem = document.querySelector(
                "#simplyin-add-card-payment-method"
              );
              const radioButton = document.querySelector(
                `input[name="simplyin-payment-option"][value="${itemId}"]`
              );
              radioButton.checked = false;
              selectedItem.classList.remove("selected");
              const container = document.getElementById(
                "simplyin-add-card-iframe-container-" + itemId
              );
              if (container) {
                container.style.display = "none";
              }
              window.SimplyinDeactivateNewOrderButton();
            } else {
              toggleAddCardIframe(itemId);
            }
          }

          const selectedItem = checkedRadio.closest(
            ".simplyin-payment-option-item"
          );
          if (selectedItem) {
            selectedItem.classList.add("selected");
          }
        } else {
          const hasToggleAddCardOld =
            checkedRadio.hasAttribute("onclick") &&
            checkedRadio
              .getAttribute("onclick")
              .includes("toggleAddCardIframe");

          if (hasToggleAddCardOld) {
            const paymentIdParts = paymentId.split("-");
            const shortId = paymentIdParts[paymentIdParts.length - 1];
            const addCardContainer = document.querySelector(
              `#simplyin-add-card-iframe-container-${shortId}`
            );
            if (addCardContainer) {
              addCardContainer.style.display = "block";
            }

            const selectedItem = checkedRadio.closest(
              ".simplyin-payment-option-item"
            );
            if (selectedItem) {
              selectedItem.classList.add("selected");
            }
          } else {
            window.addCurrentClass(checkedRadio);
          }
        }
      }
    } else {
      window.SimplyinDeactivateNewOrderButton();
    }
  }

  function handleGroupChange() {
    const checkedGroup = document.querySelector(
      'input[name="simplyin-inner-group"]:checked'
    );

    if (checkedGroup) {
      const blikContainers = document.querySelectorAll(
        ".simplyin-blik-field-container"
      );

      blikContainers.forEach((container) => {
        const inputs = container.querySelectorAll(".simplyin-blik-digit-input");
        clearAllBlikInputs(inputs);
        if (inputs.length > 0) {
          clearAllBlikErrors(inputs[0]);
        }
      });

      document
        .querySelectorAll('input[name="simplyin-payment-option"]')
        .forEach((radio) => {
          if (!radio.hasAttribute("data-toggle-add-card")) {
            radio.checked = false;
          }
        });

      document
        .querySelectorAll(".simplyin-payment-option-item")
        .forEach((item) => {
          if (isAddCardElement(item)) {
            if (!shouldAddCardElementBeSelected(item)) {
              item.classList.remove("selected");
            }
          } else {
            item.classList.remove("selected");
          }
        });

      window.SimplyinDeactivateNewOrderButton();
    }
  }

  function handleMainPaymentMethodChange() {
    const simplyInSelected = document.querySelector(
      "#payment_method_simplyin:checked"
    );

    if (!simplyInSelected) {
      window.simplyInRadioHide();

      document
        .querySelectorAll(".simplyin-blik-field-container")
        .forEach((container) => {
          const inputs = container.querySelectorAll(
            ".simplyin-blik-digit-input"
          );
          clearAllBlikInputs(inputs);
          if (inputs.length > 0) {
            clearAllBlikErrors(inputs[0]);
          }
        });

      document
        .querySelectorAll("[id^='confirm-card-button-']")
        .forEach((button) => {
          button.classList.remove("edit-mode");
          button.textContent = getTranslations().confirmButton;
          button.disabled = false;

          if (window.SimplyIn?.is_login) {
            const cardNameField = document.getElementById("card-name");
            if (cardNameField) {
              cardNameField.value = "";
            }
          }
        });

      document
        .querySelectorAll("[id^='card-success-message-']")
        .forEach((message) => {
          message.style.display = "none";
        });

      document
        .querySelectorAll('input[name="simplyin-payment-option"]')
        .forEach((radio) => {
          if (!radio.hasAttribute("data-toggle-add-card")) {
            radio.checked = false;
          }
        });

      document
        .querySelectorAll('input[name="simplyin-inner-group"]')
        .forEach((radio) => {
          radio.checked = false;
        });

      document
        .querySelectorAll(".simplyin-payment-option-item")
        .forEach((item) => {
          if (isAddCardElement(item)) {
            if (!shouldAddCardElementBeSelected(item)) {
              item.classList.remove("selected");
            }
          } else {
            item.classList.remove("selected");
          }
        });

      document
        .querySelectorAll(".simplyin-payment-option-group-item")
        .forEach((group) => {
          group.classList.remove("simplyin-selected-group", "expanded");
          const wrapper = group.querySelector(".simplyin-inner-group-wrapper");
          if (wrapper) {
            wrapper.classList.remove("active");
            wrapper.style.display = "";
          }
        });

      const isNewAccFormExistsChecked = document.querySelector(
        "#simply-save-checkbox"
      )?.checked;

      if (
        window.SimplyIn &&
        window.SimplyIn.validatePhoneNumber &&
        isNewAccFormExistsChecked
      ) {
        const isPhoneValid = window.SimplyIn.validatePhoneNumber();
        if (isPhoneValid) {
          window.SimplyinActivateNewOrderButton();
        }
      } else {
        window.SimplyinActivateNewOrderButton();
      }
    } else {
      window.simplyInRadioShow();
      window.SimplyinDeactivateNewOrderButton();
    }
  }

  function initializeWooCommercePaymentHandlers() {
    if (typeof jQuery === "undefined") return;

    jQuery(document).ready(function () {
      clearTimeout(window.simplyin_global_timer);

      var isSimplyInSelected = jQuery("#payment_method_simplyin").is(
        ":checked"
      );

      if (isSimplyInSelected) {
        window.simplyInRadioShow();
        window.SimplyinDeactivateNewOrderButton();
        setTimeout(() => {
          autoSelectAddCardOption();
        }, 500);
      } else {
        window.simplyInRadioHide();
      }

      window.simplyin_global_timer = setTimeout(function () {
        window.simplyin_global_update_checkout_in_progress = 0;
        window.simplyInRadioTest();
      }, SimplyInTimerValue);
    });

    jQuery(document).on("click", ".simplyin-add-card-label", function () {
      const addCardRadio = document.querySelector(
        'input[data-toggle-add-card="true"]'
      );

      if (addCardRadio) {
        addCardRadio.checked = true;
        const itemId = addCardRadio.getAttribute("data-item-id");
        if (itemId) {
          const container = document.getElementById(
            "simplyin-add-card-iframe-container-" + itemId
          );
          if (container) {
            container.style.display = "block";

            const iframeForm = document.getElementById(
              "simplyin-add-card-" + itemId
            );
            const hasIframe = iframeForm && iframeForm.querySelector("iframe");

            if (!hasIframe) {
              toggleAddCardIframe(itemId);
            }
          }
        }
        return;
      }
    });

    jQuery("input[name='payment_method']").on("click touchstart", function () {
      var radioButtons = jQuery("input[name='payment_method']");
      for (var i = 0; i < radioButtons.length; i++) {
        if (
          radioButtons[i].checked &&
          radioButtons[i].id !== "payment_method_simplyin"
        ) {
          window.SimplyinActivateNewOrderButton();
          window.SimplyinDeselectGroupedLi();
        }
      }

      jQuery("input[id='payment_method_simplyin']").on("click", function () {
        jQuery(".payment_box")
          .find("input[type='radio']")
          .prop("checked", false);
        jQuery(".payment_box").find("li").removeClass("selected");
        window.SimplyinDeactivateNewOrderButton();
      });

      clearTimeout(window.simplyin_global_timer);
      window.simplyin_global_timer = setTimeout(function () {
        if (0 === window.simplyin_global_update_checkout_in_progress) {
          window.simplyInRadioTest();
        }
      }, SimplyInTimerValue);

      jQuery("#payment_method_simplyin").on("click", function () {
        clearTimeout(window.simplyin_global_timer);
        window.simplyin_global_timer = setTimeout(function () {
          if (0 === window.simplyin_global_update_checkout_in_progress) {
            window.simplyInRadioShow();
          }
        }, SimplyInTimerValue);
      });

      jQuery(
        "ul.wc_payment_methods > li.wc_payment_method:not(.payment_method_simplyin)"
      ).on("click", function () {
        window.simplyInRadioHide();
      });
    });
  }

  function autoSelectAddCardOption() {
    setTimeout(() => {
      const hasSavedCards =
        document.querySelectorAll(".simplyin-saved-card").length > 0;
      if (window.SimplyIn?.is_login && hasSavedCards) {
        const addCardRadio = document.querySelector(
          'input[data-toggle-add-card="true"]'
        );

        if (addCardRadio) {
          const selectedItem = document.querySelector(
            "#simplyin-add-card-payment-method"
          );
          selectedItem.classList.remove("selected");
          addCardRadio.checked = false;
          const itemId = addCardRadio.getAttribute("data-item-id");
          if (itemId) {
            const container = document.getElementById(
              "simplyin-add-card-iframe-container-" + itemId
            );
            if (container) {
              container.style.display = "none";
            }
          }
          return;
        }
      }

      const addCardRadio = document.querySelector(
        'input[data-toggle-add-card="true"]'
      );

      if (addCardRadio && !addCardRadio.checked) {
        addCardRadio.checked = true;
        addCurrentClass(addCardRadio);

        const itemId = addCardRadio.getAttribute("data-item-id");
        if (itemId) {
          toggleAddCardIframe(itemId);

          if (window.SimplyIn?.is_login) {
            setTimeout(() => {
              window.SimplyIn.showCardSaveCheckbox();
            }, 100);
          }
        }

        if (!window.SimplyIn?.is_login) {
          addCardRadio.checked = false;
        }
      }
    }, 100);
  }

  function initialize() {
    initializeEventHandlers();
    initializeClickableAreas();
    initializeBlikField();
    initializeWooCommercePaymentHandlers();

    setTimeout(() => {
      const checkedRadio = document.querySelector(
        'input[name="simplyin-payment-option"]:checked'
      );
      if (checkedRadio) {
        const paymentId = checkedRadio.value;
        const blikContainer = document.querySelector(
          `[data-payment-id="${paymentId}"].simplyin-blik-field-container`
        );
        if (blikContainer && blikContainer.classList.contains("active")) {
          window.SimplyinDeactivateNewOrderButton();
        }
      }
    }, 200);

    document.addEventListener("change", function (event) {
      if (event.target.name === "simplyin_card_save_visible") {
        const isChecked = event.target.checked;
        const hiddenInput = document.querySelector(
          'input[name="simplyin_card_save_checkbox"]'
        );
        const cardNameInput = document.querySelector(".card-name-group");

        if (hiddenInput) {
          hiddenInput.value = isChecked ? "true" : "false";
        }

        if (cardNameInput) {
          cardNameInput.classList.toggle("card-name-group-hidden", !isChecked);
        }
      }
    });

    document.addEventListener("click", function (event) {
      if (event.target.classList.contains("simplyin-blik-digit-input")) {
        const input = event.target;
        const paymentId = input.getAttribute("data-payment-id");
        if (paymentId) {
          selectBlikRadioButton(paymentId);
        }
      }

      const addCardContainer = event.target.closest(
        ".simplyin-add-card-iframe-container"
      );
      const addCardForm = event.target.closest(".simplyin-add-card-iframe");
      const addCardFormGroup = event.target.closest(".form-group");
      const addCardFormRow = event.target.closest(".form-row");
      const addCardInput = event.target.closest(".card-input");
      const addCardField = event.target.closest(".card-field");
      const ccIframeComponent = event.target.closest(".ccIframe-component");

      if (
        addCardContainer ||
        addCardForm ||
        addCardFormGroup ||
        addCardFormRow ||
        addCardInput ||
        addCardField ||
        ccIframeComponent
      ) {
        if (window.SimplyIn) {
          window.SimplyIn.last_user_interaction = true;
        }

        let itemId = null;

        if (addCardContainer) {
          const containerId = addCardContainer.id;
          if (
            containerId &&
            containerId.startsWith("simplyin-add-card-iframe-container-")
          ) {
            itemId = containerId.replace(
              "simplyin-add-card-iframe-container-",
              ""
            );
          }
        }

        if (!itemId && addCardForm) {
          const formId = addCardForm.id;
          if (formId && formId.startsWith("simplyin-add-card-")) {
            itemId = formId.replace("simplyin-add-card-", "");
          }
        }

        if (!itemId) {
          const containerParent = event.target.closest(
            "[id*='simplyin-add-card-iframe-container-']"
          );
          if (containerParent && containerParent.id) {
            itemId = containerParent.id.replace(
              "simplyin-add-card-iframe-container-",
              ""
            );
          }
        }

        if (!itemId) {
          const formParent = event.target.closest("[id*='simplyin-add-card-']");
          if (
            formParent &&
            formParent.id &&
            formParent.id.startsWith("simplyin-add-card-")
          ) {
            itemId = formParent.id.replace("simplyin-add-card-", "");
          }
        }

        if (itemId) {
          const radioButton = document.getElementById(
            "simplyin-payment-option-" + itemId
          );

          if (radioButton && !radioButton.checked) {
            radioButton.checked = true;
            addCurrentClass(radioButton);
          }
        }

        setTimeout(() => {
          if (window.SimplyIn) {
            window.SimplyIn.last_user_interaction = false;
          }
        }, 100);
      }
    });

    document.addEventListener(
      "focus",
      function (event) {
        if (event.target.classList.contains("simplyin-blik-digit-input")) {
          const input = event.target;
          const paymentId = input.getAttribute("data-payment-id");
          if (paymentId) {
            selectBlikRadioButton(paymentId);
          }
        }

        const addCardInput = event.target.closest(".card-input");
        const addCardField = event.target.closest(".card-field");
        const ccIframeComponent = event.target.closest(".ccIframe-component");

        if (addCardInput || addCardField || ccIframeComponent) {
          let itemId = null;

          const containerParent = event.target.closest(
            "[id*='simplyin-add-card-iframe-container-']"
          );
          if (containerParent && containerParent.id) {
            itemId = containerParent.id.replace(
              "simplyin-add-card-iframe-container-",
              ""
            );
          }

          if (!itemId) {
            const formParent = event.target.closest(
              "[id*='simplyin-add-card-']"
            );
            if (
              formParent &&
              formParent.id &&
              formParent.id.startsWith("simplyin-add-card-")
            ) {
              itemId = formParent.id.replace("simplyin-add-card-", "");
            }
          }

          if (itemId) {
            const radioButton = document.getElementById(
              "simplyin-payment-option-" + itemId
            );

            if (radioButton && !radioButton.checked) {
              radioButton.checked = true;
              addCurrentClass(radioButton);
            }
          }
        }
      },
      true
    );

    document.addEventListener("input", function (event) {
      if (event.target.classList.contains("simplyin-blik-digit-input")) {
        const input = event.target;
        const paymentId = input.getAttribute("data-payment-id");

        if (paymentId) {
          selectBlikRadioButton(paymentId);
        }

        const container = input.closest(".simplyin-blik-field-container");
        if (container) {
          const inputs = container.querySelectorAll(
            ".simplyin-blik-digit-input"
          );
          const inputsArray = Array.from(inputs);
          const currentIndex = inputsArray.indexOf(input);

          if (input.dataset.keydownHandled === "true") {
            return;
          }

          let value = input.value;
          value = value.replace(/[^0-9]/g, "");

          if (value.length > 1) {
            value = value.charAt(value.length - 1);
          }

          input.value = value;

          if (value !== "") {
            input.classList.add("filled");
            input.classList.remove("error");

            if (currentIndex < inputs.length - 1) {
              setTimeout(() => {
                inputs[currentIndex + 1].focus();
              }, 5);
            }
          } else {
            input.classList.remove("filled", "valid", "error");
          }

          updateBlikValidation(inputs);
        }
      }
    });

    document.addEventListener("change", function (event) {
      if (event.target.name === "simplyin-payment-option") {
        handlePaymentMethodChange();
      }

      if (event.target.name === "simplyin-inner-group") {
        handleGroupChange();
      }

      if (event.target.name === "payment_method") {
        handleMainPaymentMethodChange();
      }
    });

    if (typeof jQuery !== "undefined") {
      jQuery(document.body).on("checkout_error", function () {
        validateBlikOnSubmit();
      });

      jQuery(document).on(
        "change",
        'input[name="payment_method"]',
        function () {
          handleMainPaymentMethodChange();
        }
      );

      jQuery(document).on(
        "change",
        'input[name="simplyin-inner-group"]',
        function () {
          handleGroupChange();
        }
      );
    }

    const form = document.querySelector("form.checkout");
    if (form) {
      form.addEventListener("submit", function (event) {
        if (!validateBlikOnSubmit()) {
          event.preventDefault();
          return false;
        }
      });
    }

    document
      .querySelectorAll(
        ".simplyin-payment-option-item, .simplyin-payment-option-group-item"
      )
      .forEach((item) => {
        item.style.transition = "all 0.2s ease";
      });

    autoSelectAddCardOption();
  }

  window.SimplyinGetBlikCode = getBlikCode;
  window.SimplyinToggleBlikField = toggleBlikField;

  window.addCurrentClass = addCurrentClass;

  window.simplyInRadioShow = function () {
    if (typeof jQuery !== "undefined") {
      const element = jQuery(".payment_box.payment_method_simplyin")[0];
      if (element) {
        element.style.transition = "opacity 0.3s ease";
        element.style.display = "block";
        requestAnimationFrame(() => {
          element.style.opacity = "1";
        });

        const showInnerBox = () => {
          const innerPaymentBox = element.querySelector(
            ".payment_box_simplyin_d8s8.payment_method_bacs"
          );
          if (innerPaymentBox) {
            innerPaymentBox.style.setProperty("display", "block", "important");

            setTimeout(() => {
              if (
                innerPaymentBox.style.display === "none" ||
                window.getComputedStyle(innerPaymentBox).display === "none"
              ) {
                innerPaymentBox.style.setProperty(
                  "display",
                  "block",
                  "important"
                );
              }
            }, 200);

            setTimeout(() => {
              if (
                innerPaymentBox.style.display === "none" ||
                window.getComputedStyle(innerPaymentBox).display === "none"
              ) {
                innerPaymentBox.style.setProperty(
                  "display",
                  "block",
                  "important"
                );
              }
            }, 500);
          }
        };

        showInnerBox();
        setTimeout(showInnerBox, 50);
        setTimeout(showInnerBox, 150);
        setTimeout(showInnerBox, 300);

        setTimeout(() => {
          autoSelectAddCardOption();
        }, 600);
      }
    }
  };

  window.simplyInRadioHide = function () {
    if (typeof jQuery !== "undefined") {
      const element = jQuery(".payment_box.payment_method_simplyin")[0];
      if (element) {
        element.style.transition = "opacity 0.3s ease";
        element.style.opacity = "0";
        setTimeout(() => {
          element.style.display = "none";

          const innerPaymentBox = element.querySelector(
            ".payment_box_simplyin_d8s8.payment_method_bacs"
          );
          if (innerPaymentBox) {
            innerPaymentBox.style.display = "none";
          }
        }, 300);
      }
    }
  };

  window.simplyInRadioTest = function () {
    if (
      typeof jQuery !== "undefined" &&
      jQuery("#payment_method_simplyin").is(":checked")
    ) {
      window.simplyInRadioShow();
    }
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initialize);
  } else {
    initialize();
  }
})();

function getTranslations() {
  const container = document.querySelector(".simplyin-payment-methods-wrapper");
  if (!container) return {};

  return {
    loadingIframe: container.dataset.loadingIframe || "Loading custom iframe:",
    iframeLoaded: container.dataset.iframeLoaded || "Iframe loaded",
    iframeError: container.dataset.iframeError || "Iframe loading error",
    loadingError: container.dataset.loadingError || "Iframe loading error",
    missingData:
      container.dataset.missingData || "Missing URL or integrator ID",
    messageReceived:
      container.dataset.messageReceived || "Received message from iframe:",
    savedCardData:
      container.dataset.savedCardData || "Saved card data for itemId:",
    iframeReady: container.dataset.iframeReady || "Iframe ready for itemId:",
    cardName: container.dataset.cardName || "Card name",
    cardNamePlaceholder: container.dataset.cardNamePlaceholder || "My card",
    cardNumber: container.dataset.cardNumber || "Card number",
    expiryDate: container.dataset.expiryDate || "Expiry date",
    securityCode: container.dataset.securityCode || "Security code",
    confirmButton: container.dataset.confirmButton || "Confirm",
    editButton: container.dataset.editButton || "Edit",
    cardDataValid:
      container.dataset.cardDataValid ||
      "Card data is valid. You can place the order.",
    processing: container.dataset.processing || "Processing...",
    enterCardName: container.dataset.enterCardName || "Enter card name",
    cardProcessingError:
      container.dataset.cardProcessingError ||
      "Card data processing error. Check entered data.",
    cardProcessingErrorRetry:
      container.dataset.cardProcessingErrorRetry ||
      "Card data processing error. Try again.",
    invalidCardData:
      container.dataset.invalidCardData ||
      "Invalid card data. Check entered information.",
    connectionProblem:
      container.dataset.connectionProblem ||
      "Connection problem. Check internet and try again.",
  };
}

function loadCCIframeScript(url) {
  return new Promise((resolve, reject) => {
    if (window.CCIframe) {
      resolve();
      return;
    }

    const script = document.createElement("script");
    script.src = url;
    script.onload = () => resolve();
    script.onerror = () => reject(new Error("Failed to load CCIframe script"));
    document.head.appendChild(script);
  });
}

function initializeCCIframeForm(itemId, integratorId) {
  try {
    const cc = CCIframe({
      integratorId: integratorId,
    });

    let form = document.getElementById("simplyin-add-card-" + itemId);

    if (!form) {
      const container = document.getElementById(
        "simplyin-add-card-iframe-container-" + itemId
      );
      if (container) {
        const wrapper = container.querySelector(".simplyin-iframe-wrapper");
        if (wrapper) {
          const newForm = document.createElement("form");
          newForm.id = "simplyin-add-card-" + itemId;
          newForm.className = "simplyin-add-card-iframe";
          newForm.style.width = "100%";
          wrapper.appendChild(newForm);
          form = newForm;
        }
      }
    }

    if (!form) {
      return;
    }

    if (form && form.querySelector("iframe")) {
      return;
    }

    const options = {
      fonts: [
        {
          family: "Inter",
          src: "url(https://fonts.gstatic.com/s/inter/v18/UcCo3FwrK3iLTcviYwYZ8UA3.woff2) format('woff2')",
          style: "normal",
          weight: "100 900",
        },
        {
          family: "Inter",
          src: "url(https://fonts.gstatic.com/s/inter/v18/UcCo3FwrK3iLTcvsYwYZ8UA3J58.woff2) format('woff2')",
          style: "normal",
          weight: "100 900",
        },
      ],
      styles: {
        base: {
          color: "rgba(0, 0, 0, 0.8)",
          fontFamily: "Inter",
          fontSize: "14px",
        },
      },
    };

    cc.createComponent("cardNumber", "#card-number", options);
    cc.createComponent("cardExp", "#expiry-date", options);
    cc.createComponent("cardCvv", "#verification-code", options);

    const successMessage = document.getElementById(
      "card-success-message-" + itemId
    );
    const errorDiv = document.getElementById("form-error-" + itemId);
    const translations = getTranslations();

    if (!window.SimplyInTokenHandlers) {
      window.SimplyInTokenHandlers = {};
    }

    if (window.SimplyInTokenHandlers[itemId]) {
      document.removeEventListener(
        "click",
        window.SimplyInTokenHandlers[itemId]
      );
    }

    const tokenHandler = function (event) {
      if (
        event.target.id !== "place_order" ||
        !document.querySelector("#simplyin-add-card-payment-method.selected")
      ) {
        return;
      }

      if (event.target.dataset?.force === "true") {
        return;
      } else {
        event.preventDefault();
      }

      if (errorDiv) {
        errorDiv.style.display = "none";
      }
      if (successMessage) {
        successMessage.style.display = "none";
      }

      cc.createToken()
        .then(function (result) {
          if (result && result.oneTimeToken) {
            const tokenData = {
              last4digits: result.last4digits || "",
              oneTimeToken: result.oneTimeToken,
              organization: result.organization || "",
              first6digits: result.first6digits || "",
            };

            window.postMessage(
              {
                type: "SIMPLYIN_CARD_TOKEN",
                itemId: itemId,
                tokenData: tokenData,
              },
              "*"
            );

            window.SimplyinActivateNewOrderButton();
            event.target.dataset.force = "true";
            event.target.click();
          } else {
            console.error("Invalid token result:", result);

            if (errorDiv) {
              errorDiv.textContent = translations.cardProcessingError;
              errorDiv.style.display = "block";
            }
          }
        })
        .catch(function (error) {
          console.error("CCIframe token creation failed:", error);

          if (errorDiv) {
            let errorMessage = translations.cardProcessingErrorRetry;

            if (error && error.message) {
              if (error.message.includes("400")) {
                errorMessage = translations.invalidCardData;
              } else if (error.message.includes("network")) {
                errorMessage = translations.connectionProblem;
              }
            }

            errorDiv.textContent = errorMessage;
            errorDiv.style.display = "block";
          }
        });
    };

    window.SimplyInTokenHandlers[itemId] = tokenHandler;
    document.addEventListener("click", tokenHandler);

    form.style.display = "block";
  } catch (error) {
    console.error("Failed to initialize CCIframe:", error);
  }
}

function disableFormFields(itemId) {
  let form = document.getElementById("simplyin-add-card-" + itemId);
  if (!form) {
    const container = document.getElementById(
      "simplyin-add-card-iframe-container-" + itemId
    );
    if (container) {
      const wrapper = container.querySelector(".simplyin-iframe-wrapper");
      if (wrapper) {
        const newForm = document.createElement("form");
        newForm.id = "simplyin-add-card-" + itemId;
        newForm.className = "simplyin-add-card-iframe";
        newForm.style.width = "100%";
        wrapper.appendChild(newForm);
        form = newForm;
      }
    }
  }

  if (!form) return;

  const cardNameField = form.querySelector("#card-name");
  if (cardNameField) {
    cardNameField.disabled = true;
  }

  const cardFields = ["#card-number", "#expiry-date", "#verification-code"];
  cardFields.forEach((selector) => {
    const field = form.querySelector(selector);
    if (field) {
      field.style.pointerEvents = "none";
      field.style.opacity = "0.6";
    }
  });
}

function enableFormFields(itemId) {
  let form = document.getElementById("simplyin-add-card-" + itemId);
  if (!form) {
    const container = document.getElementById(
      "simplyin-add-card-iframe-container-" + itemId
    );
    if (container) {
      const wrapper = container.querySelector(".simplyin-iframe-wrapper");
      if (wrapper) {
        const newForm = document.createElement("form");
        newForm.id = "simplyin-add-card-" + itemId;
        newForm.className = "simplyin-add-card-iframe";
        newForm.style.width = "100%";
        wrapper.appendChild(newForm);
        form = newForm;
      }
    }
  }

  if (!form) return;

  const cardNameField = form.querySelector("#card-name");
  if (cardNameField) {
    cardNameField.disabled = false;
  }

  const cardFields = ["#card-number", "#expiry-date", "#verification-code"];
  cardFields.forEach((selector) => {
    const field = form.querySelector(selector);
    if (field) {
      field.style.pointerEvents = "auto";
      field.style.opacity = "1";
    }
  });
}

function forceUnlockCardForm(itemId) {
  const container = document.getElementById(
    "simplyin-add-card-iframe-container-" + itemId
  );
  if (!container) return;

  container.querySelectorAll("input").forEach((input) => {
    input.disabled = false;
    input.removeAttribute("disabled");
  });

  container.querySelectorAll(".card-field").forEach((field) => {
    field.style.pointerEvents = "auto";
    field.style.opacity = "1";
    field.style.removeProperty("pointer-events");
    field.style.removeProperty("opacity");
  });

  container.querySelectorAll("button").forEach((button) => {
    button.disabled = false;
    button.removeAttribute("disabled");
  });

  container.querySelectorAll("*").forEach((element) => {
    if (element.style.pointerEvents === "none") {
      element.style.pointerEvents = "auto";
    }
    if (element.style.opacity === "0.6") {
      element.style.opacity = "1";
    }
  });
}

function toggleAddCardIframe(itemId) {
  let iframeForm = document.getElementById("simplyin-add-card-" + itemId);
  const container = document.getElementById(
    "simplyin-add-card-iframe-container-" + itemId
  );

  if (!iframeForm && container) {
    const wrapper = container.querySelector(".simplyin-iframe-wrapper");
    if (wrapper) {
      const newForm = document.createElement("form");
      newForm.id = "simplyin-add-card-" + itemId;
      newForm.className = "simplyin-add-card-iframe";
      newForm.style.width = "100%";
      wrapper.appendChild(newForm);
      iframeForm = newForm;
    }
  }

  const hasIframe = iframeForm && iframeForm.querySelector("iframe");

  if (hasIframe) {
    if (container) {
      container.style.display = "block";
    }
    return;
  }

  const loading = document.getElementById("simplyin-iframe-loading-" + itemId);
  const radioInput = document.getElementById(
    "simplyin-payment-option-" + itemId
  );
  const translations = getTranslations();

  if (radioInput && radioInput.checked) {
    const integratorId = radioInput.getAttribute("data-integrator-id");
    const iframeUrl = radioInput.getAttribute("data-iframe-url");

    if (!integratorId || !iframeUrl) {
      console.error("Missing integrator ID or iframe URL");
      return;
    }

    container.style.display = "block";
    loading.style.display = "block";

    const formTemplate = `
      <form id="card-data-form-${itemId}" method="post" style="display: none;">

        <div class="form-group">
          <label id="card-number-label">${translations.cardNumber}</label>
          <div id="card-number" class="card-field"></div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label id="expiry-date-label">${translations.expiryDate}</label>
            <div id="expiry-date" class="card-field"></div>
          </div>
          <div class="form-group">
            <label id="security-code-label">${translations.securityCode}</label>
            <div id="verification-code" class="card-field"></div>
          </div>
        </div>

        <div id="card-success-message-${itemId}"
             class="simplyin-card-success"
             style="display: none;">
          <strong>✓</strong> ${translations.cardDataValid}
        </div>

        <div id="form-error-${itemId}" class="field-error" role="alert" style="display: none;"></div>
      </form>`;

    if (iframeForm) {
      iframeForm.innerHTML = formTemplate;
    }

    loadCCIframeScript(iframeUrl)
      .then(() => {
        loading.style.display = "none";
        initializeCCIframeForm(itemId, integratorId);
      })
      .catch((error) => {
        console.error("Failed to load CCIframe library:", error);
        loading.style.display = "none";
        if (iframeForm) {
          iframeForm.innerHTML = `<div class="error">${translations.loadingError}</div>`;
        }
      });

    if (window.SimplyIn?.is_login) {
      window.SimplyIn.showCardSaveCheckbox();
    }
  } else {
    container.style.display = "none";
  }

  window.addEventListener("message", function (event) {
    if (
      event.data &&
      event.data.postmate === "emit" &&
      event.data.value.name === "change"
    ) {
      const addCardLabel = document.querySelector(
        "label.simplyin-add-card-label"
      );
      if (addCardLabel) {
        addCardLabel.click();
      }
    }

    if (event.data && event.data.property === "fetchToken") {
      const tokenData = event.data.value;

      const inputOrganization = document.querySelector(
        `input[name="simplyin_organization"]`
      );

      if (inputOrganization) {
        inputOrganization.value = tokenData.organization;
      }

      const inputLastDigits = document.querySelector(
        `input[name="simplyin_last_digits"]`
      );

      if (inputLastDigits) {
        inputLastDigits.value = tokenData.last4digits;
      }

      const inputFirstDigits = document.querySelector(
        `input[name="simplyin_first_digits"]`
      );

      if (inputFirstDigits) {
        inputFirstDigits.value = tokenData.first6digits;
      }

      const inputOtt = document.querySelector(`input[name="simplyin_ott"]`);

      if (inputOtt) {
        inputOtt.value = tokenData.oneTimeToken;
      }

      const inputCardName = document.querySelector(
        `input[name="simplyin_card_name"]`
      );

      if (inputCardName) {
        const cardNameElement = document.getElementById("card-name");
        inputCardName.value = cardNameElement ? cardNameElement.value : "";
      }

      window.SimplyinActivateNewOrderButton();
    }

    if (event.data && event.data.type === "SIMPLYIN_IFRAME_READY") {
      const itemId = event.data.itemId;

      const loading = document.getElementById(
        "simplyin-iframe-loading-" + itemId
      );
      if (loading) {
        loading.style.display = "none";
      }
    }
  });
}
