import { useEffect } from 'react'
import { BrowserRouter, Routes, Route, NavLink, useNavigate } from 'react-router-dom'
import { LayoutDashboard, PlusSquare, TrendingUp, BarChart2, Settings } from 'lucide-react'
import { ProfileProvider, useProfile } from './context/ProfileContext'
import { AuthProvider, useAuth }       from './context/AuthContext'
import { setProfileId }                from './utils/api'
import { Avatar }                      from './pages/ProfileSelect'
import SetupScreen       from './pages/SetupScreen'
import { ResetPassword } from './pages/PasswordRecovery'
import LoginScreen    from './pages/LoginScreen'
import Dashboard      from './pages/Dashboard'
import CaptureHub     from './pages/CaptureHub'
import WeightScreen   from './pages/WeightScreen'
import CircumScreen   from './pages/CircumScreen'
import CaliperScreen  from './pages/CaliperScreen'
import MeasureWizard  from './pages/MeasureWizard'
import History        from './pages/History'
import NutritionPage  from './pages/NutritionPage'
import ActivityPage   from './pages/ActivityPage'
import Analysis       from './pages/Analysis'
import SettingsPage   from './pages/SettingsPage'
import GuidePage      from './pages/GuidePage'
import AdminTierLimitsPage from './pages/AdminTierLimitsPage'
import AdminFeaturesPage from './pages/AdminFeaturesPage'
import AdminTiersPage from './pages/AdminTiersPage'
import './app.css'

function Nav() {
  const links = [
    { to:'/',         icon:<LayoutDashboard size={20}/>, label:'Übersicht' },
    { to:'/capture',  icon:<PlusSquare size={20}/>,      label:'Erfassen'  },
    { to:'/history',  icon:<TrendingUp size={20}/>,      label:'Verlauf'   },
    { to:'/analysis', icon:<BarChart2 size={20}/>,       label:'Analyse'   },
    { to:'/settings', icon:<Settings size={20}/>,        label:'Einst.'    },
  ]
  return (
    <nav className="bottom-nav">
      {links.map(l=>(
        <NavLink key={l.to} to={l.to} end={l.to==='/'} className={({isActive})=>'nav-item'+(isActive?' active':'')}>
          {l.icon}<span>{l.label}</span>
        </NavLink>
      ))}
    </nav>
  )
}

function AppShell() {
  const { session, loading: authLoading, needsSetup } = useAuth()
  const { activeProfile, loading: profileLoading }    = useProfile()
  const nav = useNavigate()

  useEffect(()=>{
    if (session?.profile_id) {
      setProfileId(session.profile_id)
      localStorage.setItem('mitai-jinkendo_active_profile', session.profile_id)
    }
  }, [session?.profile_id])

  // Handle password reset link
  const urlParams = new URLSearchParams(window.location.search)
  const resetToken = urlParams.get('reset-password') || (window.location.pathname === '/reset-password' ? urlParams.get('token') : null)
  if (resetToken) return (
    <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center',
      background:'var(--bg)',padding:24}}>
      <div style={{width:'100%',maxWidth:360}}>
        <div style={{textAlign:'center',marginBottom:20}}>
          <div style={{fontSize:28,fontWeight:800,color:'var(--accent)'}}>Mitai Jinkendo</div>
        </div>
        <div className="card" style={{padding:20}}>
          <ResetPassword token={resetToken} onDone={()=>window.location.href='/'}/>
        </div>
      </div>
    </div>
  )

  // Auth loading
  if (authLoading) return (
    <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center'}}>
      <div className="spinner" style={{width:32,height:32}}/>
    </div>
  )

  // First run
  if (needsSetup) return <SetupScreen/>

  // Need to log in
  if (!session) return <LoginScreen/>

  // Profile loading
  if (profileLoading) return (
    <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center'}}>
      <div className="spinner" style={{width:32,height:32}}/>
    </div>
  )

  return (
    <div className="app-shell">
      <header className="app-header">
        <span className="app-logo">Mitai Jinkendo</span>
        <NavLink to="/settings" style={{textDecoration:'none'}}>
          {activeProfile
            ? <Avatar profile={activeProfile} size={30}/>
            : <div style={{width:30,height:30,borderRadius:'50%',background:'var(--accent)'}}/>
          }
        </NavLink>
      </header>
      <main className="app-main">
        <Routes>
          <Route path="/"          element={<Dashboard/>}/>
          <Route path="/capture"   element={<CaptureHub/>}/>
          <Route path="/wizard"    element={<MeasureWizard/>}/>
          <Route path="/weight"    element={<WeightScreen/>}/>
          <Route path="/circum"    element={<CircumScreen/>}/>
          <Route path="/caliper"   element={<CaliperScreen/>}/>
          <Route path="/history"   element={<History/>}/>
          <Route path="/nutrition" element={<NutritionPage/>}/>
          <Route path="/activity"  element={<ActivityPage/>}/>
          <Route path="/analysis"  element={<Analysis/>}/>
          <Route path="/settings"  element={<SettingsPage/>}/>
          <Route path="/guide"     element={<GuidePage/>}/>
          <Route path="/admin/tier-limits" element={<AdminTierLimitsPage/>}/>
          <Route path="/admin/features" element={<AdminFeaturesPage/>}/>
          <Route path="/admin/tiers" element={<AdminTiersPage/>}/>
        </Routes>
      </main>
      <Nav/>
    </div>
  )
}

export default function App() {
  return (
    <AuthProvider>
      <ProfileProvider>
        <BrowserRouter>
          <AppShell/>
        </BrowserRouter>
      </ProfileProvider>
    </AuthProvider>
  )
}
