'use client'

import { Suspense, useEffect, useState } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { elternApi } from '@/lib/eltern/api'

function LoginInner() {
  const router = useRouter()
  const search = useSearchParams()
  const [error, setError] = useState<string | null>(null)
  const [done, setDone] = useState(false)

  useEffect(() => {
    const token = search.get('token')
    if (!token) {
      setError('Kein Token in der URL. Bitte den Link aus der Einladung verwenden.')
      return
    }
    elternApi.redeem(token)
      .then(() => { setDone(true); setTimeout(() => router.replace('/eltern'), 800) })
      .catch(e => setError(e instanceof Error ? e.message : 'Login fehlgeschlagen'))
  }, [router, search])

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-indigo-900 via-purple-900 to-pink-800 text-white">
      <div className="max-w-md w-full mx-4 p-6 rounded-2xl bg-white/10 border border-white/20 backdrop-blur-xl" data-testid="eltern-login">
        <h1 className="text-2xl font-semibold mb-3">Eltern-Login</h1>
        {!error && !done && <p className="opacity-80">Pruefe Token …</p>}
        {done && <p className="text-emerald-200">Erfolgreich angemeldet. Weiterleitung …</p>}
        {error && (
          <div className="p-3 rounded-lg bg-red-500/20 border border-red-500/40 text-red-200 text-sm">{error}</div>
        )}
      </div>
    </div>
  )
}

export default function ElternLoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginInner />
    </Suspense>
  )
}
