import { useState, useEffect, useRef } from 'react'
import { Link } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import api from '../api/client'

const TURNSTILE_SITE_KEY = window.__APP_CONFIG__?.TURNSTILE_SITE_KEY || ''

function TurnstileWidget({ onVerify }) {
  const ref = useRef(null)
  useEffect(() => {
    if (!TURNSTILE_SITE_KEY) return
    // Load script if needed
    if (!document.getElementById('cf-turnstile-script')) {
      const s = document.createElement('script')
      s.id = 'cf-turnstile-script'
      s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js'
      s.async = true
      document.head.appendChild(s)
    }
    const tryRender = () => {
      if (!window.turnstile || !ref.current) return setTimeout(tryRender, 200)
      const id = window.turnstile.render(ref.current, { sitekey: TURNSTILE_SITE_KEY, callback: onVerify })
      return () => { try { window.turnstile.remove(id) } catch {} }
    }
    const cleanup = tryRender()
    return () => { if (typeof cleanup === 'function') cleanup() }
  }, [])
  if (!TURNSTILE_SITE_KEY) return null
  return <div ref={ref} style={{ margin: '8px 0' }} />
}

export default function RegisterPage() {
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  const [done, setDone] = useState(false)
  const [turnstileToken, setTurnstileToken] = useState('')
  const { loginWithToken } = useAuth()

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      const res = await api.post('/auth/register', { email, password, name, turnstile_token: turnstileToken || null })
      if (res.data.requires_verification) {
        setDone(true)
      } else {
        // First user (auto-verified admin) — log in immediately
        await loginWithToken(res.data.access_token)
        window.location.href = '/'
      }
    } catch (err) {
      const detail = err.response?.data?.detail
      if (typeof detail === 'string') setError(detail)
      else if (Array.isArray(detail)) {
        const hasEmail = detail.some(e => e.loc?.includes('email'))
        setError(hasEmail ? 'Invalid email address.' : 'Please check your input and try again.')
      } else setError('Registration failed')
    } finally {
      setLoading(false)
    }
  }

  if (done) {
    return (
      <div className="auth-page">
        <div className="auth-card" style={{ textAlign: 'center' }}>
          <div style={{ fontSize: '3rem', marginBottom: 16 }}>📧</div>
          <h1 style={{ marginBottom: 12 }}>Check your email</h1>
          <p style={{ color: '#64748b', marginBottom: 8 }}>
            We sent a verification link to <strong>{email}</strong>.
          </p>
          <p style={{ color: '#64748b', fontSize: '0.875rem', marginBottom: 24 }}>
            Click the link in the email to activate your account, then you can log in.
          </p>
          <Link to="/login" className="btn btn-primary" style={{ display: 'inline-block' }}>Go to Login</Link>
          <div className="auth-link" style={{ marginTop: 16 }}>
            Wrong email? <button onClick={() => setDone(false)} style={{ background: 'none', border: 'none', color: 'var(--primary)', cursor: 'pointer', padding: 0 }}>Go back</button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="auth-page">
      <div className="auth-card">
        <h1>Create Account</h1>
        {error && <div className="alert alert-error">{error}</div>}
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label>Name</label>
            <input type="text" value={name} onChange={e => setName(e.target.value)} required />
          </div>
          <div className="form-group">
            <label>Email</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} required />
          </div>
          <div className="form-group">
            <label>Password</label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)} required minLength={8} />
          </div>
          <TurnstileWidget onVerify={setTurnstileToken} />
          <button className="btn btn-primary" style={{ width: '100%' }} disabled={loading || (TURNSTILE_SITE_KEY && !turnstileToken)}>
            {loading ? 'Creating account...' : 'Sign Up'}
          </button>
        </form>
        <div className="auth-link">
          Already have an account? <Link to="/login">Sign in</Link>
        </div>
      </div>
    </div>
  )
}
