'use client'

import { useRouter } from 'next/navigation'
import { useEffect } from 'react'

import { AuthFlow } from '@/components/auth/auth-flow'
import { useAuthContext } from '@/contexts/AuthContext'
import { getHomePathFromUser } from '@/lib/routing'

export default function LoginPage() {
  const router = useRouter()
  const { user, isLoading } = useAuthContext()

  useEffect(() => {
    if (isLoading) return

    if (user?.organization) {
      const homePath = getHomePathFromUser(user)
      console.warn('🔑 LoginPage - User has organization, redirecting to', homePath)
      router.replace(homePath)
    } else if (user && !user.organization) {
      console.warn('🔑 LoginPage - User has incomplete registration, redirecting to /register')
      router.replace('/register')
    }
    // Если нет пользователя - остаемся на /login и показываем AuthFlow
  }, [router, user, isLoading])

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-smooth flex items-center justify-center">
        <div className="text-center text-white">
          <div className="animate-spin rounded-full h-16 w-16 border-4 border-white border-t-transparent mx-auto mb-4"></div>
          <p className="text-white/80">Проверяем авторизацию...</p>
        </div>
      </div>
    )
  }

  // Показываем AuthFlow только для неавторизованных пользователей
  return <AuthFlow />
}
