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

# Contexts

# Frontend Context Providers Documentation

This document provides comprehensive documentation for all React Context providers in the STO Education Platform.

## Context Architecture Overview

The application uses React Context API for state management, providing a centralized way to share state across components without prop drilling. Each context is designed for specific functionality and user roles.

## Context Providers

### 1. AdminContext

#### Location: `src/context/AdminContext.tsx`

#### Purpose

Manages admin authentication and role-based access control throughout the application.

#### Features

* **Admin Status Checking**: Verifies if the current user has admin privileges
* **Authentication Integration**: Works with Supabase authentication
* **Real-time Updates**: Automatically updates when authentication state changes
* **Role Validation**: Checks user role from the profiles table

#### Context Interface

```typescript theme={null}
interface AdminContextType {
  isAdmin: boolean;           // Current admin status
  isAdminChecked: boolean;    // Whether admin check is complete
}
```

#### Implementation Details

* **Provider Component**: `AdminProvider`
* **Custom Hook**: `useAdmin()`
* **Error Handling**: Throws error if used outside provider
* **Auto-subscription**: Listens to Supabase auth state changes

#### Usage Example

```typescript theme={null}
import { useAdmin } from '../context/AdminContext';

function MyComponent() {
  const { isAdmin, isAdminChecked } = useAdmin();
  
  if (!isAdminChecked) {
    return <LoadingSpinner />;
  }
  
  return (
    <div>
      {isAdmin && <AdminPanel />}
    </div>
  );
}
```

#### Dependencies

* **Supabase**: For authentication and user data
* **React**: Core React hooks and context

#### Security Features

* **Row Level Security**: Leverages Supabase RLS policies
* **Server-side Validation**: Admin status verified on backend
* **Session Management**: Automatic session validation

***

### 2. CartContext

#### Location: `src/context/CartContext.tsx`

#### Purpose

Manages shopping cart state for teacher mark schemes and other purchasable items.

#### Features

* **Cart Management**: Add, remove, and manage cart items
* **Total Calculation**: Automatic total price calculation
* **Currency Support**: Multi-currency support (defaults to EGP)
* **Duplicate Prevention**: Prevents duplicate items in cart
* **State Persistence**: Cart state management with reducer pattern

#### Context Interface

```typescript theme={null}
interface CartContextType {
  state: CartState;
  addItem: (item: CartItem) => void;
  removeItem: (id: string) => void;
  clearCart: () => void;
  getItemCount: () => number;
  getTotal: () => number;
}

interface CartState {
  items: CartItem[];
  total: number;
  currency: string;
}

interface CartItem {
  id: string;
  teacher_mark_scheme_id: string;
  original_filename: string;
  subject_id: string;
  exam_category: string;
  paper_year: string;
  paper_season: string;
  paper_category: string;
  teacher_explanation: string;
  file_url: string;
  price: number;
  currency: string;
}
```

#### Implementation Details

* **Provider Component**: `CartProvider`
* **Custom Hook**: `useCart()`
* **Reducer Pattern**: Uses useReducer for complex state management
* **Action Types**: ADD\_ITEM, REMOVE\_ITEM, CLEAR\_CART, UPDATE\_QUANTITY

#### Usage Example

```typescript theme={null}
import { useCart } from '../context/CartContext';

function ProductCard({ product }) {
  const { addItem, getItemCount } = useCart();
  
  const handleAddToCart = () => {
    addItem(product);
  };
  
  return (
    <div>
      <h3>{product.name}</h3>
      <button onClick={handleAddToCart}>
        Add to Cart ({getItemCount()})
      </button>
    </div>
  );
}
```

#### Cart Actions

* **ADD\_ITEM**: Adds item to cart (prevents duplicates)
* **REMOVE\_ITEM**: Removes item by ID
* **CLEAR\_CART**: Empties entire cart
* **UPDATE\_QUANTITY**: Updates item quantity (not used for mark schemes)

#### Business Logic

* **Mark Scheme Focus**: Optimized for teacher mark scheme purchases
* **Quantity Limitation**: Each item has quantity of 1
* **Price Calculation**: Automatic total calculation
* **Currency Handling**: Default EGP currency support

***

### 3. LayoutContext

#### Location: `src/context/LayoutContext.tsx`

#### Purpose

Manages UI layout state, particularly sidebar visibility and collapse states across the application.

#### Features

* **Sidebar Management**: Controls sidebar visibility and collapse state
* **Responsive Design**: Adapts to different screen sizes
* **State Synchronization**: Keeps layout state consistent across components
* **Toggle Functionality**: Smart toggle behavior for sidebar

