import { afterEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'

vi.mock('next/script', () => ({ default: () => null }))

afterEach(() => {
  vi.unstubAllEnvs()
  vi.unstubAllGlobals()
  vi.resetModules()
})

describe('reCAPTCHA browser switch', () => {
  it('renders no script and never executes Google even with an existing site key', async () => {
    vi.stubEnv('NEXT_PUBLIC_RECAPTCHA_ENABLED', 'false')
    vi.stubEnv('NEXT_PUBLIC_RECAPTCHA_SITE_KEY', 'old-domain-key')
    const execute = vi.fn()
    const ready = vi.fn()
    vi.stubGlobal('window', { location: { host: 'heavyhaulagent.com' }, grecaptcha: { execute, ready } })
    const { RecaptchaScript, recaptchaToken } = await import('@/lib/security/recaptcha-client')
    expect(RecaptchaScript()).toBeNull()
    for (const action of ['password_login', 'email_code_start', 'google_login', 'google_signup', 'signup_request', 'early_access']) {
      expect(await recaptchaToken(action)).toBeNull()
    }
    expect(execute).not.toHaveBeenCalled()
    expect(ready).not.toHaveBeenCalled()
  })

  it('does not wait for the Google script when disabled', async () => {
    vi.stubEnv('NEXT_PUBLIC_RECAPTCHA_ENABLED', 'false')
    vi.stubEnv('NEXT_PUBLIC_RECAPTCHA_SITE_KEY', 'old-domain-key')
    const { recaptchaToken } = await import('@/lib/security/recaptcha-client')
    expect(await recaptchaToken('password_login')).toBeNull()
  })

  it('requires the Google script again after re-enabling', async () => {
    vi.stubEnv('NEXT_PUBLIC_RECAPTCHA_ENABLED', 'true')
    vi.stubEnv('NEXT_PUBLIC_RECAPTCHA_SITE_KEY', 'public-key')
    vi.stubGlobal('window', { location: { host: 'heavyhaulagent.com' } })
    const { RecaptchaScript, recaptchaToken } = await import('@/lib/security/recaptcha-client')
    expect(RecaptchaScript()).not.toBeNull()
    await expect(recaptchaToken('password_login')).rejects.toThrow('Security verification is loading')
  })

  it('enables Google signup without CAPTCHA keys when Supabase is configured', async () => {
    vi.stubEnv('NEXT_PUBLIC_RECAPTCHA_ENABLED', 'false')
    vi.stubEnv('NEXT_PUBLIC_RECAPTCHA_SITE_KEY', '')
    vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', 'https://example.supabase.co')
    vi.stubEnv('NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY', 'publishable-key')
    const { GoogleAuthButton } = await import('@/components/auth/google-auth-button')
    const html = renderToStaticMarkup(createElement(GoogleAuthButton, { mode: 'signup' }))
    expect(html).not.toContain('disabled=""')
    expect(html).toContain('Create account with Google')
  })
})
