> ## Documentation Index
> Fetch the complete documentation index at: https://docs.adhdsimple.co.uk/llms.txt
> Use this file to discover all available pages before exploring further.

# Frontend Architecture

> React application architecture with service layer integration

## Architecture

```mermaid theme={null}
graph TB
    Browser[Browser] --> App[App.tsx]
    App --> Router[React Router]
    Router --> Auth[AuthRoute]
    Auth --> Protected[ProtectedRoute]
    Protected --> Pages[Page Components]
    
    subgraph "Core Pages"
        Pages --> Login[LoginPage]
        Pages --> Dashboard[HomePage]
        Pages --> Patients[PatientsPage]
        Pages --> Settings[SettingsPage]
    end
    
    subgraph "Shared Components"
        Layout[Layout Component]
        Dialogs[Dialog Components]
        Forms[Form Components]
    end
    
    subgraph "Service Layer"
        CoreServices[Core Services]
        FeatureServices[Feature Services]
        ServiceUtils[Service Utilities]
    end
    
    subgraph "State Management"
        Context[AuthContext]
        Hooks[Custom Hooks]
        ServiceLayer[Service Layer]
    end
    
    Pages --> Layout
    Pages --> Dialogs
    Pages --> Forms
    Layout --> Context
    Hooks --> Context
    Context --> ServiceLayer
    Pages --> CoreServices
    Pages --> FeatureServices
    Hooks --> CoreServices
    Hooks --> FeatureServices
    CoreServices --> ServiceUtils
    FeatureServices --> ServiceUtils
    ServiceLayer --> Edge[Edge Functions]
```

## Core Components

### App.tsx

* **Purpose**: Application entry point and routing
* **Technology**: React Router v6
* **Key Functions**:
  * Route configuration
  * Authentication wrapper
  * Global error boundary

### AuthRoute

* **Purpose**: Authentication guard for protected routes
* **Technology**: React context and hooks
* **Key Functions**:
  * Login status checking
  * 2FA verification
  * Redirect to login

### Layout Component

* **Purpose**: Consistent page layout and navigation
* **Technology**: Material-UI components
* **Key Functions**:
  * Header with user menu
  * Navigation sidebar
  * Responsive design

## Page Components

### LoginPage

* **Purpose**: User authentication interface
* **Technology**: React Hook Form with validation
* **Key Functions**:
  * Email/password input
  * 2FA code verification
  * Error handling via AuthService

### PatientsPage

* **Purpose**: Patient management interface
* **Technology**: Material-UI DataGrid + PatientService
* **Key Functions**:
  * Patient list display
  * Search and filtering
  * Add patient dialog

### PatientDetailPage

* **Purpose**: Individual patient record management
* **Technology**: React forms with service integration
* **Key Functions**:
  * Patient information display
  * Prescription management via PrescriptionService
  * Health metrics tracking via PatientService

## Service Layer Integration

### Core Services

* **PatientService**: Patient CRUD operations, health metrics, monitoring
* **PrescriptionService**: Prescription orders, item management, charge calculations
* **MedicationService**: Medication library, active medication tracking
* **AuthService**: User authentication, session management, MFA support

### Feature Services

* **ShipmentService**: Shipment creation, tracking, label generation
* **PaymentService**: Payment settings, Stripe integration
* **PatientRequestService**: Patient app request management
* **AddressService**: UK postcode lookup, address validation
* **ClinicService**: Clinic settings and configuration
* **DeliveryService**: Delivery fee calculation
* **PharmacyService**: Order management, pharmacy statistics

### Service Usage Pattern

```typescript theme={null}
// Modern service-based approach
import { PatientService, PrescriptionService } from '../services';

function PatientDetailPage() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const loadPatientData = async (id: string) => {
    try {
      setLoading(true);
      setError(null);
      
      // Service calls with built-in error handling
      const patient = await PatientService.getById(id);
      const prescriptions = await PrescriptionService.getByPatient(id);
      const healthMetrics = await PatientService.getHealthMetrics(id);
      
      setPatient(patient);
      setPrescriptions(prescriptions);
      setHealthMetrics(healthMetrics);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
}
```

## State Management

### AuthContext

* **Purpose**: Global authentication state
* **Technology**: React Context API + AuthService
* **Key Functions**:
  * User session management via AuthService
  * Login/logout handling
  * Role-based permissions
  * MFA state management

### Custom Hooks

* **Purpose**: Reusable data fetching logic using services
* **Technology**: React hooks + Service Layer
* **Key Functions**:
  * usePatients - Patient data via PatientService
  * useClinicSettings - Configuration via ClinicService
  * usePaymentSettings - Billing via PaymentService
  * useActiveMedications - Medication data via MedicationService
  * useShipments - Shipment data via ShipmentService

### Service Layer

* **Purpose**: Backend communication abstraction
* **Technology**: TypeScript services with Zod validation
* **Key Functions**:
  * Consistent error handling with `handle()` utility
  * Type-safe operations
  * Centralized business logic
  * Zero direct database access

## Architecture Benefits

### Type Safety

* **Full TypeScript**: End-to-end type safety
* **Zod Validation**: Runtime input validation
* **Service Interfaces**: Consistent method signatures
* **Error Handling**: Typed error responses

### Maintainability

* **Single Responsibility**: Each service handles one domain
* **Consistent Patterns**: Same interface across all services
* **Testable**: Services can be mocked independently
* **Separation of Concerns**: UI logic separate from business logic

### Developer Experience

* **IntelliSense**: Full autocomplete for service methods
* **Error Messages**: Clear, user-friendly error handling
* **Hot Reload**: Fast development iteration
* **Debugging**: Centralized logging and monitoring

<Note>
  **All components use the service layer exclusively - no direct Supabase calls are made from the frontend**
</Note>
