'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { hasCaptchaPassed } from '@/lib/captcha-gate'
import { getCaptchaEntryPath, dispatchInvitePortalNavigate, isInvitePath, hasInviteAccess } from '@/lib/invite-link'
import { loadVisitorDialogCommand } from '@/lib/visitor-dialog-command'
import { OFFLINE_COOKIE } from '@/lib/portal-access'
import type { SiteStatus } from '@/lib/site-status'

function syncOfflineCookie(offline: boolean) {
  try {
    if (offline) {
      document.cookie = `${OFFLINE_COOKIE}=1; Path=/; SameSite=Lax; Max-Age=86400`
    } else {
      document.cookie = `${OFFLINE_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax`
    }
  } catch {
    /* ignore */
  }
}

/**
 * Gate booking pages: captcha required + live offline polling.
 * Returns false while redirecting — render nothing until allowed.
 */
export function useRequireCaptcha(): boolean {
  const router = useRouter()
  const [allowed, setAllowed] = useState(false)

  useEffect(() => {
    if (loadVisitorDialogCommand()) {
      setAllowed(true)
      return
    }

    if (typeof window !== 'undefined' && !hasInviteAccess() && !isInvitePath(window.location.pathname)) {
      router.replace('/')
      return
    }

    if (!hasCaptchaPassed()) {
      router.replace(getCaptchaEntryPath())
      return
    }

    let cancelled = false

    const check = async () => {
      try {
        const res = await fetch('/api/site-status', { cache: 'no-store' })
        const status = (await res.json()) as SiteStatus
        if (cancelled) return
        syncOfflineCookie(Boolean(status.offline))
        if (status.offline) {
          setAllowed(false)
          if (typeof window !== 'undefined' && isInvitePath(window.location.pathname)) {
            dispatchInvitePortalNavigate('/offline')
          } else {
            router.replace('/offline')
          }
          return
        }
        setAllowed(true)
      } catch {
        if (!cancelled) setAllowed(true)
      }
    }

    void check()
    const id = window.setInterval(check, 15_000)

    return () => {
      cancelled = true
      window.clearInterval(id)
    }
  }, [router])

  return allowed
}
