import { Routes, Route, Navigate, Link } from 'react-router-dom'
import { BookOpen, CheckSquare, LayoutDashboard, Trophy, Settings, LogOut, Target } from 'lucide-react'
import { useApp } from './store/AppContext'
import Mark from './components/ui/Mark'
import BuildStamp from './components/ui/BuildStamp'
import ChatLauncher from './components/chat/ChatLauncher'

import Login from './pages/Login'
import Onboarding from './pages/Onboarding'
import OnboardingTrack from './pages/OnboardingTrack'
import Dashboard from './pages/Dashboard'

import Admin from './pages/Admin'
import Leren from './pages/Leren'
import Testen from './pages/Testen'
import TopicTest from './pages/TopicTest'
import Leaderboard from './pages/Leaderboard'

// Protected Route Wrapper
const ProtectedRoute = ({ children, requireAdmin, skipEnrollmentGate }) => {
  const { state, logout } = useApp()

  if (state.isLoading) return <div className="p-8">Loading...</div>

  if (!state.currentUser) {
    return <Navigate to="/login" replace />
  }

  if (requireAdmin && state.currentUser.role !== 'admin') {
    return <Navigate to="/" replace />
  }

  // Block any non-enrolled user from reaching curriculum pages.
  // Admins are exempt from the gate when they're heading to the admin panel.
  const needsEnrollment = state.currentUser.enrollment_status !== 'active'
  const isAdmin = state.currentUser.role === 'admin'
  if (needsEnrollment && !skipEnrollmentGate && !(requireAdmin && isAdmin)) {
    return <Navigate to="/onboarding" replace />
  }

  return (
    <div className="min-h-screen bg-bg text-fg font-sans flex flex-col pb-16 md:pb-0">
      {/* Top Navigation Bar */}
      <nav className="bg-bg-dark text-paper p-4 shadow-soft flex justify-between items-center sticky top-0 z-50">
        <Link to="/" className="flex items-center gap-2" aria-label="Respellion home">
          <Mark state="idle" size={28} brace="#ECE9E9" letter="#ECE9E9" />
          <span className="text-paper font-semibold tracking-tight text-base md:text-lg">respellion</span>
        </Link>
        
        {/* Desktop Links */}
        <div className="hidden md:flex items-center gap-6 text-sm font-medium">
          <Link to="/" className="hover:text-accent-soft transition-colors flex items-center gap-2"><LayoutDashboard size={16}/> Dashboard</Link>
          <Link to="/learn" className="hover:text-accent-soft transition-colors flex items-center gap-2"><BookOpen size={16}/> Learn</Link>
          <Link to="/test" className="hover:text-accent-soft transition-colors flex items-center gap-2"><CheckSquare size={16}/> Theme Test</Link>
          <Link to="/topic-test" className="hover:text-accent-soft transition-colors flex items-center gap-2"><Target size={16}/> Topic Test</Link>
          <Link to="/leaderboard" className="hover:text-accent-soft transition-colors flex items-center gap-2"><Trophy size={16}/> Leaderboard</Link>
          {state.currentUser.role === 'admin' && (
            <Link to="/admin" className="hover:text-accent-soft transition-colors flex items-center gap-2">
              <Settings size={16}/> Admin
            </Link>
          )}
          <button 
            onClick={logout}
            className="ml-4 border border-bg-warm/30 rounded-[var(--r-pill)] px-3 py-1 hover:bg-paper/10 transition-colors flex items-center gap-2"
          >
            <LogOut size={14}/> Sign Out
          </button>
        </div>
        
        {/* Mobile top-right: just logout icon */}
        <div className="flex md:hidden items-center">
          <button onClick={logout} className="p-2 hover:bg-paper/10 rounded-full transition-colors text-paper">
             <LogOut size={20}/>
          </button>
        </div>
      </nav>

      {/* Mobile Bottom Navigation */}
      <nav className="md:hidden fixed bottom-0 left-0 right-0 bg-paper border-t border-bg-warm flex justify-around items-center p-2 z-50">
          <Link to="/" className="flex flex-col items-center p-2 text-fg-muted hover:text-teal"><LayoutDashboard size={20}/><span className="text-[10px] mt-1 font-medium">Home</span></Link>
          <Link to="/learn" className="flex flex-col items-center p-2 text-fg-muted hover:text-teal"><BookOpen size={20}/><span className="text-[10px] mt-1 font-medium">Learn</span></Link>
          <Link to="/test" className="flex flex-col items-center p-2 text-fg-muted hover:text-teal"><CheckSquare size={20}/><span className="text-[10px] mt-1 font-medium">Theme</span></Link>
          <Link to="/topic-test" className="flex flex-col items-center p-2 text-fg-muted hover:text-teal"><Target size={20}/><span className="text-[10px] mt-1 font-medium">Topic</span></Link>
          <Link to="/leaderboard" className="flex flex-col items-center p-2 text-fg-muted hover:text-teal"><Trophy size={20}/><span className="text-[10px] mt-1 font-medium">Score</span></Link>
          {state.currentUser.role === 'admin' && (
            <Link to="/admin" className="flex flex-col items-center p-2 text-fg-muted hover:text-teal"><Settings size={20}/><span className="text-[10px] mt-1 font-medium">Admin</span></Link>
          )}
      </nav>

      <main className="flex-1 w-full max-w-[var(--max)] mx-auto">
        {children}
      </main>

      <ChatLauncher />
    </div>
  )
}

function App() {
  const { state } = useApp()

  if (state.isLoading) return <div className="p-8 flex items-center justify-center min-h-screen">Loading application...</div>

  return (
    <>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="/onboarding" element={<Onboarding />} />
        <Route path="/" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
        {/* Onboarding track is available to any logged-in user, regardless of
            enrollment — hence skipEnrollmentGate (distinct from /onboarding, the
            enrollment page). */}
        <Route path="/onboarding-track" element={<ProtectedRoute skipEnrollmentGate><OnboardingTrack /></ProtectedRoute>} />
        <Route path="/learn" element={<ProtectedRoute><Leren /></ProtectedRoute>} />
        <Route path="/test" element={<ProtectedRoute><Testen /></ProtectedRoute>} />
        <Route path="/topic-test" element={<ProtectedRoute><TopicTest /></ProtectedRoute>} />
        <Route path="/leaderboard" element={<ProtectedRoute><Leaderboard /></ProtectedRoute>} />
        <Route path="/admin/*" element={<ProtectedRoute requireAdmin={true}><Admin /></ProtectedRoute>} />
      </Routes>
      <BuildStamp />
    </>
  )
}

export default App
