# Design: Complete All Remaining Tasks with 90%+ Test Coverage

## Context

### Current State
- **Completed Tasks**: ~87/134 tasks (65%) for migrate-to-nextjs-launchui, 44/48 (92%) for fix-dockerfile-nextjs
- **Core MVP Features**: ✅ Authentication, dashboard, portfolio CRUD, responsive design
- **Missing**: Launch UI components, advanced SEO, performance optimization, comprehensive testing, CI/CD pipeline
- **Test Coverage**: Minimal/none for Next.js code (Angular tests preserved in backup)

### Constraints
1. **90% Test Coverage**: Hard requirement across production code
2. **Next.js Best Practices**: Use App Router, RSCs where appropriate, edge cases handled
3. **No Breaking Changes**: All changes additive, backward compatible
4. **Feature Parity**: All functionality working before testing infrastructure added
5. **CI/CD Access**: Must integrate with existing Gitea or GitHub Actions
6. **Performance Targets**:
   - FCP < 1.0s
   - LCP < 1.5s
   - TTI < 2.0s
   - Bundle size ≤ 500KB main JS
7. **Accessibility**: WCAG 2.1 Level AA minimum

## Goals & Non-Goals

### Goals
- ✅ Complete all 51 remaining OpenSpec tasks with deliverables
- ✅ Establish 90%+ test coverage across production code
- ✅ Integrate Launch UI components for professional landing page
- ✅ Optimize performance and SEO for production readiness
- ✅ Configure CI/CD pipeline for automated testing and deployment
- ✅ Enable safe, monitored production rollout with rollback capability
- ✅ Document all testing patterns and deployment procedures

### Non-Goals
- ❌ Rewrite existing working code without clear value add
- ❌ Add testing overhead that slows development
- ❌ Migrate from Angular tests (preserve for reference only)
- ❌ Complex monitoring infrastructure (basic Sentry setup only)
- ❌ E2E testing framework (defer to post-MVP)
- ❌ Multi-language i18n support (beyond English)

## Technical Decisions

### 1. Testing Framework Selection
**Decision**: Jest + React Testing Library

**Rationale**:
- Next.js official recommendation
- 50%+ faster than Jasmine (from Angular era)
- Superior component testing compared to Karma
- Strong TypeScript support with built-in types
- Excellent coverage reporting and parallel execution
- Active ecosystem with good documentation

**Alternatives Considered**:
- Vitest: Faster but less mature in Next.js ecosystem
- Cypress: Better for E2E, overkill for unit tests
- Playwright: Good for E2E, defer to future

### 2. Test Structure & Organization
**Decision**: Co-located `*.test.tsx` files + `__tests__/` for setup/utilities

**Pattern**:
```
components/
├── navbar.tsx
├── navbar.test.tsx
hooks/
├── use-auth.ts
├── use-auth.test.ts
__tests__/
├── setup.ts
├── mocks/
│   ├── api-client.ts
│   └── next-router.ts
├── fixtures/
│   └── mock-data.ts
└── utils/
    └── test-helpers.ts
```

**Rationale**:
- Easy to maintain (tests next to code)
- Clear separation of concerns
- Mocks and utilities reusable
- Scales well with codebase growth

### 3. Coverage Measurement & Thresholds
**Decision**: Jest coverage + enforced minimum thresholds

**Thresholds**:
```json
{
  "global": {
    "branches": 90,
    "functions": 90,
    "lines": 90,
    "statements": 90
  }
}
```

**Exclusions**:
- `next.config.js`, `middleware.ts` - Infrastructure code (jest.config.js pattern)
- `.next/`, `node_modules/`, `angular-backup/` - Built artifacts
- Mock files and test utilities - Meta code

**Rationale**:
- 90% threshold balances rigor with practicality
- 100% coverage leads to brittleness
- Enforced thresholds prevent regression
- Focus on critical paths (auth, API client, forms)

### 4. Mocking Strategy
**Decision**: Centralized mock factory pattern

**Approach**:
- Mock `lib/api-client.ts` globally in setup.ts
- Mock Next.js router with `next/navigation` mock factory
- Mock environment variables in test setup
- Use `jest.mock()` for external dependencies
- Preserve real component rendering (no shallow render)

**Rationale**:
- Isolates unit tests from API
- Consistent mock behavior across tests
- Easier to test error scenarios
- Speeds up test execution

### 5. Launch UI Component Integration
**Decision**: Copy-paste components + local customization

