# Módulo Education

**Epic:** OQI-002 - Educativo
**Progreso:** 30%
**Responsable:** Education + Content Teams

## Descripción

El módulo educativo proporciona una plataforma completa de e-learning con cursos estructurados, video lessons, quizzes interactivos, y un sistema robusto de gamificación (XP, levels, streaks, achievements, leaderboard). Incluye herramientas para creadores de contenido como video upload, creator dashboard, certificate generation, y live streaming.

La gamificación incentiva el aprendizaje continuo mediante recompensas de XP por completar lecciones y quizzes, badges de achievements, leaderboards competitivos con períodos weekly/monthly/all-time, y streak tracking para fomentar el hábito diario.

## Componentes

### Páginas

- `Courses.tsx` - Catálogo de cursos con filtering (difficulty/category/price), search, sort, pagination (12 items/page), toggle free-only
- `CourseDetail.tsx` - Información completa del curso: module accordion, stats, instructor bio, enrollment status, progress tracking, certificate display
- `MyLearning.tsx` - Dashboard de cursos enrollados con tabs (in progress/completed/all), enrollment cards, gamification stats, achievements display
- `Lesson.tsx` - Visor de lección individual: video player con controls, module sidebar, lesson navigation, progress tracking
- `Quiz.tsx` - Interface de quiz: intro, question-by-question UI, timer, progress bar, results screen con XP display, retry option
- `Leaderboard.tsx` - Rankings de gamificación: top 3 podium, full leaderboard table, period selection (weekly/monthly/all-time), user position, streak stats

### Progress & Analytics Components (3)

- `CourseProgressTracker.tsx` - Visualización comprehensiva de progreso a nivel curso con breakdown de módulos, tracking de XP
- `LearningPathVisualizer.tsx` - Visualización de path de learning progression con conexiones entre nodos
- `AssessmentSummaryCard.tsx` - Summary de resultados de assessment con feedback question-level

### Gamification Components (4)

- `XPProgress.tsx` - Barra de progreso de XP level con detalles
- `StreakCounter.tsx` - Display de current/longest streak con milestones
- `AchievementBadge.tsx` - Badge individual de achievement
- `LeaderboardTable.tsx` - Tabla rankeada de usuarios con filtrado por período

### Content & Interaction Components (4)

- `VideoProgressPlayer.tsx` - Enhanced video player con bookmarks y notes
- `LessonNotes.tsx` - Interface de note-taking para lecciones
- `CourseReviews.tsx` - Display de reviews/ratings de curso
- `RecommendedCourses.tsx` - Carousel de cursos recomendados

### Creator Tools (OQI-002) (5)

- `VideoUploadForm.tsx` - Upload de video con metadata y progress tracking
- `CreatorDashboard.tsx` - Stats de creator, recent activity, course management
- `CertificateGenerator.tsx` - Generación de certificado desde template
- `CertificatePreview.tsx` - Preview y validación de certificado
- `LiveStreamPlayer.tsx` - Live streaming con chat y reactions

## Estructura de Carpetas

```
modules/education/
├── components/
│   ├── CourseProgressTracker.tsx
│   ├── LearningPathVisualizer.tsx
│   ├── AssessmentSummaryCard.tsx
│   ├── XPProgress.tsx
│   ├── StreakCounter.tsx
│   ├── AchievementBadge.tsx
│   ├── LeaderboardTable.tsx
│   ├── VideoProgressPlayer.tsx
│   ├── LessonNotes.tsx
│   ├── CourseReviews.tsx
│   ├── RecommendedCourses.tsx
│   ├── VideoUploadForm.tsx
│   ├── CreatorDashboard.tsx
│   ├── CertificateGenerator.tsx
│   ├── CertificatePreview.tsx
│   └── LiveStreamPlayer.tsx
├── pages/
│   ├── Courses.tsx
│   ├── CourseDetail.tsx
│   ├── MyLearning.tsx
│   ├── Lesson.tsx
│   ├── Quiz.tsx
│   └── Leaderboard.tsx
└── README.md
```

