const blikStatusChecker = {
  checkInterval: null,
  maxAttempts: 120,
  currentAttempt: 0,
  intervalTime: 1000,
  isChecking: false,
  startTime: null,
  maxDuration: 120000,
};

const getTimeoutStorageKey = () => {
  const orderId = window?.simplyInStatus?.orderId;
  const paymentUuid = window?.simplyInStatus?.paymentUuid;
  if (orderId && paymentUuid) {
    return `simplyin_payment_timeout_failed_${orderId}_${paymentUuid}`;
  }
  return orderId ? `simplyin_payment_timeout_failed_${orderId}` : null;
};

const hasTimeoutFlag = () => {
  const key = getTimeoutStorageKey();
  if (!key) return false;
  const orderId = window?.simplyInStatus?.orderId;
  const paymentUuid = window?.simplyInStatus?.paymentUuid;
  try {
    if (orderId && paymentUuid) {
      const legacyKey = `simplyin_payment_timeout_failed_${orderId}`;
      if (legacyKey !== key && localStorage.getItem(legacyKey) === "1") {
        localStorage.removeItem(legacyKey);
      }
    }
    return localStorage.getItem(key) === "1";
  } catch (e) {
    return false;
  }
};

const setTimeoutFlag = () => {
  const key = getTimeoutStorageKey();
  if (!key) return;
  const orderId = window?.simplyInStatus?.orderId;
  const paymentUuid = window?.simplyInStatus?.paymentUuid;
  try {
    if (orderId && paymentUuid) {
      const legacyKey = `simplyin_payment_timeout_failed_${orderId}`;
      if (legacyKey !== key) {
        localStorage.removeItem(legacyKey);
      }
    }
    localStorage.setItem(key, "1");
  } catch (e) {
  }
};

const isCardPayment = () => {
  const modal = document.getElementById("simplyin-blik-status-modal");
  return modal.dataset.isCardPayment === "true";
};

const getTranslations = () => {
  const modal = document.getElementById("simplyin-blik-status-modal");
  const translations = {
    paymentProcessing: modal.dataset.paymentProcessing,
    paymentPending: modal.dataset.paymentPending,
    paymentSuccess: modal.dataset.paymentSuccess,
    paymentRejected: modal.dataset.paymentRejected,
    paymentTimeout: modal.dataset.paymentTimeout,
    statusCheckError: modal.dataset.statusCheckError,
    networkError: modal.dataset.networkError,
    mainMessageProcessing: modal.dataset.mainMessageProcessing,
    mainMessagePending: modal.dataset.mainMessagePending,
    mainMessageSuccess: modal.dataset.mainMessageSuccess,
    mainMessageError: modal.dataset.mainMessageError,
    mainMessageTimeout: modal.dataset.mainMessageTimeout,
  };
  return translations;
};

const startBlikStatusChecking = () => {
  if (blikStatusChecker.checkInterval) {
    clearInterval(blikStatusChecker.checkInterval);
  }

  blikStatusChecker.currentAttempt = 0;
  blikStatusChecker.isChecking = false;
  blikStatusChecker.startTime = Date.now();

  blikStatusChecker.checkInterval = setInterval(() => {
    checkBlikPaymentStatus();
  }, blikStatusChecker.intervalTime);
};

const checkBlikPaymentStatus = async () => {
  if (blikStatusChecker.isChecking) {
    return;
  }

  const elapsedTime = Date.now() - blikStatusChecker.startTime;
  if (elapsedTime >= blikStatusChecker.maxDuration) {
    handleBlikTimeout();
    return;
  }

  blikStatusChecker.currentAttempt++;
  blikStatusChecker.isChecking = true;

  if (blikStatusChecker.currentAttempt > blikStatusChecker.maxAttempts) {
    handleBlikTimeout();
    return;
  }

  try {
    const action = isCardPayment()
      ? "simplyin_get_card_payment_status"
      : "simplyin_get_blik_payment_status";

    const params = {
      action: action,
      ajax_token: window.simplyInStatus.nonce,
      order_id: window.simplyInStatus.orderId,
      payment_uuid: window.simplyInStatus.paymentUuid || "",
    };

    const response = await fetch(window.simplyInStatus.ajaxUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams(params),
    });

    if (!response.ok) {
      const translations = getTranslations();
      const { customer_error_message } = await response.json();
      handleBlikFailure(customer_error_message || translations.paymentRejected);
      return;
    }

    const statusData = await response.json();
    const { payment_status, customer_error_message } = statusData;

    if (payment_status) {
      handleBlikStatusResponse(payment_status, customer_error_message);
    } else {
      const translations = getTranslations();
      console.error(translations.statusCheckError, statusData);
    }
  } catch (error) {
    const translations = getTranslations();
    console.error(translations.networkError, error);
  } finally {
    blikStatusChecker.isChecking = false;
  }
};

