# Context Refactoring Plan

## Executive Summary

This document outlines a comprehensive refactoring plan for the React Context library in `src/context/`. The current implementation shows several architectural issues that impact maintainability, performance, and developer experience.

## Current State Analysis

### Issues Identified

#### 1. **Inconsistent Patterns** ⚠️ HIGH PRIORITY
- **Naming**: Mixed naming conventions (e.g., `CartContextProvider` vs `AuthProvider` vs `CompareContextProvider`)
- **Exports**: Some use default exports, others use named exports
- **Hooks**: Inconsistent hook naming (`useCart`, `useHome`, `useAuth` vs missing hooks in some contexts)
- **Context Creation**: Some contexts created inline, others in separate files

#### 2. **Large Monolithic Contexts** 🔴 CRITICAL
- **HomeContext**: 50+ state variables, handles multiple concerns (products, cart, categories, search, settings, etc.)
- **CheckoutContext**: Mixed concerns (addresses, shipping, payment, location, file uploads)
- **SettingProvider**: Handles layout, theme, locale, branches, and domain data

#### 3. **Code Duplication** ⚠️ HIGH PRIORITY
- **User retrieval**: `getUser()` function duplicated across contexts
- **API calls**: Similar patterns repeated (params, fetch, error handling)
- **Error handling**: Inconsistent approaches, not all use `errorHandler` utility
- **Loading states**: Different patterns for managing loading states

#### 4. **Performance Issues** ⚠️ MEDIUM PRIORITY
- **Large context values**: HomeContext provider value has 80+ properties
- **Missing memoization**: Context values not memoized, causing unnecessary re-renders
- **No value splitting**: Related state not grouped into separate contexts

#### 5. **Error Handling Inconsistencies** ⚠️ MEDIUM PRIORITY
- Some contexts use `errorHandler` utility (DomainContext), others use manual try/catch
- Inconsistent error messages and toast notifications
- Mixed error handling patterns (`.then().catch()` vs `try/catch`)

#### 6. **API Call Patterns** ⚠️ MEDIUM PRIORITY
- Similar code structure repeated across contexts
- Inconsistent parameter building
- Mixed response parsing (text vs json)
- Duplicate request deduplication logic

#### 7. **Missing Type Safety** ⚠️ LOW PRIORITY
- No TypeScript/PropTypes
- No JSDoc comments for functions
- No interface definitions for context values

#### 8. **State Management Issues** ⚠️ MEDIUM PRIORITY
- Too much state in single contexts
- Missing state normalization
- Direct localStorage access scattered throughout
- No state synchronization patterns

## Refactoring Plan

### Phase 1: Foundation & Consistency (Week 1-2)

#### 1.1 Create Base Context Utilities
**Location**: `src/context/utils/`

**New Files**:
- `contextFactory.js` - Factory for creating consistent contexts
- `apiClient.js` - Unified API client wrapper
- `hooks.js` - Reusable hooks (useUser, useAPI, etc.)

**Benefits**:
- Consistent context creation pattern
- Shared API call logic
- Reduced duplication

**Implementation**:
```javascript
// context/utils/contextFactory.js
export function createContextFactory(name) {
  const Context = createContext(null);
  
  const Provider = ({ children, ...props }) => {
    // Standard provider logic
  };
  
  const useHook = () => {
    const context = useContext(Context);
    if (!context) {
      throw new Error(`use${name} must be used within ${name}Provider`);
    }
    return context;
  };
  
  return { Context, Provider, useHook };
}

// context/utils/apiClient.js
export function createAPIClient(domainContext) {
  return {
    async request(endpoint, method, params, options) {
      // Unified API request handling
      // Uses errorHandler utility
      // Handles loading states
      // Parses responses consistently
    }
  };
}
```

#### 1.2 Standardize Naming Convention
**Changes**:
- All providers: `{Feature}Provider` (e.g., `CartProvider`, `AuthProvider`)
- All hooks: `use{Feature}` (e.g., `useCart`, `useAuth`)
- All contexts: `{Feature}Context` (e.g., `CartContext`, `AuthContext`)

**Files to Update**:
- `CompareContext.js` → Rename to follow convention
- `CurrencyContext.js` → Standardize exports
- `WishlistContext.js` → Standardize exports

#### 1.3 Create Shared Utilities
**Location**: `src/context/utils/`

**New Files**:
- `userUtils.js` - Centralized user management
- `storageUtils.js` - Safe localStorage operations
- `validationUtils.js` - Common validation functions

**Benefits**:
- Eliminate duplication of `getUser()` functions
- Consistent storage operations
- Reusable validation logic

### Phase 2: Split Large Contexts (Week 3-4)

#### 2.1 Split HomeContext 🔴 CRITICAL
**Current**: Single context with 50+ state variables

