<script setup>
import { useScriptCloudflareTurnstile } from "../composables/turnstile";
import { useRuntimeConfig, ref, onMounted, onBeforeUnmount, useScriptTriggerElement } from "#imports";
const props = defineProps({
  modelValue: { type: String, required: false },
  trigger: { type: [String, Array, Boolean], required: false },
  element: { type: String, required: false, default: "div" },
  siteKey: { type: String, required: false },
  options: { type: Object, required: false, default: () => ({}) },
  resetInterval: { type: Number, required: false, default: 1e3 * 250 }
});
const emit = defineEmits(["update:modelValue"]);
const config = useRuntimeConfig().public.turnstile;
const el = ref();
const unmountStarted = ref(false);
let id = void 0;
let interval;
const { onLoaded } = useScriptCloudflareTurnstile({
  scriptOptions: {
    trigger: useScriptTriggerElement({ trigger: props.trigger, el })
  }
});
let _reset;
let remove;
const reset = () => {
  if (id) {
    _reset(id);
  }
};
const unmount = () => {
  unmountStarted.value = true;
  clearInterval(interval);
  if (id) {
    remove(id);
  }
};
onMounted(() => {
  onLoaded(async ({ render, reset: resetFn, remove: removeFn }) => {
    _reset = resetFn;
    remove = removeFn;
    id = await render(el.value, {
      sitekey: props.siteKey || config.siteKey,
      callback: (token) => emit("update:modelValue", token),
      ...props.options
    });
    interval = setInterval(reset, props.resetInterval);
    if (unmountStarted.value) {
      unmount();
    }
  });
});
onBeforeUnmount(unmount);
defineExpose({ reset });
</script>

<template>
  <component
    :is="element"
    ref="el"
  />
</template>
