> For the complete documentation index, see [llms.txt](https://eurus-labs.gitbook.io/eurus-labs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://eurus-labs.gitbook.io/eurus-labs/readme.md).

# Eurus Studio - Creative AI Workflow Platform

A cutting-edge Next.js application featuring **Eurus Studio** landing page design, built for creative AI workflows, collaborative content creation, and **professional video editing** with advanced Remotion integration and worker thread optimization.

## ✨ Features

### 🎯 Core Functionality

* **Interactive 3D Canvas**: Drag-and-drop nodes with real-time 3D model rendering
* **AI-Powered Workflows**: Integrated text, image, and video AI models
* **Real-time Collaboration**: Multi-user editing with cursor presence
* **Unified Asset Management**: Single source of truth with Azure-exclusive storage
* **Credit System**: Usage tracking and billing integration
* **Visual node-based workflow editor** with React Flow
* **AI-powered content generation**: Images, videos, and text
* **Advanced image analysis** with Azure OpenAI 4o mini integration
* **Context-aware generation** - Intelligent content creation based on connected nodes
* **Optimistic UI updates** - Instant deletion and real-time collaboration
* **Azure Blob Storage integration** for scalable asset management
* **Auto-detection** - Dynamic port and base URL recognition
* **Discovery and sharing platform**

### 🎬 Enhanced Video Editor

* **Remotion Integration**: Professional video rendering with React components
* **Worker Thread Architecture**: Non-blocking video processing with dedicated workers
* **Performance Monitoring**: Real-time FPS, memory, and render time tracking
* **Adaptive Quality System**: Dynamic quality adjustment based on system performance
* **Multi-format Support**: Video, audio, image, and text track editing
* **Background Processing**: Frame extraction, thumbnail generation, waveform analysis
* **Intelligent Caching**: Frame caching with automatic memory management
* **Timeline Optimization**: Advanced timeline calculations and track arrangements

### 🎪 Eurus Studio Design

* **Immersive Hero Section**: "Irreplacably Creative" with interactive draggable nodes
* **3D Model Integration**: Real-time GLB model rendering with Three.js
* **Scroll-triggered Animations**: Smooth transitions and dynamic content
* **Professional Tools Showcase**: Video backgrounds and interactive elements
* **Ideas Scroll Section**: Animated node interactions and creative prompts

### 🛠️ Technical Features

* **Next.js 15**: Latest React framework with App Router
* **TypeScript**: Full type safety and developer experience
* **Tailwind CSS**: Utility-first styling with custom animations
* **Three.js Integration**: 3D graphics and WebGL rendering
* **Firebase Integration**: Authentication and real-time database
* **Azure Blob Storage**: Cloud asset management
* **Responsive Design**: Mobile-first approach with smooth interactions
* **Worker Thread Management**: Dedicated workers for video, audio, image, and timeline processing
* **Remotion Rendering**: React-based video composition and rendering

### Recent Updates (October 2025)

### 🗂️ **Unified Asset Management System** *(ENHANCED)*

Complete asset management overhaul providing seamless integration across all application modes:

* **Azure-Exclusive Storage**: Complete elimination of IndexedDB and local storage fallbacks
* **Single Source of Truth**: All asset operations consolidated into `/src/lib/unifiedAssetManager.ts`
* **Cross-Mode Integration**: Seamless asset sharing between Project, Canvas, and Edit modes
* **Intelligent Storage Strategy**: Context-aware storage with dual persistence for canvas assets
* **Comprehensive Hook System**: Full React integration with `useUnifiedAssets.ts`
* **Type-Safe Architecture**: Complete TypeScript integration with proper interfaces
* **Performance Optimized**: Efficient queries, caching, and background processing

## 🏗️ Unified Asset Management Architecture

The Eurus platform features a completely unified asset management system that provides seamless asset operations across **Project**, **Canvas**, and **Edit** modes with intelligent context-aware storage.

### 🎯 Cross-Mode Asset Flow

```
┌─ PROJECT MODE ────────────────────┐    ┌─ CANVAS MODE ─────────────────────┐    ┌─ EDIT MODE ───────────────────────┐
│                                   │    │                                   │    │                                   │
│ 📁 Asset Library Management      │    │ 🎨 Node-Specific Uploads         │    │ 🎬 Timeline Asset Integration    │
│ ┌─────────────────────────────┐   │    │ ┌─────────────────────────────┐   │    │ ┌─────────────────────────────┐   │
│ │ • Upload to Project Gallery │   │    │ │ • Upload to Canvas Node     │   │    │ │ • Access Project Assets     │   │
│ │ • Organize & Tag Assets     │   │    │ │ • Store in Node + Collection│   │    │ │ • Import from Canvas Nodes  │   │
│ │ • Share Across Team        │   │    │ │ • Real-time Canvas Updates  │   │    │ │ • Timeline Integration      │   │
│ │ • Global Asset Search      │   │    │ │ • Context-Aware Display     │   │    │ │ • Export Ready Assets       │   │
│ └─────────────────────────────┘   │    │ └─────────────────────────────┘   │    │ └─────────────────────────────┘   │
│           │                       │    │           │                       │    │           │                       │
│           ▼                       │    │           ▼                       │    │           ▼                       │
│    Azure + Firestore             │    │    Azure + Firestore + Node      │    │    Azure + Firestore             │
└───────────────────────────────────┘    └───────────────────────────────────┘    └───────────────────────────────────┘
                                    ▲                                      ▲                                      ▲
                                    │                                      │                                      │
                                    └─────────── UNIFIED SYSTEM ──────────┴──────────────────────────────────────┘
                                              /src/lib/unifiedAssetManager.ts
```

### 📂 Storage Architecture

```
Azure Blob Storage Structure:
projects/{projectId}/
├── assets/                    # Project & Edit mode assets
│   ├── {timestamp}_{hash}_image.jpg
│   ├── {timestamp}_{hash}_video.mp4
│   └── {timestamp}_{hash}_audio.wav
└── nodes/{nodeId}/           # Canvas mode node-specific assets
    ├── {timestamp}_{hash}_upload.jpg
    └── {timestamp}_{hash}_media.mp4

Firestore Collection: 'project-assets'
├── Document: {assetId}
│   ├── projectId: string     # Index for efficient queries
│   ├── nodeId?: string       # Set for canvas uploads
│   ├── azureUrl: string      # Primary CDN URL
│   ├── fileName: string      # Original filename
│   ├── contentType: string   # MIME type for filtering
│   ├── isNodeAsset: boolean  # Canvas vs Project distinction
│   └── metadata: object      # Size, tags, upload info
```

### 🔧 Core Components

#### 1. **UnifiedAssetManager** (`/src/lib/unifiedAssetManager.ts`)

**Central orchestrator** managing all asset operations across modes:

* **Azure Integration**: Direct blob storage with CDN delivery
* **Firestore Metadata**: Efficient queries and real-time updates
* **Context-Aware Storage**: Intelligent routing based on upload context
* **Type-Safe Operations**: Full TypeScript integration throughout

#### 2. **React Hooks Ecosystem** (`/src/hooks/useUnifiedAssets.ts`)

**Complete React integration** for all asset operations:

* **`useAssetUpload`**: Universal file upload with progress tracking across all modes
* **`useProjectAssets`**: Project-level asset management with filtering and search
* **`useMediaLibrary`**: Complete media browser with cross-mode asset aggregation
* **`useNodeAssets`**: Canvas-specific operations with node context integration

#### 3. **Mode-Specific Integration**

**Project Mode** (`/src/modules/project/`):

* Asset gallery with bulk operations
* Team sharing and collaboration features
* Advanced filtering and categorization
* Export and download capabilities

**Canvas Mode** (`/src/modules/canvas/`):

* Node-specific upload via `useNodeUpload`
* Real-time canvas asset updates
* Drag-and-drop integration
* Context-aware asset suggestions

**Edit Mode** (`/src/modules/studio-editor/`):

* Timeline asset integration
* Video/audio track management
* Asset compatibility validation
* Render-ready optimization

#### 4. **API Architecture** (`/src/app/api/assets/`)

**Unified REST endpoints** supporting all modes:

* **`POST /api/assets`** - Universal upload with context detection
* **`GET /api/assets/list`** - Cross-mode asset fetching with filters
* **`DELETE /api/assets/delete`** - Safe deletion with metadata cleanup
* **`POST /api/upload-media`** - Canvas legacy compatibility endpoint

### 🎯 Key Features

#### **Cross-Mode Asset Integration**

* **Unified Access**: All modes can access and utilize the same asset pool
* **Context Intelligence**: Assets uploaded in Canvas mode are available in Project and Edit modes
* **Smart Organization**: Automatic categorization based on upload context and content type
* **Real-Time Sync**: Instant asset availability across all open modes and collaborators

#### **Intelligent Storage Strategy**

* **Azure Primary**: All files stored in Azure Blob Storage with global CDN
* **Firestore Metadata**: Rich metadata for search, filtering, and organization
* **Dual Persistence**: Canvas uploads stored in both collection and node data for performance
* **Automatic Cleanup**: Orphaned assets and metadata automatically cleaned up

#### **Performance & Scalability**

* **Lazy Loading**: Assets loaded on-demand with intelligent prefetching
* **Caching Strategy**: Multi-level caching for instant repeated access
* **Progress Tracking**: Real-time upload progress with pause/resume capabilities
* **Batch Operations**: Efficient bulk upload and management operations

#### **Type-Safe Architecture**

```typescript
interface AssetMetadata {
  id: string;
  projectId: string;
  fileName: string;
  originalName: string;
  size: number;
  contentType: string;
  azureUrl: string; // Primary CDN URL
  blobName: string; // Azure blob identifier
  uploadedAt: string;
  uploadedBy: string;
  nodeId?: string; // Canvas context
  tags?: string[];
  isNodeAsset?: boolean; // Mode differentiation
}
```

### 🚀 Usage Examples Across Modes

#### **Project Mode: Asset Gallery Management**

```typescript
import { useAssetUpload, useProjectAssets } from "@/hooks/useUnifiedAssets";

function ProjectAssetGallery() {
  const { uploadFile, uploading, progress } = useAssetUpload();
  const { assets, loading, refetch } = useProjectAssets({
    contentType: "image",
    limit: 50,
  });

  const handleGalleryUpload = async (files: File[]) => {
    for (const file of files) {
      await uploadFile(file, {
        tags: ["gallery", "project-asset"],
        generateThumbnail: true,
      });
    }
    refetch(); // Refresh gallery
  };
}
```

#### **Canvas Mode: Node-Specific Upload**

```typescript
import { useNodeUpload } from "@/modules/canvas/hooks";

function CanvasNode({ nodeId }) {
  const { uploadToNode, uploading } = useNodeUpload(nodeId, dispatch);

  const handleCanvasUpload = async (file: File) => {
    // Uploads to Azure + Firestore + updates node.mediaUrl
    const result = await uploadToNode([file], {
      generateThumbnail: true,
      nodeContext: true,
    });
  };
}
```

#### **Edit Mode: Timeline Asset Integration**

```typescript
import { useMediaLibrary } from "@/hooks/useUnifiedAssets";

function TimelineAssetPanel() {
  const { allMedia, firestoreAssets, nodeAssets } =
    useMediaLibrary(canvasNodes);

  // Access assets from all modes
  const projectImages = firestoreAssets.filter(
    (a) => a.contentType.startsWith("image/") && !a.isNodeAsset
  );
  const canvasMedia = nodeAssets; // From canvas nodes
  const combinedMedia = allMedia; // Everything together
}
```

#### **Cross-Mode Asset Sharing**

```typescript
// Asset uploaded in Canvas becomes available everywhere
import { useProjectAssets } from "@/hooks/useUnifiedAssets";

function CrossModeAssetAccess() {
  // Get all assets including canvas uploads
  const { assets } = useProjectAssets({ includeNodeAssets: true });

  // Filter by source
  const projectAssets = assets.filter((a) => !a.isNodeAsset);
  const canvasAssets = assets.filter((a) => a.isNodeAsset);
}
```

### 🔄 Migration Benefits & Cross-Mode Advantages

**Before**: Fragmented systems with separate upload logic per mode, IndexedDB inconsistencies **After**: Unified system with seamless cross-mode integration and intelligent context awareness

#### **Performance Gains**

* **Faster Cross-Mode Access**: Assets uploaded in any mode instantly available elsewhere
* **Intelligent Caching**: Smart prefetching based on usage patterns across modes
* **Reduced Network Overhead**: Single CDN with optimized delivery paths
* **Background Processing**: Non-blocking uploads with progress across all contexts

#### **User Experience Improvements**

* **Seamless Workflow**: Upload in Canvas, access in Project, use in Edit timeline
* **Consistent Interface**: Same upload experience regardless of current mode
* **Smart Suggestions**: Context-aware asset recommendations based on current work
* **Real-Time Collaboration**: Asset changes propagate instantly to all team members

#### **Developer Benefits**

* **Single API Surface**: One set of hooks and functions for all asset operations
* **Type Safety**: Comprehensive TypeScript interfaces across all modes
* **Maintainability**: Zero code duplication, single source of truth
* **Testing**: Unified test suite covering all asset operation scenarios

### 🎬 **Enhanced Video Editor Integration**

* **Remotion & Worker Threads**: Fully integrated professional video editing capabilities
* **Performance Architecture**: Worker pools for video, audio, image, timeline, and Remotion processing
* **EditorOrchestrator**: Central service coordinator managing all video editor services
* **Adaptive Rendering**: Dynamic quality adjustment based on system performance
* **Background Processing**: Non-blocking video operations with progress tracking
* **Enhanced Video Player**: Dual rendering modes (Canvas/Remotion) with fallback support

### 🎯 **Context-Based Image Analysis**

* **Smart node behavior**: Nodes with existing media create NEW analysis nodes when describing images
* **Base state optimization**: Empty nodes with image context update directly with descriptions
* **Azure OpenAI 4o mini**: Fixed parameter compatibility (`max_completion_tokens`, `temperature: 1`, `top_p: 1`)
* **Intelligent routing**: Text generation automatically detects image-to-text requests

### 🗑️ **Optimistic Deletion System**

* **Instant UI updates**: Nodes and edges delete immediately without waiting for server confirmation
* **Smart edge cleanup**: Connected edges automatically removed when nodes are deleted
* **Multiple delete keys**: Support for both `Delete` and `Backspace` keys
* **Collaborative broadcasting**: Real-time deletion sync across all users

### 🌐 **Auto-Detection & Reliability**

* **Dynamic port detection**: Automatically detects server port (3000, 3001, 3002, etc.)
* **Request-based URL resolution**: Uses request headers to determine correct base URL
* **Development flexibility**: No more manual port updates when Next.js switches ports
* **Robust error handling**: Graceful fallbacks for all network operations

### 🔧 **Technical Improvements**

* **Enhanced logging**: Comprehensive debug information for troubleshooting
* **Performance optimization**: Reduced API call latency and improved response times
* **Context data processing**: Better handling of image URLs and metadata
* **Edge case handling**: Improved stability for various content types
* **Modular architecture**: Clean separation of concerns with service-oriented design

## 🚀 Tech Stack

### Frontend

* **Framework**: Next.js 15 with App Router
* **Language**: TypeScript
* **Styling**: Tailwind CSS
* **3D Graphics**: Three.js, @react-three/fiber, @react-three/drei
* **Icons**: React Icons, Lucide React
* **Animations**: Framer Motion, CSS Animations
* **Video Editing**: Remotion, Enhanced Video Player
* **Worker Threads**: Web Workers for background processing

### Backend & Services

* **Authentication**: Firebase Auth
* **Database**: Firestore (project-assets collection)
* **Storage**: Azure Blob Storage (exclusive, no fallbacks)
* **Asset Management**: Unified system with zero redundancy
* **API Routes**: Next.js API Routes with unified endpoints
* **AI Models**: OpenAI, Gemini, Flux, Stable Diffusion
* **Video Processing**: FFmpeg.wasm, Remotion rendering
* **Performance Monitoring**: Custom performance tracking system

### Video Editor Architecture

* **Worker Pools**: Video, Audio, Image, Timeline, Remotion processing
* **Service Layer**: EditorOrchestrator, RemotionService, PerformanceMonitor
* **Rendering Engine**: Dual-mode Canvas/Remotion rendering
* **Caching System**: Intelligent frame caching with memory management
* **Health Monitoring**: Automatic service restart and failure recovery

### Development

* **Package Manager**: pnpm
* **Linting**: ESLint
* **Code Formatting**: Prettier
* **Version Control**: Git

## 🚀 Getting Started

### Quick Setup

```bash
# Clone repository
git clone https://github.com/EurusLabs/eurus-studio.git
cd eurus-studio

# Install dependencies
pnpm install

# Set up environment variables
cp azure.env.template .env.local
# Fill in your Azure credentials and API keys

# Add your API keys and configuration
# - Firebase configuration (Auth + Firestore)
# - Azure Blob Storage credentials (REQUIRED for asset management)
# - AI model API keys

# Required for Unified Asset Management:
AZURE_STORAGE_CONNECTION_STRING=your_connection_string
AZURE_STORAGE_CONTAINER_NAME=user-assets
AZURE_STORAGE_BASE_URL=https://yourstorage.blob.core.windows.net

# Start development server
pnpm dev
# Server will auto-detect available port (3000, 3001, 3002, etc.)
```

### 📋 **Setup Documentation**

#### Core Setup

See [**SETUP\_GUIDE.md**](https://github.com/EurusLabs/fauna-clone/blob/main/SETUP_GUIDE.md) for detailed configuration of:

* Azure AI Foundry (GPT-4o + SORA)
* Multi-image composition pipeline
* Troubleshooting and team collaboration

#### Remotion Lambda Setup

See [**src/remotion/README.md**](https://github.com/EurusLabs/fauna-clone/blob/main/src/remotion/README.md) for complete serverless video rendering setup:

* AWS IAM policy and role configuration
* Lambda function deployment (with optimized settings)
* Environment variables setup
* Testing and troubleshooting
* Cost optimization and monitoring

### 🎯 **New: Multi-Image Composition**

Upload multiple images and ask the system to "combine" or "merge" them:

1. **GPT-4o** analyzes all images simultaneously
2. **SORA** creates video compositions (Azure AI Foundry)
3. **Enhanced FLUX** fallback with intelligent prompts

### 🎤 **Enhanced Audio Recording**

Ultra-smooth voice-to-text functionality with Azure Whisper:

* **Instant visual feedback** with pulsing recording animations
* **Optimized audio settings** for clear speech recognition
* **Smart error handling** with user-friendly messages
* **Real-time transcription** with immediate prompt population

## 🎬 Enhanced Video Editor

### 🏗️ Architecture Overview

The enhanced video editor is built with a modular architecture that separates concerns and enables efficient background processing:

```
┌─────────────────────────────────────────────────────────────┐
│                     Editor Orchestrator                      │
│                  (Service Coordinator)                       │
├─────────────────────────────────────────────────────────────┤
│  Worker Manager  │  Remotion Service  │ Performance Monitor │
├──────────────────┼────────────────────┼─────────────────────┤
│   Video Worker   │    Audio Worker    │   Image Worker      │
│ Timeline Worker  │  Remotion Worker   │                     │
└─────────────────────────────────────────────────────────────┘
```

### 🎯 Video Editor Features

#### **Worker Thread Management**

* **WorkerPool**: Manages multiple worker instances with automatic scaling
* **WorkerManager**: Central coordinator for all worker pools
* **Task Prioritization**: Intelligent task queuing and priority management
* **Health Monitoring**: Automatic worker restart and failure recovery

#### **Remotion Integration**

* **Background Rendering**: Non-blocking video frame generation
* **Caching System**: Intelligent frame caching for smooth playback
* **Adaptive Quality**: Dynamic quality adjustment based on performance
* **Preview Optimization**: Fast preview rendering with lower quality

#### **Performance Monitoring**

* **Real-time Metrics**: CPU, memory, and rendering performance tracking
* **Health Reports**: Comprehensive system health analysis
* **Automatic Optimization**: Performance-based feature adjustments
* **Developer Tools**: Development-time performance overlays

### 🛠️ Worker Types

#### **Video Processing Worker**

* **Frame Extraction**: Extract frames from video files
* **Thumbnail Generation**: Generate video thumbnails
* **Video Analysis**: Analyze video properties and metadata
* **Compression**: Video compression with quality settings

#### **Audio Processing Worker**

* **Waveform Extraction**: Generate audio waveform data
* **Peak Analysis**: Extract audio peak information
* **Audio Normalization**: Normalize audio levels
* **Format Conversion**: Convert between audio formats

#### **Remotion Rendering Worker**

* **Frame Rendering**: Render individual Remotion frames
* **Sequence Rendering**: Render frame sequences
* **Video Export**: Export complete videos
* **Preview Generation**: Fast preview rendering

#### **Image Processing Worker**

* **Image Resizing**: Resize images with quality options
* **Filter Application**: Apply various image filters
* **Color Extraction**: Extract dominant colors
* **Optimization**: Optimize images for web

#### **Timeline Calculator Worker**

* **Layout Calculation**: Calculate timeline layouts
* **Track Optimization**: Optimize track arrangements
* **Keyframe Generation**: Generate animation keyframes
* **Validation**: Validate timeline integrity

### 🎮 Enhanced Video Player

The `EnhancedVideoPlayer` provides advanced features:

#### **Features**

* **Dual Rendering Modes**: Canvas and Remotion rendering
* **Performance Monitoring**: Real-time FPS and render time display
* **Adaptive Streaming**: Quality adjustment based on performance
* **Background Preloading**: Smooth playbook with predictive loading

#### **Usage**

### Usage\*\*

```tsx
import { Editor, editorOrchestrator } from "@/components/editor";

function VideoEditorApp() {
  useEffect(() => {
    // Initialize all services
    editorOrchestrator.initialize();

    return () => {
      // Cleanup on unmount
      editorOrchestrator.shutdown();
    };
  }, []);

  return (
    <Editor
      onStateChange={(state) => console.log("Editor state:", state)}
      className="h-screen"
    />
  );
}
```

## 🗂️ Unified Asset Management

The application features a completely unified asset management system that eliminates all redundancy and provides a single source of truth for all media operations.

### 🏗️ Architecture Overview

```
┌─ Project Tab ─────────────────────┐    ┌─ Canvas Tab ──────────────────────┐    ┌─ Edit Tab ────────────────────────┐
│ Add Asset → Azure → Firestore     │    │ Upload → Azure → Firestore + Node │    │ Same as Project Tab               │
│ Media Library ← Firestore Only    │    │ View ← Firestore + Node Extract   │    │ Azure → Firestore → Display      │
└───────────────────────────────────┘    └───────────────────────────────────┘    └───────────────────────────────────┘
                                    ▲                                      ▲                                      ▲
                                    │                                      │                                      │
                                    └─────────── UNIFIED SYSTEM ──────────┴──────────────────────────────────────┘
                                              /src/lib/unifiedAssetManager.ts
```

### 🎯 Cross-Mode Asset Flow

#### **Project Mode: Asset Library Management**

1. **Upload Flow**: Gallery Upload → Azure Blob → Firestore Collection → Real-time Sync
2. **Organization**: Tag-based categorization, bulk operations, team sharing
3. **Cross-Mode Availability**: Instantly accessible in Canvas and Edit modes
4. **Use Cases**: Brand assets, stock images, project resources, team libraries

#### **Canvas Mode: Node-Specific Asset Integration**

1. **Context Upload**: Node Upload → Azure Blob → Firestore Collection + Node Data
2. **Dual Persistence**: Asset stored in collection for cross-mode access + node for performance
3. **Real-Time Canvas**: Immediate node visual update with asset preview
4. **Use Cases**: AI-generated content, workflow outputs, iterative creations

#### **Edit Mode: Timeline Asset Integration**

1. **Asset Access**: Aggregated view of Project assets + Canvas node outputs
2. **Smart Filtering**: Content-type filtering for timeline compatibility
3. **Performance Optimization**: Lazy loading with intelligent prefetching
4. **Use Cases**: Video editing, audio tracks, image sequences, final compositions

#### **Universal Cross-Mode Benefits**

* **Asset Discoverability**: Upload anywhere, find everywhere
* **Context Preservation**: Metadata tracks origin mode and usage context
* **Collaborative Workflow**: Team members see assets regardless of their current mode
* **Version Control**: Full audit trail of asset usage across different modes

### 🛠️ Cross-Mode Component Integration

#### **Unified UI Components**

```typescript
// Universal Asset Upload Dialog - works in all modes
<UnifiedAssetUploadDialog
  isOpen={showDialog}
  onAssetUploaded={handleUpload}
  mode="project"          // "project" | "canvas" | "edit"
  nodeId={nodeId}         // Optional: for canvas context
  allowedTypes={['image', 'video', 'audio']}
  showProgress={true}
/>

// Cross-Mode Media Library - aggregates all assets
<UnifiedMediaLibrary
  onAssetSelect={handleSelect}
  showCanvasAssets={true}   // Include canvas node assets
  showProjectAssets={true}  // Include project gallery assets
  filterByMode="all"        // "project" | "canvas" | "edit" | "all"
  contentTypeFilter="image" // Type-specific filtering
/>
```

#### **Mode-Aware Hook System**

```typescript
// Automatically detects current mode and optimizes accordingly
const { uploadFile } = useAssetUpload(); // Universal uploader
const { assets } = useProjectAssets(); // Project + Canvas assets
const { allMedia } = useMediaLibrary(canvasNodes); // Everything combined

// Canvas-specific with cross-mode integration
const { uploadToNode } = useNodeUpload(nodeId); // Canvas + Collection storage
```

### 🛠️ Core Components

#### **Single Source of Truth**

```typescript
// /src/lib/unifiedAssetManager.ts
export async function uploadAsset(
  file: File,
  options: UploadOptions
): Promise<UploadResult>;
export async function uploadAssetFromUrl(
  url: string,
  fileName: string,
  options: UploadOptions
): Promise<UploadResult>;
export async function getProjectAssets(
  projectId: string,
  filter?: AssetFilter
): Promise<AssetMetadata[]>;
export async function deleteAsset(
  assetId: string,
  blobName: string
): Promise<boolean>;
```

#### **React Hook System**

```typescript
// /src/hooks/useUnifiedAssets.ts
const { uploadFile, uploading, progress } = useAssetUpload();
const { assets, loading, refetch } = useProjectAssets();
const { allMedia, firestoreAssets, nodeAssets } = useMediaLibrary();
```

#### **UI Components**

```typescript
// Unified upload dialog for all contexts
<UnifiedAssetUploadDialog
  isOpen={showDialog}
  onAssetUploaded={handleUpload}
  nodeId="canvas-node-123" // Optional: for canvas uploads
  allowedTypes={['image', 'video']}
/>

// Complete media library with filtering
<UnifiedMediaLibrary
  onAssetSelect={handleSelect}
  allowedTypes={['image']}
  showUploadButton={true}
/>
```

### 📁 Storage Architecture

#### **Azure Blob Storage Structure**

```
user-assets/
├── projects/{projectId}/
│   ├── assets/{timestamp}-{randomId}-{filename}     ← Project/Edit Tab uploads
│   └── nodes/{nodeId}/{timestamp}-{randomId}-{filename}  ← Canvas Tab uploads
└── Public URLs: https://storage.azure.com/container/...
```

#### **Firestore Collection Structure**

```typescript
// Collection: project-assets
interface AssetMetadata {
  id: string;
  projectId: string; // Index for efficient queries
  fileName: string;
  azureUrl: string; // Primary URL field
  blobName: string;
  nodeId?: string; // Set for canvas uploads
  isNodeAsset?: boolean; // Differentiates canvas vs project uploads
  uploadedAt: string;
  uploadedBy: string;
  tags?: string[];
}
```

### 🚀 Cross-Mode API Architecture

#### **Universal Upload Endpoint**

```typescript
// POST /api/assets - Handles all modes with context detection
{
  "files": [File],           // Multipart file upload
  "projectId": "proj_123",   // Required for organization
  "userId": "user_456",      // Authentication context
  "nodeId": "node_789",      // Optional: Canvas mode context
  "tags": ["gallery"],       // Optional: Categorization
  "mode": "canvas"           // "project" | "canvas" | "edit"
}

// Response includes cross-mode metadata
{
  "success": true,
  "assets": [{
    "id": "asset_123",
    "azureUrl": "https://cdn.../file.jpg",
    "isNodeAsset": true,        // Indicates canvas origin
    "availableInModes": ["canvas", "project", "edit"]
  }]
}
```

#### **Cross-Mode Asset Retrieval**

```typescript
// GET /api/assets/list - Aggregated asset fetching
{
  "projectId": "proj_123",
  "includeNodeAssets": true,    // Include canvas uploads
  "contentType": "image/*",     // Filter by type
  "mode": "all",                // "project" | "canvas" | "edit" | "all"
  "tags": ["gallery", "ai-generated"]
}

// Returns unified asset array with mode context
{
  "assets": [
    { "id": "1", "isNodeAsset": false, "uploadedInMode": "project" },
    { "id": "2", "isNodeAsset": true, "uploadedInMode": "canvas", "nodeId": "node_789" }
  ]
}
```

#### **Mode-Specific Endpoints**

```typescript
// Canvas-specific with cross-mode persistence
POST /api/upload-media
- Canvas node uploads with dual storage
- Maintains canvas functionality while enabling cross-mode access
- Automatic metadata enrichment for discoverability

// Project gallery management
POST /api/assets/bulk
- Bulk operations for project asset management
- Team sharing and collaboration features
- Cross-mode availability by default
```

### 🎯 Cross-Mode Integration Benefits

* **Seamless Workflow**: Upload in any mode, access everywhere instantly
* **Zero Context Switching**: Assets available regardless of current working mode
* **Intelligent Organization**: Context-aware categorization with cross-mode discoverability
* **Performance Optimized**: Smart caching and prefetching across all modes
* **Real-Time Collaboration**: Asset changes propagate instantly to all team modes
* **Type-Safe Operations**: Full TypeScript integration with mode-aware interfaces
* **Unified Developer Experience**: Single API surface for all asset operations
* **Scalable Architecture**: Cloud-native with automatic cross-mode synchronization

### 🔧 Service Management

#### **EditorOrchestrator**

Central service coordinator that manages:

* Service initialization and shutdown
* Cross-service communication
* Health monitoring and reporting
* Event coordination

#### **Key Methods**

```typescript
// Initialize all services
await editorOrchestrator.initialize();

// Get system health report
const health = await editorOrchestrator.getHealthReport();

// Listen for system events
editorOrchestrator.on("performance-warning", handleWarning);

// Restart services if needed
await editorOrchestrator.restart();
```

### 🚨 Error Handling & Fallbacks

#### **Graceful Degradation**

* **Service Failures**: Automatic fallback to basic functionality
* **Worker Crashes**: Automatic worker restart and task retry
* **Memory Pressure**: Reduced quality modes to free memory
* **Network Issues**: Offline mode with cached resources

#### **Error Recovery**

```typescript
try {
  await remotionService.renderFrame(options);
} catch (error) {
  // Automatic fallback to canvas rendering
  console.warn("Remotion render failed, falling back to canvas");
  useCanvasRenderer();
}
```

## Azure Integration

This project uses Azure Blob Storage and Azure OpenAI for comprehensive AI workflows:

### **Storage Configuration**

* **Storage Account**: `eurusworkflows`
* **Containers**: `discover-assets`, `node-autosave`
* **Assets**: Images, videos, and generated content
* **Management**: See `AZURE_ASSET_MANAGEMENT.md` for detailed instructions

### **AI Services**

* **Azure OpenAI 4o mini**: Image analysis and description
* **Azure OpenAI 4.1 nano**: Intent processing and context understanding
* **Azure Whisper**: Ultra-smooth speech-to-text transcription
* **Optimized parameters**: Configured for maximum compatibility and performance

## 🎮 Usage

### Landing Page

1. **Hero Section**: Experience the interactive "Irreplacably Creative" canvas
2. **Drag & Drop**: Move nodes around the canvas to see real-time interactions
3. **3D Models**: Click on 3D nodes to see GLB models rendered in real-time
4. **Scroll Experience**: Smooth scroll through different sections

### Authentication

* Click "Get Started" to open the authentication modal
* Sign in with email/password or social providers
* Access the full creative workspace after authentication

### Creative Workflows

* **Node-based Interface**: Drag and drop AI tools
* **Real-time Preview**: See results as you work
* **Collaboration**: Work with team members in real-time
* **Asset Management**: Upload and organize your creative assets

### Video Editor Workflows

* **Professional Video Editing**: Timeline-based editing with multiple tracks
* **Remotion Compositions**: React-based video component creation
* **Background Processing**: Non-blocking video operations with worker threads
* **Performance Optimization**: Automatic quality adjustment and resource management
* **Real-time Collaboration**: Multi-user video editing with live cursors
* **Export Options**: Multiple format support with quality presets

## 📁 Project Structure

```
eurus-studio/
├── app/                    # Next.js App Router
│   ├── api/               # API routes
│   ├── discover/          # Discovery page
│   ├── pricing/           # Pricing page
│   └── project/           # Project workspace
├── components/            # React components
│   ├── ui/               # Reusable UI components
│   ├── collaboration/    # Real-time collaboration
│   ├── nodes/            # Workflow nodes
│   ├── editor/           # Enhanced video editor
│   │   ├── core/         # Core editor components
│   │   ├── workers/      # Worker thread management
│   │   ├── services/     # Service layer (Orchestrator, Remotion, Performance)
│   │   ├── player/       # Enhanced video player
│   │   ├── timeline/     # Timeline components
│   │   └── panels/       # Editor panels
│   ├── landing-page.tsx  # Main landing page
│   └── navigation.tsx    # Navigation component
├── lib/                  # Utility libraries
│   ├── models/           # AI model integrations
│   ├── unifiedAssetManager.ts  # UNIFIED Asset Management (Single Source of Truth)
│   ├── azure-storage.ts  # Azure Blob Storage
│   └── firebase.ts       # Firebase configuration
├── hooks/                # Custom React hooks
│   ├── useUnifiedAssets.ts    # Unified asset management hooks
│   └── use-auth.tsx      # Authentication hooks
├── components/           # React components
│   ├── shared/           # Shared components
│   │   ├── UnifiedAssetUploadDialog.tsx  # Universal upload dialog
│   │   └── UnifiedMediaLibrary.tsx       # Complete media library
│   └── ...               # Other components
├── public/               # Static assets
│   ├── images/           # Image assets
│   ├── videos/           # Video assets
│   └── workers/          # Web worker scripts
│       ├── video-processor.js     # Video processing worker
│       ├── audio-processor.js     # Audio processing worker
│       ├── remotion-renderer.js   # Remotion rendering worker
│       ├── image-processor.js     # Image processing worker
│       └── timeline-calculator.js # Timeline calculation worker
├── hooks/                # Custom React hooks
├── types/                # TypeScript type definitions
└── styles/               # Global styles
```

## 🎨 Key Components

### Landing Page Features

* **InfiniteCanvasBackground**: Animated particle background
* **DraggableNodesLayer**: Interactive node system
* **ProductsScrollSection**: AI model showcase with videos
* **IdeasScrollNodesSection**: Creative inspiration section
* **Model3D**: 3D model rendering with error boundaries

### 3D Model Integration

* **Error Boundaries**: Graceful fallback for 3D model failures
* **Auto-rotation**: Smooth 3D model animations
* **Optimized Loading**: Preloaded GLB models for performance

### Video Editor Components

* **Editor**: Main video editor orchestrator with service management
* **EnhancedVideoPlayer**: Advanced video player with dual rendering modes
* **Timeline**: Professional timeline with multi-track support
* **WorkerManager**: Centralized worker thread coordination
* **PerformanceMonitor**: Real-time performance tracking and optimization
* **RemotionService**: High-performance React-based video rendering

## 🚀 Deployment

### Vercel (Recommended)

```bash
# Deploy to Vercel
vercel --prod

# Or connect your GitHub repository to Vercel dashboard
```

### Docker

```bash
# Build Docker image
docker build -t eurus-studio .

# Run container
docker run -p 3000:3000 eurus-studio
```

## 🔧 Configuration

### Environment Variables

```env
# Firebase
NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your_domain
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your_project_id

# Azure Storage
AZURE_STORAGE_CONNECTION_STRING=your_connection_string
AZURE_STORAGE_CONTAINER_NAME=your_container_name

# AI Models
OPENAI_API_KEY=your_openai_key
GEMINI_API_KEY=your_gemini_key
```

## 🎯 Performance Optimizations

* **Code Splitting**: Dynamic imports for heavy components
* **Image Optimization**: Next.js Image component with lazy loading
* **3D Model Caching**: GLB model preloading and caching
* **Bundle Analysis**: Optimized bundle sizes
* **SSR/SSG**: Server-side rendering for better SEO

## 🐛 Troubleshooting

### Common Issues

**3D Models Not Loading**

* Check GLB file paths in `/public/images/`
* Ensure files are not corrupted
* Check browser WebGL support

**Firebase Auth Issues**

* Verify environment variables
* Check Firebase console configuration
* Ensure auth domain is whitelisted

**Video Editor Performance Issues**

* Check worker thread support in browser
* Ensure sufficient system memory (4GB+ recommended)
* Verify Remotion dependencies are properly installed
* Monitor performance overlay in development mode
* Try fallback canvas rendering if Remotion fails

**Worker Thread Issues**

* Ensure worker scripts are accessible in `/public/workers/`
* Check browser console for worker initialization errors
* Verify CORS settings for worker script loading
* Monitor worker pool status via EditorOrchestrator health reports

**Performance Issues**

* Reduce 3D model complexity
* Optimize image sizes
* Check network requests in DevTools
* Monitor memory usage with performance overlay
* Use adaptive quality settings in video editor

## 🤝 Contributing

We welcome contributions! Please follow these steps:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

### Development Guidelines

* Follow TypeScript best practices
* Use Tailwind CSS for styling
* Write meaningful commit messages
* Add JSDoc comments for complex functions
* Test your changes thoroughly

## � Performance Best Practices

### 1. **Worker Pool Sizing**

```typescript
// Optimal worker configuration based on CPU cores
const optimalConcurrency = Math.max(
  1,
  Math.floor(navigator.hardwareConcurrency / 2)
);
```

### 2. **Memory Management**

* Monitor memory usage with `performance.memory`
* Implement automatic cache cleanup
* Use object pools for frequently created objects

### 3. **Frame Rate Optimization**

* Target 30 FPS for smooth playback
* Drop frames when performance is poor
* Preload frames during idle time

### 4. **Quality Scaling**

* Start with medium quality, adjust based on performance
* Use lower quality for previews
* Scale resolution for better performance on low-end devices

## 🎨 Customization

### Adding New Worker Types

1. Create worker script in `/public/workers/`
2. Add task types to `workers/types.ts`
3. Register with WorkerManager
4. Implement task handlers

### Custom Effects and Filters

1. Extend the Remotion composition
2. Add effect types to the schema
3. Implement rendering logic
4. Register with the effects system

### Performance Metrics

1. Extend the PerformanceMonitor
2. Add custom metric collection
3. Implement analysis functions
4. Create visualization components

## 🧪 Development Tools

### Performance Overlay

Development mode shows real-time performance metrics:

* FPS counter
* Render time
* Memory usage
* System health status

### Debug Controls

* Service restart (Ctrl+R)
* Performance logging
* Worker pool status
* Cache statistics

### Health Monitoring

Comprehensive health reports include:

* Service status
* Performance metrics
* Recommendations
* System capabilities

## 🚀 Production Considerations

### Build Optimization

* Bundle workers separately for better caching
* Minimize worker script sizes
* Use efficient data transfer formats

### Monitoring

* Implement error reporting
* Track performance metrics
* Monitor user behavior patterns

### Scaling

* Adjust worker pools based on device capabilities
* Implement progressive enhancement
* Use feature detection for advanced capabilities

## 📝 API Reference

### Core Services

* `editorOrchestrator` - Central service coordinator
* `workerManager` - Worker pool management
* `remotionService` - Remotion rendering service
* `performanceMonitor` - Performance tracking

### Components

* `Editor` - Main editor component
* `EnhancedVideoPlayer` - Advanced video player
* `Timeline` - Timeline component
* Various panels and controls

### Types

* `EditorState` - Complete editor state
* `WorkerTask` - Worker task definition
* `Clip` - Video/audio/text clip
* `Track` - Timeline track

## �📄 License

This project is licensed under the MIT License - see the [LICENSE](https://github.com/EurusLabs/fauna-clone/blob/main/LICENSE/README.md) file for details.

## 🙏 Acknowledgments

* **Eurus Studio** for the incredible landing page design
* **Three.js** community for 3D graphics support
* **Next.js** team for the amazing framework
* **Tailwind CSS** for the utility-first approach
* **Remotion** for React-based video rendering
* **Web Workers API** for background processing capabilities

## � Troubleshooting

### Asset Management Issues

#### **Cross-Mode Asset Visibility**

* **Assets uploaded in Canvas not showing in Project**: Check `includeNodeAssets: true` in `useProjectAssets`
* **Canvas assets missing from Edit mode**: Ensure `useMediaLibrary(canvasNodes)` includes current nodes
* **Mode-specific filtering issues**: Verify `isNodeAsset` field is correctly set in Firestore
* **Real-time sync delays**: Check Firestore listeners are active across all open modes

#### **Upload Context Issues**

* **Canvas uploads not persisting to node**: Verify `nodeId` parameter in upload options
* **Project uploads appearing as node assets**: Remove `nodeId` from upload calls in project mode
* **Missing cross-mode metadata**: Ensure `mode` parameter is correctly passed to upload API

#### **Core System Issues**

* **"Firestore is not initialized" Error**: Ensure operations run client-side with proper Firebase config
* **Upload fails with "userId required"**: Add `userId` to all upload calls: `uploadAsset(file, { projectId, userId })`
* **Assets not appearing**: Verify `currentProject.id` is valid and Firestore permissions allow reads
* **Azure Storage connection**: Check `AZURE_STORAGE_CONNECTION_STRING` and container permissions

#### **Performance Issues**

* **Slow cross-mode asset loading**: Enable asset prefetching and check network tab for bottlenecks
* **Memory usage in media library**: Implement virtual scrolling for large asset collections
* **Canvas performance with many assets**: Use lazy loading and thumbnail optimization

### Migration from Legacy System

* All `asset.url` references should be changed to `asset.azureUrl`
* Remove any IndexedDB or localStorage asset code
* Update import paths to use unified system only

## �📞 Support

For support, please:

* Create an issue in the repository
* Check the troubleshooting section above
* Review the unified asset system documentation
* Check the video editor architecture docs

## 📚 Further Reading

* [Remotion Documentation](https://remotion.dev/)
* [Web Workers API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)
* [Performance Monitoring](https://developer.mozilla.org/en-US/docs/Web/API/Performance)
* [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas)
* [Next.js App Router](https://nextjs.org/docs/app)
* [Three.js Documentation](https://threejs.org/docs/)

***

**Built with ❤️ using Next.js, Remotion, Three.js, and modern web technologies.**

This enhanced creative platform provides a robust, scalable foundation for professional AI workflows and video editing applications with seamless Remotion integration and efficient worker thread utilization.

## Studio WIP Deployment (stripe-integration)

This branch is connected to an Azure Static Web App (`studio-wip`) created solely for validating the new Stripe billing flows (subscriptions + pay-as-you-go). Every push to `stripe-integration` triggers the GitHub Action in `.github/workflows/azure-static-web-apps-*.yml` and automatically deploys the latest build.

> NOTE: This environment points to the **Stripe sandbox backend** and **Firebase staging project**. Do **not** use real production keys.

trigger