**Approach**:
1. Source Launch UI from GitHub (https://github.com/launch-ui/launch-ui)
2. Copy components to `/components/launch-ui/` with modifications
3. Maintain Tailwind token consistency
4. Document customizations for future updates
5. Include dark mode support infrastructure

**Rationale**:
- shadcn/ui pattern (copy-paste > npm dependency for style control)
- Allows quick fixes without dependency updates
- Responsive and accessible out of the box
- Aligned with project conventions

### 6. SEO & Performance Optimization
**Decision**: Layered optimization strategy

**Implementation**:
1. **Build-time**: Static generation for landing page + metadata
2. **Runtime**: Lazy loading for non-critical components
3. **Network**: Cache-Control headers, SWR patterns
4. **Bundle**: Code splitting via Next.js built-in + manual lazy routes
5. **Assets**: Image optimization via next/image, font subsetting

**Rationale**:
- Multi-layer approach catches different bottlenecks
- Next.js handles most automatically
- Measurable impact on Core Web Vitals
- Aligns with production readiness goals

### 7. CI/CD Pipeline Architecture
**Decision**: GitHub Actions (or Gitea CI) with Docker multi-stage builds

**Stages**:
1. **Lint & Build**: Next.js build, TypeScript check
2. **Test**: Jest with coverage enforcement
3. **Docker Build**: Multi-stage production image
4. **Registry**: Push to container registry (Harbor, Docker Hub)
5. **Deploy**: Staging environment validation
6. **Notify**: Slack/email on success/failure

**Rationale**:
- Detects issues before deployment
- Ensures consistent production builds
- Docker registry integration for CD
- Observable failure points

### 8. Deployment Strategy
**Decision**: Canary/Blue-Green with rollback capability

**Process**:
1. Build and test in CI/CD
2. Deploy to staging, validate
3. Tag production release (v1.0.x semantic versioning)
4. Gradual traffic rollout (10% → 50% → 100%)
5. Monitor for 48 hours post-cutover
6. Rollback plan: Maintain Angular version during transition

**Rationale**:
- Minimizes blast radius of issues
- Allows performance validation before full rollout
- Preserves fallback option
- Aligns with zero-downtime requirement

## Decisions Summary

| Decision | Option | Trade-offs |
|----------|--------|-----------|
| Testing Framework | Jest + React Testing Library | +Modern, -learning curve vs Jasmine |
| Coverage Target | 90% global | +Practical rigor, -edge cases uncovered |
| Component Integration | Copy-paste (shadcn/ui style) | +Control, -update overhead |
| Bundle Strategy | Next.js built-in + manual code splitting | +Performance, -complexity |
| Deployment | Canary rollout with rollback | +Safe, -slower rollout |
| Monitoring | Basic Sentry + CloudWatch | +Visibility, -advanced features deferred |

## Risks & Mitigation

| Risk | Probability | Impact | Mitigation |
|------|-------------|--------|-----------|
| 90% coverage hard to achieve | Medium | High | Focus on critical paths first, exclude infra |
| Launch UI component bugs | Low | Medium | Comprehensive component testing + accessibility tests |
| Performance regression in bundle | Medium | High | Run Lighthouse and bundle analyzer in CI |
| Deployment rollout fails | Low | High | Test in staging, have rollback process |
| CI/CD pipeline misconfigured | Medium | Medium | Document setup, test locally first |
| Test suite becomes slow | Medium | Medium | Parallel execution, mock external calls |

## Migration Plan

### Phase 1: Testing Infrastructure (Days 1-2)
1. Install Jest + React Testing Library + typings
2. Configure jest.config.js, setup.ts, test utilities
3. Create mock factory and test helpers
4. Validate basic test execution

### Phase 2: Core Module Tests (Days 3-5)
1. API client tests (mocking, error handling, auth)
2. Auth context + hooks tests
3. Form validation and submission tests
4. Utility function tests

### Phase 3: Component Tests (Days 6-8)
1. Layout and page component tests
2. Launch UI component tests (with accessibility)
3. Form component tests (login, register, portfolio creation)
4. Dashboard component tests

### Phase 4: Feature Implementation (Days 9-12)
1. Launch UI component integration
2. Landing page enhancements
3. Mobile menu and responsive design
4. SEO optimization (metadata, structured data, sitemaps)

### Phase 5: Performance & Deployment (Days 13-15)
1. Bundle analysis and code splitting
2. Image and font optimization
3. CI/CD pipeline configuration
4. Docker build integration
5. Health checks and monitoring setup

### Phase 6: Validation & Rollout (Days 16-17)
1. Staging deployment and UAT
2. Performance benchmarking
3. Accessibility compliance verification
4. Production release tagging and documentation

## Open Questions

1. **Container Registry**: Harbor, Docker Hub, or GitLab registry? (Affects CI/CD step 4)
2. **Monitoring Service**: Sentry, DataDog, or CloudWatch? (Affects error tracking)
3. **Staging Environment**: Same cluster as prod or separate? (Affects deployment config)
4. **Email Notifications**: Slack webhook or email? (Affects CI/CD notifications)
5. **Load Testing**: Need load test before production? (Affects timeline)

## Success Metrics

- ✅ All 51 tasks marked complete with verifiable deliverables
- ✅ Test coverage ≥90% across production code
- ✅ All tests passing in CI/CD
- ✅ Production build size ≤ 500KB main JS
- ✅ Core Web Vitals targets met (FCP <1s, LCP <1.5s, TTI <2s)
- ✅ WCAG 2.1 AA compliance validated with axe-core
- ✅ Staging deployment successful and stable
- ✅ Zero breaking changes to API contracts
- ✅ Both OpenSpec changes archived and specs updated
