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

const TURNSTILE_SITE_KEY = import.meta.env.VITE_TURNSTILE_SITE_KEY as string;
const USE_TURNSTILE = import.meta.env.VITE_USE_TURNSTILE !== "false";

export function useTurnstile() {
  const [token, setToken] = useState<string | null>(USE_TURNSTILE ? null : "disabled");
  const containerRef = useRef<HTMLDivElement>(null);
  const widgetIdRef = useRef<string | null>(null);

  useEffect(() => {
    if (!USE_TURNSTILE) return;

    const renderWidget = () => {
      if (!containerRef.current) return;
      widgetIdRef.current = (window as any).turnstile.render(containerRef.current, {
        sitekey: TURNSTILE_SITE_KEY,
        callback: (t: string) => setToken(t),
        "expired-callback": () => setToken(null),
        "error-callback": () => setToken(null),
      });
    };

    if ((window as any).turnstile) {
      renderWidget();
    } else {
      const interval = setInterval(() => {
        if ((window as any).turnstile) {
          clearInterval(interval);
          renderWidget();
        }
      }, 100);
      return () => clearInterval(interval);
    }

    return () => {
      if (widgetIdRef.current !== null) {
        (window as any).turnstile?.remove(widgetIdRef.current);
        widgetIdRef.current = null;
      }
    };
  }, []);

  const reset = () => {
    if (!USE_TURNSTILE) return;
    if (widgetIdRef.current !== null) {
      (window as any).turnstile?.reset(widgetIdRef.current);
    }
    setToken(null);
  };

  return { containerRef, token, enabled: USE_TURNSTILE, reset };
}
