# CLAUDE.md

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

## Project Overview

Black Canyon Tickets is a self-service ticketing platform designed for upscale venues. The platform runs at `portal.blackcanyontickets.com` and serves high-end events like dance performances, weddings, and galas.

## Development Commands

All commands are run from the root directory:

```bash
# Development
npm run dev          # Start development server at localhost:4321
npm run start        # Alias for npm run dev

# Building & Testing
npm run build        # Type check and build for production (8GB memory allocated)
npm run typecheck    # Run Astro type checking only
npm run preview      # Preview production build locally

# Code Quality
npm run lint         # Run ESLint on codebase
npm run lint:fix     # Run ESLint with auto-fix

# Testing
npx playwright test  # Run Playwright end-to-end tests
npx playwright test --headed  # Run tests with visible browser
npx playwright test --ui     # Run tests with Playwright UI

# Database
node setup-schema.js # Initialize database schema (run once)

# Docker Development (IMPORTANT: Always use --no-cache when rebuilding)
npm run docker:build        # Build Docker images using script
npm run docker:up           # Start development containers
npm run docker:down         # Stop development containers
npm run docker:logs         # View container logs
npm run docker:prod:up      # Start production containers
npm run docker:prod:down    # Stop production containers
docker-compose build --no-cache  # Clean rebuild when cache issues occur

# Stripe MCP (Model Context Protocol)
npm run mcp:stripe         # Start Stripe MCP server for AI integration
npm run mcp:stripe:debug   # Start MCP server with debugging interface
```

## Tech Stack

- **Frontend:** Astro 5.x with React islands for interactive components
- **Styling:** Tailwind CSS 4.x with custom glassmorphism design system
- **Database & Auth:** Supabase (PostgreSQL + Supabase Auth)
- **Payments:** Stripe + Stripe Connect for automated payouts and platform fees
- **QR Scanning:** Mobile-friendly browser-based scanner using HTML5 canvas
- **Emails:** Resend for transactional emails
- **Monitoring:** Sentry for error tracking and performance monitoring
- **Hosting:** Self-hosted Node.js with standalone adapter

## Architecture

### Core Application Flow
1. **Authentication**: Supabase Auth with organization-based access control
2. **Event Management**: Multi-tenant system with Row Level Security (RLS)
3. **Ticket Sales**: Inventory management with pessimistic locking
4. **Payment Processing**: Stripe Connect for direct payouts to organizers
5. **QR Scanning**: UUID-based tickets for secure door management

### Key Routes
- `/` - Homepage (public)
- `/login` - Authentication portal
- `/dashboard` - Event list and revenue summary (authenticated)
- `/events/new` - Event creation form (authenticated)
- `/events/[id]/manage` - Comprehensive event management with tabs (authenticated)
- `/e/[slug]` - Public ticket checkout page (embeddable)
- `/scan` - QR scanning interface for door staff (authenticated)
- `/admin/` - Platform administration (admin only)

### Database Schema (Core Tables)
- `organizations`: Multi-tenant isolation with Stripe Connect accounts
- `users`: Organization membership with role-based access
- `events`: Event metadata with slugs and seating configuration
- `ticket_types`: Pricing tiers with inventory tracking
- `tickets`: Individual ticket records with UUIDs for QR codes
- `presale_codes`: Time-limited access codes with usage tracking
- `seating_maps`: Venue layouts for assigned seating events

### Multi-Tenant Security
- **Row Level Security (RLS)**: All tables filtered by organization_id
- **Authentication**: Supabase Auth with organization context
- **Admin Override**: Special admin role bypasses organization filtering
- **API Security**: All API routes validate organization membership

## Key Integrations

### Supabase Configuration
- **URL**: `https://zctjaivtfyfxokfaemek.supabase.co`
- **Environment Variables**: `PUBLIC_SUPABASE_URL`, `PUBLIC_SUPABASE_ANON_KEY`
- **Auth**: Built-in authentication with organization assignment
- **Database**: PostgreSQL with migrations in `/supabase/migrations/`

### Stripe Integration
- **Connect**: Organizers onboard via Stripe Connect for direct payouts
- **Platform Fees**: Automatically split from each transaction
- **Webhooks**: Payment confirmation and dispute handling
- **Environment**: Uses publishable/secret key pairs
- **MCP Server**: AI-powered Stripe operations through Model Context Protocol

### Stripe MCP (Model Context Protocol)
- **Purpose**: AI-powered interactions with Stripe API and knowledge base
- **Tools**: Customer management, payment processing, subscriptions, refunds
- **Configuration**: See `MCP_SETUP.md` for detailed setup instructions
- **Commands**: `npm run mcp:stripe` (production) or `npm run mcp:stripe:debug` (development)
- **Integration**: Works with Claude Desktop and other AI agents

### Design System
- **Theme**: Glassmorphism with dark gradients (see DESIGN_SYSTEM.md)
- **Colors**: Blue/purple gradients with white text on dark backgrounds
- **Layouts**: `Layout.astro` (public), `SecureLayout.astro` (authenticated)
- **Animations**: CSS keyframes for fadeInUp, slideIn, and float effects

