# 🚀 Developer Quick Reference - EcoLearn Platform

**Quick lookup guide for developers working on EcoLearn**

---

## 🎯 Project At A Glance

| Aspect | Value |
|--------|-------|
| **Type** | Full-stack web application |
| **Frontend** | Next.js 14 + React 18 + TypeScript |
| **Backend** | Supabase (PostgreSQL) |
| **Styling** | Tailwind CSS |
| **Status** | Week 1 Complete ✅ |
| **Timeline** | 8 weeks MVP |

---

## 🎨 Color Palette (Tailwind Classes)

```
Eco Theme Colors:

Primary Green:      eco-primary   (#10B981)
Secondary Green:    eco-secondary (#6EE7B7)
Accent Yellow:      eco-accent    (#FBBF24)
Dark Text:          eco-dark      (#1F2937)
Light Background:   eco-light     (#F3F4F6)

Status Colors:
Success:  status-success  (#10B981)
Error:    status-error    (#EF4444)
Warning:  status-warning  (#F59E0B)
Info:     status-info     (#3B82F6)
```

### Usage
```tsx
<div className="bg-eco-primary text-white">
  Primary green background
</div>

<button className="bg-eco-accent hover:bg-eco-accent/90">
  Clickable button with yellow
</button>
```

---

## 📁 Key File Locations

### Components
```
Button:           components/common/Button.tsx
Card:             components/common/Card.tsx
Badge:            components/common/Badge.tsx
StreakIndicator:  components/common/StreakIndicator.tsx
LoginForm:        components/auth/LoginForm.tsx
SignupForm:       components/auth/SignupForm.tsx
```

### Pages
```
Landing:      app/page.tsx
Login:        app/(auth)/login/page.tsx
Signup:       app/(auth)/signup/page.tsx
Dashboard:    app/(protected)/dashboard/page.tsx
Videos:       app/(protected)/videos/page.tsx
Quiz:         app/(protected)/quiz/page.tsx
Game:         app/(protected)/game/page.tsx
Leaderboard:  app/(protected)/leaderboard/page.tsx
Profile:      app/(protected)/profile/page.tsx
```

### Utilities
```
Validators:   lib/utils/validators.ts
Streak:       lib/utils/streakUtils.ts
Constants:    lib/utils/constants.ts
Hooks:        lib/hooks/useAuth.ts, useProfile.ts
Supabase:     lib/supabase/client.ts, server.ts, types.ts
```

### API Routes
```
Signup:  app/api/auth/signup/route.ts
Login:   app/api/auth/login/route.ts
Logout:  app/api/auth/logout/route.ts
```

---

## 🔧 Common Commands

```bash
# Development
npm run dev           # Start dev server (http://localhost:3000)

# Production
npm run build         # Build for production
npm start            # Start production server

# Linting
npm run lint         # Run ESLint

# Installation
npm install          # Install dependencies
npm install <pkg>    # Add new package
```

---

## 💾 Component Usage Examples

### Button Component
```tsx
import Button from '@/components/common/Button';

// Primary button
<Button variant="primary" size="md">
  Click me
</Button>

// Secondary button
<Button variant="secondary" size="lg">
  Secondary
</Button>

// Ghost button
<Button variant="ghost" size="sm">
  Subtle
</Button>

// Loading state
<Button loading>Loading...</Button>

// Disabled
<Button disabled>Disabled</Button>
```

### Card Component
```tsx
import { Card, CardBody, CardHeader, CardFooter } from '@/components/common/Card';

<Card>
  <CardHeader>
    <h3>Card Title</h3>
  </CardHeader>
  <CardBody>
    Main content here
  </CardBody>
  <CardFooter>
    <Button>Action 1</Button>
    <Button variant="secondary">Action 2</Button>
  </CardFooter>
</Card>
```

### Badge Component
```tsx
import { Badge } from '@/components/common/Badge';

<Badge variant="eco">EcoLearn</Badge>
<Badge variant="success">Success</Badge>
<Badge variant="error">Error</Badge>
<Badge variant="warning">Warning</Badge>
<Badge variant="info">Info</Badge>
```

### StreakIndicator Component
```tsx
import { StreakIndicator } from '@/components/common/StreakIndicator';

<StreakIndicator 
  streak={7}
  multiplier={1.2}
  nextMilestone={30}
/>
```

---

## 🪝 Hook Usage

### useAuth Hook
```tsx
import { useAuth } from '@/lib/hooks/useAuth';

export const MyComponent = () => {
  const { user, loading, error } = useAuth();

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  if (!user) return <div>Not logged in</div>;

  return <div>Welcome, {user.email}!</div>;
};
```

