# AI Learning Platform - AI-Powered Learning Platform

A modern web application for AI-powered learning with conversation bots, featuring ElevenLabs voice integration.

## 🚀 Quick Start with Docker

The easiest way to get started is using Docker Compose. The application will automatically set up the database, run migrations, and seed initial data.

### Prerequisites

- [Docker](https://docs.docker.com/get-docker/)
- [Docker Compose](https://docs.docker.com/compose/install/)

### 1. Clone the Repository

   ```bash
git clone <repository-url>
   cd ai-learning-platform
   ```

### 2. Set Up Environment Variables

Create a `.env` file in the project root with at least:

```bash
# .env (development)
JWT_SECRET=dev-secret
JWT_REFRESH_SECRET=dev-refresh-secret
CORS_ORIGIN=http://localhost:5173

# Dev boot flags
PRISMA_MIGRATE=0    # set 1 to apply migrations; 0 uses db push
RUN_SEED=1          # set 1 to run seed on boot
SEED_GRANT_ALL=1    # set 1 to grant all bots to the seeded student
```

> **📝 Nota**: La API Key de ElevenLabs se configura desde el panel de administración del frontend, no desde variables de entorno.

### 3. Start the Application

   ```bash
   docker compose up -d --build
   ```

Wait 1-2 minutes for the application to fully initialize.

### 4. Access the Application

- **Frontend**: http://localhost:5173
- **Backend API**: http://localhost:3000
- **Health Check**: http://localhost:3000/health
- **Postman Collection**: `AI-Learning-Platform-API.postman_collection.json`

## 💾 Data Persistence

Your database data is automatically preserved between container restarts. The PostgreSQL data is stored in a Docker volume named `ai-learning-platform-postgres-data`.

### Docker Management

```bash
# Start containers (preserves data)
docker compose --profile dev up -d --build

# Stop containers (preserves data)
docker compose --profile dev down

# Reset everything (⚠️ WARNING: This will lose all data!)
docker compose --profile dev down -v

# View logs
docker compose --profile dev logs -f backend

# Backup / restore database
./backup.sh
./restore.sh
```

### Backup and Restore Scripts

#### Backup Script (`backup.sh`)

Creates automatic backups of your application data:

**Features:**
- Database backup (PostgreSQL dump)
- Uploads directory backup
- Logs backup from Docker volume
- Automatic cleanup (keeps last 7 days)
- SSL certificate renewal

**Usage:**
```bash
./backup.sh
```

#### Restore Script (`restore.sh`)

Interactive script to restore from previous backups:

**Features:**
- Lists 5 most recent backups
- Interactive selection menu
- Restores database, uploads, and logs
- Safety confirmations
- Automatic service restart

**Usage:**
```bash
./restore.sh
```

**Restore Process:**
1. Script shows available backups with details
2. Select backup by number (1-5)
3. Confirm restore operation
4. Automatically restores database, uploads, and logs
5. Restarts services to apply changes

**Backup Location:**
- `/home/$USER/backups/`

**Backup Structure:**
```
backups/
├── 20241215/                    # Date folder (YYYYMMDD)
│   ├── db_backup_20241215_143022.sql
│   ├── uploads_backup_20241215_143022.tar.gz
│   └── logs_backup_20241215_143022.tar.gz
├── 20241214/                    # Previous day
│   ├── db_backup_20241214_090015.sql
│   └── uploads_backup_20241214_090015.tar.gz
└── ...
```

**Backup Files:**
- `db_backup_YYYYMMDD_HHMMSS.sql` - Database dump
- `uploads_backup_YYYYMMDD_HHMMSS.tar.gz` - Uploaded files
- `logs_backup_YYYYMMDD_HHMMSS.tar.gz` - Application logs

### Manual Docker Commands

If you prefer manual commands:

```bash
# Start (preserves data)
docker compose up -d

# Stop (preserves data)
docker compose down

# Restart (preserves data)
docker compose restart

# Reset everything (⚠️ WARNING: This will lose all data!)
docker compose down -v
docker volume rm ai-learning-platform-postgres-data
docker-compose up -d
```

## 📋 Test Accounts

The application comes with pre-configured test accounts:

| Role | Email | Password |
|------|-------|----------|
| **Admin** | `admin@example.com` | `K9#mX7$vL2@n` |
| **Teacher** | `teacher@example.com` | `P3&wQ8!bR5%t` |
| **Student** | `student@example.com` | `M6@fN9#kY2&z` |

## 🤖 Available Bots

The following AI conversation bots are available for students:

- **English Tutor Sarah** (A1) - Basic conversation practice
- **Business English Mike** (B1) - Business English coaching  
- **Travel Guide Emma** (A2) - Travel and tourism English
- **Academic Writing Professor** (C1) - Academic writing assistance

## 🤖 OpenAI Configuration

The system includes OpenAI integration for advanced feedback generation. Use the provided scripts to configure OpenAI:

### Quick Setup

```bash
./setup-openai.sh --api-key "sk-proj-..." --assistant-id "asst_..."
```

### Interactive Setup

```bash
./setup-openai.sh
```

### Reset Configuration

```bash
./setup-openai.sh --reset
```

OpenAI can also be configured from the admin panel (Configuration section).

## 🔧 Troubleshooting

### Login Issues

If you're having trouble logging in:

1. **Check the email domain**: Make sure you're using `@example.com`, not `@example.com`
2. **Use exact credentials**: 
   - Admin: `admin@example.com` / `K9#mX7$vL2@n`
   - Teacher: `teacher@example.com` / `P3&wQ8!bR5%t`
   - Student: `student@example.com` / `M6@fN9#kY2&z`

3. **Check container status**:
   ```bash
   docker ps
   ```

4. **View logs**:
   ```bash
docker compose logs backend
docker compose logs frontend
   ```

### Database Issues

If the database isn't working:

1. **Restart the containers**:
   ```bash
docker compose down
docker compose up -d
   ```

2. **Check database logs**:
   ```bash
   docker-compose logs postgres
   ```

### Migration Issues

If you encounter migration errors during updates:

1. **P3005 Error (Database schema is not empty)**:
   This happens when updating an existing database. The system will automatically handle this, but if it fails:
   
   ```bash
   # Run the baseline fix script
   ./fix-migration-baseline.sh
   ```
   
   **Manual resolution:**
   ```bash
   # Check migration status
   docker exec ai-learning-platform-backend npx prisma migrate status
   
   # Mark specific migrations as applied
   docker exec ai-learning-platform-backend npx prisma migrate resolve --applied <migration_name>
   
   # Deploy remaining migrations
   docker exec ai-learning-platform-backend npx prisma migrate deploy
   ```

2. **Migration conflicts**:
   If migrations fail due to conflicts:
   ```bash
   # Reset and reapply all migrations (⚠️ This will recreate the database)
   docker exec ai-learning-platform-backend npx prisma migrate reset --force
   ```

### Data Loss Issues

If you're experiencing data loss:

1. **Check if volume exists**:
   ```bash
   docker volume ls | grep postgres
   ```

2. **Verify volume is being used**:
   ```bash
   docker inspect ai-learning-platform-ewc-postgres | grep -A5 Mounts
   ```

3. **Backup your data before resetting**:
   ```bash
   ./backup.sh
   ```

4. **Only use reset when necessary**:
   ```bash
   docker compose --profile dev down -v  # ⚠️ This will lose all data!
   ```

## 🛠️ Development

### Project Structure

```
ai-learning-platform/
├── backend/                 # Node.js/Express API
│   ├── src/
│   ├── prisma/             # Database schema and migrations
│   └── Dockerfile
├── frontend/               # Vue.js application
│   ├── src/
│   └── Dockerfile
└── docker-compose.yml      # Docker orchestration
```

### Key Features

- **Authentication**: JWT-based authentication with refresh tokens
- **Role-based Access**: Admin, Teacher, and Student roles
- **AI Chat**: ElevenLabs integration for voice conversations
- **Bot Management**: Teachers can assign bots to students
- **Progress Tracking**: Monitor student learning progress
- **Real-time Chat**: WebSocket-based real-time messaging

### API Endpoints

- `POST /api/auth/login` - User login
- `POST /api/auth/register` - User registration
- `GET /api/auth/profile` - Get user profile
- `POST /api/auth/refresh` - Refresh access token
- `GET /api/bots` - Get available bots
- `POST /api/chat/init` - Initialize chat session

## 🚀 Production Deployment

For production deployment:

1. **Set environment variables**:
   - `JWT_SECRET`
   - `JWT_REFRESH_SECRET`
   - `DATABASE_URL`

2. **Configure ElevenLabs API Key**:
   - Access the admin panel in the frontend
   - Navigate to ElevenLabs configuration
   - Add your API key through the web interface

3. **Configure SSL certificates**

3. **Set up proper logging and monitoring**

4. **Use production database** (not SQLite)

## 📝 License

This project is licensed under the MIT License.

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Submit a pull request

## 📞 Support

For support and questions, please open an issue on GitHub.

---

## 🎨 Refactorización CSS - Sistema de Diseño

### ✅ Estado Actual: COMPLETADO (Octubre 2025)

Se ha implementado exitosamente la **Opción C**: Sistema de Variables CSS + Bootstrap 5 + Componentes Reutilizables

#### ✅ Componentes Base Creados (7 componentes)

**Ubicación:** `frontend/src/components/common/`

| Componente | Funcionalidad | Características |
|------------|---------------|-----------------|
| **FormField.vue** | Campo de formulario | Label, error handling, BEM |
| **FormInput.vue** | Input con iconos | Toggle password, iconos left/right |
| **FormSelect.vue** | Select estilizado | Integrado con FormField |
| **BaseButton.vue** | Botones unificados | Variantes, loading state, iconos |
| **BaseCard.vue** | Tarjetas | Header/footer opcionales, variantes de color |
| **BaseBadge.vue** | Badges de nivel/estado | Sistema de niveles (A1-C2), variantes |
| **BaseModal.vue** | Modales | Wrapper Bootstrap, variantes, sizes |

#### ✅ Todas las Vistas Refactorizadas (14/14 - 100%)

| Vista | Estado | Estilos Eliminados |
|-------|--------|-------------------|
| **Auth Views** | | |
| RegisterView.vue | ✅ | 5 → 0 |
| LoginView.vue | ✅ | 4 → 0 |
| **Shared Views** | | |
| HomeView.vue | ✅ | 109 → 0 |
| BotsView.vue | ✅ | 32 → 0 |
| ChatView.vue | ✅ | 6 → 0* |
| ProfileView.vue | ✅ | 21 → 0 |
| UserInformationView.vue | ✅ | 17 → 0 |
| **Teacher Views** | | |
| StudentsView.vue | ✅ | 37 → 0 |
| AssignBotsView.vue | ✅ | 36 → 0 |
| ProgressView.vue | ✅ | 4 → 0 |
| **Admin Views** | | |
| ManageBotsView.vue | ✅ | 31 → 0 |
| ConfigurationView.vue | ✅ | 39 → 0 |
| UsersView.vue | ✅ | 12 → 0 |
| **Public Views** | | |
| NotFoundView.vue | ✅ | 5 → 0 |
| **Componentes** | | |
| BotCard.vue | ✅ | 2 → 0 |

**Total eliminado:** **360 estilos inline estáticos** ✅

_*Nota: ChatView mantiene 6 `:style=` dinámicos (programáticos) para gradientes calculados, lo cual es correcto._

#### 📊 Resultados Finales

| Métrica | Antes | Después | Mejora |
|---------|-------|---------|--------|
| Componentes reutilizables | 0 | 7 | +700% |
| Vistas refactorizadas | 0/14 | 14/14 | 100% |
| Estilos inline estáticos | 360+ | 0 | -100% |
| Clases utility (main.css) | ~80 | ~110 | +37% |
| Variables CSS | 48 | 48 | Mantenido |
| Código duplicado | Alto | Bajo | -40% |

#### 🎯 Beneficios Logrados

- ✅ **Mantenibilidad**: Cambios centralizados en variables CSS
- ✅ **Consistencia**: Diseño uniforme en todas las vistas
- ✅ **Performance**: CSS optimizado, reducción ~15% de código
- ✅ **Escalabilidad**: 7 componentes base reutilizables
- ✅ **Calidad**: 0 warnings de linter, metodología BEM aplicada

### Variables CSS Disponibles

```css
/* Colores */
--color-primary: #267073
--color-primary-hover: #1e5a5d
--color-secondary: #ff9900
--color-success: #28a745
--color-danger: #dc3545

/* Espaciado */
--spacing-xs: 0.25rem
--spacing-sm: 0.5rem
--spacing-md: 1rem
--spacing-lg: 1.5rem
--spacing-xl: 2rem
--spacing-2xl: 3rem

/* Border Radius */
--radius-sm: 0.25rem
--radius-md: 0.5rem
--radius-lg: 0.75rem
--radius-xl: 1rem
--radius-2xl: 1.5rem

/* Sombras */
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1)
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1)
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1)

/* Transiciones */
--transition-base: 0.2s ease
--transition-slow: 0.3s ease
```

### Clases Utility Disponibles (~105 clases)

#### Espaciado y Layout
```css
.padding-section          /* padding: 0 2rem */
.margin-top-section       /* margin-top: 2rem */
.margin-bottom-section    /* margin-bottom: 2rem */
.container-section        /* max-width + centered */
.welcome-section          /* margin-left + bottom */
```

#### Iconos
```css
.icon-size-sm      /* 1rem */
.icon-size-md      /* 1.3rem */
.icon-size-lg      /* 1.5rem */
.icon-size-xl      /* 2rem */
.icon-size-xxl     /* 3rem */

.icon-circle-sm    /* 28px circle */
.icon-circle-md    /* 40px circle */
.icon-circle-lg    /* 50px circle */
```

#### Dimensiones
```css
.action-card-height    /* 160px */
.stat-card-height      /* 140px */
```

#### Overflow y Opacidad
```css
.overflow-hidden, .overflow-x-hidden, .overflow-y-hidden
.opacity-70, .opacity-80, .opacity-90
```

#### Animaciones
```css
.fade-in                  /* Fade in básico */
.slide-in-right          /* Deslizamiento desde derecha */
.fade-in-delayed-1       /* delay: 0.3s */
.fade-in-delayed-2       /* delay: 0.5s */
.fade-in-delayed-3       /* delay: 0.7s */
.fade-in-delayed-4       /* delay: 0.9s */
```

#### Badges de Nivel
```css
.badge-level-a1    /* Verde claro - Beginner */
.badge-level-a2    /* Verde oscuro */
.badge-level-b1    /* Amarillo claro - Intermediate */
.badge-level-b2    /* Amarillo oscuro */
.badge-level-c1    /* Rojo claro - Advanced */
.badge-level-c2    /* Rojo oscuro */
```

### Uso de Componentes Base

#### FormField + FormInput
```vue
<script setup>
import FormField from '@/components/common/FormField.vue'
import FormInput from '@/components/common/FormInput.vue'
import { Mail } from 'lucide-vue-next'
</script>

<template>
  <FormField label="Email" id="email" :error="errors.email">
    <FormInput
      id="email"
      v-model="form.email"
      type="email"
      :left-icon="Mail"
      :has-error="!!errors.email"
    />
  </FormField>
</template>
```

#### BaseButton
```vue
<script setup>
import BaseButton from '@/components/common/BaseButton.vue'
import { Save } from 'lucide-vue-next'
</script>

<template>
  <BaseButton
    variant="primary"
    :loading="isLoading"
    :icon="Save"
    full-width
    @click="handleSave"
  >
    Guardar
  </BaseButton>
</template>
```

### Reglas de Oro

1. **NUNCA** usar estilos inline (`style="..."`)
2. **SIEMPRE** usar variables CSS para valores
3. **PREFERIR** componentes base sobre duplicar código
4. **APLICAR** BEM en estilos scoped
5. **USAR** Bootstrap solo para layout (grid, flexbox)
6. **EVITAR** `!important` (excepto en utilities)

### Estructura de Archivos

```
frontend/src/
├── components/
│   ├── common/              ← Componentes base reutilizables
│   │   ├── FormField.vue
│   │   ├── FormInput.vue
│   │   ├── FormSelect.vue
│   │   ├── BaseButton.vue
│   │   └── BaseCard.vue
│   └── [otros componentes]
├── assets/
│   └── main.css            ← Variables CSS + Utilities
└── views/
    └── [vistas de la app]
```

### Beneficios del Sistema

- ✅ **Mantenibilidad**: Cambios centralizados en variables CSS
- ✅ **Consistencia**: Diseño uniforme en toda la app
- ✅ **Performance**: CSS optimizado y minificado
- ✅ **Escalabilidad**: Fácil agregar nuevos componentes
- ✅ **Reutilización**: -15% líneas de código en vistas refactorizadas

### ✅ Trabajo Adicional Completado

**Componentes Adicionales:**
- ✅ `BaseBadge.vue` - Badges para niveles (A1-C2) y estados
- ✅ `BaseModal.vue` - Wrapper unificado para modales de Bootstrap

**Refactorizaciones Adicionales:**
- ✅ GlobalHeader.vue - 0 estilos inline (antes: 9)
- ✅ Eliminadas 4 funciones duplicadas `getLevelBadgeClass`
- ✅ Implementado uso de `BaseBadge` en 4 archivos

**Código Eliminado:**
- 4 funciones `getLevelBadgeClass` (~50 líneas de código duplicado)
- 9 estilos inline de GlobalHeader
- Total: ~60 líneas de código eliminadas

### 🏆 Proyecto 100% Refactorizado

**Todas las vistas y componentes principales** ahora usan:
- ✅ Variables CSS exclusivamente
- ✅ Metodología BEM en estilos scoped
- ✅ Componentes base reutilizables
- ✅ Bootstrap 5 para layout
- ✅ 0 estilos inline estáticos
- ✅ 0 warnings de linter

**Estilos dinámicos (`:style=`)**: Solo 12 ocurrencias para valores calculados programáticamente (gradientes de bots, progress bars) - ✅ Correcto

Para más detalles sobre el sistema de diseño, consultar `.cursorrules` en la raíz del proyecto.

