You are an expert AI coding assistant tasked with building a fully functional, multi-page Next.js MVP application based on the 'Music for Programming' concept. The application, named 'FlowTune', aims to enhance focus and productivity for individuals engaged in deep work like programming, writing, and design. It will offer personalized music and ambient soundscapes tailored to the user's mood, activity, and preferences.
**1. PROJECT OVERVIEW:**
FlowTune is a productivity-focused application providing a curated listening experience for deep work. It addresses the need for distraction-free, mentally stimulating audio environments that boost concentration and creativity. The core value proposition is personalized, AI-driven audio that adapts to the user's current state and task, leading to increased productivity and a more enjoyable work experience. It will go beyond simple playlists by integrating ambient sounds and intelligent recommendations.
**2. TECH STACK:**
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL or SQLite)
- **UI Library:** shadcn/ui (for accessible, reusable components)
- **Authentication:** NextAuth.js (for seamless Google and Email/Password login)
- **State Management:** Zustand or React Context API for global state, local component state as needed.
- **API Layer:** Server Actions and Route Handlers within Next.js.
- **Database:** PostgreSQL (preferred for scalability) or SQLite for simpler MVP setup.
- **Deployment:** Vercel
- **Other:** Axios (for potential external API integrations if needed later), React Icons/Lucide React.
**3. DATABASE SCHEMA:**
```sql
-- Users Table
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL,
emailVerified TIMESTAMP(3),
image TEXT,
hashedPassword TEXT,
createdAt TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP
);
-- Accounts Table (for NextAuth.js)
CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
userId UUID REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(255) NOT NULL,
provider VARCHAR(255) NOT NULL,
providerAccountId VARCHAR(255) NOT NULL,
refresh_token TEXT,
access_token TEXT,
expires_at BIGINT,
token_type VARCHAR(255),
scope VARCHAR(255),
id_token TEXT,
session_state VARCHAR(255),
UNIQUE(provider, providerAccountId)
);
-- Sessions Table (for NextAuth.js)
CREATE TABLE sessions (
sid VARCHAR(255) PRIMARY KEY,
userId UUID REFERENCES users(id) ON DELETE CASCADE,
expires TIMESTAMP(3) NOT NULL,
expiresAt BIGINT
);
-- Playlists Table
CREATE TABLE playlists (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
userId UUID REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
description TEXT,
isPublic BOOLEAN DEFAULT FALSE,
createdAt TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP
);
-- Tracks Table
CREATE TABLE tracks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
artist VARCHAR(255),
duration INT, -- Duration in seconds
url TEXT NOT NULL, -- URL to the audio file/stream
type VARCHAR(50) NOT NULL -- e.g., 'music', 'ambient'
);
-- PlaylistTracks (Many-to-Many Relationship)
CREATE TABLE playlist_tracks (
playlistId UUID REFERENCES playlists(id) ON DELETE CASCADE,
trackId UUID REFERENCES tracks(id) ON DELETE CASCADE,
trackOrder INT, -- To maintain order within a playlist
PRIMARY KEY (playlistId, trackId)
);
-- UserPreferences Table
CREATE TABLE user_preferences (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
userId UUID REFERENCES users(id) ON DELETE CASCADE UNIQUE,
preferredMood VARCHAR(100), -- e.g., 'Focus', 'Relax', 'Energize'
preferredActivity VARCHAR(100), -- e.g., 'Coding', 'Writing', 'Reading'
ambientSoundMix JSONB, -- Stores preferred ambient sounds and their volume levels { 'rain': 0.5, 'cafe': 0.3 }
createdAt TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP
);
-- AI Recommendations Table (Future expansion)
CREATE TABLE ai_recommendations (
id UUID PRIMARY KEY DEFAULT gen_random_random_uuid(),
userId UUID REFERENCES users(id) ON DELETE CASCADE,
recommendedTrackId UUID REFERENCES tracks(id),
reason TEXT, -- Why it was recommended
createdAt TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP
);
```
**Notes:**
- Use `UUID` for primary keys for better scalability and security.
- `emailVerified` and `hashedPassword` are standard for email auth.
- `accounts`, `sessions` tables are required for NextAuth.js.
- `playlist_tracks` handles the many-to-many relationship between playlists and tracks.
- `user_preferences` stores user-specific settings for personalization.
- `ambientSoundMix` uses JSONB to store flexible combinations of ambient sounds and their volumes.
**4. CORE FEATURES & USER FLOW:**
**a. Authentication (NextAuth.js):**
- **Flow:** User lands on homepage -> Clicks 'Sign Up' or 'Login' -> Presented with options: 'Continue with Google', 'Login with Email'.
- **Google Auth:** Redirect to Google OAuth -> User grants permission -> Redirect back to FlowTune -> User session created/found.
- **Email/Password:** User enters email and password -> Server validates credentials against `users` table -> If valid, session created. If invalid, error message shown.
- **Sign Up:** User enters email, password, confirms password -> Server creates new user in `users` table, hashes password -> Logs user in.
- **Edge Case:** Handle incorrect login attempts (rate limiting, error messages), already existing email during sign-up.
- **Protected Routes:** All application features (dashboard, player, settings) require authentication. Access denied redirects to login page.
**b. Dashboard & Music Discovery:**
- **Flow:** Authenticated user lands on Dashboard -> Displays personalized recommendations based on `user_preferences` (mood/activity) and past listening history (implicitly via liked tracks or playlist additions).
- **Sections:** 'Recommended for You', 'Your Playlists', 'Explore Ambient Sounds'.
- **Interaction:** Clicking a recommended track/playlist starts playback. Clicking 'Explore Ambient Sounds' navigates to a dedicated section.
- **State:** Dashboard components fetch data relevant to the logged-in user.
- **Empty State:** If no preferences set or history exists, show default recommendations and prompts to set preferences.
**c. Music Player:**
- **Flow:** User clicks 'Play' on a track or playlist from Dashboard or Playlist view.
- **UI:** Persistent player at the bottom of the screen showing current track title, artist, album art (if available), play/pause, next/previous, volume slider, progress bar.
- **Functionality:** Handles playback logic using HTML5 `<audio>` element or a library like Howler.js. Manages track queue for playlists.
- **Ambient Sounds:** If enabled in `user_preferences`, ambient sounds are layered with the music. Volume controls for both music and ambient layers.
- **State:** Player state (current track, playing status, volume, queue) managed globally.
**d. Playlist Management:**
- **Flow:** User navigates to 'My Playlists' section -> Can view existing playlists, create new ones, add tracks to playlists, remove tracks, reorder tracks.
- **Create Playlist:** Click 'New Playlist' -> Enter name, optional description -> Playlist created in `playlists` table, linked to user.
- **Add Track:** From track search/recommendations, click 'Add to Playlist' -> Select playlist or create new one.
- **View Playlist:** Click a playlist -> Displays track list, options to play all, remove, reorder.
- **Edge Case:** Handling empty playlists, maximum playlist length (if any).
**e. Preference Settings:**
- **Flow:** User navigates to 'Settings' -> 'Preferences' tab.
- **UI:** Forms to select preferred mood ('Focus', 'Relax', 'Energize'), preferred activity ('Coding', 'Writing', 'Design'). Sliders or checkboxes for ambient sound selection (e.g., Rain, Waves, Cafe, Forest) and their volumes.
- **Functionality:** Updates the `user_preferences` record for the logged-in user via Server Actions or API routes.
- **Save:** 'Save Preferences' button triggers the update.
**5. API & DATA FETCHING:**
- **Architecture:** Utilize Next.js App Router features: Server Components for static data rendering, Client Components for interactivity. Server Actions for mutations (POST, PUT, DELETE) and direct data fetching on the server.
- **API Routes (Route Handlers):** For dynamic data fetching, especially for auth and potentially real-time features later. Example: `GET /api/user/preferences`.
- **Data Fetching:** Primarily use `fetch` on the server (Server Components, Server Actions) to interact with the database via Drizzle ORM.
- **Example (Server Action for updating preferences):**
```typescript
// app/settings/actions.ts
'use server';
import { db } from '@/lib/db'; // Drizzle DB instance
import { userPreferences } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import { revalidatePath } from 'next/cache';
export async function savePreferences(formData: FormData, userId: string) {
const preferredMood = formData.get('mood');
const preferredActivity = formData.get('activity');
// ... other fields ...
try {
await db.insert(userPreferences).values({
userId,
preferredMood,
preferredActivity,
// ... other values ...
}).onConflictDoUpdate({
target: userPreferences.userId,
set: { preferredMood, preferredActivity /* ... */ }
});
revalidatePath('/settings'); // Clear cache for settings page
return { success: true };
} catch (error) {
console.error('Failed to save preferences:', error);
return { success: false, message: 'Failed to save settings.' };
}
}
```
- **Auth:** Integrate NextAuth.js for session management. Access user ID from session in Server Components/Actions.
**6. COMPONENT BREAKDOWN:**
- **Pages (App Router structure):**
- `app/layout.tsx`: Root layout (include Navbar, Footer, global providers).
- `app/(auth)/login/page.tsx`: Login page (Email/Password form, Google button).
- `app/(auth)/signup/page.tsx`: Signup page.
- `app/page.tsx`: Landing page / Homepage (Marketing content, CTA to login/signup).
- `app/(app)/dashboard/page.tsx`: Main dashboard after login (Recommendations, quick access).
- `app/(app)/player/page.tsx`: Full-screen player view (optional).
- `app/(app)/playlists/[playlistId]/page.tsx`: Individual playlist view.
- `app/(app)/settings/page.tsx`: User settings (Profile, Preferences).
- `app/(app)/explore/page.tsx`: Explore ambient sounds/music genres.
- **Reusable UI Components (shadcn/ui based):**
- `components/ui/button`: For all buttons.
- `components/ui/input`: For form inputs.
- `components/ui/label`: Form labels.
- `components/ui/card`: For displaying tracks, playlists.
- `components/ui/slider`: For volume controls.
- `components/ui/avatar`: User profile image.
- `components/ui/navbar`: Top navigation bar.
- `components/ui/sidebar`: (If needed) for navigation.
- `components/ui/player/PlayerControls`: Play, Pause, Next, Prev buttons.
- `components/ui/player/ProgressBar`: Track progress indicator.
- `components/ui/player/VolumeControl`: Volume slider.
- `components/ui/player/TrackInfo`: Display current track details.
- `components/player/PersistentPlayer`: The bottom bar player component.
- `components/dashboard/RecommendationCard`: Displays a single music/ambient recommendation.
- `components/playlist/PlaylistTrackItem`: Displays a track within a playlist view.
- `components/settings/PreferenceForm`: Form for mood/activity/ambient sound selection.
- **State Management:**
- **Global State (Zustand/Context):** Player state (current track, isPlaying, volume, queue), User authentication status, User preferences.
- **Server State:** Data fetched via Server Components or Server Actions (playlists, user profile data).
- **Local State:** UI-specific states like form input values, modal open/closed status.
**7. UI/UX DESIGN & VISUAL IDENTITY:**
- **Style:** Minimalist Clean with subtle futuristic/tech elements. Focus on clarity, ease of use, and a calming aesthetic.
- **Color Palette:**
- Primary: Deep Blue (`#1A202C` - Dark background)
- Secondary: Muted Teal (`#4FD1C5` - Accent buttons, highlights)
- Accent: Soft Purple (`#9F7AEA` - Active states, interactive elements)
- Text: Light Gray (`#CBD5E0` - Primary text), White (`#FFFFFF` - Headers, important text)
- Background Elements: Darker Gray (`#2D3748`)
- **Typography:** Use a clean, readable sans-serif font like Inter or Poppins.
- Headings: Semibold, 24-36px
- Body Text: Regular, 16px
- **Layout:**
- Use a responsive grid system (Tailwind CSS defaults).
- Clear visual hierarchy. Main content area, persistent player at the bottom, navigation accessible.
- Generous whitespace to reduce cognitive load.
- **Interactivity:** Subtle hover effects on buttons and interactive elements. Smooth transitions between pages and component states.
- **Responsive Rules:** Mobile-first approach. Ensure usability and aesthetic appeal on all screen sizes (smartphones, tablets, desktops).
**8. SAMPLE/MOCK DATA:**
**Tracks (for `tracks` table):**
1. `{ name: 'Lo-fi Chill Beat 1', artist: 'Study Beats', duration: 180, url: '/audio/lofi_chill_1.mp3', type: 'music' }`
2. `{ name: 'Ambient Forest', artist: 'Nature Sounds', duration: 300, url: '/audio/ambient_forest.mp3', type: 'ambient' }`
3. `{ name: 'Coding Flow State', artist: 'Focus Music Project', duration: 240, url: '/audio/coding_flow.mp3', type: 'music' }`
4. `{ name: 'Rain on Window', artist: 'Weather Sounds', duration: 600, url: '/audio/rain_window.mp3', type: 'ambient' }`
5. `{ name: 'Deep Focus Electronic', artist: 'Synthwave Masters', duration: 210, url: '/audio/deep_focus.mp3', type: 'music' }`
6. `{ name: 'Ocean Waves', artist: 'Coastal Sounds', duration: 480, url: '/audio/ocean_waves.mp3', type: 'ambient' }`
**User Preferences (for `user_preferences` table):**
1. `{ userId: 'user-uuid-1', preferredMood: 'Focus', preferredActivity: 'Coding', ambientSoundMix: { 'rain': 0.6, 'nature': 0.2 } }`
2. `{ userId: 'user-uuid-2', preferredMood: 'Relax', preferredActivity: 'Reading', ambientSoundMix: { 'cafe': 0.4 } }`
**Playlists (for `playlists` table):**
1. `{ id: 'playlist-uuid-1', userId: 'user-uuid-1', name: 'My Coding Focus Mix', description: 'Beats to code to', isPublic: false }`
2. `{ id: 'playlist-uuid-2', userId: 'user-uuid-1', name: 'Relaxation Station', description: 'Chill vibes', isPublic: false }`
**Playlist Tracks (for `playlist_tracks` table):**
1. `{ playlistId: 'playlist-uuid-1', trackId: 'track-uuid-3', trackOrder: 1 }` (Coding Flow State in playlist 1)
2. `{ playlistId: 'playlist-uuid-1', trackId: 'track-uuid-1', trackOrder: 2 }` (Lo-fi Chill Beat 1 in playlist 1)
3. `{ playlistId: 'playlist-uuid-2', trackId: 'track-uuid-4', trackOrder: 1 }` (Rain on Window in playlist 2)
**9. TURKISH TRANSLATIONS:**
- **App Title:** Akış Tonu (FlowTune)
- **Page Titles:**
- Dashboard: Kontrol Paneli
- Player: Oynatıcı
- Playlists: Listelerim
- Settings: Ayarlar
- Explore: Keşfet
- **Buttons:**
- Login: Giriş Yap
- Sign Up: Kayıt Ol
- Save: Kaydet
- Play: Oynat
- Pause: Duraklat
- Skip: Sonraki
- Add to Playlist: Listeye Ekle
- New Playlist: Yeni Liste
- **Labels & Placeholders:**
- Email: E-posta
- Password: Şifre
- Search: Ara...
- Mood: Ruh Hali
- Activity: Aktivite
- Volume: Ses Seviyesi
- Focus: Odaklanma
- Relax: Rahatlama
- Energize: Enerji
- Coding: Kodlama
- Writing: Yazma
- Design: Tasarım
- Ambient Sounds: Ortam Sesleri
- **General Text:**
- 'Recommended for You': 'Senin İçin Önerilenler'
- 'Your Playlists': 'Listelerin'
- 'Create a new playlist': 'Yeni bir liste oluştur'
- 'No playlists found.': 'Liste bulunamadı.'
- 'Logged in as': 'Olarak giriş yapıldı'
- 'Sign out': 'Çıkış Yap'
**10. ANIMATIONS:**
- **Page Transitions:** Use Next.js's built-in router transitions or libraries like `Framer Motion` for smooth fade-in/out or slide animations between pages.
- **Component Mount/Unmount:** Animate the appearance and disappearance of elements (e.g., cards, modals) with subtle fade or slide effects.
- **Button Hovers:** Slight scale-up or background color change on hover.
- **Loading States:** Use spinners or skeleton loaders (e.g., from shadcn/ui) with subtle pulse animations while data is being fetched.
- **Player Progress Bar:** Smooth animation for the progress bar as the track plays.
**11. EDGE CASES:**
- **Authentication:** Handle expired sessions, invalid tokens, failed login attempts (show clear error messages).
- **Empty States:** Design informative and visually appealing empty states for dashboards, playlists, search results. Include CTAs to guide users (e.g., 'Create your first playlist').
- **Data Validation:** Implement client-side and server-side validation for all form inputs (login, signup, playlist creation, settings).
- **Error Handling:** Gracefully handle API errors, database connection issues, playback errors. Display user-friendly messages.
- **Network Issues:** Provide feedback during network interruptions or slow loading times.
- **Audio Playback:** Ensure cross-browser compatibility for the audio element. Handle potential issues with audio file loading or decoding.
- **No Preferences:** If `user_preferences` is null for a user, provide default settings or prompt the user to set them up. Display generic recommendations initially.