import { useEffect, useRef } from 'react'
import { Routes, Route, useNavigate, useLocation } from 'react-router-dom'
import { supabase } from '@/lib/supabase'
import { useAuthStore } from '@/stores/auth'
import { useOnlineStatus } from '@/hooks/useOnlineStatus'
import { Layout } from '@/components/layout/Layout'
import { Home } from '@/pages/Home'
import { Explore } from '@/pages/Explore'
import { Auth } from '@/pages/Auth'
import { Upload } from '@/pages/Upload'
import { PodcastDetail } from '@/pages/PodcastDetail'
import { Profile } from '@/pages/Profile'
import { Favorites } from '@/pages/Favorites'
import { Settings } from '@/pages/Settings'
import { MyPodcasts } from '@/pages/MyPodcasts'
import { Offline } from '@/pages/Offline'
import { Trending } from '@/pages/Trending'
import { Following } from '@/pages/Following'
import { ForYou } from '@/pages/ForYou'
import { Playlists } from '@/pages/Playlists'
import { PlaylistDetail } from '@/pages/PlaylistDetail'
import { Notifications } from '@/pages/Notifications'
import { ShowDetail } from '@/pages/ShowDetail'
import { MyShows } from '@/pages/MyShows'
import { Dashboard } from '@/pages/Dashboard'

export default function App() {
  const { setUser, fetchProfile } = useAuthStore()
  const isOnline = useOnlineStatus()
  const navigate = useNavigate()
  const location = useLocation()
  const prevPathRef = useRef(location.pathname)

  useEffect(() => {
    supabase.auth.getSession().then(({ data: { session } }) => {
      setUser(session?.user ?? null)
      if (session?.user) fetchProfile()
    })

    const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
      setUser(session?.user ?? null)
      if (session?.user) fetchProfile()
    })

    return () => subscription.unsubscribe()
  }, [setUser, fetchProfile])

  // Redirect to /offline when connection drops, restore when back online
  useEffect(() => {
    if (!isOnline && location.pathname !== '/offline') {
      prevPathRef.current = location.pathname
      navigate('/offline', { replace: true })
    } else if (isOnline && location.pathname === '/offline') {
      navigate(prevPathRef.current || '/', { replace: true })
    }
  }, [isOnline, location.pathname, navigate])

  return (
    <Routes>
      <Route element={<Layout />}>
        <Route index element={<Home />} />
        <Route path="explore" element={<Explore />} />
        <Route path="auth" element={<Auth />} />
        <Route path="upload" element={<Upload />} />
        <Route path="podcast/:id" element={<PodcastDetail />} />
        <Route path="profile/:username" element={<Profile />} />
        <Route path="favorites" element={<Favorites />} />
        <Route path="my-podcasts" element={<MyPodcasts />} />
        <Route path="settings" element={<Settings />} />
        <Route path="trending" element={<Trending />} />
        <Route path="following" element={<Following />} />
        <Route path="for-you" element={<ForYou />} />
        <Route path="playlists" element={<Playlists />} />
        <Route path="playlist/:id" element={<PlaylistDetail />} />
        <Route path="notifications" element={<Notifications />} />
        <Route path="show/:id" element={<ShowDetail />} />
        <Route path="my-shows" element={<MyShows />} />
        <Route path="dashboard" element={<Dashboard />} />
        <Route path="offline" element={<Offline />} />
      </Route>
    </Routes>
  )
}
