'use client';

import { useEffect, useRef, useState } from 'react';
import Script from 'next/script';

declare global {
  interface Window {
    turnstile?: {
      render: (container: HTMLElement, options: Record<string, unknown>) => string;
      remove: (widgetId: string) => void;
    };
  }
}

// Renders nothing if the site key isn't set yet (before a Cloudflare account
// exists), so pages don't show a broken widget.
//
// Uses Cloudflare's *explicit* render API rather than its class-based
// auto-render: auto-render only scans the DOM once, when the script first
// loads. Since this component can appear on multiple pages (this page's form
// plus the footer newsletter form present on every page), a client-side
// route change mounts a fresh `cf-turnstile` div after that one-time scan
// already ran — auto-render would silently never pick it up, and only a hard
// refresh (which reloads and rescans) would work. Calling `turnstile.render()`
// ourselves on every mount avoids that.
//
// The widget also verifies asynchronously after it renders, so submitting
// immediately (before it finishes) sends an empty/stale token and the server
// rejects it. We disable the form's submit button until Cloudflare's
// callback confirms a token is ready, and re-disable it if the token expires.
export default function Turnstile() {
  const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;
  const containerRef = useRef<HTMLDivElement>(null);
  const widgetIdRef = useRef<string | null>(null);
  const [scriptReady, setScriptReady] = useState(false);

  useEffect(() => {
    if (typeof window !== 'undefined' && window.turnstile) setScriptReady(true);
  }, []);

  useEffect(() => {
    if (!siteKey || !scriptReady || !containerRef.current || !window.turnstile) return;

    const submitButton = containerRef.current.closest('form')?.querySelector<HTMLButtonElement>('button[type="submit"]');
    if (submitButton) submitButton.disabled = true;

    const widgetId = window.turnstile.render(containerRef.current, {
      sitekey: siteKey,
      callback: () => {
        if (submitButton) submitButton.disabled = false;
      },
      'expired-callback': () => {
        if (submitButton) submitButton.disabled = true;
      },
    });
    widgetIdRef.current = widgetId;

    return () => {
      if (widgetIdRef.current && window.turnstile) window.turnstile.remove(widgetIdRef.current);
      widgetIdRef.current = null;
    };
  }, [siteKey, scriptReady]);

  if (!siteKey) return null;

  return (
    <>
      <Script
        src="https://challenges.cloudflare.com/turnstile/v0/api.js"
        strategy="afterInteractive"
        onReady={() => setScriptReady(true)}
      />
      <div ref={containerRef} />
    </>
  );
}
