# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Development Commands

- `npm install` - Install dependencies  
- `npm run dev` - Start development server (runs on http://localhost:3000)
- `npm run build` - Build for production
- `npm start` - Start production server
- `npx prisma migrate dev` - Run database migrations
- `npx prisma studio` - Open database GUI

Note: This project has been migrated from Vite to Next.js for full-stack capabilities.

## Project Overview

This project is a **Collaborative Layered Music Generator** built with Next.js + React + TypeScript + Prisma. Users can:

1. **Generate individual audio layers** using text prompts (e.g., "jazz drums", "electric bass")
2. **Stack layers together** to build complete musical compositions
3. **Share compositions** with friends who can add their own layers
4. **Play back the combined result** with real-time waveform visualization

The core concept is collaborative music creation where each person contributes a layer to build a track together.

## Current Application State

### 🎵 **Core Features Implemented**
- **Text Prompt Generation**: Users describe what they want (e.g., "tech house drums in C major at 120 BPM")
- **Professional Waveform Visualization**: Canvas-based waveforms with progress tracking and click-to-seek
- **Real-time Audio Mixing**: Web Audio API for playing multiple layers simultaneously
- **Layer Management**: Volume controls, mute/unmute, remove layers
- **Musical Parameters**: Key signature selection (all major/minor keys) and BPM input

### 🛠 **Technical Architecture**

#### **Audio Engine (`src/utils/audioEngine.ts`)**
- `LayeredAudioEngine` class handles Web Audio API mixing
- Loads audio buffers and generates waveform data
- Supports play/pause/seek with synchronized playback
- Per-layer volume/mute controls

#### **Waveform System**
- `WaveformAnalyzer` (`src/utils/waveformAnalyzer.ts`): Processes audio buffers into visualization data
- `LayerWaveform` (`src/components/LayerWaveform.tsx`): Canvas-based rendering with progress indicators
- High-DPI support and responsive width sizing

#### **Generation Logic (`src/hooks/useLayerGeneration.ts`)**
- Uses Suno API for AI music generation
- Supports free-form text prompts instead of predefined instruments
- Combines prompt + BPM + key signature (e.g., "jazz drums 120 BPM in C major")
- Handles async generation with polling for completion

#### **Component Structure**
- `App.tsx`: Main application with minimal UI (logo/title left, play button right)
- `LayerStack.tsx`: Container for all generated layers (no header, just clips)
- `LayerControl.tsx`: Individual layer with title above waveform, volume/mute controls on right
- Clean, focused UI with no extraneous elements

### 🎨 **UI Design Philosophy**
- **Minimal interface**: Only essential elements for core functionality
- **Focused workflow**: Prompt + Key + BPM → Generate → Stack → Play
- **Clean layer presentation**: Title above, waveform center, controls right
- **Professional waveforms**: Blue gradient bars with real-time progress and seek

### 🔄 **Generation Flow**
1. User enters text prompt (e.g., "electro swing bass")
2. Selects key signature from dropdown (C major, A minor, etc.)
3. Sets BPM (defaults to 120)
4. Clicks "Generate Layer"
5. System creates full prompt: "electro swing bass 120 BPM in C major"
6. Layer appears with processing state, then waveform when ready
7. Users can play all layers together with synchronized playback

### 📁 **Key Files**
- `src/App.tsx` - Main app with generation panel and layer management
- `src/components/LayerStack.tsx` - Container for generated layers
- `src/components/LayerControl.tsx` - Individual layer UI with waveform
- `src/components/LayerWaveform.tsx` - Canvas-based waveform visualization
- `src/utils/audioEngine.ts` - Web Audio API mixing engine
- `src/utils/waveformAnalyzer.ts` - Audio buffer to visualization data processing
- `src/hooks/useAudioEngine.ts` - React hooks for audio playback
- `src/hooks/useLayerGeneration.ts` - Suno API integration for generation
- `src/utils/types.ts` - TypeScript definitions for layers and composition

### ✅ **Collaboration Features (IMPLEMENTED)**
The collaborative features have been fully implemented:
- **Database persistence**: PostgreSQL with Prisma for session/layer storage
- **Shareable URLs**: `/session/{uuid}` links for collaboration
- **Session management**: Create, load, and share musical sessions
- **Layer persistence**: All layer metadata and audio URLs stored in database
- **Real-time sharing**: Users can access shared sessions and add new layers

## Project Architecture

This is a Next.js + React + TypeScript + Prisma full-stack application with the following key architectural patterns:

### API Integration

- **Suno API**: Uses custom integration with `https://studio-api.staging.suno.com/api/v2/external`
- **Authentication**: Requires `NEXT_PUBLIC_SUNO_API_TOKEN` environment variable
- **Generation Flow**: POST to `/generate/` endpoint, then poll `/clips/` for completion
- **Database API**: Next.js API routes for session and layer CRUD operations

### State Management

- **React State**: Simple useState for composition and layer management
- **Audio Context**: Web Audio API for real-time mixing
- **Layer State**: Each layer tracks generation status, audio data, and waveform

### Styling System

- **Tailwind CSS v4**: Uses the new Vite plugin (`@tailwindcss/vite`)
- **Custom Colors**: Defined in `tailwind.colors.ts`
- **Theme Styles**: In `theme.css` and `colors.css`
- **Utility Classes**: Standard Tailwind approach with clsx for conditional styling

Note: you should maintain a consistent style throughout the app, with consistent background and foreground coloring. Ask the user if you are unsure about styling decisions, but prefer reasonably modern defaults consistent with existing styling.

### Environment Setup

- Copy `.env.copy` to `.env.local` and set required environment variables:
  - `NEXT_PUBLIC_SUNO_API_TOKEN` - Suno API token for music generation
  - `DATABASE_URL` - PostgreSQL connection string for database
- Run `npx prisma migrate dev` to create database tables

### Code Style

- **Component Organization**: Keep related components together, extract when complex
- **TypeScript**: Strict typing with interfaces for layers, composition, and generation
- **Audio Handling**: All audio operations through `LayeredAudioEngine` class
- **Waveform Rendering**: Canvas-based with high-DPI support and responsive sizing
- **State Updates**: Immutable updates with proper React patterns

## Key Files

### Frontend
- `src/App.tsx` - Main application with generation UI, playback controls, and session handling
- `src/components/LayerStack.tsx` - Renders stack of generated layers
- `src/components/LayerControl.tsx` - Individual layer with waveform and controls
- `src/components/LayerWaveform.tsx` - Canvas waveform visualization
- `src/utils/audioEngine.ts` - Web Audio API mixing and playback
- `src/utils/waveformAnalyzer.ts` - Audio buffer analysis for visualization
- `src/hooks/useAudioEngine.ts` - React hooks for audio state management
- `src/hooks/useLayerGeneration.ts` - Suno API integration for generation

### Backend (Next.js)
- `app/layout.tsx` - Root layout component
- `app/[[...slug]]/page.tsx` - Dynamic routing for session URLs
- `app/api/sessions/route.ts` - Session CRUD operations
- `app/api/sessions/[sessionId]/layers/route.ts` - Layer management within sessions
- `prisma/schema.prisma` - Database schema for sessions and layers

# Key Application Concepts

## Layer Generation System

### Text Prompt Based Generation
- Users enter free-form text prompts instead of selecting predefined instruments
- Prompts are enhanced with BPM and key signature automatically
- Example: "jazz drums" + "120 BPM" + "C major" = "jazz drums 120 BPM in C major"

### Musical Parameters
- **Key Signature**: Dropdown with all major/minor keys (C major, A minor, F# major, etc.)
- **BPM**: Number input (60-200 range)
- **Prompt**: Free text describing the desired sound

### Generation Flow
1. User fills prompt, key, and BPM
2. System combines into full prompt for AI
3. Calls Suno API with enhanced prompt
4. Polls for completion and audio URL
5. Loads audio buffer and generates waveform data
6. Layer becomes available for playback

## Audio Mixing System

### Web Audio API Integration
- `LayeredAudioEngine` manages audio context and mixing
- Each layer gets its own gain node for volume control
- Master gain node for overall composition volume
- Synchronized playback across all layers

### Waveform Visualization
- Canvas-based rendering with gradient fills
- Real-time progress indicator during playback
- Click-to-seek functionality
- Responsive width with high-DPI support
- Loading states with skeleton bars

### Playback Controls
- Play/Pause button in header (only enabled when layers are ready)
- Per-layer volume sliders and mute buttons
- Seek functionality by clicking on waveforms
- Synchronized timing across all layers

## UI Design Principles

### Minimal Interface
- Logo and title in top left (small and unobtrusive)
- Play button in top right
- No unnecessary headers or info sections
- Focus on core functionality: generate → stack → play

### Layer Presentation
- Clean white containers with subtle borders
- Title above waveform for clear identification
- Volume/mute controls on right side for easy access
- Waveforms take up most horizontal space
- No instrument icons or status badges (simplified)

### Generation Panel
- Prominent text prompt input (full width)
- Key and BPM in same row to save vertical space
- Clear generate button
- Error handling with user-friendly messages

## Collaboration Features (IMPLEMENTED)

The collaborative features are fully implemented and working:

### Database-Backed Sessions
- PostgreSQL database with Prisma ORM for data persistence
- Sessions table stores collaborative session metadata (UUID, title, timestamps)
- Layers table stores layer data (prompt, BPM, key, audio URL, volume, mute state)
- Foreign key relationships with cascading deletes for data integrity

### Session Sharing Workflow
1. User generates layers in local session
2. Clicks "Share" button to create database session
3. All layers saved to database with metadata
4. Shareable URL generated: `/session/{uuid}`
5. Recipients access URL to load session and add new layers

### URL-Based Collaboration
- Dynamic routing via `app/[[...slug]]/page.tsx` handles `/session/{uuid}` URLs
- Session loading on page load with loading indicators
- Automatic layer reconstruction from database with audio loading
- Session indicator shows when in collaborative mode

### API Architecture
- RESTful Next.js API routes for session and layer management
- Session endpoints: POST (create), GET (retrieve with layers)
- Layer endpoints: POST (add to session), PATCH (update), DELETE (remove)
- Proper error handling and validation throughout

### Data Flow
- Local sessions remain in React state until shared
- Database sessions persist layers with full metadata
- Audio URLs stored for remote loading across devices
- Layer order preserved via `orderIndex` field