import { useEffect, useRef } from "react";
import { Box, Typography } from "@mui/material";
import { useI18n } from "../i18n/I18nProvider";

type Props = { siteKey: string; action: "login" | "register"; onToken: (token: string) => void; };

export default function TurnstileWidget({ siteKey, action, onToken }: Props) {
  const { language, t } = useI18n();
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    let widgetId: string | undefined;
    let cancelled = false;
    const render = () => {
      if (cancelled || !ref.current || !(window as any).turnstile) return;
      widgetId = (window as any).turnstile.render(ref.current, {
        sitekey: siteKey, action, theme: "auto", size: "flexible", language: language === "nb" ? "nb" : "en",
        callback: onToken,
        "expired-callback": () => onToken(""),
        "error-callback": () => onToken(""),
      });
    };
    const existing = document.querySelector<HTMLScriptElement>('script[data-turnstile]');
    if ((window as any).turnstile) render();
    else if (existing) existing.addEventListener("load", render, { once: true });
    else {
      const script = document.createElement("script");
      script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
      script.async = true; script.defer = true; script.dataset.turnstile = "true";
      script.addEventListener("load", render, { once: true });
      document.head.appendChild(script);
    }
    return () => { cancelled = true; if (widgetId && (window as any).turnstile) (window as any).turnstile.remove(widgetId); };
  }, [action, language, onToken, siteKey]);

  return <Box><Typography variant="caption" color="text.secondary">{t("securityCheck")}</Typography><Box ref={ref} sx={{ minHeight: 65, mt: 0.5 }} /></Box>;
}
