# EL3AB — Master Plan

**What is this:** A GAME that runs in the browser. Not a website with games. A game.
**Stack:** PHP 8.3 (API-only backend) + Vanilla JS game engine (frontend) + CSS
**Database:** PostgreSQL 15 via Supabase (self-hosted, 106 tables)
**Deploy:** Docker → CapRover (auto-deploy on git push)
**Companion:** EL3AB Management System (separate repo, already built — 38 admin modules)

---

## System Context

EL3AB has THREE codebases sharing ONE Supabase database:

| System | Repo | Purpose | Status |
|--------|------|---------|--------|
| **Player App** (this repo) | el3ab-player | Player-facing web app | IN PROGRESS |
| **Management Panel** | el3ab-management | Admin panel (38 modules) | BUILT |
| **Unity Mobile App** | (Unity project) | Mobile game client | EXISTS |

All three share the same Supabase instance (106 tables, 165 FKs, 111 RLS policies).

---

## Architecture Overview

```
┌─────────────────────────────────────────────────────────┐
│                    SUPABASE (PostgreSQL)                  │
│  106 tables · 22 enums · 11 functions · 9 storage buckets│
├─────────────────────────────────────────────────────────┤
│         │                    │                    │       │
│    Player App          Management Panel     Unity App    │
│    (this repo)         (el3ab-management)   (mobile)     │
│                                                          │
│  • Uses ANON key       • Uses SERVICE key  • Uses ANON   │
│  • RLS enforced        • Bypasses RLS      • RLS + RPC   │
│  • User JWT auth       • Session auth      • GoTrue JWT  │
│  • PHP API proxy       • PHP direct CRUD   • Direct REST │
└─────────────────────────────────────────────────────────┘
```

---

## Server & Connections

| Resource | URL/Host |
|----------|----------|
| Server IP | 3.68.63.185 |
| SSH | `ssh -i "Connections and docs /NewServer.pem" ubuntu@3.68.63.185` |
| Supabase Kong | https://safe-supabase-kong.caprover.al-arcade.com |
| Supabase Studio | https://safe-supabase-studio.caprover.al-arcade.com |
| Supabase Anon Key | eyJhbGci...anon... |
| Supabase Service Key | eyJhbGci...service_role... |
| App URL | https://el3ab-player.caprover.al-arcade.com |
| Stockfish API | https://stockfishapi.caprover.al-arcade.com |
| Swiss API | https://swissapi.caprover.al-arcade.com/api/v1 |

---

## What the Management System Already Handles

The management panel (el3ab-management) already provides admin CRUD for:

**Core:** Dashboard, Players, Games, Chess Bots, Tournaments, Organizations, Economy, Ads, Moderation, Feature Flags, Settings, Branding, Analytics, Notifications, Audit Log

**Org System (18 modules):** Achievements, Announcements, Applications, Challenges, Chat, Content, Events, Frames, Invites, Leaderboards, Loyalty, Media, Partnerships, Recruitment, Rosters, Spotlights, Training, Transfers, Treasury

**Tournament Services:** Swiss pairing engine, Bracket engine, Arena engine, Phase manager, Bot simulation, Export (TRF/JSON), Live tournament pages

**This means:** The player app does NOT need admin functionality. It only needs player-facing features.

---

## Player App Scope

The player app handles ONLY what players interact with:

### Must Have (Phase 1-5)
1. Auth (login/register/session)
2. Player profile (view/edit own + view others)
3. Chess game (vs bot, vs human, time controls, ratings)
4. Matchmaking (queue, find opponent, start game)
5. Domino multiplayer (create/join room, play)
6. Ludo multiplayer (create/join room, play)
7. Friends (request/accept/list/online status)
8. Notifications (realtime)
9. Leaderboards (by game/time-control)
10. Puzzles (chess training)

### Should Have (Phase 6-8)
11. Shop (cosmetics purchase/equip)
12. Achievements (progress, unlock)
13. Daily rewards (claim, streak)
14. Tournament registration + bracket viewing
15. Organizations (browse, join via invite)
16. Analysis (post-game analysis)

### Nice to Have (Phase 9+)
17. Backgammon game
18. Activity feed
19. Org chat
20. Spectator mode

---

## Core Philosophy

1. **This is a GAME.** Screens, not pages. Scenes, not routes. HUD, not header. Reward ceremonies, not success messages.
2. **Modular.** Each game/feature is a sealed module. Working on Module X = touching ONLY Module X's folder.
3. **Always alive.** No dead screens. Ambient animations. Pulsing elements. The game breathes.
4. **Immediate feedback.** Every tap gets visual + audio response in < 16ms.
5. **Progression visible.** XP bar, coin counter, rank badge visible at ALL times in the HUD.
6. **No page loads.** Single HTML shell. Scene manager handles all transitions in-memory.

## Tech Decisions

