import { createSignal, onMount } from "solid-js";
import { PageHead } from "~/components/PageHead";
import SubdomainHeader from "~/components/SubdomainHeader";
import Button from "~/components/ui/Button";
import { env } from "~/env/client";
import { useSite } from "~/context/SiteContext";
import { useDarkMode } from "~/context/darkMode";
export default function NookCheckout() {
const site = useSite();
const { isDark } = useDarkMode();
const [loading, setLoading] = createSignal(false);
const [error, setError] = createSignal("");
const [turnstileToken, setTurnstileToken] = createSignal("");
const brandColor = () =>
isDark() ? (site().brandColorDark ?? site().brandColor) : site().brandColor;
onMount(() => {
const script = document.createElement("script");
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";
script.async = true;
script.defer = true;
script.onload = () => {
const container = document.getElementById("turnstile-widget-nook");
if (container && (window as any).turnstile) {
(window as any).turnstile.render(container, {
sitekey: env.VITE_TURNSTILE_SITE_KEY,
theme: isDark() ? "dark" : "light",
callback: (token: string) => setTurnstileToken(token),
"expired-callback": () => setTurnstileToken("")
});
}
};
document.head.appendChild(script);
});
const buy = async () => {
if (loading()) return;
if (!turnstileToken()) {
setError("Complete the security check to continue.");
return;
}
setLoading(true);
setError("");
try {
const res = await fetch("/api/the-nook/checkout", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ turnstileToken: turnstileToken() })
});
const data = (await res.json()) as {
checkoutUrl?: string;
error?: string;
};
if (!res.ok || !data.checkoutUrl) {
setError(data.error ?? "Unable to start checkout. Please try again.");
return;
}
window.location.href = data.checkoutUrl;
} catch {
setError("Unable to start checkout. Please try again.");
} finally {
setLoading(false);
}
};
return (
<>