// Loads Stripe.js from js.stripe.com on demand. Stripe requires the library be
// served from their CDN (not bundled) so card data never touches our origin —
// that's what keeps PCI scope minimal. We inject the <script> once and cache
// the promise; `window.Stripe` is the global constructor it exposes.
//
// Typed as `any`: we deliberately don't pull in @stripe/stripe-js just for its
// types. The surface we use (elements, confirmCardSetup) is small and stable.

let stripeJsPromise: Promise<unknown> | null = null

export function loadStripeJs(): Promise<unknown> {
  if (!import.meta.client) return Promise.resolve(null)
  const w = window as unknown as { Stripe?: unknown }
  if (w.Stripe) return Promise.resolve(w.Stripe)
  if (!stripeJsPromise) {
    stripeJsPromise = new Promise((resolve, reject) => {
      const src = 'https://js.stripe.com/v3/'
      const existing = document.querySelector<HTMLScriptElement>(`script[src="${src}"]`)
      if (existing) {
        existing.addEventListener('load', () => resolve(w.Stripe))
        existing.addEventListener('error', () => reject(new Error('Failed to load Stripe.js')))
        if (w.Stripe) resolve(w.Stripe)
        return
      }
      const s = document.createElement('script')
      s.src = src
      s.async = true
      s.onload = () => resolve(w.Stripe)
      s.onerror = () => reject(new Error('Failed to load Stripe.js'))
      document.head.appendChild(s)
    })
  }
  return stripeJsPromise
}