**Proposed Split**:
1. **ProductContext** - Product listings, details, search
   - `products`, `filteredProducts`, `product`, `category`, `getProductDetails`, `getSearchSuggestions`, etc.

2. **CategoryContext** - Category management
   - `categories`, `categoryList`, `categoryChildren`, `featuredCategories`, `getCategories`, `getCategoryData`

3. **HomeDataContext** - Home page specific data
   - `sliders`, `bannerType`, `videoUrl`, `featuredProducts`, `newProducts`, `flashDeals`, `ads`, `promotions`, `getHomeData`

4. **SearchContext** - Search functionality
   - `filteredProducts`, `filteredCategories`, `minPrice`, `maxPrice`, `totalCount`, `getSearchSuggestions`, `getQuestionnaireResults`

5. **CartContext** (existing) - Keep cart-specific logic
   - Already exists, but ensure clear boundaries

**Benefits**:
- Reduced re-renders (components only subscribe to needed contexts)
- Better separation of concerns
- Easier testing and maintenance

#### 2.2 Split CheckoutContext
**Proposed Split**:
1. **AddressContext** (exists) - Address management
   - Keep as is, already separated

2. **ShippingContext** - Shipping methods
   - `shippingMethods`, `selectedShippingMethod`, `getShippingMethods`

3. **PaymentContext** - Payment methods
   - `billingMethods`, `selectedPaymentMethod`

4. **OrderContext** (exists) - Order placement and review
   - Extend with order review functionality

#### 2.3 Refactor SettingProvider
**Proposed Split**:
1. **ThemeContext** - Theme and layout
   - `darkTheme`, `layout`, `layoutColor`, `layoutFun`, `setIsDark`

2. **LocaleContext** - Locale and direction
   - `locale`, `setLocale`, `direction`

3. **BranchContext** - Branch management
   - `storeBranches`, `selectedStoreBranch`, `getBranches`, `selectBranch`

4. **DomainContext** (exists) - Keep domain/API configuration
   - Already well-structured

### Phase 3: Optimize Performance (Week 5)

#### 3.1 Memoize Context Values
**Implementation**:
```javascript
const contextValue = useMemo(() => ({
  // context properties
}), [dependencies]);
```

**Affected Files**:
- All context providers
- Especially important for large contexts

#### 3.2 Split Context Values
**Strategy**: Group related state into separate context objects

**Example**:
```javascript
// Instead of:
<Context.Provider value={{ prop1, prop2, ...prop80 }}>

// Use:
<StateContext.Provider value={stateValue}>
  <ActionsContext.Provider value={actionsValue}>
    {children}
  </ActionsContext.Provider>
</StateContext.Provider>
```

**Benefits**:
- Components only re-render when specific parts change
- Better performance for large contexts

#### 3.3 Optimize Provider Nesting
**Current**: 10+ nested providers

**Proposed**: Create a single `AppProviders` component
```javascript
// context/providers/AppProviders.jsx
export function AppProviders({ children }) {
  return (
    <DomainProvider>
      <SettingProvider>
        <AuthProvider>
          {/* ... */}
        </AuthProvider>
      </SettingProvider>
    </DomainProvider>
  );
}
```

**Benefits**:
- Cleaner `_app.js`
- Easier to manage provider order
- Better performance with provider memoization

### Phase 4: Error Handling & API Calls (Week 6)

#### 4.1 Standardize Error Handling
**Strategy**: Use `errorHandler` utility everywhere

**Implementation**:
- Create `useAPI` hook that wraps `errorHandler`
- Replace all manual error handling
- Consistent error messages

**Example**:
```javascript
const useAPI = () => {
  const { getEndpointData } = useDomain();
  
  const request = async (endpoint, method, params, options) => {
    try {
      const { API_URL, requestOptions } = await getEndpointData(endpoint, method, params);
      const response = await fetchWithTimeout(API_URL, requestOptions, options?.timeout);
      const data = await response.json();
      
      if (!data.success) {
        handleAPIResponse(data, {
          context: options?.context || endpoint,
          fallbackMessage: options?.fallbackMessage,
        });
        return null;
      }
      
      return data;
    } catch (error) {
      handleError(error, {
        context: options?.context || endpoint,
        fallbackMessage: options?.fallbackMessage,
      });
      return null;
    }
  };
  
  return { request };
};
```

#### 4.2 Standardize API Call Patterns
**Strategy**: Use consistent patterns across all contexts

**Pattern**:
1. Build params using `URLSearchParams`
2. Get endpoint data using `getEndpointData`
3. Use `fetchWithTimeout` from errorHandler
4. Parse response consistently (always JSON)
5. Handle errors using `handleAPIResponse` or `handleError`

#### 4.3 Add Request Deduplication
**Strategy**: Prevent duplicate simultaneous requests

