"use client";

import { useEffect, useId, useRef, useState } from "react";

declare global {
  interface Window {
    turnstile?: {
      render: (
        container: HTMLElement,
        options: {
          sitekey: string;
          callback?: (token: string) => void;
          "expired-callback"?: () => void;
          "error-callback"?: () => void;
        },
      ) => string;
    };
  }
}

type ContactTurnstileProps = {
  siteKey: string;
};

export function ContactTurnstile({ siteKey }: ContactTurnstileProps) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [token, setToken] = useState("");
  const [error, setError] = useState("");
  const widgetId = useId();

  useEffect(() => {
    if (!siteKey || !containerRef.current) {
      return undefined;
    }

    let cancelled = false;

    function renderWidget() {
      if (cancelled || !containerRef.current || !window.turnstile) {
        return;
      }

      if (containerRef.current.dataset.widgetMounted === widgetId) {
        return;
      }

      containerRef.current.innerHTML = "";
      window.turnstile.render(containerRef.current, {
        sitekey: siteKey,
        callback: (nextToken) => {
          setToken(nextToken);
          setError("");
        },
        "expired-callback": () => {
          setToken("");
          setError("Verification expired. Please try again.");
        },
        "error-callback": () => {
          setToken("");
          setError("Verification could not be completed.");
        },
      });
      containerRef.current.dataset.widgetMounted = widgetId;
    }

    function ensureScript() {
      const existingScript = document.querySelector<HTMLScriptElement>(
        'script[src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"]',
      );

      if (existingScript) {
        if (window.turnstile) {
          renderWidget();
        } else {
          existingScript.addEventListener("load", renderWidget, { once: true });
        }

        return;
      }

      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", renderWidget, { once: true });
      document.head.appendChild(script);
    }

    ensureScript();

    return () => {
      cancelled = true;
    };
  }, [siteKey, widgetId]);

  if (!siteKey) {
    return null;
  }

  return (
    <div className="space-y-2">
      <div ref={containerRef} />
      <input type="hidden" name="turnstileToken" value={token} />
      {error ? <p className="text-xs text-destructive">{error}</p> : null}
    </div>
  );
}
