const stripe = Stripe('pk_live_51RfyLBRsO3VEr1wB7j1TuL6Y17RcXyL5yip1oslbCZzfuEjZVf8K8dOgHUfHyRppf42661gEmZN3PFOLAdN3Nfje00qknZKnO0');

const elements = stripe.elements();
const card = elements.create('card');
card.mount('#card-element');

var cardComplete = false;

card.on('change', event => {
  if(event.complete) cardComplete = true;
});

document.getElementById('payment-form').addEventListener('submit', async (e) => {
  e.preventDefault();

  if(!cardComplete) return;

  const amount = document.getElementById('amount').value;
  if(!amount) return;

  const res = await fetch('/stripe/intent', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({ amount })
  });

  const data = await res.json();

  const email = document.getElementById('email').value;

  const result = await stripe.confirmCardPayment(data.client_secret, {
    payment_method: {
      card: card,
      billing_details: {
        email: email
      }
    }
  });

  if(result.error) {
    alert(result.error.message);
  } else if(result.paymentIntent && result.paymentIntent.status === 'succeeded') {
    document.dispatchEvent(new Event('emptycart'));
    window.location = '/garage';
  }
});