### useProfile Hook
```tsx
import { useProfile } from '@/lib/hooks/useProfile';
import { useAuth } from '@/lib/hooks/useAuth';

export const ProfilePage = () => {
  const { user } = useAuth();
  const { profile, loading, updateProfile } = useProfile(user?.id);

  const handleUpdate = async () => {
    await updateProfile({ bio: 'New bio' });
  };

  return <div>{profile?.username}</div>;
};
```

---

## ✔️ Validation Utilities

```tsx
import { validators } from '@/lib/utils/validators';

// Email validation
validators.email('test@email.com')  // true/false

// Password validation
const { valid, errors } = validators.password('MyPass123');
// returns: { valid: true/false, errors: string[] }

// Username validation
const { valid, error } = validators.username('john_doe');
// returns: { valid: true/false, error?: string }

// Password match
validators.passwordMatch('password123', 'password123')  // true/false
```

---

## 🔥 Streak Utilities

```tsx
import { streakUtils } from '@/lib/utils/streakUtils';

// Calculate multiplier
streakUtils.calculateMultiplier(7)    // 1.2
streakUtils.calculateMultiplier(30)   // 1.5
streakUtils.calculateMultiplier(365)  // 2.0

// Calculate daily reward
streakUtils.calculateDailyReward(50, 1.2)  // 60

// Format streak display
streakUtils.formatStreakDisplay(7)    // "1 minggu 🎉"

// Get milestone message
streakUtils.getMilestoneMessage(30)   // "Wow! Anda sudah 30 hari..."

// Get days until next milestone
streakUtils.getDaysUntilNextMilestone(7)
// { days: 23, milestone: 30 }
```

---

## 🌐 API Routes

### Signup
```bash
POST /api/auth/signup
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "SecurePass123",
  "username": "john_doe"
}

Response (201):
{
  "message": "Pendaftaran berhasil...",
  "user": { ... }
}
```

### Login
```bash
POST /api/auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "SecurePass123"
}

Response (200):
{
  "message": "Login berhasil",
  "user": { ... },
  "session": { ... }
}
```

### Logout
```bash
POST /api/auth/logout

Response (200):
{
  "message": "Logout berhasil"
}
```

---

## 📱 Responsive Breakpoints

```
Mobile:   < 640px
Tablet:   640px - 1023px (md: prefix)
Desktop:  1024px+ (lg: prefix)

Examples:
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4">
  Responsive grid: 1 col mobile, 2 col tablet, 4 col desktop
</div>

<div className="p-4 md:p-8">
  Responsive padding: 4 mobile, 8 desktop
</div>
```

---

## 🔐 Protected Route Pattern

```tsx
// app/(protected)/my-page/page.tsx
'use client';

import { useAuth } from '@/lib/hooks/useAuth';
import { useRouter } from 'next/navigation';
import { PAGE_ROUTES } from '@/lib/utils/constants';

export default function MyPage() {
  const { user, loading } = useAuth();
  const router = useRouter();

  // Redirect if not authenticated
  useEffect(() => {
    if (!loading && !user) {
      router.push(PAGE_ROUTES.LOGIN);
    }
  }, [user, loading, router]);

  if (loading) return <div>Loading...</div>;
  if (!user) return null;

  return <div>Protected content</div>;
}
```

---

## 🎨 Layout Pattern

```tsx
<div className="max-w-6xl mx-auto p-4 md:p-8">
  {/* Container with max width and responsive padding */}
  
  <div className="mb-8">
    {/* Title section */}
    <h1 className="text-3xl font-bold text-eco-dark mb-2">
      Page Title
    </h1>
    <p className="text-gray-600">Subtitle</p>
  </div>

  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
    {/* Content grid */}
  </div>
</div>
```

---

## 📝 Form Pattern

```tsx
export const MyForm = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [formData, setFormData] = useState({ email: '', password: '' });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    setError('');
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const res = await fetch('/api/endpoint', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || 'Error occurred');
        return;
      }

      // Success handling
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && (
        <div className="p-3 bg-status-error/10 border border-status-error rounded-card text-status-error">
          {error}
        </div>
      )}

      <input
        name="email"
        value={formData.email}
        onChange={handleChange}
        placeholder="Email"
      />

      <Button type="submit" loading={loading}>
        Submit
      </Button>
    </form>
  );
};
```

---

## 🚀 Environment Variables

```bash
# .env.local

# Supabase
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key_here
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key_here

# App
NEXT_PUBLIC_APP_URL=http://localhost:3000
NODE_ENV=development
```

---

## 🔍 Debugging Tips

### Check Auth Status
```tsx
import { supabaseClient } from '@/lib/supabase/client';

const checkAuth = async () => {
  const { data: { session } } = await supabaseClient.auth.getSession();
  console.log('Current session:', session);
};
```

