"use client";

import { useEffect, useRef } from "react";

type TurnstileProps = {
  action?: string;
  onToken: (token: string) => void;
  onError?: (message: string) => void;
};

export default function TurnstileField({ action, onToken, onError }: TurnstileProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const widgetId = useRef<string | null>(null);
  const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || "";

  useEffect(() => {
    if (!siteKey || !containerRef.current) return;
    let cancelled = false;
    let script = document.getElementById("cloudflare-turnstile-script") as HTMLScriptElement | null;

    const render = () => {
      const w = window as unknown as { turnstile?: { render: (el: HTMLElement, opts: object) => string; remove: (id: string) => void } };
      if (cancelled || !w.turnstile || !containerRef.current || widgetId.current) return;
      widgetId.current = w.turnstile.render(containerRef.current, {
        sitekey: siteKey,
        ...(action ? { action } : {}),
        callback: (token: string) => onToken(token),
        "expired-callback": () => onToken(""),
        "error-callback": () => onError?.("Could not load verification. Refresh the page and try again."),
      });
    };

    let checkInterval: NodeJS.Timeout | null = null;
    const w = window as unknown as { turnstile?: unknown };
    if (w.turnstile) {
      render();
    } else {
      if (!script) {
        script = document.createElement("script");
        script.id = "cloudflare-turnstile-script";
        script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
        script.async = true;
        script.defer = true;
        document.head.appendChild(script);
      }
      script.addEventListener("load", render, { once: true });

      checkInterval = setInterval(() => {
        if (cancelled) return;
        const live = window as unknown as { turnstile?: unknown };
        if (live.turnstile && !widgetId.current && containerRef.current) {
          render();
          if (checkInterval) clearInterval(checkInterval);
        }
      }, 200);
    }

    return () => {
      cancelled = true;
      if (checkInterval) clearInterval(checkInterval);
      script?.removeEventListener("load", render);
      if (widgetId.current) {
        try { (window as unknown as { turnstile?: { remove: (id: string) => void } }).turnstile?.remove(widgetId.current); } catch {}
        widgetId.current = null;
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!siteKey) {
    return <p style={{ color: "#f8d6d6", fontSize: 12, margin: "8px 0 0" }}>Signup verification is not configured.</p>;
  }

  return <div ref={containerRef} style={{ display: "flex", justifyContent: "center", minHeight: 65, marginTop: 14 }} />;
}