**Servicios y estado compartidos:**
- **Service:** `services/education.service.ts` (Axios, 38 endpoints)
- **Store:** `stores/educationStore.ts` (Zustand)
- **Types:** `types/education.types.ts`

## APIs Consumidas

### Categories APIs (Base URL: `/api/v1`)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/education/categories` | GET | Listar todas las categorías |
| `/education/categories` | POST | Crear categoría (admin) |

### Courses APIs (7)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/education/courses` | GET | Listar cursos (params: categoryId, level, search, sortBy, page, pageSize) |
| `/education/courses/popular` | GET | Top 6 cursos populares |
| `/education/courses/new` | GET | 6 cursos más nuevos |
| `/education/courses/:courseId` | GET | Detalle completo del curso |
| `/education/courses/slug/:slug` | GET | Obtener curso por slug |
| `/education/courses/:courseId/modules` | GET | Módulos del curso |
| `/education/courses/:courseId/stats` | GET | Estadísticas del curso |

### Lessons APIs (4)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/education/lessons/:lessonId` | GET | Detalle de lección con contenido |
| `/education/lessons/:lessonId/progress` | POST | Actualizar progreso de watch |
| `/education/lessons/:lessonId/complete` | POST | Marcar completa (awards XP) |
| `/education/modules/:moduleId/lessons` | GET | Lecciones de un módulo |

### Enrollments APIs (4)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/education/my/enrollments` | GET | Cursos enrollados del usuario |
| `/education/my/stats` | GET | Estadísticas de learning del usuario |
| `/education/courses/:courseId/enroll` | POST | Enrollarse en curso |
| `/education/courses/:courseId/enrollment` | GET | Check enrollment status |

### Quizzes APIs (9)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/education/lessons/:lessonId/quiz` | GET | Obtener quiz de lección |
| `/education/quizzes/:quizId` | GET | Detalle de quiz |
| `/education/courses/:courseId/quizzes` | GET | Quizzes del curso |
| `/education/quizzes/:quizId/start` | POST | Iniciar attempt |
| `/education/quizzes/attempts/:attemptId/submit` | POST | Submit answers |
| `/education/quizzes/attempts/:attemptId/results` | GET | Obtener resultados |
| `/education/quizzes/:quizId/my-attempts` | GET | Attempts del usuario |
| `/education/quizzes/:quizId/stats` | GET | Estadísticas de quiz |
| `/education/my/quiz-stats` | GET | Estadísticas de quizzes del usuario |

### Gamification APIs (9)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/education/gamification/profile` | GET | Profile de gamificación del usuario |
| `/education/gamification/profile/:userId` | GET | Profile público de otro usuario |
| `/education/gamification/level-progress` | GET | Detalles de progreso de level |
| `/education/gamification/streak` | GET | Estadísticas de streak |
| `/education/gamification/daily-activity` | POST | Registrar actividad diaria |
| `/education/gamification/achievements` | GET | Achievements del usuario |
| `/education/gamification/achievements/:userId` | GET | Achievements de otro usuario |
| `/education/gamification/leaderboard` | GET | Leaderboard completo (params: period, limit) |
| `/education/gamification/leaderboard/my-position` | GET | Posición del usuario en leaderboard |
| `/education/gamification/leaderboard/nearby` | GET | Posiciones cercanas al usuario |
| `/education/gamification/summary` | GET | Todos los datos de gamificación |

### Admin/Instructor APIs (8+)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/education/courses` | POST | Crear curso |
| `/education/courses/:courseId` | PATCH | Actualizar curso |
| `/education/courses/:courseId` | DELETE | Eliminar curso |
| `/education/courses/:courseId/publish` | POST | Publicar curso |
| `/education/courses/:courseId/modules` | POST | Crear módulo |
| `/education/modules/:moduleId` | DELETE | Eliminar módulo |
| `/education/modules/:moduleId/lessons` | POST | Crear lección |
| Video upload endpoints | POST | Upload de videos (multipart form) |

## Uso Rápido

