import { useEffect } from 'react'
import { Routes, Route } from 'react-router-dom'
import { supabase } from '@/lib/supabase'
import { useAuthStore } from '@/stores/auth'
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'

export default function App() {
  const { setUser, fetchProfile } = useAuthStore()

  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])

  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="settings" element={<Settings />} />
      </Route>
    </Routes>
  )
}
