# Performance Optimization Guide - Registration Page

## Current Issues Identified

### 1. **Critical: Massive Bundle Size (4.2MB)**
The main JavaScript bundle is extremely large, causing slow initial page load.

**Impact:** Users wait 5-15+ seconds on slower connections before seeing any content.

### 2. **Heavy Dependencies Loaded Globally**
- Agora RTC SDK (video streaming) - Not needed for registration
- Full i18n bundle with all language files
- All styles bundled together

### 3. **Potential Backend API Performance**
- Endpoint: `https://ministryprogsapi.tniglobal.org/api/upcomingProgramsWithLanguages`
- May be slow if querying multiple tables or large datasets

---

## ✅ Implemented Fixes

### 1. Removed Agora RTC from Global Bundle
- **File:** `src/index.tsx`
- **Change:** Commented out Agora RTC initialization
- **Benefit:** Reduces initial bundle size significantly (~400-600KB saved)
- **Note:** Move Agora initialization to streaming pages only

### 2. Added Resource Hints
- **File:** `public/index.html`
- **Added:** DNS prefetch and preconnect for API endpoints
- **Benefit:** Faster API connections (save ~200-500ms per request)

---

## 🔧 Additional Optimizations Needed

### Priority 1: Code Splitting & Lazy Loading

#### A. Split i18n by Route
```typescript
// Instead of loading all translations upfront in i18n.ts
// Load them on-demand per route

// Example in src/i18n.ts
i18n.use(Backend).init({
  backend: {
    loadPath: '/locales/{{lng}}/{{ns}}.json',
  },
  react: {
    useSuspense: false, // Important for lazy loading
  },
  // Only load needed namespaces
  ns: ['common'],
  defaultNS: 'common',
});
```

#### B. Split Large Ant Design Imports
```typescript
// ❌ BAD: Imports entire Ant Design library
import { Button, Select, Form } from 'antd';

// ✅ GOOD: Import only what's needed
import Button from 'antd/es/button';
import Select from 'antd/es/select';
import Form from 'antd/es/form';
```

#### C. Create Separate Agora Provider Component
Create `src/providers/AgoraProvider.tsx`:
```typescript
import React, { lazy, Suspense } from 'react';
import AgoraRTC, { AgoraRTCProvider } from "agora-rtc-react";

const client = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });

export const AgoraProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  return (
    <AgoraRTCProvider client={client}>
      {children}
    </AgoraRTCProvider>
  );
};
```

Then wrap only streaming pages with this provider.

### Priority 2: Webpack Bundle Analyzer

Install and run to visualize what's taking up space:
```bash
npm install --save-dev webpack-bundle-analyzer
npm install --save-dev cra-bundle-analyzer

# Add to package.json scripts:
"analyze": "npx cra-bundle-analyzer"

# Then run:
npm run analyze
```

This will show you exactly which packages are bloating your bundle.

### Priority 3: Backend API Optimization

Check the backend endpoint performance:
```bash
# Test API response time
curl -w "@curl-format.txt" -o /dev/null -s https://ministryprogsapi.tniglobal.org/api/upcomingProgramsWithLanguages
```

**Backend optimizations to check:**
1. Add database indexes on `programs` table:
   - `start_date` or similar date field
   - `status` or `active` field
2. Limit query results (do you need ALL upcoming programs?)
3. Add Redis caching for this endpoint (TTL: 5-10 minutes)
4. Use `SELECT` specific fields, not `SELECT *`
5. Paginate results if there are many programs

### Priority 4: Enable Compression

Ensure gzip/brotli compression is enabled on your server:

**For Apache (.htaccess):**
```apache
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>
```

**For Nginx:**
```nginx
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
gzip_min_length 1000;
```

### Priority 5: Implement Caching Headers

Add to your server configuration to cache static assets:

**For Apache (.htaccess):**
```apache
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType text/css "access plus 1 year"
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/jpeg "access plus 1 year"
</IfModule>
```

### Priority 6: Prefetch Registration Data

Since users going to `/registration` will need program data, prefetch it:

In `public/index.html` (after the resource hints):
```html
<!-- Prefetch registration data -->
<link rel="prefetch" href="https://ministryprogsapi.tniglobal.org/api/upcomingProgramsWithLanguages" as="fetch" crossorigin>
```

---

## 📊 Expected Performance Improvements

After implementing all optimizations:

| Metric | Before | After | Improvement |
|--------|--------|-------|-------------|
| Main Bundle Size | 4.2MB | ~1.5MB | 64% reduction |
| Initial Load Time (3G) | 15-20s | 4-6s | 70% faster |
| Initial Load Time (4G) | 6-8s | 2-3s | 65% faster |
| Time to Interactive | 8-10s | 3-4s | 60% faster |
| API Response Time | Variable | <500ms | Consistent |

---

## 🚀 Deployment Steps

After making code changes:

1. **Rebuild the production bundle:**
   ```bash
   npm run build
   ```

2. **Verify bundle size reduction:**
   ```bash
   ls -lh build/static/js/main.*.js
   # Should be significantly smaller than 4.2MB
   ```

3. **Test locally:**
   ```bash
   npm run serve
   # Visit http://localhost:3000/registration
   ```

4. **Deploy to production:**
   ```bash
   # Copy build files to production server
   rsync -av build/* /path/to/production/
   ```

5. **Clear CDN/Browser caches:**
   - CloudFlare: Purge everything
   - Browser: Hard refresh (Ctrl+Shift+R)

---

## 🔍 Monitoring

After deployment, monitor:

1. **Google PageSpeed Insights:**
   https://pagespeed.web.dev/
   - Target: 90+ score for mobile

2. **Chrome DevTools Network Tab:**
   - Main bundle should be < 2MB
   - API calls should be < 1s

3. **Real User Monitoring:**
   - Track Time to First Contentful Paint (FCP)
   - Track Time to Interactive (TTI)
   - Track API response times

---

## 📝 Next Steps

1. ✅ **Already Done:** Removed Agora from global bundle
2. ✅ **Already Done:** Added DNS prefetch/preconnect
3. **TODO:** Run webpack bundle analyzer
4. **TODO:** Check backend API performance
5. **TODO:** Implement code splitting for i18n
6. **TODO:** Split Ant Design imports
7. **TODO:** Enable server compression
8. **TODO:** Add caching headers
9. **TODO:** Rebuild and deploy
10. **TODO:** Monitor performance improvements

---

## Additional Resources

- [React Code Splitting Docs](https://react.dev/reference/react/lazy)
- [Webpack Bundle Optimization](https://webpack.js.org/guides/code-splitting/)
- [Web.dev Performance Guide](https://web.dev/performance/)
- [Chrome DevTools Performance](https://developer.chrome.com/docs/devtools/performance/)