## File Structure

```
src/
├── components/          # Reusable UI components
│   ├── Navigation.astro    # Main navigation with auth state
│   ├── TicketCheckout.tsx  # React component for ticket purchasing
│   └── ProtectedRoute.astro # Auth guard wrapper
├── layouts/
│   ├── Layout.astro        # Base layout with SEO and meta
│   └── SecureLayout.astro  # Authenticated layout with glassmorphism
├── lib/                    # Utility modules
│   ├── supabase.ts        # Database client configuration
│   ├── stripe.ts          # Payment processing utilities
│   ├── auth.ts            # Authentication helpers
│   ├── database.types.ts  # Generated TypeScript types
│   └── validation.ts      # Form validation schemas
├── middleware.ts           # Security headers and HTTPS redirect
├── pages/
│   ├── api/               # API endpoints
│   │   ├── inventory/     # Ticket reservation and purchase
│   │   ├── webhooks/      # External service callbacks
│   │   └── admin/         # Admin-only endpoints
│   ├── events/[id]/
│   │   └── manage.astro   # Complex event management interface
│   └── e/[slug].astro     # Public ticket sales page
└── styles/
    ├── global.css         # Global styles and imports
    └── glassmorphism.css  # Design system utilities
```

## Development Patterns

### Component Architecture
- **Astro Components**: Server-rendered with minimal JavaScript
- **React Islands**: Interactive components (forms, real-time updates)
- **TypeScript**: Strict typing with generated database types
- **Props Validation**: Zod schemas for API and form validation

### State Management
- **Server State**: Supabase real-time subscriptions
- **Client State**: React hooks for interactive components
- **Form State**: Native form handling with progressive enhancement
- **Auth State**: Supabase auth context with organization data

### API System
- **Centralized API Client**: `/src/lib/api-client.ts` - Main client with authentication
- **API Router**: `/src/lib/api-router.ts` - Browser-friendly wrapper for common operations
- **Authentication**: Automatic session management and organization context
- **Error Handling**: Consistent error responses with user-friendly messages
- **Usage**: Use `import { api } from '../lib/api-router'` in components

#### API System Usage Examples:
```typescript
// In Astro components (client-side scripts)
const { api } = await import('../lib/api-router');

// Load event stats
const stats = await api.loadEventStats(eventId);

// Load event details
const event = await api.loadEventDetails(eventId);

// Load complete event page data
const { event, stats, error } = await api.loadEventPage(eventId);

// Format currency and dates
const formattedPrice = api.formatCurrency(priceInCents);
const formattedDate = api.formatDate(dateString);
```

### API Design
- **RESTful**: Standard HTTP methods with proper status codes
- **Authentication**: Automatic Supabase JWT validation on all API calls
- **Error Handling**: Consistent error responses with user-friendly messages
- **Rate Limiting**: Built-in protection against abuse

## Security Implementation

### Content Security Policy
- **Strict CSP**: Defined in middleware.ts with Stripe and Supabase exceptions
- **HTTPS**: Forced in production with HSTS headers
- **XSS Protection**: Content type validation and frame options

### Data Protection
- **Row Level Security**: Database-level access control
- **Input Validation**: Zod schemas for all user inputs
- **SQL Injection**: Parameterized queries via Supabase client
- **Secrets Management**: Environment variables for all sensitive data

## Testing & Monitoring

### Testing Strategy
- **End-to-End Tests**: Playwright for critical user flows and authentication
- **Test Configuration**: `playwright.config.js` configured for localhost:3000
- **Test Files**: Pattern `test-*.js` and `test-*.cjs` for various scenarios
- **Test Execution**: Tests assume server is running (use `npm run dev` first)
- **Authentication Tests**: Comprehensive login/logout flow validation
- **Mobile Testing**: Responsive design and mobile menu testing

### Error Tracking
- **Sentry**: Configured for both client and server-side errors (currently disabled in config)
- **Logging**: Winston for server-side logging to files
- **Performance**: Sentry performance monitoring enabled

### Environment Variables Required
```bash
# Supabase
PUBLIC_SUPABASE_URL=https://zctjaivtfyfxokfaemek.supabase.co
PUBLIC_SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ...

# Stripe
STRIPE_PUBLISHABLE_KEY=pk_...
STRIPE_SECRET_KEY=sk_...
STRIPE_WEBHOOK_SECRET=whsec_...

# Email
RESEND_API_KEY=re_...

# Monitoring
SENTRY_DSN=https://...
```

## Common Development Tasks

### Adding New Features
1. **Database Changes**: Add migration to `/supabase/migrations/`
2. **API Endpoints**: Create in `/src/pages/api/` with proper validation
3. **UI Components**: Follow glassmorphism design system patterns
4. **Types**: Update `database.types.ts` or regenerate from Supabase
5. **Testing**: Add Playwright tests for critical user flows
6. **Code Quality**: Run `npm run lint:fix` before committing

