# EL3AB Multiplayer Overhaul — Implementation Plan

## Status: PHASE 1 COMPLETE — READY FOR PHASE 2

---

## AUDIT RESULTS SUMMARY

### Total Issues Found: 73
- **CRITICAL**: 24
- **HIGH**: 31
- **MEDIUM**: 29
- **LOW**: 18

---

## TOP CRITICAL ISSUES (Must Fix First)

### Ludo Critical
1. **START_POSITIONS mismatch**: `rules.js [0,13,26,39]` vs `board-map.js [1,14,27,40]` — OFF BY 1, breaks ALL capture logic
2. **Positions data format mismatch**: server sends `[{pos:[]},{pos:[]}]` but client expects same — live multiplayer state sync BROKEN
3. **Dead code in doMove()**: unreachable code after early return
4. **Capture position mapping**: `toGlobalPos()` confusion breaks capture detection entirely
5. **Home stretch captures**: pieces in home column can be incorrectly captured
6. **Queue race condition**: not atomic, player can be in multiple matches

### Chess Critical
7. **No server-side move validation**: client sends any FEN, server trusts it — CHEATING POSSIBLE
8. **Draw offer unimplemented**: button does nothing
9. **Live polling race condition**: 2s gap can skip opponent's moves
10. **Clock timing drift**: 100ms interval accumulates 5-10s error per hour
11. **Rating-based matching not implemented**: matches ANY opponent regardless of rating
12. **No game state locking**: simultaneous requests can corrupt match

### Core Infrastructure Critical
13. **Duplicate realtime code**: net.js has copy of realtime.js logic — maintenance nightmare
14. **Token refresh infinite loop**: 401 → refresh → 401 → refresh → stack overflow
15. **No reconnection backoff**: fixed 3s retry hammers server on outage
16. **Silent error swallowing**: EVERY catch block is empty `catch(e){}`
17. **Hardcoded credentials**: ANON_KEY in plaintext in two files
18. **Connection state race**: subscribe() called before WebSocket fully connected

---

## PHASE 2: Ludo Rules & Board Fix

### Priority Fixes
1. Fix START_POSITIONS constant (align rules.js with board-map.js)
2. Fix positions data format (server/client agreement)
3. Fix toGlobalPos capture logic
4. Prevent home column captures
5. Add "three 6s = lose turn" rule
6. Fix exact finish requirement
7. Fix bot AI priority (finish > capture > enter > advance)
8. Remove dead code in doMove()

---

## PHASE 3: Ludo Game Feel (30+ features)

### To Implement
1. Landing squish/bounce on each hop
2. Trail particles during movement
3. Capture explosion with particles
4. Home entry sparkle
5. Star twinkle ambient animation
6. Dice anticipation buildup
7. Turn change swoosh
8. Win sequence (pieces dance)
9. Near-finish tension glow
10. Stacking indicator
11. Move preview (ghost piece)
12. Camera zoom on captures
13. Piece selection pulse
14. Invalid move shake
15. Timer urgency effects
16. Move history log
17. Spectator count
18. Rating change on result
19. Rematch with countdown
20. Disconnect overlay
21. Reconnection indicator
22. Piece shadow grows during hop
23. Board edge glow on player's turn
24. Dice face cycling animation (not just random)
25. Victory confetti from winner's corner
26. Sound pitch ladder (ascending per hop)
27. Bot "personality" emotes (different per bot)
28. Piece wobble when waiting for selection
29. Safe square pulse when piece lands
30. Finish zone celebration per piece

---

## PHASE 4: Bot Personalities

### Profiles to Build
| Profile | Think Time | Decision | Emotes | Move Quality |
|---------|-----------|----------|--------|-------------|
| Speed Demon | 0.3-0.8s | Instant | 😎💨 | Always aggressive |
| Casual | 1-3s | Slow | 👋🤷 | Sometimes suboptimal |
| Strategist | 1.5-2.5s | Methodical | 🤔💡 | Always optimal |
| Beginner | 2-4s | Hesitant | 😅❓ | Often wrong piece |
| Troll | 0.5-1s | Fast | 😂🤣 | Captures only |

---

## PHASE 5: Multiplayer Integration

### Player Identity (Both Games)
- Real avatar from profile (not emoji)
- Username (not "Opponent" or "Bot X")
- Level badge
- Rank tier color
- Tap to inspect/add friend

### Presence System
- Green/Yellow/Red connection dot ✅ (exists but needs fixing)
- "Opponent thinking..." indicator
- "Opponent disconnected" full overlay with countdown
- Auto-win after 60s disconnect

---

## PHASE 6: Sync Architecture Redesign

### Current: Polling (2s)
- Race conditions
- Missed moves possible
- High server load
- No ordering guarantee

### Target: Hybrid (Realtime + Fallback Polling)
- Supabase Realtime as primary channel
- 5s polling as fallback (not 2s)
- Event sequence numbers
- Server validates move legality
- Optimistic local execution
- Rollback on server reject

---

## PHASE 7: Chess Animation

### Fixes
- Smooth piece movement tween (200ms ease-out)
- Capture animation (piece fades + particles)
- Highlight sync in multiplayer
- Implement draw offer UI
- Fix clock with performance.now()
- Activate premove system

---

## PHASE 8: Reusable Player Panel

### Component API
```javascript
PlayerPanel({
  avatar, username, level, rank, rating,
  isActive, connectionStatus,
  onTap: () => showProfile()
})
```
- Used by Chess, Ludo, Domino
- Consistent sizing across games
- Animated turn indicator
- Connection quality dot

---

## PHASE 9: Framework Extraction

### New Core Modules
- `core/match-manager.js` — lifecycle state machine
- `core/turn-system.js` — turn management + timers
- `core/presence.js` — WebSocket presence tracking
- `core/reconnect.js` — exponential backoff + state recovery
- `core/validation.js` — server-side move validation patterns

---

## PHASE 10: Testing Matrix

| Test Case | Chess | Ludo |
|-----------|-------|------|
| Bot game to completion | ✅ Works | ✅ Works |
| Live 2-player match | ⚠️ Polling issues | ⚠️ Broken sync |
| Disconnect + reconnect | ❌ Not handled | ❌ Not handled |
| Simultaneous moves | ❌ Race condition | ❌ Race condition |
| Emote sync | ⚠️ Partial | ⚠️ Partial |
| Friend add from match | ✅ Works | ✅ Works |
| Rating update | ✅ Works | ❌ Not implemented |

---

## EXECUTION ORDER

1. Fix Ludo START_POSITIONS (5 min)
2. Fix positions data format (10 min)
3. Fix capture logic (30 min)
4. Remove dead code (5 min)
5. Fix bot AI priority (10 min)
6. Add turn timeout (20 min)
7. Build player panel component (1 hr)
8. Implement chess draw offer (30 min)
9. Fix clock precision (20 min)
10. Add reconnection backoff (30 min)
11. Error handling sweep (1 hr)
12. Game feel animations (2 hr)
13. Bot personalities (1 hr)
14. Sync architecture (2 hr)
15. End-to-end testing (1 hr)

**Estimated total: ~10 hours of work**
