# CLAUDE.md

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

## Development Commands

### Frontend Development
- `npm run dev` - Start Vite development server
- `npm run build` - Build for production
- `npm run build:ssr` - Build with SSR support
- `npm run lint` - Run ESLint with auto-fix
- `npm run types` - Run TypeScript type checking
- `npm run format` - Format code with Prettier
- `npm run format:check` - Check code formatting

### Backend Development
- `composer dev` - Start full development environment (Laravel server, queue worker, logs, Vite)
- `composer dev:ssr` - Start development with SSR
- `composer test` - Run PHP tests with Pest
- `php artisan serve` - Start Laravel development server
- `php artisan queue:listen --tries=1` - Start queue worker
- `php artisan pail --timeout=0` - Start log viewer

## Architecture Overview

### Stack
- **Backend**: Laravel 12 with PHP 8.2+
- **Frontend**: React 19 + TypeScript with Inertia.js
- **Database**: PostgreSQL with pgvector extension for embeddings
- **Queue System**: Laravel Horizon for job processing
- **Payment**: Laravel Cashier with Stripe integration
- **Media Processing**: FFmpeg integration via pbmedia/laravel-ffmpeg
- **Authentication**: Laravel Sanctum + Google OAuth via Socialite

### Core Application Structure

**MemeAI Generator Platform**: This is a meme generation platform that uses AI to create memes from user inputs.

#### Key Models & Relationships
- `User` - Uses Billable trait for Stripe, has UUID-based public IDs
- `Meme` - Generated memes with keyword categorization (action/emotion/misc)
- `MemeMedia` - Template media files for meme generation
- `BackgroundMedia` - Background images/videos for memes
- `Category` - Hierarchical categories using kalnoy/nestedset
- `UserUsage` & `UserPlan` - Usage tracking and subscription management
- `KeywordEmbedding` & `MemeMediaEmbedding` - Vector embeddings for content matching

#### AI Integration Points
- `CloudflareAI`, `OpenAI`, `RunwareAI` - Multiple AI service integrations
- `MemeGenerator` - Core meme generation logic with keyword matching via vector similarity
- Uses pgvector for semantic search and content matching

#### Frontend Architecture

**Core Stack & Integration**
- **React 19 + TypeScript** with Inertia.js for seamless full-stack Laravel integration
- **Vite** as build tool with HMR and optimized bundling
- **Error Boundaries** with detailed fallback components for robust error handling
- **Context Providers**: GA4, Mitt.js, and Axios contexts wrapped at app level

**State Management & Data Flow**
- **Zustand** with devtools for reactive state management
- **MediaStore**: AI generation, meme/background selection, API calls, generation history, job polling
- **VideoEditorStore**: Video playback state, text element selection for canvas interactions
- **UserStore**: Authentication, billing, credits, premium export functionality
- **PricingStore**: Subscription management and pricing tiers
- **localSettingsStore**: User preferences, UI settings, and appearance themes

**Component Communication Architecture**
- **Mitt.js Event System**: Decoupled event-driven communication between components
- **Core Events**: `video-play`, `video-reset`, `video-open-download-modal`, `open-ai-editor-sheet`, `text-element-selected`
- **Responsive Design**: Mobile-first approach with progressive enhancement and viewport detection hooks
- **Layout Calculations**: Dynamic responsive width calculations with ResizeObserver and MutationObserver

**Editor System Architecture**
- **Main Editor** (`editor.jsx`): Central orchestrator with responsive design, sidebar management, and viewport detection
- **Video Editor** (`video-editor.jsx`): Konva.js canvas with timeline processing, drag-and-drop, and FFmpeg export
- **Editor Controls** (`editor-controls.jsx`): Play/pause, reset, refresh, download controls via event emission
- **AI Integration** (`editor-ai-sheet.jsx`): AI generation interface with job polling and status tracking
- **Multiple Sidebars**: EditNavSidebar (content navigation), EditSidebar (main editing), TextSidebar (text customization)

**Media Processing & Canvas**
- **Konva.js + React-Konva** for high-performance canvas-based video editing
- **Timeline Support**: Video element positioning, text overlay management
- **FFmpeg.wasm** for client-side video processing and multi-format export
- **9:16 Aspect Ratio**: Optimized for social media with responsive scaling (720x1280px base)
- **Drag-and-Drop Interface**: Interactive element positioning with real-time preview

#### Media Processing Pipeline
- Video templates stored as JSON configurations
- Canvas-based editor with timeline support
- Server-side FFmpeg processing for final video generation
- S3/R2 storage integration via Laravel Filesystem

