package main

// CaptchaWidget renders the self-hosted Cap (trycap.dev) proof-of-work widget.
// When placed inside a <form>, the widget injects a hidden `cap-token` field on
// solve, which the form handler verifies against the instance's redeem endpoint.
//
// Vendored from the CMS built-in blocks.CaptchaWidget (cms/backend/blocks/
// captcha_widget.templ): a standalone wasm plugin cannot import the CMS-internal
// blocks package, but the widget markup is fully static (served from this
// instance's own origin), so it is reproduced here verbatim. Re-copy if the
// upstream widget changes.
templ CaptchaWidget() {
	<script>
		window.CAP_CUSTOM_WASM_URL = "/assets/captcha/cap_wasm_bg.wasm";
		window.CAP_PAKO_URL = "/assets/captcha/pako_inflate.min.js";
	</script>
	<cap-widget
		data-cap-api-endpoint="/api/captcha/"
		data-cap-worker-count="2"
	></cap-widget>
	<script src="/assets/captcha/cap.min.js" defer></script>
	<script>
		(function(){
			var s = document.currentScript;
			var form = s && s.closest ? s.closest('form') : null;
			if (!form) return;
			// Reset the widget after each htmx submit so a single-use token that
			// was already spent (verify succeeded, business logic may have failed)
			// is cleared and the visitor can re-solve for a retry.
			form.addEventListener('htmx:afterRequest', function(){
				var w = form.querySelector('cap-widget');
				if (w && typeof w.reset === 'function') w.reset();
			});
		})();
	</script>
}