const handleBlikStatusResponse = (status, customer_error_message) => {
  const translations = getTranslations();

  switch (status) {
    case "SUCCESS":
      handleBlikSuccess();
      break;
    case "FAILURE":
      handleBlikFailure(customer_error_message || translations.paymentRejected);
      break;
    case "PENDING":
      updateBlikStatus(translations.paymentPending, "pending");
      break;
    case "CHECK_BANK_APP":
      updateBlikStatus(translations.acceptPaymentMessage, "processing");
      break;
    default:
      updateBlikStatus(translations.paymentProcessing, "processing");
  }
};

const updateBlikIcon = (type) => {
  const iconContainer = document.querySelector(".simplyin-blik-icon svg");
  if (!iconContainer) return;

  const icons = {
    success: `<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="#4CAF50"></path>`,
    error: `<circle cx="12" cy="12" r="10" fill="#f44336"></circle><path d="M15 9l-6 6m0-6l6 6" stroke="white" stroke-width="2" stroke-linecap="round"></path>`,
    pending: `<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z" fill="#FF9800"></path>`,
    processing: `<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" fill="#2196F3"></path><circle cx="12" cy="12" r="3" fill="#2196F3" opacity="0.3"><animate attributeName="opacity" values="0.3;1;0.3" dur="1.5s" repeatCount="indefinite"></animate></circle>`,
    timeout: `<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z" fill="#f44336"></path>`,
  };

  iconContainer.innerHTML = icons[type] || icons.processing;
};

const updateBlikStatus = (message, type) => {
  const messageEl = document.getElementById("blik-status-message");
  const mainMessageEl = document.querySelector(".simplyin-blik-main-message");
  const modal = document.getElementById("simplyin-blik-status-modal");
  const translations = getTranslations();

  const mainMessages = {
    success: translations.mainMessageSuccess,
    error: translations.mainMessageError,
    pending: translations.mainMessagePending,
    processing: translations.mainMessageProcessing,
    timeout: translations.mainMessageTimeout,
  };

  updateBlikIcon(type);

  if (messageEl) {
    messageEl.textContent = message;
  }

  if (mainMessageEl) {
    mainMessageEl.textContent = mainMessages[type] || mainMessages.processing;
  }

  if (modal) {
    modal.classList.remove(
      "simplyin-blik-success",
      "simplyin-blik-error",
      "simplyin-blik-pending",
      "simplyin-blik-processing",
      "simplyin-blik-timeout"
    );
    if (type === "success") {
      modal.classList.add("simplyin-blik-success");
    } else if (type === "error") {
      modal.classList.add("simplyin-blik-error");
    } else if (type === "pending") {
      modal.classList.add("simplyin-blik-pending");
    } else if (type === "processing") {
      modal.classList.add("simplyin-blik-processing");
    } else if (type === "timeout") {
      modal.classList.add("simplyin-blik-timeout");
    }
  }
};

const handleBlikSuccess = () => {
  const translations = getTranslations();
  stopBlikChecking();
  hideBlikLoader();
  updateBlikStatus(translations.paymentSuccess, "success");
};

const handleBlikFailure = (message) => {
  stopBlikChecking();
  hideBlikLoader();
  updateBlikStatus(message, "error");
};

const handleBlikTimeout = () => {
  const translations = getTranslations();
  stopBlikChecking();
  hideBlikLoader();
  setTimeoutFlag();

  try {
    const action = isCardPayment()
      ? "simplyin_card_payment_timeout"
      : "simplyin_blik_payment_timeout";

    const params = {
      action: action,
      ajax_token: window.simplyInStatus.nonce,
      order_id: window.simplyInStatus.orderId,
    };

    fetch(window.simplyInStatus.ajaxUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams(params),
    }).catch(() => {}).finally( () => {
        window.location.href = window.location.href;
      })
  } catch (e) {
  }

  updateBlikStatus(translations.paymentTimeout, "timeout");
};

const hideBlikLoader = () => {
  const loader = document.getElementById("blik-loader");
  if (loader) {
    loader.classList.add("hidden");
  }
};

const stopBlikChecking = () => {
  if (blikStatusChecker.checkInterval) {
    clearInterval(blikStatusChecker.checkInterval);
    blikStatusChecker.checkInterval = null;
  }
};

window.addEventListener("load", () => {
  if (!window.simplyInStatus) {
    return;
  }

  const translations = getTranslations();

  if (window.simplyInStatus.timeoutFailed) {
    setTimeoutFlag();
    hideBlikLoader();
    updateBlikStatus(translations.paymentTimeout, "timeout");
    return;
  }

  if (hasTimeoutFlag()) {
    hideBlikLoader();
    updateBlikStatus(translations.paymentTimeout, "timeout");
    return;
  }

  startBlikStatusChecking();
});
