# Widget Generation Workflow

> **Single source of truth** para el proceso de generación de widgets.

**Status:** MANDATORY - Read before generating any widget

---

## Quick Start Checklist

Antes de generar cualquier widget:

- [ ] Leer `INDEX.md` (iconos PascalCase, warnings críticos)
- [ ] Tener `reference/architecture.md` abierto para referencia
- [ ] Iniciar desde el `dynamic-react-vite-base-template` canonical (Prompt `widgets-init-project` → Tool `widgets-scaffold`)
- [ ] Verificar que el prompt describe **funcionalidades de negocio**, no capas técnicas

---

## 🚨 CRITICAL PRINCIPLE: Always Deliver Functional Value

**RULE:** Every generation phase MUST produce a widget that:
- ✅ Compiles without errors
- ✅ Runs and displays data
- ✅ Includes package.json with ALL dependencies
- ✅ Passes validator >= 95%
- ✅ Uses correct icon format (PascalCase)

**NEVER generate:**
- ❌ Partial widget that doesn't compile
- ❌ Types/repositories without UI
- ❌ Technical layers that user can't see/use

---

## 📊 Token Budget Strategy

Before generating, estimate token requirements:

### Simple Widget (< 4000 tokens)
- 2-3 components
- 1-2 features
- Basic mock data
- **Strategy:** Generate in single phase

### Medium Widget (4000-8000 tokens)
- 4-6 components
- 3-4 features
- Complex data structures
- **Strategy:** Generate in 2 phases (MVP → Full)

### Complex Widget (> 8000 tokens)
- 7+ components
- 5+ features
- Multiple data sources
- Charts/visualizations
- **Strategy:** Generate in 3+ phases (MVP → Enhanced → Complete)

### Token Budget Guidelines
- Simple component: ~500 tokens
- Repository + mock: ~800 tokens
- Store slice: ~600 tokens
- Complex component: ~1200 tokens
- Complete widget (MVP): ~4000 tokens

---

## 🎯 Generation Phases (Business-Focused)

### ✅ CORRECT: Divide by Business Features

**Example: Banking Dashboard**

**Phase 1 - MVP (Must be FUNCTIONAL):**
```
Features:
- Display account balance in hero card
- Show table of last 10 transactions
- Search by transaction description

Output: Complete working widget
```

**Phase 2 - Analytics:**
```
Add to Phase 1:
- Line chart: balance trend over 6 months
- Pie chart: spending by category
- Summary cards: income, expenses, savings

Output: Enhanced working widget (Phase 1 + charts)
```

**Phase 3 - Advanced:**
```
Add to Phase 2:
- Transaction detail modal
- Category and date filters
- Unusual spending alerts

Output: Complete widget with all features
```

### ❌ INCORRECT: Divide by Technical Layers

**NEVER divide like this:**
```
Phase 1: Create types, repositories, mocks
Phase 2: Create store and hooks
Phase 3: Create UI components
```

**Why wrong:** User sees NOTHING until Phase 3. Phases 1-2 are not functional.

---

## 🔄 Generation Order (Internal)

Within each phase, generate files in this order:

