PROJECT OVERVIEW:
Build a comprehensive SaaS platform called 'RetroOptimize' that delves into the optimization techniques of classic, well-regarded games like RollerCoaster Tycoon. The core value proposition is to educate modern software developers, particularly those interested in systems programming, game development, and performance optimization, by dissecting the underlying principles, efficient algorithms, and low-level coding practices (like Assembly) that made these older games perform exceptionally well on limited hardware. The platform will offer interactive analysis tools, educational modules, and a community forum.
TECH STACK:
- Frontend: Next.js (App Router), React, Tailwind CSS, shadcn/ui
- Backend: Node.js (within Next.js API routes/server actions)
- Database: PostgreSQL with Drizzle ORM
- Authentication: NextAuth.js (with PostgreSQL adapter)
- State Management: React Context API / Zustand for global state, component-local state where appropriate.
- Other: Libraries for syntax highlighting (e.g., `react-syntax-highlighter`), charting (e.g., `Chart.js` or `Recharts`), potentially a WASM-based parser for simulated Assembly analysis.
DATABASE SCHEMA:
1. `users` table:
- `id` (UUID, primary key)
- `name` (VARCHAR)
- `email` (VARCHAR, unique)
- `emailVerified` (TIMESTAMP)
- `image` (VARCHAR, optional)
- `createdAt` (TIMESTAMP, default NOW())
- `updatedAt` (TIMESTAMP)
2. `accounts` table (for NextAuth.js):
- `id` (VARCHAR, primary key)
- `userId` (UUID, foreign key to users.id)
- `type` (VARCHAR)
- `provider` (VARCHAR)
- `providerAccountId` (VARCHAR)
- `refresh_token` (TEXT, optional)
- `access_token` (TEXT, optional)
- `expires_at` (BIGINT, optional)
- `token_type` (VARCHAR, optional)
- `scope` (VARCHAR, optional)
- `id_token` (TEXT, optional)
- `session_state` (VARCHAR, optional)
3. `sessions` table (for NextAuth.js):
- `sessionToken` (VARCHAR, primary key)
- `userId` (UUID, foreign key to users.id)
- `expires` (TIMESTAMP)
4. `verification_tokens` table (for NextAuth.js):
- `identifier` (VARCHAR)
- `token` (VARCHAR)
- `expires` (TIMESTAMP)
5. `games` table:
- `id` (UUID, primary key)
- `title` (VARCHAR, e.g., 'RollerCoaster Tycoon')
- `developer` (VARCHAR, e.g., 'Chris Sawyer')
- `releaseYear` (INTEGER)
- `description` (TEXT)
- `createdAt` (TIMESTAMP, default NOW())
6. `optimizationTechniques` table:
- `id` (UUID, primary key)
- `gameId` (UUID, foreign key to games.id, nullable for general techniques)
- `title` (VARCHAR, e.g., 'Assembly Optimization', 'Memory Management', 'Agent Simulation Logic')
- `description` (TEXT)
- `complexity` (VARCHAR, e.g., 'Beginner', 'Intermediate', 'Advanced')
- `createdAt` (TIMESTAMP, default NOW())
7. `codeSnippets` table:
- `id` (UUID, primary key)
- `techniqueId` (UUID, foreign key to optimizationTechniques.id)
- `language` (VARCHAR, e.g., 'Assembly', 'Pseudocode', 'C')
- `code` (TEXT)
- `explanation` (TEXT)
- `createdAt` (TIMESTAMP, default NOW())
8. `userAnalysis` table (for user-uploaded snippets or interactions):
- `id` (UUID, primary key)
- `userId` (UUID, foreign key to users.id)
- `snippetId` (UUID, foreign key to codeSnippets.id, optional)
- `analysisResult` (JSONB)
- `createdAt` (TIMESTAMP, default NOW())
9. `forumPosts` table:
- `id` (UUID, primary key)
- `userId` (UUID, foreign key to users.id)
- `title` (VARCHAR)
- `content` (TEXT)
- `createdAt` (TIMESTAMP, default NOW())
- `updatedAt` (TIMESTAMP)
10. `forumComments` table:
- `id` (UUID, primary key)
- `postId` (UUID, foreign key to forumPosts.id)
- `userId` (UUID, foreign key to users.id)
- `content` (TEXT)
- `createdAt` (TIMESTAMP, default NOW())
- `updatedAt` (TIMESTAMP)
CORE FEATURES & USER FLOW:
1. Authentication (Email/Password, OAuth with Google/GitHub):
- User lands on the homepage.
- Clicks 'Sign Up' or 'Login'.
- Option to sign up with email/password or via OAuth providers.
- For email/password: Enter email, password, confirm password. Submit.
- Backend validates credentials, creates user in `users` table, generates auth tokens.
- For OAuth: Redirect to provider, authenticate, receive user info, create/find user in `users` table, generate auth tokens.
- Upon successful login, redirect to the dashboard.
- Protected routes redirect unauthenticated users to the login page.
2. Game Analysis Module (Focus: RollerCoaster Tycoon):
- User navigates to 'Games' -> 'RollerCoaster Tycoon'.
- Displays game overview, developer info, release year.
- Section: 'Optimization Deep Dive'.
- Sub-sections for key techniques (e.g., 'Assembly Core', 'Pathfinding Efficiency', 'Memory Allocation').
- Each sub-section presents explanations, interactive code visualizations (simulated Assembly), and performance metric examples.
- User Flow: Click technique -> View explanation -> Interact with code snippet (highlighting, simple step-through simulation) -> See performance impact visualization.
3. Interactive Code Analysis ('Sandbox'):
- User navigates to 'Tools' -> 'Code Sandbox'.
- Option to select a technique (e.g., 'Loop Unrolling') or upload/paste their own pseudocode/simulated Assembly.
- The sandbox provides a simulated execution environment.
- Basic analysis: Loop iterations, memory access patterns, potential bottlenecks identification.
- Results are displayed visually (charts, highlighted code sections) and in a text summary.
- User Flow: Select technique/paste code -> Run analysis -> View results -> Save analysis (optional) -> Navigate to forum to discuss.
4. Educational Modules:
- User navigates to 'Learn' -> 'Modules'.
- Browse modules by topic (e.g., 'Low-Level Optimization', 'Data Structure Efficiency', 'Algorithm Analysis').
- Each module consists of text, diagrams, interactive examples (linking to Sandbox), and quizzes.
- User Flow: Select module -> Read content -> Complete interactive exercises -> Take quiz -> Module marked as complete.
5. Community Forum:
- User navigates to 'Community' -> 'Forum'.
- View list of posts, filter by category.
- Click a post to view content and comments.
- Authenticated users can create new posts and reply to existing ones.
- User Flow: Browse topics -> Read post -> Reply -> Create new post.
API & DATA FETCHING:
- Use Next.js API Routes (or Server Actions for cleaner integration) for all backend logic.
- Data fetching primarily server-side (SSR) or static site generation (SSG) where possible for performance and SEO.
- Use client-side fetching (e.g., SWR or React Query) within components for dynamic data or user-specific interactions (like forum replies).
- API Examples:
- `POST /api/auth/signup`: Register new user.
- `POST /api/auth/login`: Authenticate user.
- `GET /api/games/{gameId}/techniques`: Fetch optimization techniques for a specific game.
- `GET /api/techniques/{techniqueId}/snippets`: Fetch code snippets related to a technique.
- `POST /api/sandbox/analyze`: Submit code for analysis (request body: `{ code: string, language: string }`, response body: `{ analysis: object, highlights: array }`).
- `POST /api/forum/posts`: Create a new forum post.
- `GET /api/forum/posts/{postId}/comments`: Fetch comments for a post.
- Data will be fetched and passed as props to Server Components or used in Client Components via hooks.
COMPONENT BREAKDOWN (Next.js App Router Structure):
- `app/layout.tsx`: Root layout (HTML, head, body, global providers, Tailwind CSS setup).
- `app/page.tsx`: Homepage (Hero section, feature overview, call to action).
- `app/dashboard/page.tsx`: User dashboard (Personalized overview, recent activity, module progress).
- `app/auth/(routes)/login/page.tsx`: Login page.
- `app/auth/(routes)/signup/page.tsx`: Sign up page.
- `app/games/[gameId]/page.tsx`: Individual game analysis page (e.g., `/games/rollercoaster-tycoon`).
- Components: `GameOverview`, `OptimizationTechniqueList`, `CodeSnippetViewer`.
- `app/tools/sandbox/page.tsx`: Code sandbox page.
- Components: `CodeEditor` (using `react-syntax-highlighter`), `AnalysisRunner`, `ResultsDisplay`.
- `app/learn/page.tsx`: Main learning modules page.
- `app/learn/[moduleId]/page.tsx`: Individual learning module page.
- Components: `ModuleContent`, `InteractiveExercise`, `Quiz`.
- `app/community/page.tsx`: Forum index page.
- Components: `PostList`, `CategoryFilter`.
- `app/community/[postId]/page.tsx`: Individual forum post page.
- Components: `PostDetail`, `CommentList`, `CommentForm`.
- `app/components/ui/`: Reusable UI components from shadcn/ui (Button, Card, Input, Dialog, etc.).
- `app/components/layout/`: Layout components (Navbar, Sidebar, Footer).
- `app/lib/`: Utility functions, ORM client setup, auth configuration.
UI/UX DESIGN & VISUAL IDENTITY:
- Style: 'Modern Minimalist with Retro Accents'. Clean lines, ample whitespace, focus on readability.
- Color Palette:
- Primary: `#3b82f6` (a strong, reliable blue)
- Secondary: `#6366f1` (a vibrant purple for accents)
- Neutral Dark: `#1f2937` (for backgrounds, text)
- Neutral Light: `#f3f4f6` (for backgrounds, cards)
- Accent/Highlight: `#f59e0b` (a warm orange for calls to action, warnings)
- Typography:
- Headings: A clean sans-serif like 'Inter' or 'Manrope'.
- Body Text: 'Inter' or 'Roboto' for excellent readability.
- Layout: Two-column or three-column layouts for content, clear navigation (sidebar or top nav).
- Animations: Subtle fade-ins for content loading, smooth transitions on hover effects for buttons and cards, gentle loading spinners.
- Responsive Rules: Mobile-first approach. Single-column layout on small screens, expanding to multi-column on larger screens. Navigation collapses into a hamburger menu on mobile.
SAMPLE/MOCK DATA:
1. Game: `{ id: '...', title: 'RollerCoaster Tycoon', developer: 'Chris Sawyer', releaseYear: 1999 }`
2. Technique: `{ id: '...', gameId: '...', title: 'Assembly Optimization', description: 'Leveraging low-level instructions for maximum CPU efficiency...', complexity: 'Advanced' }`
3. Code Snippet (Assembly Simulation):
```assembly
section .data
my_array dw 1, 2, 3, 4, 5
array_len equ ($ - my_array) / 2
section .text
global _start
_start:
mov esi, my_array ; Pointer to array
mov ecx, array_len ; Loop counter
mov eax, 0 ; Accumulator for sum
sum_loop:
add eax, [esi] ; Add current element to sum
add esi, 2 ; Move to next element (word = 2 bytes)
loop sum_loop ; Decrement ECX and jump if not zero
; Exit syscall (simplified)
mov ebx, eax ; syscall arg 1: sum
mov eax, 1 ; syscall number (sys_exit)
int 0x80 ; invoke kernel
```
Explanation: 'This snippet demonstrates summing array elements in Assembly, highlighting register usage (EAX, ECX, ESI) and the loop instruction for efficiency.'
4. Forum Post: `{ id: '...', userId: '...', title: 'Performance Bottlenecks in RCT Pathfinding?', content: 'I was analyzing the pathfinding algorithm in RCT and noticed...', createdAt: '...' }`
5. Forum Comment: `{ id: '...', postId: '...', userId: '...', content: 'Great analysis! Have you considered the impact of diagonal movement costs?', createdAt: '...' }`
6. User Analysis Result: `{ analysis: { avgInstructionsPerLoop: 15, memoryAccesses: 1000, bottleneckLikelihood: 'Medium' }, highlights: [{ line: 10, type: 'Potential Optimization', message: 'Consider loop unrolling here.' }] }`
7. Module: `{ id: '...', title: 'Efficient Memory Management', description: 'Learn how to manage memory effectively...' }`
8. User Progress: `{ userId: '...', moduleId: '...', completed: true, score: 85 }`
ANIMATIONS:
- Page Transitions: `framer-motion` for smooth page entry/exit animations (e.g., `AnimatePresence`).
- Component Mounts: Staggered fade-in or slide-in animations for lists and cards as they appear.
- Hover Effects: Subtle scaling, background color changes, or shadow lifts on interactive elements (buttons, cards, links).
- Loading States: Skeleton loaders or subtle pulsing animations while data is being fetched, especially in the Sandbox and Forum sections.
- Chart Interactions: Tooltips with smooth transitions, animated bar/line growths upon initial load.
EDGE CASES:
- **Initial State**: Dashboard, Sandbox, and Forum should display informative messages or placeholders when empty (e.g., "No analyses yet. Try the sandbox!", "Start a new discussion!").
- **Authentication**: Redirect unauthenticated users from protected pages. Handle expired tokens gracefully (e.g., redirect to login). Implement robust error handling for login/signup failures (e.g., incorrect password, email already exists).
- **Authorization**: Ensure users can only edit/delete their own forum posts/comments. Implement role-based access if tiered subscriptions are introduced later.
- **Data Validation**: Client-side and server-side validation for all form inputs (signup, login, forum posts, sandbox code submission). Use libraries like Zod with Drizzle.
- **API Errors**: Consistent error handling for API calls. Display user-friendly error messages. Implement retry mechanisms for transient network issues where appropriate.
- **Sandbox Errors**: Handle syntax errors in user-submitted code. Provide clear feedback on the error location and type. Gracefully handle potential runtime errors or infinite loops in the simulated environment (e.g., timeout limits).
- **Responsiveness**: Ensure all components and layouts adapt correctly to various screen sizes, from small mobile devices to large desktops.