"use client";

import { useEffect, useRef, useCallback, forwardRef, useImperativeHandle } from "react";
import { renderWidget, resetWidget } from "@/lib/recaptcha";

interface Props {
  onToken?: (token: string) => void;
}

export interface RecaptchaHandle {
  reset: () => void;
  getToken: () => string;
}

const RecaptchaV2 = forwardRef<RecaptchaHandle, Props>(function RecaptchaV2({ onToken }, ref) {
  const containerRef = useRef<HTMLDivElement>(null);
  const widgetId = useRef<number | null>(null);
  const tokenRef = useRef<string>("");

  useImperativeHandle(ref, () => ({
    reset: () => {
      if (widgetId.current !== null) resetWidget(widgetId.current);
      tokenRef.current = "";
    },
    getToken: () => tokenRef.current,
  }));

  useEffect(() => {
    if (!containerRef.current) return;
    renderWidget("recaptcha-v2-container", (token) => {
      tokenRef.current = token;
      onToken?.(token);
    }).then((id) => {
      // Only store non-null widgetId (second StrictMode mount
      // returns null because iframe/Set guard prevents re-render)
      if (id !== null) widgetId.current = id;
    });
    return () => {
      if (widgetId.current !== null) resetWidget(widgetId.current);
    };
  }, [onToken]);

  return <div id="recaptcha-v2-container" ref={containerRef} style={{ marginTop: 12, minHeight: 78 }} />;
});

export default RecaptchaV2;
