<script lang="ts" context="module">
	declare global {
		interface Window {
			turnstile?: {
				render: (element: HTMLElement, options: {
					sitekey: string;
					callback?: (token: string) => void;
					'error-callback'?: () => void;
					'expired-callback'?: () => void;
					theme?: string;
					size?: string;
				}) => string;
				remove: (widgetId: string) => void;
				reset: (widgetId: string) => void;
			};
		}
	}
	export {};
</script>

<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import { TURNSTILE_SITE_KEY, ENABLE_TURNSTILE } from '../../constants/config';
	import { turnstileLoaded, captcha } from '../../stores/global';
	export let callback: (token: string) => void = () => {};
	export let errorCallback: () => void = () => {};

	let widgetId: string | null = null;
	let containerElement: HTMLDivElement;
	let scriptLoaded = false;

	// Don't load if turnstile is disabled
	$: if (!ENABLE_TURNSTILE) {
		// Set a dummy token so the form works
		captcha.set('turnstile-disabled');
	}

	onMount(() => {
		if (!ENABLE_TURNSTILE) return;

		// Load Turnstile script if not already loaded
		if (!$turnstileLoaded) {
			const script = document.createElement('script');
			script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
			script.async = true;
			script.defer = true;
			script.addEventListener(
				'load',
				() => {
					turnstileLoaded.set(true);
					scriptLoaded = true;
					renderWidget();
				},
				{ once: true }
			);
			document.head.appendChild(script);
		} else {
			scriptLoaded = true;
			renderWidget();
		}
	});

	function renderWidget() {
		if (!containerElement || !window.turnstile || !ENABLE_TURNSTILE) return;

		widgetId = window.turnstile.render(containerElement, {
			sitekey: TURNSTILE_SITE_KEY,
			callback: (token: string) => {
				captcha.set(token);
				callback(token);
			},
			'error-callback': () => {
				captcha.set(undefined);
				errorCallback();
			},
			'expired-callback': () => {
				captcha.set(undefined);
			},
			theme: 'light',
			size: 'normal'
		});
	}

	onDestroy(() => {
		if (widgetId && window.turnstile && ENABLE_TURNSTILE) {
			window.turnstile.remove(widgetId);
		}
	});

</script>

{#if ENABLE_TURNSTILE}
	<div bind:this={containerElement} class="flex justify-center"></div>
{:else}
	<!-- Turnstile disabled - no captcha required -->
{/if}
