<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useScript } from "../composables/useScript";
import { useScriptTriggerElement } from "../composables/useScriptTriggerElement";
const props = defineProps({
  trigger: { type: [String, Array, Boolean], required: false, default: "visible" },
  publishableKey: { type: String, required: true },
  pricingTableId: { type: String, required: true },
  clientReferenceId: { type: String, required: false },
  customerEmail: { type: String, required: false },
  customerSessionClientSecret: { type: String, required: false }
});
const emit = defineEmits(["ready", "error"]);
defineSlots();
const rootEl = ref();
const containerEl = ref();
const trigger = useScriptTriggerElement({ trigger: props.trigger, el: rootEl });
const instance = useScript(`https://js.stripe.com/v3/pricing-table.js`, {
  trigger
});
const { onLoaded, status } = instance;
const pricingTable = ref();
onMounted(() => {
  onLoaded(() => {
    const StripePricingTable = window.customElements.get("stripe-pricing-table");
    const stripePricingTable = new StripePricingTable();
    stripePricingTable.setAttribute("publishable-key", props.publishableKey);
    stripePricingTable.setAttribute("pricing-table-id", props.pricingTableId);
    if (props.clientReferenceId)
      stripePricingTable.setAttribute("client-reference-id", props.clientReferenceId);
    if (props.customerEmail)
      stripePricingTable.setAttribute("customer-email", props.customerEmail);
    if (props.customerSessionClientSecret)
      stripePricingTable.setAttribute("customer-session-client-secret", props.customerSessionClientSecret);
    pricingTable.value = stripePricingTable;
    rootEl.value.appendChild(stripePricingTable);
    emit("ready", instance);
  });
  watch(status, (status2) => {
    if (status2 === "error") {
      emit("error");
    }
  });
});
onBeforeUnmount(() => {
  pricingTable.value?.remove();
});
const rootAttrs = computed(() => {
  return {
    ...trigger instanceof Promise ? trigger.ssrAttrs || {} : {}
  };
});
</script>

<template>
  <div ref="rootEl" v-bind="rootAttrs">
    <div ref="containerEl" />
    <slot v-if="status === 'loading'" name="loading" />
    <slot v-if="status === 'awaitingLoad'" name="awaitingLoad" />
    <slot v-else-if="status === 'error'" name="error" />
    <slot />
  </div>
</template>