### Build Configuration
- **Memory Optimization**: Build script uses `--max-old-space-size=8192` for large builds
- **Standalone Mode**: Node.js adapter configured for self-hosting
- **Server Configuration**: Default port 3000 with HMR support

### Event Management System
The `/events/[id]/manage.astro` page is the core of the platform:
- **Tab-based Interface**: Tickets, Venue, Orders, Attendees, Analytics
- **Real-time Updates**: Supabase subscriptions for live data
- **Complex State**: Multiple modals and forms with validation
- **Responsive Design**: Mobile-first with glassmorphism effects

### QR Code System
- **Generation**: UUID-based tickets prevent enumeration
- **Scanning**: HTML5 camera API with canvas processing
- **Validation**: Server-side verification with attendance tracking
- **Security**: Tamper-proof tickets with database verification

## Important Notes

- **Mobile-First**: Scanner interface optimized for phone screens
- **Performance**: Glassmorphism effects may impact mobile performance
- **Accessibility**: WCAG AA compliance maintained throughout
- **SEO**: Server-side rendering for public pages
- **Multi-tenant**: All features must respect organization boundaries

## Authentication System - CRITICAL FIX APPLIED

### Login Loop Issue (RESOLVED)
**Problem**: Users experienced infinite login loops where successful authentication would redirect to dashboard, then immediately back to login page.

**Root Cause**: Client-server authentication mismatch due to httpOnly cookies:
- Login API sets httpOnly cookies using server-side Supabase client ✅
- Dashboard server reads httpOnly cookies correctly ✅  
- Dashboard client script tried to read httpOnly cookies using client-side Supabase ❌

**Solution Implemented**:
1. **Fixed Admin Dashboard**: Removed non-existent `is_super_admin` column references in `/src/pages/admin/dashboard.astro`
2. **Created Auth Check API**: `/src/pages/api/admin/auth-check.ts` provides server-side auth validation for client scripts
3. **Updated Admin API Router**: `/src/lib/admin-api-router.ts` now uses auth check API instead of client-side Supabase

**Key Files Modified**:
- `/src/pages/admin/dashboard.astro` - Fixed database queries
- `/src/pages/api/admin/auth-check.ts` - NEW: Server-side auth validation API
- `/src/lib/admin-api-router.ts` - Uses API calls instead of client-side auth
- `/src/pages/api/auth/session.ts` - Return 200 status for unauthenticated users
- `/src/pages/login.astro` - Enhanced cache clearing and session management

**Testing**: Automated Playwright tests in `/test-login.js` validate end-to-end login flow

**Documentation**: See `AUTHENTICATION_FIX.md` for complete technical details

**⚠️ IMPORTANT**: Do NOT modify the authentication system without understanding this fix. The httpOnly cookie approach is intentional for security and requires server-side validation for client scripts.

## Calendar System - RENDERING ISSUES FIXED

### Calendar Page Rendering (RESOLVED)
**Problem**: Calendar page was not rendering correctly and required authentication when it should be public.

**Root Cause**: Multiple issues affecting calendar functionality:
- Authentication requirement blocking public access
- Theme system defaulting to light mode instead of dark mode for glassmorphism
- Dual calendar implementations causing confusion

**Solution Implemented**:
1. **Made Calendar Public**: Removed authentication requirement from `/src/pages/calendar.astro`
2. **Fixed Theme System**: Changed default theme to dark mode for better glassmorphism appearance
3. **Chose Primary Implementation**: Regular calendar (`/calendar`) is the primary working implementation

**Key Files Modified**:
- `/src/pages/calendar.astro` - Removed auth requirement, fixed theme default
- `/src/pages/calendar-enhanced.astro` - Removed forced dark mode theme blocking

**Current Status**: 
- ✅ Calendar page loads correctly at `/calendar` 
- ✅ Beautiful glassmorphism theme with purple gradients
- ✅ Full calendar functionality (navigation, filters, search, view toggles)
- ✅ All navigation links point to working calendar page
- ✅ Responsive design works on desktop and mobile
- ⚠️ Enhanced calendar at `/calendar-enhanced` has React component mounting issues (not used in production)

## Development Workflow

### Code Quality Standards
- **ESLint**: Configured with TypeScript support and custom rules
- **Astro Files**: ESLint parsing disabled for `.astro` files
- **TypeScript**: Strict typing enforced with generated database types
- **Unused Variables**: Warnings for unused vars (prefix with `_` to ignore)

### Before Committing
1. Run `npm run lint:fix` to fix code style issues
2. Run `npm run typecheck` to validate TypeScript
3. Run `npm run build` to ensure production build works
4. Test critical flows with `npx playwright test`

### Development Server
- **Port**: Defaults to 3000 (configurable via PORT env var)
- **HMR**: Hot module replacement enabled on all interfaces
- **Security**: Origin checking enabled for production security