# Project Context

## Purpose

This is a **Portfolio Hosting Management Platform** - a SaaS application that enables users to create, upload, deploy, and manage their portfolio websites with custom domains. Users can register for accounts, upload portfolio content as ZIP files, and deploy them to custom domains with automated hosting infrastructure.

### Primary Goals
- Provide a simple, user-friendly interface for portfolio deployment
- Enable non-technical users to host professional portfolio websites
- Support multiple portfolios per user with custom domain mapping
- Offer seamless file upload and deployment workflows
- Display public portfolio examples to attract new users

## Tech Stack

### Current Stack (Angular - To Be Migrated)
- **Frontend Framework**: Angular 20 (standalone components)
- **Language**: TypeScript 5.8.2
- **Styling**: Tailwind CSS 4.1.8
- **State Management**: RxJS 7.8.0 (BehaviorSubjects)
- **Forms**: Angular Reactive Forms
- **HTTP Client**: Angular HttpClient with interceptors
- **Routing**: Angular Router
- **Testing**: Jasmine 5.7.0 + Karma 6.4.0
- **Build Tool**: Angular CLI 20.0.0
- **Package Manager**: npm

### Target Stack (Next.js - Migration in Progress)
- **Frontend Framework**: Next.js 15 (App Router)
- **UI Component Library**: Launch UI (shadcn/ui + Tailwind CSS 4.0)
- **Language**: TypeScript 5.0
- **Styling**: Tailwind CSS 4.0
- **State Management**: React Context API + hooks
- **Forms**: React Hook Form
- **HTTP Client**: Native fetch with custom wrapper
- **Icons**: Lucide React
- **Testing**: Jest + React Testing Library
- **Build Tool**: Next.js + Turbopack
- **Package Manager**: npm

### Backend (Unchanged)
- **API Server**: Separate backend service (not part of this repository)
- **Authentication**: JWT Bearer tokens
- **API Base URL**:
  - Development: `http://localhost:8000/api`
  - Production: `https://api.portfolio-host.com/api`

### Infrastructure
- **Containerization**: Docker (Dockerfile in repository)
- **Deployment**: Kubernetes with Ingress
- **Version Control**: Git (current branch: `main`)

## Project Conventions

### Code Style

#### TypeScript
- **Strict Mode**: Enabled (`strict: true` in tsconfig.json)
- **Null Checks**: Enforced (`strictNullChecks: true`)
- **Explicit Types**: Required (`noImplicitAny: true`)
- **Target**: ES2022

#### Naming Conventions
- **Files**: kebab-case (e.g., `api-client.ts`, `auth-provider.tsx`)
- **Components**: PascalCase (e.g., `LoginComponent`, `DashboardPage`)
- **Functions/Variables**: camelCase (e.g., `getUserData`, `isAuthenticated`)
- **Constants**: UPPER_SNAKE_CASE (e.g., `API_BASE_URL`, `MAX_FILE_SIZE`)
- **Interfaces/Types**: PascalCase with descriptive names (e.g., `Portfolio`, `ApiResponse<T>`)

#### Code Organization (Next.js Target)
- **Components**: `/components` directory, grouped by feature or UI library
  - `/components/launch-ui/` - Launch UI components
  - `/components/ui/` - shadcn/ui primitives
  - `/components/auth/` - Authentication-related components
- **Pages**: `/app` directory using App Router conventions
- **Utilities**: `/lib` directory for shared utilities and API client
- **Hooks**: `/hooks` directory for custom React hooks
- **Types**: `/lib/types.ts` or co-located with features

#### Formatting
- **Indentation**: 2 spaces (no tabs)
- **Quotes**: Single quotes for strings (except JSX attributes use double quotes)
- **Semicolons**: Required
- **Line Length**: 100 characters (soft limit)
- **Trailing Commas**: Yes (for multi-line arrays/objects)

### Architecture Patterns

#### Component Architecture (Next.js)
- **React Server Components (RSC)**: Default for pages and non-interactive components
- **Client Components**: Explicitly marked with `'use client'` directive
- **Composition Over Inheritance**: Prefer component composition
- **Single Responsibility**: Each component has one clear purpose

#### State Management
- **Global State**: React Context API for authentication and user data
- **Local State**: `useState` for component-level state
- **Server State**: `useEffect` + fetch for data fetching (consider SWR/React Query for future enhancement)
- **Form State**: React Hook Form for all forms

