'use client'

import Script from 'next/script'

const siteKey = process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY

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

export function RecaptchaScript() {
  return siteKey ? <Script src={`https://www.google.com/recaptcha/api.js?render=${encodeURIComponent(siteKey)}`} strategy="afterInteractive" /> : null
}

export async function recaptchaToken(action: string): Promise<string | null> {
  if (!siteKey) return null
  if (!window.grecaptcha) throw new Error('Security verification is loading. Please try again.')
  await new Promise<void>((resolve) => window.grecaptcha!.ready(resolve))
  return window.grecaptcha.execute(siteKey, { action })
}