#### Key Helper Classes
- `MediaEngine` - Media processing utilities
- `PurchaseHelper`, `SubscriptionHelper` - Payment processing
- `WatermarkUsageHelper` - Usage tracking and limits
- `StripeHelper` - Stripe integration utilities

### Development Notes

#### Testing
- Uses Pest PHP for backend testing
- Test files in `tests/Feature/` and `tests/Unit/`
- Run tests with `composer test`

#### Code Organization
- Custom helpers in `app/Helpers/FirstParty/`
- Global helper functions in `app/Helpers/Global/helpers.php`
- Frontend components organized by feature in `resources/js/modules/`
- Reusable UI components in `resources/js/components/ui/` (Radix UI + Tailwind)
- State management stores in `resources/js/stores/`
- React hooks in `resources/js/hooks/`
- Custom plugins and context providers in `resources/js/plugins/`

#### Special Configurations
- CORS headers configured for FFmpeg.wasm in Vite config
- Vector search capabilities via PostgreSQL pgvector extension
- Hashids for public ID generation (users, etc.)
- Queue-based background processing for media generation

#### Environment-Specific Features
- Test routes can be enabled via `ENABLE_TEST_ROUTES=true`
- Uses Laravel Horizon for queue management in production
- Supports both regular and SSR deployments

## Platform Features Overview

### Core AI Features
- **Text-to-Meme Generation**: Users input text prompts, AI generates appropriate memes using vector similarity matching
- **Multi-AI Integration**: OpenAI, Cloudflare AI, and Runware AI for different generation tasks
- **Smart Keyword Matching**: PostgreSQL pgvector for semantic search and content matching
- **AI Hint System**: Provides keyword suggestions organized by action/emotion/misc categories
- **AI Caption & Background Generation**: Automatic witty captions and custom background creation

### Video/Media Editing
- **Canvas-Based Editor**: 9:16 aspect ratio video canvas (720x1280px) with responsive scaling
- **Drag-and-Drop Interface**: Interactive positioning of elements with timeline controls
- **Template Library**: 30+ meme video templates and 30+ AI-generated background media
- **Export System**: Multiple formats (MOV, WebM, GIF, WebP) with watermark-free premium exports
- **FFmpeg Integration**: Client-side processing via FFmpeg.wasm

### User Management & Authentication
- **Google OAuth + Email/Password**: Dual authentication methods via Laravel Sanctum
- **UUID-based Public IDs**: Secure user identification using Hashids
- **User Dashboard**: Personalized interface with usage statistics and generation history

### Credit System & Monetization
- **Credit-Based Economy**: 2 credits per meme generation (1 caption + 1 background)
- **Stripe Integration**: Laravel Cashier for subscriptions and one-time purchases
- **Usage Tracking**: Real-time credit balance, transaction history, and consumption analytics
- **Subscription Management**: Multiple plan types with billing portal access

### Technical Features
- **Queue Processing**: Laravel Horizon with background job processing and real-time status updates
- **Vector Search**: Semantic content matching using PostgreSQL pgvector extension
- **Responsive Design**: Mobile-first interface with progressive enhancement
- **Generation History**: Users can view last 20 generations with regeneration capability
- **Security**: CSRF protection, rate limiting, input validation, secure file handling

### Admin/Management
- **Content Management**: Categorized meme library with hierarchical categories (kalnoy/nestedset)
- **Background Generation Tool**: Admin interface for creating new background media
- **Usage Analytics**: Platform-wide statistics and user consumption patterns
- **Bulk Operations**: Mass content management and moderation tools

## Frontend Component Structure

### Application Entry & Shell (`/resources/js/`)
- **app.tsx**: Main Inertia.js application entry with error boundaries, context providers (GA4, Mitt, Axios), and global toaster
- **app-shell.tsx**: Layout wrapper providing either header or sidebar variants using SidebarProvider
- **ssr.tsx**: Server-side rendering entry point for enhanced performance

### Editor System (`/resources/js/modules/editor/`)
- **editor.jsx**: Central responsive orchestrator managing canvas, sidebars, viewport detection, and responsive design
- **editor-controls.jsx**: Video playback controls with play/pause, reset, refresh, download via event emission
- **editor-canvas.jsx**: Responsive canvas wrapper that scales the video editor to fit different screen sizes
- **editor-ai-sheet.jsx**: AI-powered meme generation interface with job polling, status tracking, and credit management
- **editor-header.jsx**: Header component for the editor interface with navigation controls

### Canvas & Video Processing (`/resources/js/modules/editor/partials/canvas/`)
- **video-editor.jsx**: Core Konva.js canvas with timeline processing, video/image handling, and FFmpeg export
- **video-preview.jsx**: Video preview component with element selection and transformation utilities
- **video-download-modal.jsx**: Download interface for multiple export formats (MOV, WebM, GIF, WebP)
- **video-export.jsx**: Export functionality with FFmpeg.wasm integration and format conversion

