'use client' import { createContext, use, useCallback, useState } from 'react' import { Turnstile } from './Turnstile.js' type TurnstileContextValue = { setToken: (t: null | string) => void /** Public site key from the provider (read server-side, passed once). */ siteKey: null | string /** Current token (null until solved / after expiry). */ token: null | string } const TurnstileContext = createContext(null) /** * Provides the Turnstile site key once for the whole app, like ConsentProvider * for cookies. The project reads the key server-side and passes it here in the * layout; forms then use + useTurnstile() with NO per-form * key wiring. * * // layout.tsx (server) → read key, pass to provider * import { TurnstileProvider } from '@intecion/ipal-kit/client' * import { getTurnstileConfig } from '@intecion/ipal-kit' * const { siteKey } = await getTurnstileConfig(payload) // null unless both keys are set * {children} * * When siteKey is null (Turnstile not configured), widgets render nothing and * token stays null — submitForm skips the check too, so the form just works. */ export function TurnstileProvider({ children, siteKey, }: { children: React.ReactNode siteKey: null | string }) { const [token, setToken] = useState(null) return ( {children} ) } /** * Hook giving a form the Turnstile token + a widget bound to the provider's key. * No per-form siteKey plumbing — the provider supplies it. * * const { token, TurnstileWidget, reset } = useTurnstile() * // in JSX: * // at submit: submitForm({ ..., turnstileToken: token }) * // after submit: reset() // clear for the next submission */ export function useTurnstile(): { /** True when Turnstile is configured (site key present). */ enabled: boolean reset: () => void token: null | string TurnstileWidget: (props?: { theme?: 'auto' | 'dark' | 'light' }) => React.ReactNode } { const ctx = use(TurnstileContext) if (!ctx) { throw new Error('useTurnstile must be used within ') } return useTurnstileFrom(ctx) } const NO_PROVIDER: TurnstileContextValue = { setToken: () => {}, siteKey: null, token: null } /** * useTurnstile without the provider requirement: outside * it reports `enabled: false` (no widget, no token) instead of throwing. For * shared components (BuilderForm) that must not crash a page missing the provider. */ export function useOptionalTurnstile(): ReturnType { return useTurnstileFrom(use(TurnstileContext) ?? NO_PROVIDER) } function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType { const { setToken, siteKey, token } = ctx const reset = useCallback(() => setToken(null), [setToken]) const TurnstileWidget = useCallback( (props?: { theme?: 'auto' | 'dark' | 'light' }) => { if (!siteKey) {return null} return }, [siteKey, setToken], ) return { enabled: Boolean(siteKey), reset, token, TurnstileWidget } }