#### Context Interface

```typescript theme={null}
interface LayoutContextType {
  isSidebarCollapsed: boolean;      // Sidebar collapsed state
  isSidebarHidden: boolean;         // Sidebar hidden state
  setSidebarCollapsed: (collapsed: boolean) => void;
  setSidebarHidden: (hidden: boolean) => void;
  toggleSidebar: () => void;        // Smart toggle function
  hideSidebar: () => void;          // Hide sidebar
  showSidebar: () => void;          // Show sidebar (uncollapsed)
}
```

#### Implementation Details

* **Provider Component**: `LayoutProvider`
* **Custom Hook**: `useLayout()`
* **State Management**: Uses useState for simple state
* **Smart Toggle**: Intelligent toggle behavior based on current state

#### Usage Example

```typescript theme={null}
import { useLayout } from '../context/LayoutContext';

function SidebarToggle() {
  const { 
    isSidebarCollapsed, 
    isSidebarHidden, 
    toggleSidebar 
  } = useLayout();
  
  return (
    <button onClick={toggleSidebar}>
      {isSidebarHidden ? 'Show' : 'Hide'} Sidebar
    </button>
  );
}
```

#### Toggle Logic

```typescript theme={null}
const toggleSidebar = () => {
  if (isSidebarHidden) {
    // If hidden, show it (uncollapsed)
    setIsSidebarHidden(false);
    setIsSidebarCollapsed(false);
  } else {
    // If visible, hide it completely
    setIsSidebarHidden(true);
  }
};
```

#### Layout States

* **Visible + Expanded**: Normal sidebar state
* **Visible + Collapsed**: Sidebar visible but minimized
* **Hidden**: Sidebar completely hidden

***

### 4. PageContentContext

#### Location: `src/context/PageContentContext.tsx`

#### Purpose

Manages dynamic page content for the Content Management System (CMS), allowing administrators to edit page content in real-time.

#### Features

* **Dynamic Content**: Editable page content management
* **Auto-initialization**: Automatically initializes content if none exists
* **Real-time Updates**: Live content updates without page refresh
* **Admin-only Editing**: Content editing restricted to admin users
* **Content Persistence**: Automatic saving to Supabase database
* **Loading States**: Proper loading state management

#### Context Interface

```typescript theme={null}
interface PageContentContextType {
  content: PageContentItem;                    // Current page content
  isLoading: boolean;                          // Loading state
  updateContent: (key: string, value: string) => Promise<void>;
  getContent: (key: string, defaultValue: string) => string;
  saveAllContent: () => Promise<number>;       // Save all content on page
}

interface PageContentItem {
  [key: string]: string;                       // Key-value content pairs
}
```

#### Implementation Details

* **Provider Component**: `PageContentProvider`
* **Custom Hook**: `usePageContent()`
* **Page-specific**: Each page has its own content context
* **Auto-save**: Background saving of content changes

#### Usage Example

```typescript theme={null}
import { usePageContent } from '../context/PageContentContext';

function EditableText({ contentKey, defaultValue }) {
  const { getContent, updateContent, isLoading } = usePageContent();
  
  if (isLoading) {
    return <div>Loading...</div>;
  }
  
  const content = getContent(contentKey, defaultValue);
  
  return (
    <div
      contentEditable={isAdmin}
      onBlur={(e) => updateContent(contentKey, e.target.textContent)}
    >
      {content}
    </div>
  );
}
```

#### Content Management Features

* **DOM Scanning**: Automatically scans page for content elements
* **Data Attributes**: Uses `data-content-key` for content identification
* **Image Support**: Supports editable images with `data-image-key`
* **Batch Operations**: Can save all content at once

#### Content Initialization Process

1. **Load Existing Content**: Fetches content from database
2. **Check for Empty State**: Detects if no content exists
3. **Auto-initialization**: Creates default content if needed
4. **DOM Scanning**: Scans page for content elements
5. **Content Mapping**: Maps DOM elements to content keys
6. **Database Save**: Saves content to Supabase

#### Loading State Management

```typescript theme={null}
// Loading state with smooth transition
{isLoading ? (
  <div className="min-h-screen bg-white dark:bg-[#051220] flex items-center justify-center">
    <div className="animate-pulse text-primary dark:text-neutral-light text-center">
      <div className="w-16 h-16 mx-auto border-4 border-current border-t-transparent rounded-full animate-spin mb-4"></div>
      <p className="text-lg">Loading content...</p>
    </div>
  </div>
) : (
  children
)}
```

