# MaplePress Frontend Documentation

This directory contains comprehensive documentation for the MaplePress React frontend application.

## Documentation Index

### Architecture & Design

- **[FRONTEND_ARCHITECTURE.md](./FRONTEND_ARCHITECTURE.md)** - Complete architecture guide
  - Three-layer service architecture (API → Manager → Storage)
  - Dependency injection system
  - Component patterns
  - Authentication & authorization
  - State management
  - Best practices and conventions

- **[ARCHITECTURE_SIMPLE.md](./ARCHITECTURE_SIMPLE.md)** - Quick reference guide
  - Project structure overview
  - Key concepts
  - Technology stack
  - Development workflow

### API Integration Guides

All API integration guides are located in the [API](./API/) subdirectory.

- **[HEALTH_API.md](./API/HEALTH_API.md)** - Health Check
  - Backend service health verification
  - Backend API integration (`GET /health`)
  - HealthService implementation
  - Monitoring and availability checks
  - Application startup verification
  - Load balancer health probes

- **[REGISTRATION_API.md](./API/REGISTRATION_API.md)** - User Registration
  - Complete registration flow implementation
  - Backend API integration (`POST /api/v1/register`)
  - RegisterService implementation
  - Form validation and error handling
  - Token storage and session management
  - Testing procedures

- **[LOGIN_API.md](./API/LOGIN_API.md)** - User Login
  - Complete login flow implementation
  - Backend API integration (`POST /api/v1/login`)
  - LoginService implementation
  - Rate limiting and account lockout
  - Token management
  - Error handling and recovery

- **[REFRESH_TOKEN_API.md](./API/REFRESH_TOKEN_API.md)** - Token Refresh
  - Complete token refresh implementation
  - Backend API integration (`POST /api/v1/refresh`)
  - RefreshTokenService implementation
  - Automatic token refresh (proactive and reactive)
  - Token rotation and security
  - Session persistence and validation

- **[HELLO_API.md](./API/HELLO_API.md)** - Hello (Authenticated Endpoint)
  - Simple authenticated endpoint for testing
  - Backend API integration (`POST /api/v1/hello`)
  - HelloService implementation
  - Input validation and XSS prevention
  - Authentication verification
  - Use cases for testing tokens

- **[ME_API.md](./API/ME_API.md)** - User Profile (Me Endpoint)
  - Get authenticated user's profile
  - Backend API integration (`GET /api/v1/me`)
  - MeService implementation
  - Role-based access control helpers
  - Tenant context verification
  - Profile display and validation

- **[TENANT_API.md](./API/TENANT_API.md)** - Tenant Management
  - Create and manage tenants (organizations)
  - Backend API integration (`POST /api/v1/tenants`, `GET /api/v1/tenants/{id}`, `GET /api/v1/tenants/slug/{slug}`)
  - TenantService implementation
  - Slug generation and validation helpers
  - Multi-tenant architecture support
  - Organization management

- **[USER_API.md](./API/USER_API.md)** - User Management
  - Create and manage users within tenants
  - Backend API integration (`POST /api/v1/users`, `GET /api/v1/users/{id}`)
  - UserService implementation
  - Tenant context and multi-tenant isolation
  - Email and name validation helpers
  - Team member management

- **[SITE_API.md](./API/SITE_API.md)** - WordPress Site Management
  - Create and manage WordPress sites
  - Backend API integration (`POST /api/v1/sites`, `GET /api/v1/sites`, `GET /api/v1/sites/{id}`, `DELETE /api/v1/sites/{id}`, `POST /api/v1/sites/{id}/rotate-api-key`)
  - SiteService implementation
  - API key management (shown only once, rotation with grace period)
  - Site usage statistics and storage tracking
  - Pagination support for large site lists
  - Hard delete with immediate key invalidation

- **[ADMIN_API.md](./API/ADMIN_API.md)** - Admin Account Management
  - Check account lock status and unlock accounts
  - Backend API integration (`GET /api/v1/admin/account-status`, `POST /api/v1/admin/unlock-account`)
  - AdminService implementation
  - CWE-307 protection (excessive authentication attempts)
  - Security event logging for audit trail
  - Admin role enforcement
  - Account lockout management

