"use client";

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

declare global {
  interface Window {
    grecaptcha: {
      ready: (callback: () => void) => void;
      execute: (siteKey: string, options: { action: string }) => Promise<string>;
    };
  }
}

interface ReCaptchaProps {
  siteKey: string;
  onVerify: (token: string) => void;
  onError: (error: Error) => void;
}

export default function ReCaptcha({ siteKey, onVerify, onError }: ReCaptchaProps) {
  const [isScriptLoaded, setIsScriptLoaded] = useState(false);

  useEffect(() => {
    if (isScriptLoaded) {
      window.grecaptcha.ready(() => {
        executeReCaptcha();
      });
    }
  }, [isScriptLoaded]);

  const executeReCaptcha = async () => {
    try {
      const token = await window.grecaptcha.execute(siteKey, { action: "contact_form" });
      onVerify(token);
    } catch (error) {
      onError(error instanceof Error ? error : new Error("Failed to execute reCAPTCHA"));
    }
  };

  return (
    <>
      <Script
        src={`https://www.google.com/recaptcha/api.js?render=${siteKey}&badge=bottomright`}
        onLoad={() => setIsScriptLoaded(true)}
      />
      <style jsx global>{`
        .grecaptcha-badge {
          visibility: hidden !important;
        }
      `}</style>
    </>
  );
}