#### Content Saving Strategy

* **Immediate Update**: Local state updated immediately
* **Background Save**: Database save happens in background
* **Error Handling**: Graceful error handling for save failures
* **Optimistic Updates**: UI updates before database confirmation

***

## Context Integration Patterns

### 1. Provider Hierarchy

```typescript theme={null}
function App() {
  return (
    <HelmetProvider>
      <AdminProvider>
        <CartProvider>
          <LayoutProvider>
            <Router>
              {/* App content */}
            </Router>
          </LayoutProvider>
        </CartProvider>
      </AdminProvider>
    </HelmetProvider>
  );
}
```

### 2. Conditional Context Usage

```typescript theme={null}
function ConditionalProvider({ children, condition }) {
  if (condition) {
    return (
      <PageContentProvider page="about">
        {children}
      </PageContentProvider>
    );
  }
  
  return children;
}
```

### 3. Context Composition

```typescript theme={null}
function CombinedContext({ children }) {
  return (
    <AdminProvider>
      <LayoutProvider>
        <PageContentProvider page="dashboard">
          {children}
        </PageContentProvider>
      </LayoutProvider>
    </AdminProvider>
  );
}
```

## Context Best Practices

### 1. Performance Optimization

* **Context Splitting**: Separate contexts for different concerns
* **Memoization**: Use useMemo for expensive context values
* **Selective Subscriptions**: Only subscribe to needed context values
* **Lazy Loading**: Load context data only when needed

### 2. Error Handling

* **Error Boundaries**: Wrap context providers with error boundaries
* **Fallback Values**: Provide sensible default values
* **Validation**: Validate context data before use
* **Error Recovery**: Graceful error recovery mechanisms

### 3. Type Safety

* **TypeScript Interfaces**: Strong typing for context interfaces
* **Generic Types**: Use generics for reusable context patterns
* **Type Guards**: Runtime type checking for context data
* **Documentation**: Clear type documentation

### 4. Testing Strategy

* **Context Testing**: Test context providers in isolation
* **Hook Testing**: Test custom hooks independently
* **Integration Testing**: Test context integration with components
* **Mock Contexts**: Mock contexts for component testing

## Context Security Considerations

### 1. Data Validation

* **Input Sanitization**: Sanitize all context data
* **Type Validation**: Runtime type checking
* **Access Control**: Role-based access to context data
* **Audit Logging**: Log context data changes

### 2. State Management Security

* **Sensitive Data**: Avoid storing sensitive data in context
* **Session Management**: Proper session handling
* **Token Management**: Secure token storage and refresh
* **Permission Checks**: Regular permission validation

## Context Performance Monitoring

### 1. Performance Metrics

* **Render Count**: Monitor context-related re-renders
* **Memory Usage**: Track context memory consumption
* **Update Frequency**: Monitor context update patterns
* **Bundle Size**: Track context-related bundle size

### 2. Optimization Strategies

* **Context Splitting**: Split large contexts into smaller ones
* **Memoization**: Memoize context values and selectors
* **Lazy Loading**: Load context data on demand
* **Caching**: Implement context data caching

## Future Context Enhancements

### 1. Planned Features

* **Context Persistence**: Local storage integration
* **Context Synchronization**: Multi-tab context sync
* **Context Middleware**: Context action middleware
* **Context DevTools**: Development debugging tools

### 2. Advanced Patterns

* **Context Composition**: Advanced context composition patterns
* **Context Providers**: Provider factory patterns
* **Context Hooks**: Advanced custom hook patterns
* **Context Testing**: Enhanced testing utilities

### 3. Performance Improvements

* **Context Optimization**: Advanced optimization strategies
* **Memory Management**: Better memory management
* **Update Batching**: Batched context updates
* **Selective Rendering**: Selective component rendering

## Context Documentation Standards

### 1. Code Documentation

* **JSDoc Comments**: Comprehensive context documentation
* **Type Definitions**: Clear TypeScript interfaces
* **Usage Examples**: Practical usage examples
* **API Reference**: Complete API documentation

### 2. User Documentation

* **Context Purpose**: Clear purpose and use cases
* **Integration Guide**: Step-by-step integration guide
* **Best Practices**: Context usage best practices
* **Troubleshooting**: Common issues and solutions

### 3. Developer Documentation

* **Architecture Overview**: Context architecture explanation
* **Implementation Details**: Technical implementation details
* **Extension Guide**: How to extend existing contexts
* **Migration Guide**: Context migration strategies
