"use client";

import { createContext, ReactNode, useContext, useEffect, useState } from "react";

const SITE_KEY = "6Le1vXklAAAAACqYA7oFFZS5ekm3Oitl_P7654LF";

interface RecaptchaContextValue {
  ready: boolean;
  getToken: () => Promise<string | null>;
}

const RecaptchaContext = createContext<RecaptchaContextValue>({
  ready: false,
  getToken: async () => null,
});

export function useRecaptcha() {
  return useContext(RecaptchaContext);
}

export function RecaptchaProvider({ children }: { children: ReactNode }) {
  const [ready, setReady] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined" || (window as any).grecaptcha) {
      setReady(true);
      return;
    }
    const script = document.createElement("script");
    script.src = `https://www.google.com/recaptcha/api.js?render=${SITE_KEY}`;
    script.async = true;
    script.onload = () => {
      (window as any).grecaptcha?.ready(() => {
        setReady(true);
        (window as any).grecaptcha
          ?.execute(SITE_KEY, { action: "submit" })
          .then((token: string) => {
            document.querySelectorAll('input[name="token"]').forEach((el) => {
              (el as HTMLInputElement).value = token;
            });
          });
      });
    };
    document.head.appendChild(script);
    return () => {
      document.head.removeChild(script);
    };
  }, []);

  const getToken = async (): Promise<string | null> => {
    const g = (window as any).grecaptcha;
    if (!g) return null;
    try {
      return await g.execute(SITE_KEY, { action: "submit" });
    } catch {
      return null;
    }
  };

  return (
    <RecaptchaContext.Provider value={{ ready, getToken }}>
      {children}
    </RecaptchaContext.Provider>
  );
}
