You are an expert AI assistant tasked with generating a fully functional, multi-page Next.js MVP application for 'Rhythm Visualizer Pro'. This application will allow users to create and control audio-reactive LED strips with ease, without needing deep programming or electronics knowledge.
**1. PROJECT OVERVIEW:**
* **App Name:** Rhythm Visualizer Pro
* **Problem:** Creating sophisticated audio-reactive LED strip effects is notoriously difficult, requiring extensive knowledge of audio processing, real-time programming, and electronics. Existing solutions are often complex, limited, or require significant setup.
* **Solution:** Rhythm Visualizer Pro is a SaaS platform that simplifies the creation of stunning, real-time audio-visual experiences using LED strips. It provides an intuitive web interface for users to upload music, select LED configurations, customize visual effects, and synchronize them with audio input, bridging the gap between sound and light.
* **Value Proposition:** Empower anyone – from hobbyists to professionals – to effortlessly transform audio into dynamic, personalized LED light shows. Focus on ease of use, advanced customization, and seamless integration.
**2. TECH STACK:**
* **Framework:** Next.js (App Router)
* **Language:** TypeScript
* **Styling:** Tailwind CSS
* **Database:** Drizzle ORM with PostgreSQL (or SQLite for local MVP development)
* **UI Library:** shadcn/ui (for accessible, reusable components)
* **State Management:** Zustand or Jotai for global state, React Context for local/shared state.
* **Authentication:** NextAuth.js (with credentials provider for MVP, potentially Google/GitHub OAuth for future iterations).
* **Audio Processing:** Web Audio API for real-time analysis, potentially a lightweight library like `audio-visualizer` or custom FFT implementation. For offline analysis, a server-side library might be considered if performance is an issue.
* **Real-time Communication (for hardware sync):** WebSockets (e.g., using `socket.io` or native WebSockets).
* **Form Handling:** React Hook Form with Zod for validation.
* **Icons:** Lucide React.
* **Deployment:** Vercel (recommended for Next.js).
**3. DATABASE SCHEMA:**
We'll use Drizzle ORM to define the schema. The primary tables will be:
* **`users` Table:**
* `id` (UUID, primary key)
* `email` (VARCHAR, unique, not null)
* `hashedPassword` (VARCHAR, not null)
* `createdAt` (TIMESTAMPZ, default now())
* `updatedAt` (TIMESTAMPZ, default now())
* **`led_strips` Table:** (Represents user-defined LED strip configurations)
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to `users.id`, not null)
* `name` (VARCHAR, not null) - e.g., "Living Room Setup"
* `type` (VARCHAR, not null) - e.g., "WS2812B", "APA102"
* `ledCount` (INTEGER, not null) - Number of LEDs
* `chipset` (VARCHAR) - e.g., "SK6812"
* `brightness` (INTEGER, default 100) - Max brightness percentage (0-100)
* `gammaCorrection` (BOOLEAN, default true)
* `createdAt` (TIMESTAMPZ, default now())
* `updatedAt` (TIMESTAMPZ, default now())
* **`visualizations` Table:** (Stores user-created visualization presets)
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to `users.id`, not null)
* `ledStripId` (UUID, foreign key to `led_strips.id`, not null)
* `name` (VARCHAR, not null) - e.g., "Bass Drop Effect"
* `algorithm` (VARCHAR, not null) - e.g., "frequency-spectrum", "beat-detection", "amplitude-mapping"
* `parameters` (JSONB) - Stores algorithm-specific settings (e.g., `{ "lowFreq": 50, "highFreq": 2000, "decayRate": 0.8 }`)
* `colorPalette` (JSONB) - Array of colors (e.g., `["#FF0000", "#00FF00"]` or gradient definition)
* `effectType` (VARCHAR, default "solid") - e.g., "scroll", "pulse", "chase", "solid"
* `animationSpeed` (INTEGER, default 100)
* `isEnabled` (BOOLEAN, default true)
* `createdAt` (TIMESTAMPZ, default now())
* `updatedAt` (TIMESTAMPZ, default now())
* **`audio_sources` Table:** (Optional for MVP, for managing uploaded tracks)
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to `users.id`, not null)
* `name` (VARCHAR, not null) - e.g., "My Favorite Track.mp3"
* `filePath` (VARCHAR, not null) - Path in storage (e.g., S3)
* `duration` (INTEGER)
* `createdAt` (TIMESTAMPZ, default now())
**4. CORE FEATURES & USER FLOW:**
* **Authentication:**
* **Flow:** User lands on the homepage. Clicks "Sign Up" or "Login". Redirected to the Auth page (`/auth`). User enters email/password. On successful login, redirect to the Dashboard (`/dashboard`). On sign up, create user in DB, log them in, redirect to Dashboard.
* **Edge Case:** Invalid credentials -> show error message. Already logged in -> redirect to Dashboard.
* **Dashboard (`/dashboard`):**
* **Flow:** Authenticated users see a list of their created LED strip configurations and visualization presets. Options to create new ones or edit existing ones.
* **Components:** `DashboardLayout`, `StripList`, `VisualizationList`, `CreateNewButton`.
* **State:** Fetch user's strips and visualizations on mount. Manage loading and error states.
* **LED Strip Configuration (`/dashboard/strips/new` or `/dashboard/strips/[id]/edit`):**
* **Flow:** User clicks "Create New Strip" or "Edit". Navigates to the configuration page. User selects strip type (WS2812B, APA102, etc.), enters LED count, name, and optionally other parameters like chipset. User saves the configuration. On edit, pre-fill form with existing data.
* **Components:** `StripForm` (using React Hook Form, Zod validation), `Input`, `Select`, `NumberInput`, `ColorPicker` (for potential defaults), `SaveButton`.
* **API:** POST `/api/strips` (create), PUT `/api/strips/[id]` (update), GET `/api/strips` (fetch list), GET `/api/strips/[id]` (fetch single).
* **Validation:** `ledCount` must be > 0. `name` is required.
* **Visualization Editor (`/dashboard/visualizations/new` or `/dashboard/visualizations/[id]/edit`):**
* **Flow:** User clicks "Create New Visualization" or "Edit". Navigates to the editor. User selects a configured `ledStripId`. Chooses an `algorithm` (e.g., "Frequency Spectrum", "Amplitude Mapping"). Configures algorithm parameters via dynamic form elements. Selects/creates a `colorPalette`. Chooses an `effectType` (e.g., "Scroll", "Pulse"). Sets `animationSpeed`. Saves the preset.
* **Components:** `VisualizationForm`, `Select` (for strip, algorithm, effect), Dynamic Parameter Inputs based on selected algorithm, `ColorPaletteSelector` (can be a simple array of hex inputs for MVP or a more advanced gradient picker), `Slider` (for speed, sensitivity), `SaveButton`.
* **API:** POST `/api/visualizations` (create), PUT `/api/visualizations/[id]` (update), GET `/api/visualizations` (fetch list), GET `/api/visualizations/[id]` (fetch single).
* **Edge Cases:** Algorithm parameter forms must adapt to the selected algorithm.
* **Real-time Preview & Control (`/visualize/[id]`):**
* **Flow:** User selects a saved visualization preset and clicks "Visualize" (or similar). Navigates to a dedicated visualization page. This page attempts to connect to the user's hardware (via WebSocket). It takes audio input (either uploaded track playback or live mic input) and processes it using the selected algorithm and parameters. The processed data is translated into LED commands and sent to the connected hardware.
* **Components:** `AudioPlayer` (if using uploaded track), `LiveAudioInput` (using Web Audio API `getUserMedia`), `VisualizationCanvas` (renders the effect in the browser as a preview and sends data via WebSocket), `ControlPanel` (play/pause, volume, select visualization).
* **API:** WebSocket endpoint (`/ws/sync`) to send commands to hardware.
* **Real-time:** Use Web Audio API for FFT analysis. Send small, frequent updates over WebSockets.
**5. API & DATA FETCHING:**
* **Next.js API Routes (App Router):** All API routes will be under `src/app/api/`. Example: `src/app/api/strips/route.ts`.
* **REST Endpoints:** Standard CRUD operations for `strips` and `visualizations` (GET, POST, PUT, DELETE).
* **Data Fetching:** Use server components where possible for initial data loading. Use client components with `fetch` or a library like SWR/React Query for dynamic data and form submissions.
* **WebSocket:** Establish a WebSocket connection from the client (visualization page) to the backend server for real-time command transmission to the hardware. The backend will need to manage these connections and relay data.
* **Request/Response:** Use JSON for all API requests/responses. Implement clear error handling (e.g., HTTP status codes, JSON error messages).
**6. COMPONENT BREAKDOWN (Next.js App Router Structure):**
* **`src/app/`**
* **`layout.tsx`**: Root layout (includes global styles, providers).
* **`page.tsx`**: Landing Page.
* **`auth/page.tsx`**: Login/Sign Up form.
* **`dashboard/`**
* **`layout.tsx`**: Dashboard layout (sidebar, header).
* **`page.tsx`**: Main dashboard view (lists strips, visualizations).
* **`strips/`**
* **`new/page.tsx`**: Create new strip form.
* **`[id]/edit/page.tsx`**: Edit strip form.
* **`visualizations/`**
* **`new/page.tsx`**: Create new visualization form.
* **`[id]/edit/page.tsx`**: Edit visualization form.
* **`visualize/[id]/page.tsx`**: Real-time visualization/preview page.
* **`api/`**
* **`auth/[...nextauth]/route.ts`**: NextAuth.js handler.
* **`strips/route.ts`**: CRUD for strips.
* **`strips/[id]/route.ts`**: CRUD for single strip.
* **`visualizations/route.ts`**: CRUD for visualizations.
* **`visualizations/[id]/route.ts`**: CRUD for single visualization.
* **`ws/sync/route.ts` (or similar):** WebSocket handler for real-time sync.
* **`src/components/`**
* **`ui/`**: Re-exported shadcn/ui components (`Button`, `Input`, `Card`, `Sheet`, `Slider`, etc.).
* **`auth/`**: `LoginForm`, `SignUpForm`.
* **`dashboard/`**: `DashboardLayout`, `StripList`, `VisualizationList`, `ListItemCard`.
* **`forms/`**: `StripForm`, `VisualizationForm`, `DynamicParameterForm`.
* **`visualize/`**: `AudioPlayer`, `LiveAudioInput`, `VisualizationCanvas`, `LiveControls`.
* **`shared/`**: `Header`, `Footer`, `Sidebar`, `LoadingSpinner`, `ErrorMessage`.
* **`lib/`**: Utility functions, Drizzle config, auth config, WebSocket client.
* **`hooks/`**: Custom hooks (e.g., `useWebSocket`, `useAudioAnalysis`).
* **`store/`**: Zustand/Jotai store definitions.
**7. UI/UX DESIGN & VISUAL IDENTITY:**
* **Style:** Modern, clean, slightly futuristic with subtle dark-mode preference. Focus on clarity and intuitive interaction.
* **Color Palette:**
* **Dark Mode:** Primary: `#0f172a` (Dark Slate), Secondary: `#1e293b` (Slate), Accent: `#3b82f6` (Indigo/Blue), Text: `#e2e8f0` (Slate Gray), Subtle Highlights: `#60a5fa` (Light Blue).
* **Light Mode (Optional):** Primary: `#ffffff`, Secondary: `#f8fafc`, Accent: `#2563eb`, Text: `#1e293f`.
* **Typography:** Inter or similar sans-serif font. Clear hierarchy using font weights and sizes.
* **Layout:** Use a consistent grid system (Tailwind's default). Sidebar navigation for logged-in users. Main content area is clean and spacious. Visualizations page should be immersive.
* **Responsiveness:** Mobile-first approach. Ensure usability on small screens, scaling up gracefully to tablets and desktops.
* **Visual Elements:** Use subtle gradients in buttons or headers. Loading states should be animated spinners or skeleton screens. Interactive elements should have clear hover and focus states.
**8. SAMPLE/MOCK DATA:**
* **User:** `{ id: '...', email: 'test@example.com', hashedPassword: '...' }`
* **LED Strip (WS2812B):** `{ id: '...', userId: '...', name: 'Bedroom Strip', type: 'WS2812B', ledCount: 60, brightness: 80, createdAt: '...', updatedAt: '...' }`
* **LED Strip (APA102):** `{ id: '...', userId: '...', name: 'Desk Setup', type: 'APA102', ledCount: 30, brightness: 100, createdAt: '...', updatedAt: '...' }`
* **Visualization (Bass Beat):** `{ id: '...', userId: '...', ledStripId: '...', name: 'Bass Beat', algorithm: 'frequency-spectrum', parameters: { "lowFreq": 30, "highFreq": 150, "decayRate": 0.7 }, colorPalette: ['#FF4500', '#FFD700'], effectType: 'pulse', animationSpeed: 80, createdAt: '...', updatedAt: '...' }`
* **Visualization (Synth Wave Scroll):** `{ id: '...', userId: '...', ledStripId: '...', name: 'Synth Wave Scroll', algorithm: 'amplitude-mapping', parameters: { "threshold": 0.2, "attack": 0.3, "release": 0.9 }, colorPalette: ['#8A2BE2', '#4169E1', '#00FFFF'], effectType: 'scroll', animationSpeed: 120, createdAt: '...', updatedAt: '...' }`
* **Audio Source:** `{ id: '...', userId: '...', name: 'Track01.mp3', filePath: '/uploads/Track01.mp3', duration: 240, createdAt: '...' }`
**9. ANIMATIONS:**
* **Page Transitions:** Subtle fades or slide-ins using Next.js (e.g., Framer Motion or simple CSS transitions).
* **Component Transitions:** Smooth appearance/disappearance of elements (e.g., modals, dropdowns) using CSS transitions or libraries.
* **Button/Link States:** Subtle hover effects (slight scale up, background color change).
* **Loading Indicators:** Animated spinners (`@radix-ui/react-spinner` or similar) or skeleton loaders for data fetching.
* **Visualization Effects:** Smooth color blending, easing functions for animations (e.g., pulse, scroll speed changes).
**10. EDGE CASES & VALIDATION:**
* **Authentication:** Implement robust checks for logged-in status. Protect routes appropriately. Handle token expiry.
* **Empty States:** Display informative messages and clear calls-to-action when lists (strips, visualizations) are empty.
* **Form Validation:** Use Zod and React Hook Form for all form inputs. Provide clear, inline validation messages.
* **Audio Input:** Handle permissions for microphone access. Provide fallback for users who deny permission or have no microphone.
* **WebSocket Errors:** Implement reconnection logic and inform the user if the connection to the hardware cannot be established or is lost.
* **Audio Processing Limits:** Ensure real-time audio processing doesn't freeze the UI. Use Web Workers if necessary for heavy computations. Handle very short or very long audio files gracefully.
* **Hardware Compatibility:** Clearly document supported hardware. Provide debugging tips for common issues.
* **Error Handling:** Implement global error handling (e.g., using Error Boundaries) and specific error handling for API calls and WebSocket communication. Return meaningful error messages to the user.
**11. TURKISH TRANSLATIONS (Key UI elements):**
* Sign Up: Kayıt Ol
* Login: Giriş Yap
* Dashboard: Kontrol Paneli
* My LED Strips: LED Şeritlerim
* My Visualizations: Görselleştirmelerim
* Create New Strip: Yeni Şerit Oluştur
* Create New Visualization: Yeni Görselleştirme Oluştur
* Edit: Düzenle
* Save: Kaydet
* Cancel: İptal
* Name: Ad
* LED Count: LED Sayısı
* Strip Type: Şerit Tipi
* Algorithm: Algoritma
* Parameters: Parametreler
* Color Palette: Renk Paleti
* Effect Type: Efekt Tipi
* Animation Speed: Animasyon Hızı
* Visualize: Görselleştir
* Play: Oynat
* Pause: Duraklat
* Volume: Ses
* Real-time Preview: Gerçek Zamanlı Önizleme
* Upload Music: Müzik Yükle
* Use Live Audio: Canlı Ses Kullan
* Settings: Ayarlar
* Logout: Çıkış Yap
* Loading: Yükleniyor...
* No data available: Veri bulunamadı.
* Error: Hata
* Success: Başarılı
* Updated Successfully: Başarıyla güncellendi.
* Created Successfully: Başarıyla oluşturuldu.
* Connection Lost: Bağlantı Kayboldu.
* Connecting...: Bağlanıyor...