1. **Foundation:** package.json, configs (tsconfig, vite.config.ts)
2. **Types:** src/types/*.ts
3. **Data:** src/services/mocks/data/*.ts, src/services/repositories/*.ts
4. **State:** src/store/useUIStore.ts
5. **Logic:** src/hooks/*.ts, src/utils/*.ts
6. **UI:** src/components/*.tsx, App.tsx, index.tsx
7. **Supporting:** src/locales/*.json, README.md

---

## Pre-Generation Checklist

### Documentation Review
- [ ] Read `INDEX.md` (critical warnings)
- [ ] Check `quick-reference.md` for component lookup
- [ ] Verify components are documented in `components/`

### Icons
- [ ] PascalCase → ver `components/icons.md`

### Structure
- [ ] Start from the canonical `dynamic-react-vite-base-template` first (NEVER create configs from scratch)
- [ ] Know file locations (`reference/architecture.md`)

### Mocks y APIs
- [ ] Usar patrón Liquid para toggle mocks/API (`patterns/liquid-environment.md`)
- [ ] NO usar `.env` ni `import.meta.env.VITE_*` para configuración de mocks
- [ ] Repositorios importan `USE_MOCKS` desde `config/widgetConfig.ts`

### Components
- [ ] Check `components/_index.md` for available components
- [ ] For undocumented components → READ SOURCE FIRST
- [ ] Don't guess prop names

---

## During Generation Checklist

- [ ] Root uses `.container` (NOT `.container-fluid`)
- [ ] Icons use PascalCase (NOT kebab-case)
- [ ] Props verified against docs/source (NOT guessed)
- [ ] Scripts copied from base-template (NOT invented)
- [ ] Arrow functions for components (NOT function declarations)

---

## Post-Generation Checklist

### Verification Commands
```bash
# Check container usage (must return 0 matches)
grep -rn "container-fluid" src/

# Check icon format (must return 0 matches)
grep -rn 'icon.*=["'"'"'][a-z]+-' src/

# TypeScript check
npx tsc --noEmit

# Validator (target: >= 95%) — preferido: tool MCP `widgets-validate`
# (acepta projectPath o projectFiles). Fallback sin MCP:
npx @modyo/widget-validator /path/to/widget
```

### Visual Checks
- [ ] Widget displays correctly
- [ ] No "?" icons (all icons render)
- [ ] No "NaN" values displayed
- [ ] No console errors
- [ ] Layout looks correct

---

## Common Mistakes

### 1. DSpinner no existe
```tsx
// ❌ WRONG
import { DSpinner } from '@dynamic-framework/ui-react';

// ✅ CORRECT - Use Bootstrap spinner
<div className="spinner-border text-primary" role="status">
  <span className="visually-hidden">Loading...</span>
</div>
```
**See:** `components/feedback.md` → Loading States

### 2. DPaginator estado no controlado
```tsx
// ❌ WRONG - current from API response
<DPaginator current={apiResponse.page} ... />

// ✅ CORRECT - current from local state
<DPaginator current={filters.page || 1} ... />
```
**See:** `components/navigation.md` → DPaginator

### 3. Function declarations en lugar de arrow functions
```tsx
// ❌ WRONG
function MyComponent() { ... }

// ✅ CORRECT
const MyComponent = () => { ... };
```
**See:** `INDEX.md` → Code Style

### 4. Wrong container class
```tsx
// ❌ WRONG - stretches too wide
<div className="container-fluid py-4">

// ✅ CORRECT
<div className="container py-4">
```

### 5. Wrong icon format
```tsx
// ❌ WRONG - shows "?"
<DIcon icon="credit-card" />

// ✅ CORRECT
<DIcon icon="CreditCard" />
```

### 6. DBadge iconStart (no existe)
```tsx
// ❌ WRONG - prop doesn't exist
<DBadge text="Auto" iconStart="Car" />

// ✅ CORRECT - text only
<DBadge text="Auto" color="secondary" />
```
**See:** `components/feedback.md` → DBadge

---

## Debugging Workflow

1. **Error de compilación**: Check exact message, search in `components/`
2. **Componente no existe**: Verify in `components/_index.md` for alternatives
3. **Props incorrectos**: Read component category file in `components/`
4. **Validator falla**: Check `reference/validator-rules.md`
5. **Icons show "?"**: Convert to PascalCase

---

## Reference Files

| Necesito... | Archivo |
|-------------|---------|
| Empezar (leer primero) | `INDEX.md` |
| Lista de componentes | `components/_index.md` |
| Componentes de input | `components/inputs.md` |
| Loading states / spinners | `components/feedback.md` |
| Paginación | `components/navigation.md` |
| Iconos disponibles | `components/icons.md` |
| Estructura de carpetas | `reference/architecture.md` |
| Patrón Zustand | `patterns/zustand.md` |
| Patrón TanStack Query | `patterns/tanstack-query.md` |
| Patrón Repository | `patterns/repository.md` |
| Patrón Liquid (mocks/API) | `patterns/liquid-environment.md` |
| Patrón i18n | `patterns/i18n.md` |
| Troubleshooting | `reference/troubleshooting.md` |

---

## Success Metrics

**Target per widget:**
- Time: ≤ 40 minutes
- Errors: ≤ 1
- Iterations: ≤ 3
- Validator: ≥ 95%

**Track for each widget:**
- Generation time (minutes)
- Number of errors
- Number of iterations
- Types of errors (categorize)
- Documentation gaps found

---

**Remember:** Your goal is to deliver working code, not perfect code. User can iterate and improve after validating the MVP.