**Implementation**:
```javascript
const requestCache = new Map();

function dedupeRequest(key, requestFn) {
  if (requestCache.has(key)) {
    return requestCache.get(key);
  }
  
  const promise = requestFn().finally(() => {
    requestCache.delete(key);
  });
  
  requestCache.set(key, promise);
  return promise;
}
```

### Phase 5: State Management Improvements (Week 7)

#### 5.1 Normalize State Structure
**Strategy**: Use normalized state patterns for collections

**Example**:
```javascript
// Instead of:
const [products, setProducts] = useState([]);

// Use:
const [productsById, setProductsById] = useState({});
const [productIds, setProductIds] = useState([]);

// Derived:
const products = productIds.map(id => productsById[id]);
```

#### 5.2 Centralize Storage Operations
**Strategy**: Use `safeStorage` from errorHandler

**Implementation**:
- Replace all direct `localStorage` access
- Use `safeStorage.get()` and `safeStorage.set()`
- Consistent error handling

#### 5.3 Add State Synchronization
**Strategy**: Sync related state across contexts

**Implementation**:
- Create `useSyncState` hook
- Sync cart state between CartContext and HomeContext
- Sync wishlist state between WishlistContext and HomeContext

### Phase 6: Type Safety & Documentation (Week 8)

#### 6.1 Add JSDoc Comments
**Strategy**: Document all public functions and context values

**Implementation**:
```javascript
/**
 * Adds a product to the shopping cart
 * @param {Object} item - Product to add
 * @param {number} quantity - Quantity to add (default: 1)
 * @param {Object|null} selectedVariant - Selected product variant
 * @returns {Promise<Object|null>} API response or null on error
 */
const addToCart = async (item, quantity = 1, selectedVariant = null) => {
  // ...
};
```

#### 6.2 Add PropTypes (Optional)
**Strategy**: Add runtime type checking

**Implementation**:
- Define PropTypes for context values
- Add validation in development mode

#### 6.3 Create Context Type Definitions (Future)
**Strategy**: Prepare for TypeScript migration

**Implementation**:
- Create `.d.ts` files with type definitions
- Document context interfaces

## Implementation Priority

### 🔴 Critical (Do First)
1. Split HomeContext (50+ state variables)
2. Standardize naming conventions
3. Memoize context values

### ⚠️ High Priority (Do Next)
4. Create base utilities (contextFactory, apiClient)
5. Standardize error handling
6. Split CheckoutContext
7. Optimize provider nesting

### 📋 Medium Priority (Do After)
8. Standardize API call patterns
9. Add request deduplication
10. Normalize state structure
11. Centralize storage operations

### 💡 Low Priority (Nice to Have)
12. Add JSDoc comments
13. Add PropTypes
14. Create type definitions

## Migration Strategy

### Step-by-Step Approach

1. **Create utilities first** - Build foundation without breaking existing code
2. **Refactor one context at a time** - Start with smallest/simplest
3. **Update consumers incrementally** - Update components that use each context
4. **Test thoroughly** - Ensure no regressions
5. **Document changes** - Update README with new patterns

### Backward Compatibility

- Keep old exports during migration
- Use aliases for renamed exports
- Gradual deprecation warnings
- Migration guide for consumers

## Testing Strategy

### Unit Tests
- Test each context provider
- Test custom hooks
- Test utility functions

### Integration Tests
- Test context interactions
- Test API call patterns
- Test error handling

### Performance Tests
- Measure re-render counts
- Test with large datasets
- Profile context updates

## Success Metrics

### Code Quality
- ✅ Reduced code duplication (target: -50%)
- ✅ Consistent patterns across all contexts
- ✅ Better separation of concerns

### Performance
- ✅ Reduced unnecessary re-renders (target: -30%)
- ✅ Faster context updates
- ✅ Better memory usage

### Maintainability
- ✅ Easier to add new contexts
- ✅ Better error handling
- ✅ Improved documentation

## Risk Assessment

### Low Risk
- Creating new utility files
- Adding documentation
- Standardizing naming

### Medium Risk
- Splitting large contexts (requires consumer updates)
- Refactoring error handling
- Changing API call patterns

### High Risk
- Major context restructuring
- Provider order changes
- Breaking changes to public APIs

## Timeline Estimate

- **Phase 1-2**: 4 weeks (Foundation + Split contexts)
- **Phase 3-4**: 2 weeks (Performance + Error handling)
- **Phase 5-6**: 2 weeks (State management + Documentation)
- **Total**: 8 weeks with parallel work on low-risk items

## Next Steps

1. Review and approve this plan
2. Set up development branch
3. Start with Phase 1 (low-risk, high-value)
4. Create tracking issues for each phase
5. Schedule regular reviews

---

**Document Version**: 1.0  
**Last Updated**: 2024  
**Author**: AI Assistant  
**Review Status**: Draft
