// components/TurnstileChallenge.tsx
import { useEffect, useRef, useState } from "react"
// import toast from "react-hot-toast"

interface TurnstileChallengeProps {
  siteKey: string
  onSuccess: (token: string) => void
  onError?: () => void
  autoStart?: boolean
}

declare global {
  interface Window {
    turnstile: any
  }
}

const TurnstileChallenge = ({
  siteKey,
  onSuccess,
  onError,
  autoStart = true,
}: TurnstileChallengeProps) => {
  const containerId = "cf-turnstile-container"
  const widgetId = useRef<string | null>(null)
  const [ready, setReady] = useState(false)

  useEffect(() => {
    const tryRender = () => {
      if (!window.turnstile || !document.getElementById(containerId)) return

      if (widgetId.current) return

      const id = window.turnstile.render(`#${containerId}`, {
        sitekey: siteKey,
        callback: (token: string) => {
          onSuccess(token)
        },
        "error-callback": () => {
          onError?.()
        },
        "refresh-callback": () => {
          console.log("refresh callback CALLEd")
          // toast.error("Refresh callback called")
        },
      })

      widgetId.current = id
      setReady(true)
    }

    const interval = setInterval(() => {
      if (window.turnstile && document.getElementById(containerId)) {
        clearInterval(interval)
        if (autoStart) tryRender()
      }
    }, 200)

    return () => clearInterval(interval)
  }, [siteKey, autoStart, onSuccess, onError])

  return (
    <div className="">
      <div id={containerId} data-refresh-timeout="auto" />
      {!ready && <p className="">...</p>}
      {/* <button onClick={reset}>RESET</button> */}
    </div>
  )
}

export default TurnstileChallenge
