<div class="w-full max-w-lg px-4 mt-4 mx-auto">
  <div class="flex-1 bg-white dark:bg-gray-800 shadow-md rounded px-8 py-4 mb-4 mt-8">
    <div class="w-full pt-2 text-xl font-bold dark:text-gray-100">
      Your account is being upgraded...
    </div>

    <p class="text-gray-500 dark:text-gray-200 text-sm py-4">
      Thank you for upgrading your subscription! We're still working on 
      upgrading your account, and you'll be automatically redirected in a few
      seconds.
    </p>

    <p hidden id="timeout-notice" class="text-gray-500 dark:text-gray-200 text-sm">
      Your subscription is taking longer than usual to upgrade. If you're not
      redirected soon, please contact <a class="text-indigo-500" href="mailto:hello@plausible.io">hello@plausible.io</a>.
    </p>

    <div class="loading my-12 mx-auto"><div></div></div>

    <script>
      const PING_SUBSCRIPTION_API = "<%= Routes.billing_path(@conn, :ping_subscription) %>"
      const REDIRECT_TO = "<%= Routes.auth_path(@conn, :user_settings) %>"
      const PING_EVERY_MS = 2000
      const TIMEOUT_AFTER_MS = 15000

      const ping = async function(fun) {
        let result = {}

        while (!result.is_subscribed) {
          await wait();
          const response = await fetch(PING_SUBSCRIPTION_API)
          result = await response.json()
        }

        window.location = REDIRECT_TO
      }

      const wait = function() {
        return new Promise(resolve => { setTimeout(resolve, PING_EVERY_MS) })
      }

      setTimeout(() => {
        document.getElementById("timeout-notice").removeAttribute("hidden")
      }, TIMEOUT_AFTER_MS)

      // Pings pingSubscriptionUrl every 2 seconds until an active subscription
      // is created from Paddle webhooks.
      ping()
    </script>
  </div>
</div>