#### API Integration
- **API Client Pattern**: Centralized fetch wrapper in `/lib/api-client.ts`
- **Generic Methods**: Typed request methods (`get<T>`, `post<T>`, etc.)
- **Error Handling**: Centralized error handling with automatic 401 logout
- **Authentication**: Bearer token injection via function wrapper (not middleware in fetch)
- **Response Model**: All API responses follow `ApiResponse<T>` interface

#### Routing Strategy
- **File-Based Routing**: Next.js App Router (`/app` directory)
- **Protected Routes**: Middleware-based authentication check
- **Layouts**: Shared layouts in `layout.tsx` files
- **Metadata**: Page-level SEO metadata using Next.js metadata API

#### Styling Strategy
- **Utility-First CSS**: Tailwind CSS utilities for all styling
- **Component Variants**: shadcn/ui variant patterns (e.g., `variant="outline"`)
- **Responsive Design**: Mobile-first breakpoints (sm, md, lg, xl, 2xl)
- **Custom Themes**: Extend Tailwind config for brand colors and typography
- **CSS Modules**: Avoid - prefer Tailwind utilities

### Testing Strategy

#### Current (Angular - To Be Replaced)
- **Unit Tests**: Jasmine + Karma for component and service tests
- **Test Location**: `*.spec.ts` files co-located with source files
- **Coverage Target**: Not formally defined

#### Target (Next.js)
- **Unit Tests**: Jest + React Testing Library
- **Component Tests**: Test user interactions and rendering
- **Integration Tests**: Test authentication flows and API interactions
- **E2E Tests**: (Future) Playwright or Cypress for critical user journeys
- **Test Location**: `*.test.tsx` or `__tests__/` directories
- **Coverage Target**: 70%+ for critical paths (auth, API client)
- **Accessibility Tests**: axe-core integration for WCAG 2.1 AA compliance

#### Testing Principles
- Test user behavior, not implementation details
- Mock external API calls in unit tests
- Use integration tests for authentication flow validation
- Validate form validation logic thoroughly
- Test error states and edge cases

### Git Workflow

#### Branching Strategy
- **Main Branch**: `main` (production-ready code)
- **Feature Branches**: `feature/<feature-name>` (e.g., `feature/nextjs-migration`)
- **Bugfix Branches**: `fix/<bug-description>` (e.g., `fix/login-redirect`)
- **Hotfix Branches**: `hotfix/<issue>` for production issues

#### Commit Conventions
- **Format**: `<type>(<scope>): <subject>`
- **Types**:
  - `feat`: New feature
  - `fix`: Bug fix
  - `refactor`: Code refactoring
  - `docs`: Documentation changes
  - `style`: Formatting changes
  - `test`: Adding or updating tests
  - `chore`: Build tasks, dependencies

**Examples**:
- `feat(auth): implement JWT token refresh`
- `fix(dashboard): correct portfolio status badge logic`
- `refactor(api): migrate from Angular HttpClient to fetch`

#### Pull Request Process
- Create PR with descriptive title and summary
- Link related issues or OpenSpec changes
- Request code review from at least one team member
- Ensure CI/CD checks pass (tests, linting, build)
- Squash commits before merging to main

## Domain Context

### Core Domain Concepts

#### Portfolio
A user's website project that can be uploaded, deployed, and hosted.
- **Status States**:
  - `Inactive` - Payment pending (not active)
  - `Pending Upload` - Active but no files uploaded (no path)
  - `Uploaded` - Files uploaded, ready for deployment (has path)
- **Deployment**: Portfolio ZIP files are extracted and served at custom domains
- **Domain Mapping**: Each portfolio has a unique domain (user-defined)

#### User Authentication
- **Registration**: Users provide name, email, and password
- **Login**: Email/password authentication returns JWT token
- **Session Management**: JWT tokens stored in localStorage, included in API requests
- **Token Refresh**: Backend supports token refresh endpoint

#### File Upload
- **Format**: ZIP files containing portfolio HTML/CSS/JS
- **Process**: Upload → Extract → Deploy to domain
- **Size Limits**: (Backend-defined, not enforced in frontend)

### User Roles
Currently single-role system:
- **Authenticated User**: Can create, upload, and manage their own portfolios

### Key User Flows

