/**
 * Client-side interceptor for "Continue to Payment" button
 * This script intercepts clicks on the Continue to Payment button
 * and redirects to MY_DOMAIN instead of the actual payment page
 */

(function() {
  'use strict';
  
  console.log('[PAYMENT-REDIRECT] Interceptor loaded');
  
  // Function to handle payment button click
  function interceptPaymentButton() {
    // Find the Continue to Payment button
    const paymentButton = document.querySelector('[data-testid="funnel-footer-cta-btn"]');
    
    if (paymentButton) {
      console.log('[PAYMENT-REDIRECT] Found payment button:', paymentButton.textContent);
      
      // Check if button text contains "Payment" but NOT "Next Guest"
      // We want to intercept "Continue to Payment" but NOT "Next Guest"
      const buttonText = paymentButton.textContent.toLowerCase().trim();
      const isPaymentButton = buttonText.includes('payment') || 
                              (buttonText.includes('continue') && buttonText.includes('payment'));
      const isNextGuestButton = buttonText.includes('next') || buttonText.includes('guest');
      
      if (isPaymentButton && !isNextGuestButton) {
        console.log('[PAYMENT-REDIRECT] Intercepting Continue to Payment button click');
        
        // Remove existing click handlers and add our redirect
        const newButton = paymentButton.cloneNode(true);
        paymentButton.parentNode.replaceChild(newButton, paymentButton);
        
        newButton.addEventListener('click', function(e) {
          console.log('[PAYMENT-REDIRECT] Payment button clicked - redirecting to MY_DOMAIN');
          e.preventDefault();
          e.stopPropagation();
          e.stopImmediatePropagation();
          
          // Redirect to MY_DOMAIN
          window.location.href = process.env.MY_DOMAIN;
          return false;
        }, true);
        
        console.log('[PAYMENT-REDIRECT] Payment button intercepted successfully');
      }
    } else {
      console.log('[PAYMENT-REDIRECT] Payment button not found yet');
    }
  }
  
  // Try to intercept button on page load
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', interceptPaymentButton);
  } else {
    interceptPaymentButton();
  }
  
  // Also try again after a short delay (in case button loads dynamically)
  setTimeout(interceptPaymentButton, 1000);
  setTimeout(interceptPaymentButton, 2000);
  setTimeout(interceptPaymentButton, 3000);
  
  // Watch for DOM changes (button might be added dynamically)
  if (window.MutationObserver) {
    const observer = new MutationObserver(function(mutations) {
      for (const mutation of mutations) {
        if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
          // Check if payment button was added
          for (const node of mutation.addedNodes) {
            if (node.nodeType === Node.ELEMENT_NODE) {
              const button = node.querySelector ? node.querySelector('[data-testid="funnel-footer-cta-btn"]') : null;
              if (button || (node.dataset && node.dataset.testid === 'funnel-footer-cta-btn')) {
                console.log('[PAYMENT-REDIRECT] Payment button detected via mutation observer');
                interceptPaymentButton();
                break;
              }
            }
          }
        }
      }
    });
    
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
    
    console.log('[PAYMENT-REDIRECT] Mutation observer activated');
  }
  
  // Also intercept form submissions to payment URLs
  const originalFormSubmit = HTMLFormElement.prototype.submit;
  HTMLFormElement.prototype.submit = function() {
    const action = this.action || '';
    if (action.includes('/checkout/payment') || action.includes('/payment')) {
      console.log('[PAYMENT-REDIRECT] Form submission to payment intercepted - redirecting to MY_DOMAIN');
      window.location.href = process.env.MY_DOMAIN;
      return false;
    }
    return originalFormSubmit.call(this);
  };
  
  // Intercept addEventListener for forms
  const originalAddEventListener = EventTarget.prototype.addEventListener;
  EventTarget.prototype.addEventListener = function(type, listener, options) {
    if (type === 'submit' && this.tagName === 'FORM') {
      const wrappedListener = function(e) {
        const action = this.action || '';
        if (action.includes('/checkout/payment') || action.includes('/payment')) {
          console.log('[PAYMENT-REDIRECT] Form submission to payment intercepted via event listener');
          e.preventDefault();
          e.stopPropagation();
          window.location.href = process.env.MY_DOMAIN;
          return false;
        }
        return listener.call(this, e);
      };
      return originalAddEventListener.call(this, type, wrappedListener, options);
    }
    return originalAddEventListener.call(this, type, listener, options);
  };
  
  console.log('[PAYMENT-REDIRECT] All interceptors ready');
})();

