/**
 * 3DS Redirect functionality for SimplyIn payment gateway
 */
const SimplyIn3DSRedirect = {
  /**
   * Handle 3DS redirect to bank authentication page
   * @param {string} redirectUrl - URL to redirect to
   * @param {number} orderId - Order ID for session storage key
   */
  handleRedirect(redirectUrl, orderId) {
    try {
      const key = 'simplyin_3ds_redirect_' + String(orderId);
      const alreadyRedirected = sessionStorage.getItem(key) === '1';
      
      if (!alreadyRedirected) {
        sessionStorage.setItem(key, '1');
        
        // Show redirect message to user
        const messageEl = document.querySelector('.simplyin-blik-main-message');
        if (messageEl) {
          messageEl.textContent = 'Redirecting to bank for authentication...';
        }
        
        // Small delay for UX
        setTimeout(() => {
          window.location.replace(redirectUrl);
        }, 1000);
      }
    } catch (e) {
      // Fallback to hard redirect
      window.location.href = redirectUrl;
    }
  },

  /**
   * Initialize 3DS redirect if needed
   * Checks for data attributes on the modal and triggers redirect
   */
  init() {
    const modal = document.getElementById("simplyin-blik-status-modal");
    if (modal && modal.dataset.redirectUrl && modal.dataset.orderId) {
      const redirectUrl = modal.dataset.redirectUrl;
      const orderId = modal.dataset.orderId;
      const paymentStatus = modal.dataset.paymentStatus;
      
      if (redirectUrl && paymentStatus === 'PENDING') {
        this.handleRedirect(redirectUrl, orderId);
      }
    }
  }
};

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
  SimplyIn3DSRedirect.init();
});

// Also initialize on window load as fallback
window.addEventListener('load', () => {
  SimplyIn3DSRedirect.init();
});

