"use client";

import Script from "next/script";
import { useCallback, useEffect, useRef } from "react";

declare global {
  interface Window {
    turnstile?: {
      render: (
        el: HTMLElement,
        opts: {
          sitekey: string;
          action?: string;
          theme?: "light" | "dark" | "auto";
          appearance?: "always" | "execute" | "interaction-only";
          callback?: (token: string) => void;
          "expired-callback"?: () => void;
          "error-callback"?: () => void;
        },
      ) => string;
      reset: (widgetId?: string) => void;
      remove: (widgetId?: string) => void;
    };
  }
}

export function turnstileSiteKey(): string {
  return process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY?.trim() || "";
}

export function isTurnstileConfiguredClient(): boolean {
  return Boolean(turnstileSiteKey());
}

type Props = {
  /** Must match panel siteverify `action` (waitlist | request-demo). */
  action: string;
  onToken: (token: string | null) => void;
  resetSignal?: number;
  className?: string;
};

export function TurnstileWidget({
  action,
  onToken,
  resetSignal = 0,
  className,
}: Props) {
  const siteKey = turnstileSiteKey();
  const hostRef = useRef<HTMLDivElement>(null);
  const widgetIdRef = useRef<string | null>(null);
  const onTokenRef = useRef(onToken);
  onTokenRef.current = onToken;

  const mount = useCallback(() => {
    if (!siteKey || !hostRef.current || !window.turnstile) return;
    if (widgetIdRef.current) {
      try {
        window.turnstile.remove(widgetIdRef.current);
      } catch {
        /* ignore */
      }
      widgetIdRef.current = null;
    }
    hostRef.current.innerHTML = "";
    widgetIdRef.current = window.turnstile.render(hostRef.current, {
      sitekey: siteKey,
      action,
      theme: "light",
      appearance: "always",
      callback: (token) => onTokenRef.current(token),
      "expired-callback": () => onTokenRef.current(null),
      "error-callback": () => onTokenRef.current(null),
    });
  }, [siteKey, action]);

  useEffect(() => {
    if (!siteKey) {
      onTokenRef.current(null);
      return;
    }
    if (window.turnstile) mount();
    return () => {
      if (widgetIdRef.current && window.turnstile) {
        try {
          window.turnstile.remove(widgetIdRef.current);
        } catch {
          /* ignore */
        }
        widgetIdRef.current = null;
      }
    };
  }, [siteKey, mount]);

  useEffect(() => {
    if (!siteKey || resetSignal === 0) return;
    if (widgetIdRef.current && window.turnstile) {
      onTokenRef.current(null);
      window.turnstile.reset(widgetIdRef.current);
    } else {
      mount();
    }
  }, [resetSignal, siteKey, mount]);

  if (!siteKey) return null;

  return (
    <div className={className}>
      <Script
        src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"
        strategy="afterInteractive"
        onLoad={mount}
      />
      <div
        ref={hostRef}
        className="cf-turnstile flex min-h-16 justify-center"
        data-sitekey={siteKey}
        data-action={action}
      />
    </div>
  );
}