### Sidebar Components (`/resources/js/modules/editor/partials/`)
- **edit-nav-sidebar.jsx**: Navigation sidebar for switching between memes and backgrounds
- **edit-sidebar.jsx**: Main editing sidebar with content selection interfaces
- **text-sidebar.jsx**: Text editing sidebar for customizing meme captions and text properties

### Authentication System (`/resources/js/modules/auth/`)
- **AuthDialog.jsx**: Modal dialog for Google OAuth authentication with login/signup switching
- **auth-user.jsx**: User authentication component and user state management

### State Management Stores (`/resources/js/stores/`)
- **MediaStore.js**: Comprehensive store for meme/background selection, AI generation, API calls, generation history, job polling
- **VideoEditorStore.js**: Video playback state, text element selection for canvas interactions
- **UserStore.js**: User authentication, billing, credits, premium export functionality
- **PricingStore.js**: Subscription management, pricing tiers, and upgrade flows
- **localSettingsStore.js**: User preferences, UI settings, appearance themes

### Page Components (`/resources/js/pages/`)
- **Home System**: `home.tsx` with Hero, Features, FAQ sections and animated counters
- **Dashboard**: `dashboard.tsx` with user analytics and generation history
- **Authentication Pages**: Login, register, password reset, email verification flows
- **Settings Pages**: Profile, appearance, password management interfaces
- **Admin Pages**: Dashboard, background generation tools for content management

### UI Component Library (`/resources/js/components/ui/`)
- **Radix UI Base**: Complete accessible component primitives (buttons, dialogs, sheets, forms, tables)
- **Form Controls**: Input, textarea, select, checkbox, radio-group with validation
- **Layout Components**: Card, dialog, sheet, sidebar, tabs, accordion for structured layouts
- **Feedback Components**: Alert, toast, progress, skeleton, spinner for user feedback
- **Navigation**: Breadcrumb, navigation-menu, pagination for app navigation
- **Data Display**: Table, avatar, badge, chart for content presentation

### Enhanced UI Components (`/resources/js/components/magicui/` & `/resources/js/components/reactbits/`)
- **Animation Components**: Animated beam, gradient text, sparkles text, word rotation
- **Special Effects**: CountUp, GlitchText, ShinyText, TiltedCard for engaging interactions
- **Layout Enhancements**: Bento grid, marquee, pulsating button for dynamic layouts

### Utility Systems (`/resources/js/`)
- **Hooks**: Custom React hooks for appearance, mobile detection, user initials, navigation
- **Plugins**: Context providers for Axios, Google Analytics, Mitt.js event system
- **Layouts**: Flexible layout system with auth, app, and settings variants
- **Types**: TypeScript definitions for global types, API responses, and component props

## Backend Architecture

### API Structure (`/routes/api.php`)
- **Authentication**: `/user/register`, `/user/login` (Sanctum-based)
- **User Management**: `/user/` (profile), `/user/subscribe`, `/user/purchase`, `/user/billing-portal`
- **Meme Generation**: `/user/generate_meme/*` (generate, status, active job, history)
- **Export System**: `/user/premium-export/*` (request, complete)
- **Media APIs**: `/app/init`, `/app/memes`, `/app/background`
- **AI Integration**: `/ai-hints` for keyword suggestions

### Controller Organization
- **FrontMediaController**: Media initialization and content delivery
- **UserAIController**: AI-powered meme generation with job processing
- **UserAccountController**: User profile and account management
- **UserPurchaseController**: Stripe integration and subscription management
- **UserExportController**: Premium export functionality
- **AdminControllers**: Background generation and admin dashboard

### Database Models & Relationships
- **User**: Billable trait for Stripe, UUID-based public IDs, soft deletes
- **Meme**: Generated memes with keyword categorization, relationships to media
- **MemeMedia**: Template media with pgvector embeddings for semantic search
- **BackgroundMedia**: Background assets with completion status
- **UserMemeGeneration**: Job tracking for async meme generation
- **UserUsage & UserPlan**: Credit tracking and subscription management
- **Category**: Hierarchical keyword organization (kalnoy/nestedset)

### Key Features
- **Queue-Based Processing**: GenerateMemeJob for async AI generation
- **Cache-Based Job Status**: Redis caching for real-time job status updates
- **Vector Search**: pgvector for semantic content matching
- **Credit System**: CreditsService for usage tracking and payment integration
- **Stripe Integration**: Laravel Cashier for subscriptions and payments
- **Media Processing**: FFmpeg integration for video generation
- **Authentication**: Laravel Sanctum + Google OAuth via Socialite