## Getting Started

### For Developers

If you're new to the project, start here:

1. **Read [FRONTEND_ARCHITECTURE.md](./FRONTEND_ARCHITECTURE.md)** - Understand the overall architecture
2. **Check [HEALTH_API.md](./API/HEALTH_API.md)** - Verify backend connectivity and health
3. **Review [REGISTRATION_API.md](./API/REGISTRATION_API.md)** - See a complete feature implementation
4. **Check [LOGIN_API.md](./API/LOGIN_API.md)** - Understand authentication flow
5. **Read [REFRESH_TOKEN_API.md](./API/REFRESH_TOKEN_API.md)** - Learn about automatic session maintenance
6. **Try [HELLO_API.md](./API/HELLO_API.md)** - Test authentication with a simple endpoint
7. **Use [ME_API.md](./API/ME_API.md)** - Get user profile and implement role-based access
8. **Explore [TENANT_API.md](./API/TENANT_API.md)** - Manage tenants for multi-tenant architecture
9. **Implement [SITE_API.md](./API/SITE_API.md)** - Manage WordPress sites with API key management
10. **Admin [ADMIN_API.md](./API/ADMIN_API.md)** - Admin operations for account lockout management

### For Contributors

When adding new features:

1. Follow the three-layer service pattern (API → Manager → Storage)
2. Use dependency injection via Services.jsx
3. Create comprehensive documentation similar to existing API guides
4. Include testing procedures and troubleshooting

## Project Structure

```
maplepress-frontend/
├── docs/                        # This directory
│   ├── README.md               # This file
│   ├── FRONTEND_ARCHITECTURE.md # Complete architecture guide
│   ├── ARCHITECTURE_SIMPLE.md  # Quick reference
│   ├── ACCESS_REFRESH_TOKEN_IMPLEMENTATION.md # Token refresh guide
│   ├── TOKEN_REFRESH_ANALYSIS.md # Token refresh analysis
│   └── API/                    # API integration guides
│       ├── REGISTRATION_API.md
│       ├── LOGIN_API.md
│       ├── REFRESH_TOKEN_API.md
│       ├── HELLO_API.md
│       ├── ME_API.md
│       ├── TENANT_API.md
│       ├── USER_API.md
│       ├── SITE_API.md
│       └── ADMIN_API.md
│
├── src/
│   ├── services/               # Service layer
│   │   ├── API/               # API services (HTTP)
│   │   ├── Manager/           # Manager services (orchestration)
│   │   └── Services.jsx       # Service registry + DI
│   │
│   ├── pages/                 # Page components
│   │   ├── Home/             # Landing page
│   │   ├── Auth/             # Login/Register
│   │   └── Dashboard/        # User dashboard
│   │
│   ├── hooks/                # Custom React hooks
│   ├── App.jsx               # Main app with routing
│   └── main.jsx              # Entry point
│
├── README.md                  # Project overview
└── package.json              # Dependencies
```

## Architecture Overview

### Three-Layer Service Pattern

```
┌─────────────────────────────────────────┐
│         React Components                │
│         (UI Layer)                      │
└─────────────────┬───────────────────────┘
                  │
                  ↓
┌─────────────────────────────────────────┐
│      Manager Layer (Orchestration)      │
│   - AuthManager                         │
│   - Business logic                      │
│   - State management                    │
└─────────────────┬───────────────────────┘
                  │
                  ↓
┌─────────────────────────────────────────┐
│      API Layer (HTTP Communication)     │
│   - RegisterService                     │
│   - LoginService                        │
│   - ApiClient                          │
└─────────────────┬───────────────────────┘
                  │
                  ↓
┌─────────────────────────────────────────┐
│      Backend API                        │
│   POST /api/v1/register                 │
│   POST /api/v1/login                    │
└─────────────────────────────────────────┘
```

### Service Registration (Dependency Injection)

All services are registered in `Services.jsx`:

```javascript
// Create services with dependencies
const authManager = new AuthManager();
const apiClient = ApiClient;

// Register in context
const services = {
  authManager,
  apiClient,
};

// Use in components
const { authManager } = useAuth();
```

