You are an expert full-stack developer and startup consultant tasked with creating a fully functional, multi-page Next.js MVP application. This application will be a browser-based embedded systems simulator, inspired by Velxio, but with enhanced features for learning and collaboration.
**PROJECT OVERVIEW:**
Develop 'BrowserSim' (Simülatör), a Software-as-a-Service (SaaS) platform that empowers students, hobbyists, and developers to simulate popular embedded hardware like Arduino, ESP32, and Raspberry Pi Pico directly within their web browser. The core value proposition is to provide an accessible, cost-effective, and instant environment for learning, prototyping, and debugging embedded systems without the need for physical hardware. It will offer an integrated experience for writing code (Arduino C++ and MicroPython), compiling, simulating with accurate CPU emulation, and interacting with a variety of virtual electronic components. Key differentiators will include a focus on educational clarity, collaborative features, and a smooth user experience.
**TECH STACK:**
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **UI Components:** shadcn/ui
- **Database ORM:** Drizzle ORM
- **Database:** PostgreSQL (recommended for Drizzle)
- **Authentication:** NextAuth.js (e.g., with GitHub, Google providers)
- **State Management:** React Context API or Zustand (for global state)
- **Backend (for compilation/simulation):** Potentially a separate Node.js service or leveraging serverless functions (e.g., AWS Lambda, Vercel Functions) to handle resource-intensive compilation and simulation tasks, possibly using technologies like WebAssembly for in-browser emulation or a backend service with QEMU.
- **Other:** React Hook Form (for forms), Zod (for schema validation), potentially a library for code editing (e.g., Monaco Editor).
**DATABASE SCHEMA (Drizzle ORM for PostgreSQL):**
```typescript
// schema.ts
import { pgTable, serial, text, timestamp, integer, boolean, jsonb } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name'),
email: text('email').unique().notNull(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: text('image'),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
export const accounts = pgTable('accounts', {
id: serial('id').primaryKey(),
userId: integer('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
type: text('type').notNull(), // 'oauth' or 'email'
provider: text('provider').notNull(), // e.g., 'github', 'google'
providerAccountId: text('providerAccountId').notNull(),
refresh_token: text('refresh_token'),
access_token: text('access_token'),
expires_at: integer('expires_at'),
token_type: text('token_type'),
scope: text('scope'),
id_token: text('id_token'),
session_state: text('session_state'),
});
export const sessions = pgTable('sessions', {
id: serial('id').primaryKey(),
sessionToken: text('sessionToken').unique().notNull(),
userId: integer('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
expires: timestamp('expires', { mode: 'date' }).notNull(),
});
export const verificationTokens = pgTable('verificationTokens', {
id: serial('id').primaryKey(),
identifier: text('identifier').notNull(),
token: text('token').notNull(),
expires: timestamp('expires', { mode: 'date' }).notNull(),
});
export const projects = pgTable('projects', {
id: serial('id').primaryKey(),
userId: integer('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
name: text('name').notNull(),
description: text('description'),
boardType: text('boardType').notNull(), // e.g., 'arduino-uno', 'esp32', 'rpi-pico'
language: text('language').notNull(), // e.g., 'cpp', 'python'
code: text('code').notNull(), // Stores the user's code
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
export const components = pgTable('components', {
id: serial('id').primaryKey(),
projectId: integer('projectId').notNull().references(() => projects.id, { onDelete: 'cascade' }),
type: text('type').notNull(), // e.g., 'led', 'button', 'potentiometer'
config: jsonb('config'), // e.g., { pin: '13', color: '#FF0000' } for LED, { pin: '2' } for button
position: jsonb('position'), // e.g., { x: 100, y: 150 } for visual layout
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Example relationships (using Drizzle's relation syntax)
// import { relations } from 'drizzle-orm';
// export const userRelations = relations(users, ({ many }) => ({
// projects: many(projects),
// }));
// export const projectRelations = relations(projects, ({ one, many }) => ({
// user: one(users, { fields: [projects.userId], references: [users.id] }),
// components: many(components),
// }));
```
**CORE FEATURES & USER FLOW:**
1. **User Authentication:**
* **Flow:** User visits the landing page -> Clicks 'Sign Up' or 'Log In' -> Presented with OAuth options (Google, GitHub) and potentially email/password -> Upon successful authentication, user is redirected to their dashboard.
* **Edge Cases:** Invalid credentials, OAuth callback errors, session expiry.
2. **Dashboard:**
* **Flow:** Authenticated user lands on their dashboard -> Displays a list of their existing projects ('My Projects') -> Option to create a new project.
* **UI:** List view with project name, board type, last modified. 'New Project' button.
* **Edge Cases:** Empty state (no projects yet), loading state, error fetching projects.
3. **Project Creation/Editing:**
* **Flow:** User clicks 'New Project' or an existing project's 'Edit' button -> Navigates to the main IDE view.
* **IDE View Components:**
* **Code Editor:** Top section. User writes/pastes code (e.g., `void setup() { pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); }`). Language selection (C++/Python) updates syntax highlighting.
* **Component Selector:** Sidebar. Drag-and-drop or click-to-add common components (LED, Button, Potentiometer, Serial Monitor).
* **Simulator Control:** Toolbar. Buttons for 'Compile', 'Run/Simulate', 'Stop', 'Reset'. Displays simulation status (Compiling, Running, Error).
* **Output/Serial Monitor:** Bottom pane. Displays compiler output, simulation logs, and serial print data (`Serial.println()`).
* **Configuration Panel:** Contextual panel (appears when a component is selected or project settings are accessed). Allows configuring component properties (e.g., LED pin number, button pull-up/down, potentiometer initial value, RPi model).
* **User Flow (Coding & Simulating):**
1. User selects board type (e.g., Arduino Uno).
2. User writes code in the editor.
3. User adds and configures components (e.g., an LED on pin 13, a button on pin 2).
4. User clicks 'Compile'. Backend service compiles the code. Output appears in the Serial Monitor pane.
5. If compilation is successful, user clicks 'Run/Simulate'.
6. The simulation starts. Virtual components react based on the code. LED should light up, button presses could be simulated via UI interaction.
7. User can interact with simulated components (e.g., click the virtual button).
8. User can stop/reset the simulation.
9. User clicks 'Save Project'. Code and component configurations are saved to the database.
* **Edge Cases:** Invalid code syntax, compilation errors, simulation logic errors, component misconfiguration, unsupported board features, resource limits exceeded.
4. **Project Management:**
* **Flow:** From the dashboard, users can view, rename, delete, or duplicate their projects.
* **UI:** Project list on dashboard, actions available on hover or via a kebab menu.
* **Edge Cases:** Deleting a project, handling large numbers of projects.
**API & DATA FETCHING (Next.js App Router):**
- **Authentication Routes:** Handled by NextAuth.js (`/api/auth/...`).
- **Project API Routes (Server Actions or Route Handlers):**
* `POST /api/projects`: Create a new project.
* Request Body: `{ name: string, boardType: string, language: string, code: string, components: Component[] }`
* Response: `{ success: boolean, projectId: number, error?: string }`
* `GET /api/projects`: Get a list of user's projects.
* Response: `Project[]`
* `GET /api/projects/[id]`: Get a single project's details.
* Response: `Project & { components: Component[] }`
* `PUT /api/projects/[id]`: Update an existing project.
* Request Body: `{ name?: string, code?: string, components?: Component[] }`
* Response: `{ success: boolean, error?: string }`
* `DELETE /api/projects/[id]`: Delete a project.
* Response: `{ success: boolean, error?: string }`
- **Simulation API (Potentially separate service or Server Action):**
* `POST /api/simulate`: Trigger compilation and simulation.
* Request Body: `{ boardType: string, language: string, code: string, components: ComponentConfig[] }`
* Response: `{ status: 'compiling' | 'running' | 'success' | 'error', output: string, simulationState?: any }` (Simulation state could be a snapshot of component states).
- **Data Fetching:** Utilize Server Components for initial data loading (projects list) and Client Components with `fetch` or libraries like SWR/React Query for dynamic data interactions (e.g., saving code, fetching simulation results).
**COMPONENT BREAKDOWN (Next.js App Router Structure):**
```
app/
├── api/
│ ├── auth/[...nextauth]/route.ts // NextAuth.js handler
│ ├── projects/
│ │ ├── route.ts // CRUD operations for projects
│ │ └── [id]/route.ts // Specific project operations
│ └── simulate/route.ts // Simulation triggering
├── (authenticated)/
│ ├── dashboard/
│ │ └── page.tsx // User dashboard, project list
│ ├── projects/
│ │ └── [projectId]/
│ │ └── page.tsx // IDE view: editor, simulator controls, output
│ ├── settings/
│ │ └── page.tsx // User settings page
│ └── layout.tsx // Authenticated layout (navbar, sidebar)
├── layout.tsx // Root layout
└── page.tsx // Landing Page
components/
├── ui/
│ ├── *.tsx // shad-cn/ui components (button, input, card, etc.)
│ └── *.
├── auth/
│ ├── SignInButton.tsx
│ └── SignOutButton.tsx
├── common/
│ ├── Navbar.tsx
│ ├── Sidebar.tsx
│ └── Footer.tsx
├── ide/
│ ├── CodeEditor.tsx // Monaco Editor instance or similar
│ ├── ComponentSelector.tsx // Draggable/selectable components list
│ ├── SimulatorControls.tsx // Compile, Run, Stop buttons
│ ├── SerialMonitor.tsx // Output display area
│ ├── ConfigurationPanel.tsx // Settings for selected components/project
│ └── SimulationCanvas.tsx // (Optional) Visual representation of circuit
├── projects/
│ └── ProjectList.tsx // Displays projects on dashboard
│ └── ProjectListItem.tsx // Individual project row
└── ... (other shared components)
```
- **State Management:** Primarily use Server Components for fetching and passing data. Utilize React Context API or Zustand for managing UI state within client components (e.g., IDE layout state, selected component, current simulation status).
**UI/UX DESIGN & VISUAL IDENTITY:**
- **Style:** Minimalist Clean with subtle futuristic accents.
- **Color Palette:**
- Primary: `#0070f3` (A vibrant blue for accents, buttons, links)
- Secondary: `#343a40` (Dark gray for backgrounds, sidebars, footers)
- Accent: `#28a745` (Green for success states, 'Run' button)
- Warning: `#ffc107` (Yellow for pending/compiling states)
- Danger: `#dc3545` (Red for errors, 'Stop' button)
- Background: `#f8f9fa` (Light gray for main content area)
- Text: `#212529` (Dark text on light backgrounds)
- Code Editor Background: `#1e1e1e` (Dark background for code)
- Code Editor Text: `#d4d4d4` (Light text for code)
- **Typography:** Inter or Roboto (Sans-serif, clean, readable).
- **Layout:**
- Landing Page: Hero section, features overview, testimonials, call-to-action.
- Dashboard: Clean list layout, clear 'New Project' button.
- IDE View: Three-column layout (or split view) - Left: Component Selector, Right: Editor, Bottom: Output/Serial Monitor. Collapsible panels.
- **Responsiveness:** Mobile-first approach. IDE view will likely be simplified or less functional on very small screens, focusing on code editing. Dashboard and Landing page will be fully responsive.
**ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/out using Next.js `next/transition` or a similar library.
- **Button Hovers:** Slight scale-up or background color change.
- **Loading States:** Use shad-cn/ui's `Skeleton` or `Spinner` components for data fetching and compilation/simulation processes.
- **Drag and Drop:** Smooth visual feedback when dragging components in the IDE.
- **Collapsible Panels:** Smooth slide animation for panel expansion/collapse.
**EDGE CASES & VALIDATION:**
- **Code Validation:** Real-time linting and error highlighting in the editor using Zod for schema validation and potentially a dedicated compiler API. Error messages in the Serial Monitor should be clear and actionable.
- **Auth:** Handle expired sessions, network errors during auth, invalid tokens.
- **Empty States:** Provide clear messages and guidance when project lists are empty, or when the IDE has no components added.
- **Resource Limits:** Implement checks for code complexity, simulation time, or memory usage (especially for QEMU-based simulations like RPi) and provide user feedback or throttle requests.
- **Cross-Browser Compatibility:** Test thoroughly on major browsers (Chrome, Firefox, Safari, Edge).
- **Data Integrity:** Use Drizzle ORM's transaction capabilities and Zod validation for all API inputs and database operations.
**SAMPLE/MOCK DATA:**
* **User:**
```json
{
"id": 1,
"name": "Ali Veli",
"email": "ali.veli@example.com",
"image": "https://example.com/ali.jpg"
}
```
* **Project (Arduino Example):**
```json
{
"id": 101,
"userId": 1,
"name": "Blink LED",
"boardType": "arduino-uno",
"language": "cpp",
"code": "void setup() { pinMode(13, OUTPUT); }\nvoid loop() { digitalWrite(13, HIGH); delay(500); digitalWrite(13, LOW); delay(500); }",
"createdAt": "2024-07-26T10:00:00Z",
"updatedAt": "2024-07-26T10:05:00Z"
}
```
* **Project (ESP32 MicroPython Example):**
```json
{
"id": 102,
"userId": 1,
"name": "WiFi Connect",
"boardType": "esp32",
"language": "python",
"code": "import network\nimport time\n\nssid = 'YOUR_WIFI_SSID'\npassword = 'YOUR_WIFI_PASSWORD'\n\nwlan = network.WLAN(network.STA_IF)\nwlan.active(True)\nwlan.connect(ssid, password)\n\nwhile not wlan.isconnected():\n print('Connecting to WiFi...')\n time.sleep(1)\n\nprint('Connected to:', wlan.ifconfig())",
"createdAt": "2024-07-26T11:00:00Z",
"updatedAt": "2024-07-26T11:15:00Z"
}
```
* **Project Components (for Blink LED):**
```json
[
{
"id": 1,
"projectId": 101,
"type": "led",
"config": { "pin": "13", "color": "#00FF00" },
"position": { "x": 200, "y": 100 },
"createdAt": "2024-07-26T10:01:00Z",
"updatedAt": "2024-07-26T10:01:00Z"
},
{
"id": 2,
"projectId": 101,
"type": "serial-monitor",
"config": { "baudRate": 9600 },
"position": { "x": 200, "y": 250 },
"createdAt": "2024-07-26T10:02:00Z",
"updatedAt": "2024-07-26T10:02:00Z"
}
]
```
* **Project Components (for WiFi Connect ESP32):**
```json
[
{
"id": 3,
"projectId": 102,
"type": "esp32-dev",
"config": { "model": "esp32-wroom", "flashSize": "4MB" },
"position": { "x": 300, "y": 100 },
"createdAt": "2024-07-26T11:05:00Z",
"updatedAt": "2024-07-26T11:05:00Z"
},
{
"id": 4,
"projectId": 102,
"type": "serial-monitor",
"config": { "baudRate": 115200 },
"position": { "x": 300, "y": 250 },
"createdAt": "2024-07-26T11:06:00Z",
"updatedAt": "2024-07-26T11:06:00Z"
}
]
```
* **Simulation Output Example:**
```
[Compile Output]
Compiling sketch... OK
Uploading...
Upload complete.
[Serial Monitor]
Connecting to WiFi...
Connecting to WiFi...
Connected to: ('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8')
```
* **Component Configuration Panel (LED):**
`Board Type: Arduino Uno`
`Component: LED`
`PIN: [Input field with value '13']`
`Color: [Color Picker with value '#00FF00']`
`Add/Remove Button`
**TURKISH TRANSLATIONS (Key UI Elements):**
- Sign Up: Kayıt Ol
- Log In: Giriş Yap
- Dashboard: Kontrol Paneli
- My Projects: Projelerim
- New Project: Yeni Proje
- Save Project: Projeyi Kaydet
- Compile: Derle
- Run/Simulate: Çalıştır/Simüle Et
- Stop: Durdur
- Reset: Sıfırla
- Settings: Ayarlar
- Code Editor: Kod Editörü
- Component Selector: Bileşen Seçici
- Serial Monitor: Seri Monitör
- Output: Çıktı
- Error: Hata
- Connecting to WiFi...: WiFi'ye bağlanılıyor...
- Connected to: ...: Bağlandı: ...
- Component Pin: Bileşen Pini
- Configuration: Yapılandırma
- Board Type: Kart Tipi
- Language: Dil
- Loading...: Yükleniyor...
- No projects found.: Hiç proje bulunamadı.
- Create your first project!: İlk projenizi oluşturun!