'use client'

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

import { useAuthContext } from '@/contexts/AuthContext'
import { getHomePathFromUser } from '@/lib/routing'

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

  useEffect(() => {
    console.warn('📍 app/page.tsx - routing decision triggered:', {
      isLoading,
      hasUser: !!user,
      hasOrganization: !!user?.organization,
      isAuthenticated,
      currentPath: typeof window !== 'undefined' ? window.location.pathname : 'server',
      timestamp: new Date().toISOString(),
      userDetails: user
        ? {
            id: user.id,
            phone: user.phone,
            organizationId: user.organization?.id,
            organizationType: user.organization?.type,
          }
        : null,
    })

    // КРИТИЧНО: Ждем завершения всех проверок AuthContext
    if (isLoading) {
      console.warn('📍 app/page.tsx - still loading, waiting...')
      return
    }

    // Добавляем небольшую задержку для гарантии синхронизации состояния
    const routingTimer = setTimeout(() => {
      if (user?.organization) {
        const homePath = getHomePathFromUser(user)
        console.warn('📍 app/page.tsx - DECISION: User has organization →', homePath)
        router.replace(homePath)
      } else if (isAuthenticated && user && !user.organization) {
        console.warn(
          '📍 app/page.tsx - DECISION: User authenticated but no organization → /register (continue registration)',
        )
        router.replace('/register')
      } else if (!isAuthenticated && !user) {
        console.warn('📍 app/page.tsx - DECISION: No user and not authenticated → /login')
        router.replace('/login')
      } else {
        // Неопределенное состояние - ждем
        console.warn('📍 app/page.tsx - UNCERTAIN STATE, waiting...', {
          isAuthenticated,
          hasUser: !!user,
          hasOrganization: !!user?.organization,
        })
      }
    }, 100) // Небольшая задержка для синхронизации

    // Добавляем задержку для проверки состояния после перенаправления
    setTimeout(() => {
      console.warn('📍 app/page.tsx - POST-REDIRECT CHECK (1000ms later):', {
        currentPath: typeof window !== 'undefined' ? window.location.pathname : 'server',
        userStillExists: !!user,
        stillLoading: isLoading,
        timestamp: new Date().toISOString(),
      })
    }, 1000)

    return () => clearTimeout(routingTimer)
  }, [router, user, isLoading, isAuthenticated])

  return (
    <div className="min-h-screen bg-gradient-smooth flex items-center justify-center">
      <div className="text-white">Загрузка...</div>
    </div>
  )
}