| Decision | Choice | Reason |
|----------|--------|--------|
| Frontend Architecture | Game engine (scene manager + module system) | Game feel, not web feel |
| Backend | PHP 8.3 (API-only, JSON responses) | No HTML rendering, pure data server |
| Frontend | Vanilla JS (ES6 modules) + CSS | Zero framework overhead, game-loop friendly |
| Chess logic | chess.js (client) | Instant move validation, standard PGN/FEN |
| Bot moves | Stockfish API | External service, already running |
| Realtime | Supabase Realtime (WS) | Native to the DB, no extra infra |
| Auth | Supabase GoTrue (REST) | Already configured, trigger creates profile |
| Animation | Custom tween engine | Game-quality animations without a library |
| Audio | Web Audio API + sprite sheets | Sound is a first-class game concern |
| State | Reactive store + event bus | Modules communicate without coupling |
| API pattern | PHP proxy layer (JSON only) | Hides keys, CORS-free, stateless |

---

## Design System

| Token | Value | Usage |
|-------|-------|-------|
| --bg-0 | #050D17 | Page background |
| --bg-1 | #0A1525 | Header/nav |
| --bg-2 | #142640 | Cards |
| --bg-3 | #1C3254 | Inputs, elevated |
| --gold | #E7A832 | Brand accent, primary CTA |
| --cyan | #15D7FF | Secondary accent |
| --blue | #2979FF | Links |
| Font | IBM Plex Sans Arabic + Inter | Arabic-first |
| Direction | RTL | dir="rtl" on html |
| Icons | SVG sprite | No emojis anywhere |

---

## Key Database Tables (Player App)

| Table | Player App Usage |
|-------|-----------------|
| profiles (50+ cols) | Central player identity, ratings, stats, economy |
| matches (39 cols) | Chess game records (FEN, PGN, moves, ratings) |
| domino_matches | Domino game state (board, hands, scores) |
| ludo_matches | Ludo game state (positions, dice, turns) |
| matchmaking_queue | Live matchmaking |
| friendships | Friend requests/connections |
| notifications | Player notifications |
| leaderboards | Cached rankings |
| puzzles | Chess puzzles |
| cosmetics / player_cosmetics | Shop items |
| achievements / player_achievements | Achievement system |
| economy_transactions | Currency history |
| player_game_ratings | Multi-game ratings |
| rating_history | Rating over time |
| el3ab_tournaments | Tournament listings |
| tournament_registrations | Player signups |
| game_plugins | Available games |
| feature_flags | Feature toggles |
| xp_levels | Level thresholds |

---

## API Endpoints (Player App)

| File | Methods | Purpose |
|------|---------|---------|
| api/auth.php | POST | signup, login, logout, refresh |
| api/profile.php | GET, PATCH | get/update profile, avatar |
| api/game.php | POST | start, move, resign, draw, complete |
| api/matchmaking.php | POST, DELETE | queue, dequeue, find |
| api/domino.php | POST | create, join, move, end |
| api/ludo.php | POST | create, join, roll, move, end |
| api/friends.php | GET, POST, DELETE | list, request, accept, remove |
| api/notifications.php | GET, PATCH | list, mark-read |
| api/leaderboard.php | GET | by game/time-control/country |
| api/puzzles.php | GET, POST | random, by-rating, submit |
| api/shop.php | GET, POST | list, purchase, equip |
| api/achievements.php | GET | list with progress |
| api/daily-reward.php | POST | claim |
| api/tournaments.php | GET, POST | list, register, cancel |
| api/bots.php | GET, POST | list bots, proxy move |
| api/ratings.php | GET | history |
| api/analysis.php | POST | request analysis |
| api/orgs.php | GET | browse, detail |
| api/multiplayer.php | POST | generic room management |
| api/theme.php | GET | current theme tokens |
| api/config.php | GET | feature flags, game plugins |

---

## Implementation Phases (16 phases, 106/106 tables covered)

### Phase 0: Engine Core (14 tables)
Scene manager, store, bus, net, tween, audio, HUD, module loader, **dynamic theming system** (3-layer: platform + game + org), **ad slot system**, config API.

### Phase 1: Auth Module (4 tables)
Splash → Login → Register. Token management. Profile bootstrap. Role awareness.

### Phase 2: Play World (2 tables)
Game carousel with canvas previews. PLAY button. Mode picker. Bot/time selectors. Queue scene. **Lobby ad banner slot.**

### Phase 3: Chess Module (4 tables)
Full chess vs bots. Canvas board@60fps. Clock. Moves. Rating calc. Result ceremony. **In-game emotes + text chat (for friends).** **Report opponent.**

### Phase 4: Chess Live (0 new tables)
Matchmaking. Realtime moves. Clock sync. Draw offer. Rematch. **Interstitial ad between matches.**

### Phase 5: Domino Module (2 tables)
2-4p domino. Canvas table. Tile chains. Scoring. Multi-round. Realtime. Bot AI. Chat/emotes.

### Phase 6: Ludo Module (2 tables)
2-4p ludo. Canvas board. Dice. Captures. Extra turns. Finish. Bot fill. Chat/emotes.

### Phase 7: Social Module (4 tables)
Friends. Notifications (realtime badge). **Activity feed (social timeline).** **Report system.** Org entry point.

