import { useEffect, useState } from 'react';
import { BrowserRouter, Routes, Route, useParams } from 'react-router-dom';
import { api } from '@/api/client';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { RightRail } from '@/components/RightRail';
import { Home } from '@/pages/Home';
import { Project } from '@/pages/Project';
import { Session } from '@/pages/Session';
import { Toaster } from '@/components/ui/sonner';
import { useUserEvents } from '@/hooks/useUserEvents';

function SessionRightRail() {
  const { id } = useParams<{ id: string }>();
  if (!id) return null;
  return <RightRailForSession sessionId={id} />;
}

function RightRailForSession({ sessionId }: { sessionId: string }) {
  const [projectId, setProjectId] = useState<string | null>(null);
  useEffect(() => {
    api.sessions
      .get(sessionId)
      .then((s) => setProjectId(s.project_id))
      .catch((err) => console.warn('RightRail: failed to fetch session', err));
  }, [sessionId]);
  if (!projectId) return null;
  return <RightRail projectId={projectId} />;
}

function AppShell() {
  useUserEvents();
  return (
    <div className="dark h-screen flex bg-background text-foreground">
      <ProjectSidebar />
      <main className="flex-1 flex flex-col min-w-0">
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/project/:id" element={<Project />} />
          <Route path="/session/:id" element={<Session />} />
        </Routes>
      </main>
      <Routes>
        <Route path="/session/:id" element={<SessionRightRail />} />
      </Routes>
      <Toaster position="bottom-right" />
    </div>
  );
}

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