```tsx
import { Courses, CourseDetail, MyLearning, Lesson, Quiz, Leaderboard } from '@/modules/education';
import { useEducationStore } from '@/stores/educationStore';

// Uso en router
<Route path="/courses" element={<Courses />} />
<Route path="/course/:slug" element={<CourseDetail />} />
<Route path="/my-learning" element={<MyLearning />} />
<Route path="/lesson/:lessonId" element={<Lesson />} />
<Route path="/quiz/:quizId" element={<Quiz />} />
<Route path="/leaderboard" element={<Leaderboard />} />

// Uso de store
function MyComponent() {
  const {
    courses,
    currentCourse,
    gamificationProfile,
    fetchCourses,
    enrollInCourse,
    markLessonComplete,
    recordDailyActivity
  } = useEducationStore();

  useEffect(() => {
    fetchCourses();
  }, []);

  const handleEnroll = async (courseId: string) => {
    await enrollInCourse(courseId);
  };

  const handleCompleteLesson = async (lessonId: string) => {
    await markLessonComplete(lessonId);
    // XP awarded automatically
  };

  return (
    <div>
      <h2>Courses: {courses.length}</h2>
      <p>XP: {gamificationProfile?.totalXp}</p>
      <p>Level: {gamificationProfile?.currentLevel}</p>
      <p>Streak: {gamificationProfile?.streakDays} days</p>
    </div>
  );
}
```

## Características Principales

### Student Features
- Browse courses con advanced filtering (12 items/page)
- View full course modules y lesson list
- Enroll en cursos free o paid
- Watch videos con interactive player
- Track progress per lesson y curso
- Complete quizzes con timed attempts
- View achievements y badges
- Compete en leaderboards (weekly/monthly/all-time)
- Earn XP y level up

### Creator Features
- Upload videos con metadata
- Create courses y modules
- Design quizzes con multiple question types
- Generate certificates
- View analytics dashboard
- Monitor student progress
- Manage course publishing

### Gamification System
- **XP Rewards:** Lecciones, quizzes, cursos completados
- **Level Progression:** Sistema de niveles con milestones
- **Daily Streak Tracking:** Con milestones y bonuses
- **Achievements:** Con rarity levels (common, rare, epic, legendary)
- **Leaderboards:** Con position tracking y períodos competitivos
- **Weekly/Monthly Competitions:** Reset periódico para engagement

### Quiz System
- Multiple question types: multiple_choice, multiple_answer, true_false, short_answer
- Time limits configurables
- Passing score requirements
- Shuffle de preguntas y opciones
- Detailed results con per-question feedback
- Multiple attempts permitidos

## Tests

```bash
# Tests unitarios del módulo
npm run test modules/education

# Tests de integración de gamificación
npm run test:integration education/gamification

# Tests E2E de flujos de learning
npm run test:e2e education
```

## Roadmap

### Pendientes - Alta Prioridad (P1)
- [ ] **Video Upload System** (60h) - Sistema completo de upload con encoding y CDN
- [ ] **Live Streaming** (80h) - Streaming en vivo con chat y reactions
- [ ] **Certificate Automation** (20h) - Auto-generación de certificados al completar curso

### Mediano Plazo (P2)
- [ ] **Peer Review System** (40h) - Sistema de peer review para assignments
- [ ] **Discussion Forums** (50h) - Foros de discusión por curso
- [ ] **Offline Mode** (60h) - Download de videos para viewing offline
- [ ] **Mobile App** (120h) - App nativa iOS/Android

### Largo Plazo (P3)
- [ ] **AI Tutor** (90h) - Tutor virtual con IA para Q&A
- [ ] **Adaptive Learning** (80h) - Paths de learning adaptativos según performance
- [ ] **Corporate Training** (70h) - Features para enterprise training

## Dependencias

- `zustand` - State management
- `axios` - HTTP client
- `lucide-react` - Icons
- `react-router-dom` - Navigation
- Video player library (por definir)

## Documentación Relacionada

- **ET Specs:**
  - ET-EDU-007: Video Player Advanced
- **User Stories:** US-EDU-001 a US-EDU-015
- **Backend API Docs:** `/docs/api/education.md`
- **Gamification System:** `/docs/features/gamification.md`

---

**Última actualización:** 2026-01-25
**Autor:** Claude Opus 4.5