### Phase 8: Organization Module — THE BIG ONE (28 tables)
Full org member experience as a **sub-world inside SOCIAL**: browse, join (link/code/application), org home, announcements, chat (channels + realtime), events (calendar + RSVP + training), members, compete (internal leaderboard + inter-org challenges + seasonal rankings + rosters), rewards (org achievements + loyalty claims), content (articles + media gallery), recruitment (browse posts + apply), treasury view, referrals, spotlights, **org theming applied.** Clubs merged as lightweight orgs.

### Phase 9: Rewards Module (4 tables)
Daily rewards (chest animation). Achievements (grid + progress + unlock ceremony). Level-up. Coin/gem particle effects. Rank-up animation.

### Phase 10: Profile Module (3 tables)
Player card + frame system. Stats. Rating chart. Match history. Frame equip/browse. Settings.

### Phase 11: Shop Module (2 tables)
Cosmetics browsing (categories, rarity). Purchase flow. Equip. Collection. Limited-time items.

### Phase 12: Rank Module (22 tables)
Leaderboards (tabs). **Tournaments** (full): list, detail, register, brackets, standings, rounds, announcements, media, prizes, **sponsor branding, charity badges**, format info, multi-phase viewing, realtime bracket updates. **Tournament ad slots.**

### Phase 13: Puzzles Module (1 table)
Chess puzzles. Timer. Rating. Streaks. Reward video ad option.

### Phase 14: Trivia Module — PLANNED (1 table)
Module slot registered. "Coming soon" card in carousel. API stub.

### Phase 15: Clubs (2 tables)
Merged into org system. Clubs appear as lightweight orgs in browser.

### Phase 16: Polish (3 tables)
Loading/empty/error states. RTL polish. Responsive. Offline. Security. Workflow rules respect. Approval request states. Deploy.

**Coverage: 106/106 tables. 103 player-facing (built). 3 admin-only (not applicable).**

**Each phase is ONE module. Working on it means touching ONLY that module's folder (+ its API endpoint).**

---

## Autonomous Development Workflow

I (Claude) operate fully autonomously. No permission prompts. No human check-ins. The workflow:

### Development Loop
```
1. Build module code locally
2. Test locally if possible (PHP syntax check, JS lint)
3. Git add + commit (descriptive message)
4. Git push (triggers CapRover auto-deploy)
5. Wait ~30s for deploy
6. SSH into server to verify deployment succeeded
7. Use curl/wget to hit the deployed app and validate
8. If something breaks: fix, commit, push, re-verify
9. Move to next task in the phase
```

### SSH Access
```bash
ssh -i "Connections and docs /NewServer.pem" ubuntu@3.68.63.185
```

### Deploy Verification
```bash
# Check CapRover app is running
ssh ... "sudo docker ps | grep el3ab-player"

# Check app responds
curl -s -o /dev/null -w "%{http_code}" https://el3ab-player.caprover.al-arcade.com

# Check specific API endpoints
curl -s https://el3ab-player.caprover.al-arcade.com/api/config.php
```

### Testing Strategy (Per Module)
- **Auth:** Register a test user, verify login, check token refresh
- **Chess:** Start game vs bot, make moves, verify Stockfish responds, verify rating calc
- **Domino/Ludo:** Create room, verify state updates via API
- **Social:** Create friendship, send notification, verify realtime
- **Shop:** List cosmetics, attempt purchase, verify balance deducted
- **Tournaments:** List tournaments, register, verify bracket data
- **Each game mode:** Play through to completion, verify result stored correctly

### Error Recovery
- If deploy fails: check Docker logs via SSH
- If API returns 500: read PHP error log via SSH
- If Supabase returns error: check table/column names against audit
- If CapRover unreachable: wait 60s, retry

### Git Strategy
- One commit per logical unit of work (not per file)
- Commit messages: `feat(module): description` or `fix(module): description`
- Push after every working increment (don't batch)
- Never force push

### Permissions Config
`.claude/settings.json` is set to `bypassPermissions` — all tools allowed without prompting.

---

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|-----------|
| Rating calc bugs | Players lose trust | Unit test Elo formula, match management panel values |
| Realtime race conditions | Corrupted game state | Validate full state server-side on each move |
| Service key exposure | Security breach | Never in client code, env vars only |
| Dual org/tournament systems | Confusing queries | Player app only uses el3ab_* tables |
| Unity app column conflicts | Data inconsistency | Respect existing columns (numeric_id, unity_auth_id) |

---

## Coordination with Management Panel

The management panel at el3ab-management already handles:
- All admin CRUD operations (service_role key)
- Tournament creation/pairing/results
- Player banning/currency grants
- Feature flag management
- Org administration
- Bot management

The player app should:
- NEVER duplicate admin functionality
- Use same DB tables, same column names, same enums
- Respect RLS policies (use anon key + user JWT)
- Match management panel's API patterns (cURL-based Supabase REST)
- Share the same design language (adapted for player context)
