import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { useState, useEffect } from 'react'
import { initTelegramApp, getTelegramUser } from './utils/telegram'
import { verifyAuth } from './utils/api'
import { initTheme } from './utils/theme'
import Layout from './components/Layout'
import Feed from './pages/Feed'
import Search from './pages/Search'
import Notifications from './pages/Notifications'
import Profile from './pages/Profile'
import UserProfile from './pages/UserProfile'
import './styles/index.css'

function App() {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  useEffect(() => {
    // Инициализировать тему
    initTheme()
    initApp()
  }, [])

  const initApp = async () => {
    try {
      // Инициализация Telegram Web App
      initTelegramApp()
      
      // Получить данные пользователя из Telegram
      const telegramUser = getTelegramUser()
      
      if (!telegramUser) {
        throw new Error('Telegram User не найден')
      }

      // Верифицировать через API
      const userData = await verifyAuth()
      setUser(userData)
    } catch (err) {
      console.error('Ошибка инициализации:', err)
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column',
        gap: '16px'
      }}>
        <div className="spinner" />
        <p style={{ color: 'var(--text-secondary)' }}>Загрузка...</p>
      </div>
    )
  }

  if (error) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column',
        gap: '16px',
        padding: '20px'
      }}>
        <p style={{ color: 'var(--text-primary)', textAlign: 'center' }}>
          Ошибка загрузки приложения
        </p>
        <p style={{ color: 'var(--text-secondary)', textAlign: 'center' }}>
          {error}
        </p>
      </div>
    )
  }

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout user={user} />}>
          <Route index element={<Navigate to="/feed" replace />} />
          <Route path="feed" element={<Feed user={user} />} />
          <Route path="search" element={<Search user={user} />} />
          <Route path="notifications" element={<Notifications user={user} />} />
          <Route path="profile" element={<Profile user={user} setUser={setUser} />} />
          <Route path="user/:id" element={<UserProfile currentUser={user} />} />
        </Route>
      </Routes>
    </BrowserRouter>
  )
}

export default App

