{# Payment JS — conditionally loads provider SDK on checkout pages.
   Include via {% block paddle %}{% include "_payment_js.html" %}{% endblock %}
   Paddle: loads Paddle.js SDK + initializes overlay checkout.
   Stripe: no SDK needed (server-side Checkout Session + redirect). #}

{% if config.PAYMENT_PROVIDER == "paddle" %}
<script defer src="https://cdn.paddle.com/paddle/v2/paddle.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    {% if config.PADDLE_ENVIRONMENT == "sandbox" %}
    Paddle.Environment.set("sandbox");
    {% endif %}
    {% if config.PADDLE_CLIENT_TOKEN %}
    Paddle.Initialize({
      token: "{{ config.PADDLE_CLIENT_TOKEN }}",
      eventCallback: function(ev) {
        if (ev.name === "checkout.error") console.error("Paddle checkout error:", ev.data);
      },
      checkout: {
        settings: {
          displayMode: "overlay",
          theme: "light",
          locale: "en",
        }
      }
    });
    {% else %}
    console.warn("Paddle: PADDLE_CLIENT_TOKEN not configured");
    {% endif %}
  });
</script>
{% endif %}

<script>
/**
 * startCheckout — dual-path checkout handler.
 * Paddle: opens overlay with items/customData/settings from response JSON.
 * Stripe: redirects to checkout_url from response JSON.
 */
function startCheckout(data) {
  if (data.checkout_url) {
    window.location.href = data.checkout_url;
  } else if (data.items) {
    Paddle.Checkout.open({
      items: data.items,
      customData: data.customData,
      settings: data.settings,
    });
  }
}
</script>
