# 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
npm run typecheck    # Run Astro type checking only
npm run preview      # Preview production build locally

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

## 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

### 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 Design
- **RESTful**: Standard HTTP methods with proper status codes
- **Authentication**: Supabase JWT validation on all protected routes
- **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

### Error Tracking
- **Sentry**: Configured for both client and server-side errors
- **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

### 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