1. **New User Registration**
   - User visits landing page
   - Clicks "Sign Up" → Registration form
   - Submits name, email, password → Backend creates account
   - Redirects to login page

2. **Existing User Login**
   - User navigates to /login
   - Submits email + password
   - Receives JWT token → Stored in localStorage
   - Redirects to dashboard

3. **Portfolio Creation & Deployment**
   - User creates new portfolio (name + domain)
   - Uploads ZIP file → Backend processes
   - Clicks "Deploy" → Portfolio goes live at custom domain
   - Visits domain to view live portfolio

4. **Portfolio Example Discovery**
   - Visitor on landing page clicks "View Example"
   - Random portfolio fetched from API
   - Redirects to example portfolio domain

## Important Constraints

### Technical Constraints
- **API Compatibility**: Frontend must remain compatible with existing backend API (no backend changes allowed during migration)
- **JWT Token Format**: Must preserve existing JWT authentication pattern
- **Bundle Size**: Next.js production bundle should be ≤500KB (main JS)
- **Browser Support**: Modern browsers (Chrome, Firefox, Safari, Edge - latest 2 versions)
- **TypeScript Version**: Next.js migration requires TypeScript 5.0 (downgrade from 5.8)
- **Mobile Responsiveness**: Must support viewports down to 375px width

### Business Constraints
- **Zero Downtime Deployment**: Migration must not cause service interruption
- **Session Preservation**: Minimize user re-authentication during migration (stretch goal)
- **Feature Parity**: All Angular features must be replicated in Next.js version before cutover
- **Performance Requirements**: Core Web Vitals must meet or exceed current benchmarks
  - First Contentful Paint (FCP): <1.0s
  - Largest Contentful Paint (LCP): <1.5s
  - Time to Interactive (TTI): <2.0s

### Design Constraints
- **UI Library**: Launch UI (free version) must be used for landing page components
- **Accessibility**: WCAG 2.1 Level AA compliance required
- **SEO**: Server-side rendering required for public pages (landing, login, register)

### Infrastructure Constraints
- **Deployment Platform**: Must remain Docker-based (Dockerfile required)
- **Environment Variables**: Must support development and production configurations
- **Reverse Proxy**: Deployment assumes reverse proxy/Ingress for routing

## External Dependencies

### APIs
- **Backend API**: RESTful API for authentication and portfolio management
  - Base URL: `{environment.apiUrl}/api`
  - Endpoints: `/auth/*`, `/portfolios/*`, `/portfolio/random`
  - Authentication: Bearer token (JWT)
  - Response Format: `{ success: boolean, data?: T, message?: string, errors?: any }`

### Third-Party Libraries
- **Launch UI**: Open-source UI component library (MIT license)
  - Repository: https://github.com/launch-ui/launch-ui
  - Components: Navbar, Hero, Items, Logos, FAQ, Stats, CTA, Footer
  - Foundation: shadcn/ui + Tailwind CSS
- **shadcn/ui**: Headless component library (copy-paste components)
- **Lucide Icons**: Icon library (MIT license)
- **Tailwind CSS**: Utility-first CSS framework (MIT license)

### Build & Development Tools
- **Next.js**: React framework (MIT license)
- **TypeScript**: JavaScript superset (Apache 2.0)
- **PostCSS**: CSS processing (MIT license)
- **Autoprefixer**: CSS vendor prefixing (MIT license)

### Testing & Quality Tools
- **Jest**: Testing framework (MIT license)
- **React Testing Library**: Component testing (MIT license)
- **axe-core**: Accessibility testing (Mozilla Public License 2.0)

## Migration Notes

### Current Status
- **Phase**: Planning and proposal stage (OpenSpec change in progress)
- **Change ID**: `migrate-to-nextjs-launchui`
- **Affected Capabilities**: frontend, ui-components, authentication, routing, state-management

### Key Decisions
1. **Next.js App Router** over Pages Router (future-proof, Launch UI compatibility)
2. **React Hook Form** for form management (performance, TypeScript support)
3. **React Context API** for state (simplicity, adequate for scale)
4. **Native fetch** with custom wrapper (Next.js optimization, smaller bundle)
5. **Parallel deployment** strategy (risk mitigation, gradual rollout)

### Post-Migration Conventions
Once migration is complete, this section will be removed and the conventions above will reflect the Next.js stack as the primary architecture.