### Check Profile Data
```tsx
import { supabaseClient } from '@/lib/supabase/client';

const checkProfile = async (userId) => {
  const { data } = await supabaseClient
    .from('profiles')
    .select('*')
    .eq('id', userId)
    .single();
  console.log('Profile:', data);
};
```

### Check Network Requests
```
1. Open DevTools (F12)
2. Go to Network tab
3. Look for failed requests
4. Check response in inspector
5. Verify API response format
```

---

## 📋 Common Issues & Solutions

| Issue | Solution |
|-------|----------|
| "Module not found" | Run `npm install` |
| Tailwind not working | Restart dev server |
| Auth failing | Check .env.local setup |
| Port 3000 in use | Run `npm run dev -- -p 3001` |
| Type errors | Check TypeScript compilation |
| Styles not applying | Clear `.next` folder & restart |

---

## 🎯 Page Routes (Use from constants.ts)

```tsx
import { PAGE_ROUTES } from '@/lib/utils/constants';

PAGE_ROUTES.HOME              // /
PAGE_ROUTES.LOGIN             // /login
PAGE_ROUTES.SIGNUP            // /signup
PAGE_ROUTES.VERIFY_EMAIL      // /verify-email
PAGE_ROUTES.DASHBOARD         // /dashboard
PAGE_ROUTES.VIDEOS            // /videos
PAGE_ROUTES.QUIZ              // /quiz
PAGE_ROUTES.GAME              // /game
PAGE_ROUTES.LEADERBOARD       // /leaderboard
PAGE_ROUTES.PROFILE           // /profile
```

---

## 🔗 API Routes (Use from constants.ts)

```tsx
import { API_ROUTES } from '@/lib/utils/constants';

API_ROUTES.AUTH.SIGNUP        // /api/auth/signup
API_ROUTES.AUTH.LOGIN         // /api/auth/login
API_ROUTES.AUTH.LOGOUT        // /api/auth/logout
API_ROUTES.AUTH.VERIFY        // /api/auth/verify-email
API_ROUTES.PROFILE            // /api/profile (Week 2+)
API_ROUTES.VIDEOS             // /api/videos (Week 2+)
API_ROUTES.QUIZ               // /api/quiz (Week 3+)
API_ROUTES.GAMES              // /api/games (Week 4+)
API_ROUTES.LEADERBOARD        // /api/leaderboard (Week 7+)
```

---

## 💡 Best Practices

✅ **DO:**
- Use TypeScript for type safety
- Import from @/ alias for clarity
- Create reusable components
- Use Tailwind utilities
- Validate user input
- Handle errors gracefully
- Add comments for complex logic
- Follow naming conventions

❌ **DON'T:**
- Use `any` type in TypeScript
- Hard-code strings (use constants)
- Forget error handling
- Create massive components
- Use inline styles
- Skip form validation
- Ignore responsive design
- Leave console.log in production

---

## 📚 Reference Documents

Keep these bookmarked:

1. **README.md** - Project overview
2. **SETUP_GUIDE.md** - Development setup
3. **PRD.md** - Product requirements
4. **TECH_STACK.md** - Architecture details
5. **SCHEMA.md** - Database schema
6. **GAME_DESIGN.md** - Game specifications
7. **QUICK_START.md** - Development timeline

---

## 🆘 Need Help?

1. **Code questions?** → Check inline comments & code examples
2. **Design questions?** → See TECH_STACK.md Section 5 & PRD.md Section 5
3. **Architecture?** → Check TECH_STACK.md Sections 1-3
4. **Database?** → See SCHEMA.md
5. **Game mechanics?** → See GAME_DESIGN.md
6. **Project status?** → See QUICK_START.md timeline
7. **Setup issues?** → See SETUP_GUIDE.md troubleshooting

---

## 🎓 Learning Path for New Developers

**Day 1: Onboarding**
- Read README.md (15 min)
- Read SETUP_GUIDE.md (30 min)
- Understand folder structure (15 min)
- Run dev server (10 min)

**Day 2: Components**
- Study components/common/ (30 min)
- Review Button, Card, Badge (30 min)
- Create test component (30 min)

**Day 3: Pages**
- Study existing pages (45 min)
- Review routing pattern (30 min)
- Create simple page (30 min)

**Day 4-5: API & Database**
- Study API routes (45 min)
- Review Supabase setup (45 min)
- Test with data (30 min)

**Week 2+: Feature Development**
- Follow QUICK_START.md timeline
- Implement video/quiz/game features
- Follow established patterns

---

**Last Updated:** August 14, 2026  
**Version:** 1.0  
**Status:** Complete & Ready ✅

🚀 **Happy coding! Welcome to EcoLearn development!**
