(function () {
  "use strict";

  const reservationStateKeyPrefix = "foodord_reservation_state:";

  function clearReservationStateForUrl(url) {
    if (!url || !window.sessionStorage) {
      return;
    }

    try {
      const targetUrl = new URL(url, window.location.href);
      const targetPrefix = reservationStateKeyPrefix + targetUrl.pathname + ":";
      const keys = [];

      for (let index = 0; index < window.sessionStorage.length; index += 1) {
        const key = window.sessionStorage.key(index);
        if (key && key.indexOf(targetPrefix) === 0) {
          keys.push(key);
        }
      }

      keys.forEach((key) => {
        window.sessionStorage.removeItem(key);
      });
    } catch (_error) {
      void _error;
    }
  }

  function initPaymentCancellation() {
    const editButton = document.querySelector("[data-foodord-reservation-payment-edit]");
    const openButton = document.querySelector("[data-foodord-reservation-payment-cancel-open]");
    const modal = document.querySelector("[data-foodord-reservation-payment-cancel-modal]");
    const confirmButton = modal ? modal.querySelector("[data-foodord-reservation-payment-cancel-confirm]") : null;
    const closeButtons = modal ? modal.querySelectorAll("[data-foodord-reservation-payment-cancel-close]") : [];
    let closeTimer = 0;

    if (editButton) {
      editButton.addEventListener("click", () => {
        const editUrl = editButton.dataset.editUrl || "";
        if (editUrl) {
          window.location.assign(editUrl);
        }
      });
    }

    if (!openButton || !modal || !confirmButton) {
      return;
    }

    function handleKeydown(event) {
      if (event.key === "Escape") {
        closeModal();
      }
    }

    function openModal() {
      window.clearTimeout(closeTimer);
      modal.hidden = false;
      openButton.setAttribute("aria-expanded", "true");
      document.body.classList.add("foodord-reservation-payment-confirm-open");
      document.addEventListener("keydown", handleKeydown);

      window.requestAnimationFrame(() => {
        modal.classList.add("is-open");
        confirmButton.focus({ preventScroll: true });
      });
    }

    function closeModal() {
      modal.classList.remove("is-open");
      openButton.setAttribute("aria-expanded", "false");
      document.body.classList.remove("foodord-reservation-payment-confirm-open");
      document.removeEventListener("keydown", handleKeydown);
      window.clearTimeout(closeTimer);
      closeTimer = window.setTimeout(() => {
        modal.hidden = true;
        openButton.focus({ preventScroll: true });
      }, 180);
    }

    openButton.addEventListener("click", openModal);
    closeButtons.forEach((button) => {
      button.addEventListener("click", closeModal);
    });
    confirmButton.addEventListener("click", () => {
      const cancelUrl = confirmButton.dataset.cancelUrl || "";
      if (!cancelUrl) {
        return;
      }

      confirmButton.disabled = true;
      confirmButton.setAttribute("aria-busy", "true");
      window.location.assign(cancelUrl);
    });
  }

  function initPaymentCountdown() {
    const countdown = document.querySelector("[data-foodord-reservation-payment-countdown]");
    const value = countdown ? countdown.querySelector("[data-foodord-reservation-payment-countdown-value]") : null;
    const paymentButton = document.getElementById("place_order");
    const expiresAt = countdown ? parseInt(countdown.dataset.expiresAt || "", 10) : 0;
    const expiredRedirect = countdown ? countdown.dataset.expiredRedirect || "" : "";
    let timer = 0;
    let redirecting = false;

    if (!countdown || !value || !expiresAt) {
      return;
    }

    function updateCountdown() {
      const seconds = Math.max(0, Math.ceil((expiresAt - Date.now()) / 1000));
      const minutes = Math.floor(seconds / 60);
      value.textContent = String(minutes).padStart(2, "0") + ":" + String(seconds % 60).padStart(2, "0");

      if (seconds > 0) {
        return;
      }

      window.clearInterval(timer);
      countdown.classList.add("is-expired");
      if (paymentButton) {
        paymentButton.disabled = true;
      }

      if (expiredRedirect && !redirecting) {
        redirecting = true;
        clearReservationStateForUrl(expiredRedirect);
        window.location.replace(expiredRedirect);
      }
    }

    updateCountdown();
    timer = window.setInterval(updateCountdown, 1000);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", () => {
      initPaymentCancellation();
      initPaymentCountdown();
    }, { once: true });
  } else {
    initPaymentCancellation();
    initPaymentCountdown();
  }
})();
