<style>
  .checkout-button {
    background-color: #242742 !important;
    color: white !important;
    padding: 16px !important;
    width: 100% !important;
    max-width: 400px !important;
    border-radius: 99px !important;
    border: none !important;
    cursor: pointer !important;
    font-size: 16px !important;
    font-weight: 500 !important;
    text-align: center !important;
    position: relative !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
  }

  .error-banner {
    display: none;
    background-color: #fee2e2;
    border: 1px solid #ef4444;
    color: #b91c1c;
    padding: 1rem;
    position: fixed;
    top: 87px;
    left: 0;
    right: 0;
    width: 100vw;
    z-index: 1000;
    text-align: center;
    opacity: 0.98;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  .error-banner.visible {
    display: block;
  }

  .checkout-button:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }

  /* Spinner styles */
  .buy-now-spinner {
    position: absolute !important;
    left: 20px !important;
    top: 50% !important;
    margin-top: -10px !important;  /* Half of height to center */
    width: 20px !important;
    height: 20px !important;
    border: 3px solid rgba(255, 255, 255, 0.3) !important;
    border-radius: 50% !important;
    border-top-color: #ffffff !important;
    animation: buy-now-spin 1s linear infinite !important;
    visibility: hidden !important;
  }

  .buy-now-spinner.visible {
    visibility: visible !important;
  }

  @keyframes buy-now-spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
</style>

<div class="error-banner" id="errorBanner">
  Looks like we hit a tiny bump! 🌸 Give the page a quick refresh and try again.
</div>

<button type="button" onclick="handleCheckout(event)" class="checkout-button" id="checkoutButton">
  <span class="buy-now-spinner" id="spinner"></span>
  Buy Now
</button>

<script>
  const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
  
  async function makeRequest(retryCount = 0) {
    try {
      const response = await fetch('https://rpj590yvk8.execute-api.us-east-1.amazonaws.com/stat-dev-api-stage/public/create-checkout-session', {
        method: 'GET'
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      
      // Check if we have a sessionUrl in the response
      if (data && data.sessionUrl) {
        window.location.href = data.sessionUrl;
        return true;
      } else if (data && data.url) { // Fallback in case the property name is just 'url'
        window.location.href = data.url;
        return true;
      }
      
      throw new Error('No session URL in response');
      
    } catch (error) {
      newrelic.noticeError(error, { tryAttempt: retryCount });
      newrelic.addPageAction('CreateCheckoutSessionError', { tryAttempt: retryCount });
      // console.error('Error:', error);
      if (retryCount < 3) {
        // Reduced backoff: 0.3s, 0.6s, 0.9s
        await sleep(300 * (retryCount + 1));
        return makeRequest(retryCount + 1);
      }
      return false;
    }
  }

  async function handleCheckout(event) {
    event.preventDefault();

    newrelic.addPageAction('ClickedBuyNow');

    const errorBanner = document.getElementById('errorBanner');
    const checkoutButton = document.getElementById('checkoutButton');
    const spinner = document.getElementById('spinner');
    
    // Hide any existing error
    errorBanner.classList.remove('visible');
    
    // Disable button and show spinner
    checkoutButton.disabled = true;
    spinner.classList.add('visible');

    try {
      const success = await makeRequest();
      
      if (!success) {
        errorBanner.classList.add('visible');
      }
      
    } catch (error) {
      newrelic.addPageAction('HitError');
      newrelic.noticeError(error);
      errorBanner.classList.add('visible');
    } finally {
      // Only re-enable button and hide spinner if we haven't redirected
      if (document.getElementById('checkoutButton')) {
        checkoutButton.disabled = false;
        spinner.classList.remove('visible');
      }
    }
  }
</script>