'use client'

import { useEffect, useRef, useState } from 'react'

/**
 * The «I'm not a robot» box, plus the timestamp the server uses to spot a form that was filled in faster
 * than a person can read it.
 *
 * Cloudflare Turnstile is used rather than reCAPTCHA: it asks the visitor to tick one box (usually nothing
 * at all), it sets no advertising cookies, and it does not send the visitor's browsing to an ad company —
 * which matters for a site whose visitors are sixteen-year-old students and their parents.
 *
 * With no site key configured this renders only the timestamp, so the form works exactly as it did before
 * anyone created a Cloudflare account. Nothing here blocks the page: the script is loaded lazily and the
 * submit button stays usable, because a visitor on a slow connection must never be stranded by a widget.
 */
export function NotABot({ siteKey, locale }: { siteKey?: string; locale: 'ar' | 'en' }) {
  const box = useRef<HTMLDivElement>(null)
  const [stamp, setStamp] = useState('')

  // Set on the client, on mount: rendered on the server it would be the time the PAGE was built, which for
  // a cached page is hours ago and would wave every bot straight through the time trap.
  useEffect(() => setStamp(String(Date.now())), [])

  useEffect(() => {
    if (!siteKey || !box.current) return
    const render = () => {
      const w = window as unknown as { turnstile?: { render: (el: HTMLElement, o: object) => void } }
      if (!w.turnstile || !box.current || box.current.childElementCount) return
      w.turnstile.render(box.current, { sitekey: siteKey, language: locale, theme: 'light' })
    }
    if (document.getElementById('cf-turnstile-script')) {
      render()
      return
    }
    const s = document.createElement('script')
    s.id = 'cf-turnstile-script'
    s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
    s.async = true
    s.defer = true
    s.onload = render
    document.head.appendChild(s)
  }, [siteKey, locale])

  return (
    <>
      <input type="hidden" name="ts" value={stamp} />
      {siteKey ? <div ref={box} className="notabot" style={{ margin: '4px 0 2px' }} /> : null}
    </>
  )
}