## Implementation Status

### ✅ Completed Features

- **Authentication System**
  - User registration with full form validation
  - User login with rate limiting support
  - Token storage and management
  - Session persistence
  - Token expiry detection

- **Service Layer**
  - Dependency injection system
  - AuthManager (token storage, session management, automatic refresh)
  - HealthService (backend health checks and monitoring)
  - RegisterService (registration API)
  - LoginService (login API)
  - RefreshTokenService (token refresh API)
  - HelloService (authenticated test endpoint)
  - MeService (user profile and role checking)
  - TenantService (tenant/organization management)
  - UserService (user management with tenant context)
  - SiteService (WordPress site management with API key handling)
  - AdminService (admin account management and lockout handling)
  - ApiClient (HTTP client with automatic token refresh)

- **User Interface**
  - Home/landing page
  - Registration page (complete)
  - Login page (complete)
  - Dashboard page (stub)

### 🚧 In Progress / Planned

- Protected route guards
- Logout API integration
- Password recovery flow
- User profile management
- Site management UI
- API key management
- Search configuration

## Testing

### Running Tests

```bash
# Build test
npm run build

# Development server
npm run dev

# Linting
npm run lint
```

### Manual Testing

See individual API guides for testing procedures:
- [Registration Testing](./API/REGISTRATION_API.md#testing-the-registration-flow)
- [Login Testing](./API/LOGIN_API.md#testing-the-login-flow)

## Backend Integration

### API Endpoints

The frontend integrates with these backend endpoints:

- `GET /health` - Backend health check (no auth)
- `POST /api/v1/register` - User registration
- `POST /api/v1/login` - User login
- `POST /api/v1/refresh` - Token refresh
- `POST /api/v1/hello` - Authenticated test endpoint
- `GET /api/v1/me` - Get user profile
- `POST /api/v1/tenants` - Create tenant
- `GET /api/v1/tenants/{id}` - Get tenant by ID
- `GET /api/v1/tenants/slug/{slug}` - Get tenant by slug
- `POST /api/v1/users` - Create user (requires tenant context)
- `GET /api/v1/users/{id}` - Get user by ID (requires tenant context)
- `POST /api/v1/sites` - Create WordPress site
- `GET /api/v1/sites` - List WordPress sites (paginated)
- `GET /api/v1/sites/{id}` - Get WordPress site by ID
- `DELETE /api/v1/sites/{id}` - Delete WordPress site
- `POST /api/v1/sites/{id}/rotate-api-key` - Rotate site API key
- `GET /api/v1/admin/account-status` - Check account lock status (admin)
- `POST /api/v1/admin/unlock-account` - Unlock locked account (admin)

### Backend Documentation

For complete backend API documentation, see:
- [Backend API Documentation](../../../cloud/maplepress-backend/docs/API.md)

## Contributing

When adding new documentation:

1. **Create detailed guides** for new features (see existing API docs)
2. **Update this README** to include new documentation
3. **Follow existing patterns** for consistency
4. **Include examples** and testing procedures
5. **Add troubleshooting** sections

### Documentation Standards

- Use clear, descriptive headings
- Include code examples
- Provide testing procedures
- Add troubleshooting sections
- Keep table of contents updated
- Use diagrams where helpful

## Support & Resources

### Internal Resources

- [Main README](../README.md) - Project overview and setup
- [Backend API Docs](../../../cloud/mapleopentech-backend/docs/API.md) - Complete API reference
- [CLAUDE.md](../../../CLAUDE.md) - Repository structure and conventions

### External Resources

- [React 19 Documentation](https://react.dev)
- [Vite Documentation](https://vite.dev)
- [TailwindCSS Documentation](https://tailwindcss.com)
- [React Router Documentation](https://reactrouter.com)

## Questions & Issues

For questions or issues:
1. Check the relevant documentation first
2. Review troubleshooting sections in API guides
3. Check backend logs for API errors
4. Create an issue with detailed information

---

**Last Updated**: October 30, 2024
**Frontend Version**: 0.0.0
**Documentation Version**: 1.0.0
