# Next Session Plan - Frontend Phase F7: Polish & Advanced Features

**Current Status**: Phase F6 Complete - Full Game Page Integration with Real-Time Gameplay
**Last Session**: 2025-01-20 - Phase F6 completion with WebSocket authentication fix
**Date**: 2025-01-20
**Progress**: Frontend ~95% complete (Phases F1-F6 complete)

---

## Quick Start for Next AI Agent

### 🎯 Where to Begin
1. Read this entire document first
2. Start backend: `cd backend && uv run python -m app.main`
3. Start frontend: `cd frontend-sba && npm run dev`
4. Visit: http://localhost:3000/games/[game-id]
5. Test complete gameplay flow (see Testing Checklist below)

### 📍 Current Context

**Phase F6 COMPLETE** ✅ - Full game page integration with all components

**Major Accomplishment**: Complete gameplay flow from decisions → dice → outcome → result, fully integrated with WebSocket real-time updates

**What's Working**:
- ✅ Complete turn-based gameplay cycle
- ✅ All Phase F2-F5 components integrated into main game page
- ✅ Conditional panel rendering based on game phase
- ✅ WebSocket real-time state synchronization
- ✅ JWT authentication for WebSocket connection
- ✅ Mobile and desktop responsive layouts
- ✅ Dynamic sticky positioning for Play-by-Play
- ✅ Substitution modal with floating action button
- ✅ Loading states, error handling, connection recovery

**All Previous Phases Complete**:
- ✅ Phase F1: Foundation (composables, stores, types)
- ✅ Phase F2: Game Display (ScoreBoard, GameBoard, CurrentSituation, PlayByPlay)
- ✅ Phase F3: Decision Inputs (DefensiveSetup, OffensiveApproach, StolenBaseInputs, DecisionPanel) - 213 tests
- ✅ Phase F4: Dice & Outcome (DiceRoller, ManualOutcomeEntry, PlayResult, GameplayPanel) - 119 tests
- ✅ Phase F5: Substitutions (3 selectors + SubstitutionPanel) - 114 tests
- ✅ **Phase F6: Integration** - Full game page (~500 lines)

**Backend Status**: 100% ready (739/739 tests, all WebSocket handlers)
**Frontend Tests**: 446 passing (100%)

---

## What We Just Completed ✅

### Phase F6 Summary (2025-01-20)

**Major Accomplishment**: Fully functional game page with complete gameplay workflow

**Integration Work** (1 file, ~500 lines):
1. `pages/games/[id].vue` - Complete game page integration
   - Integrated GameplayPanel (Phase F4)
   - Integrated SubstitutionPanel (Phase F5)
   - Integrated DecisionPanel (Phase F3)
   - All display components (Phase F2)

**Key Features Implemented**:

#### 1. State Management Integration
- Connected all panels to Pinia game store
- Used `pendingRoll` and `lastPlayResult` from store
- Proper computed properties for all game state
- Reactive updates from WebSocket events

#### 2. Conditional Panel Rendering
```typescript
showDecisions: Decision phase (defensive/offensive)
showGameplay: Dice roll and outcome entry phase
canMakeSubstitutions: Enable substitution button
```

#### 3. Event Handlers (11 handlers)
- `handleRollDice` - Dice rolling
- `handleSubmitOutcome` - Manual outcome entry
- `handleDismissResult` - Result dismissal
- `handleDefensiveSubmit` - Defensive decisions
- `handleOffensiveSubmit` - Offensive decisions
- `handleStealAttemptsSubmit` - Steal attempts
- `handlePinchHitter` - Pinch hitter substitution
- `handleDefensiveReplacement` - Defensive substitution
- `handlePitchingChange` - Pitching change
- `handleSubstitutionCancel` - Cancel substitution

#### 4. Layout Implementation
**Mobile** (< 1024px):
- Stacked vertical layout
- Full-width panels
- Bottom-positioned action panels
- Floating action button for substitutions

**Desktop** (>= 1024px):
- 3-column grid layout
- Game visual (left 2 cols) + Play-by-Play (right 1 col)
- Action panels below game visual
- Substitution modal overlay

#### 5. Dynamic Sticky Positioning
- Measures ScoreBoard height on mount
- Updates Play-by-Play sticky position dynamically
- Responds to window resize
- No overlap regardless of content

#### 6. WebSocket Authentication Fix
**Problem**: Backend rejected connection with fake test token
**Solution**:
- Frontend fetches valid JWT from `/api/auth/token` endpoint
- Backend signs token with secret key
- Auto-clears old invalid tokens
- Timeout fallback if connection fails

**Authentication Flow**:
```
1. Check if valid token exists
2. If not, call POST /api/auth/token
3. Receive signed JWT from backend
4. Set in auth store
5. Connect to WebSocket with valid token
6. Connection accepted, game loads
```

#### 7. Error Handling & Recovery
- Connection timeout (5 seconds)
- Reconnection with exponential backoff
- Error messages displayed to user
- Loading state management
- Graceful fallbacks

**Files Modified**:
- `frontend-sba/pages/games/[id].vue` (~500 lines total)
  - Added imports for GameplayPanel, SubstitutionPanel
  - Added 11 event handlers
  - Added conditional rendering logic
  - Added dynamic sticky positioning
  - Added authentication token fetching
  - Added lifecycle management

**Test Results**: All 446 existing tests still passing (no changes to tested components)

---

## Complete Gameplay Flow (Now Working)

### Turn Cycle
```
1. Load Game
   ↓
2. Show DecisionPanel
   - Submit defensive decision
   - Submit offensive decision
   ↓
3. Show GameplayPanel
   - Roll dice
   - View dice results
   - Enter manual outcome
   ↓
4. Show PlayResult
   - View outcome and runners
   - Game state updates (scores, outs, bases)
   - Play-by-Play adds entry
   ↓
5. Next Turn (repeat from step 2)
```

### Substitutions (Anytime During Game)
```
1. Click floating action button (bottom-right)
   ↓
2. SubstitutionPanel opens (modal)
   - Tab 1: Pinch Hitter
   - Tab 2: Defensive Replacement
   - Tab 3: Pitching Change
   ↓
3. Select player and submit
   ↓
4. Lineup updates immediately
   ↓
5. Continue gameplay
```

---

## Testing Checklist (Phase F6 Validation)

### Manual Testing Completed ✅
- [x] Can load game page
- [x] WebSocket connects with valid token
- [x] Game state displays correctly
- [x] ScoreBoard shows current score/count
- [x] GameBoard shows runners
- [x] Decision panels appear at correct times
- [x] Can submit defensive decisions
- [x] Can submit offensive decisions
- [x] Gameplay panel appears after decisions
- [x] Can roll dice
- [x] Dice results display correctly
- [x] Can select and submit outcome
- [x] Play result displays after submission
- [x] Game state updates after play
- [x] Play-by-Play updates in real-time
- [x] Can open substitution panel
- [x] Floating action button works
- [x] Mobile layout responsive
- [x] Desktop layout 3-column grid
- [x] Play-by-Play sticky positioning (dynamic)
- [x] Connection error handling
- [x] Loading state dismisses properly

### Known Issues
None at this time - all major functionality working

---

## Next Steps: Phase F7 - Polish & Advanced Features

**Goal**: Add polish, advanced features, and prepare for production

**Priority**: Medium (core gameplay complete, now enhancing UX)
**Estimated Time**: 10-15 hours
**Dependencies**: Phase F6 complete ✅

### Phase F7 Deliverables

#### 1. Game Lobby System (3-4 hours)
- List all active games
- Filter by status (pending, active, completed)
- Join game as player or spectator
- Leave game
- Game status badges

**Files to Create/Modify**:
- `pages/games/index.vue` - Game list page
- `components/Game/GameCard.vue` - Game list item
- `components/Game/GameFilters.vue` - Filter controls

#### 2. Game Creation Flow (2-3 hours)
- Create new game form
- Select teams (home/away)
- Select league (SBA/PD)
- Validation
- Redirect to game page after creation

**Files to Create/Modify**:
- `pages/games/new.vue` - Game creation page
- `components/Game/CreateGameForm.vue` - Form component

#### 3. Spectator Mode Improvements (1-2 hours)
- Disable action panels for spectators
- Show "spectating" indicator
- Allow spectator chat (future)
- Prevent spectators from submitting actions

**Files to Modify**:
- `pages/games/[id].vue` - Add spectator checks
- `composables/useGameState.ts` - Add `isSpectator` computed

#### 4. Box Score View (2-3 hours)
- Full game statistics
- Player batting lines
- Pitcher lines
- Team totals
- Inning-by-inning scores

**Files to Create**:
- `components/Game/BoxScore.vue` - Box score display
- `components/Game/BattingLines.vue` - Batter stats
- `components/Game/PitchingLines.vue` - Pitcher stats

#### 5. UI/UX Polish (2-3 hours)
- Loading skeletons instead of spinners
- Smooth transitions between panels
- Toast notifications for actions
- Confirm dialogs for critical actions
- Keyboard shortcuts (space to roll dice, etc.)
- Accessibility improvements (ARIA labels)

**Files to Modify**:
- `pages/games/[id].vue` - Add transitions
- `components/**/*.vue` - Add ARIA labels
- `store/ui.ts` - Enhance toast system

#### 6. Performance Optimizations (1-2 hours)
- Lazy load heavy components
- Debounce resize handlers
- Memoize expensive computeds
- Virtual scrolling for long play-by-play
- Code splitting

**Files to Modify**:
- `pages/games/[id].vue` - Add lazy loading
- `components/Game/PlayByPlay.vue` - Virtual scrolling

#### 7. Error Boundary & Logging (1 hour)
- Global error boundary
- Client-side error logging
- User-friendly error messages
- Crash recovery

**Files to Create**:
- `components/ErrorBoundary.vue`
- `utils/errorLogger.ts`

---

## File Structure After Phase F7

```
frontend-sba/
├── components/
│   ├── Game/
│   │   ├── ScoreBoard.vue          ✅ F2
│   │   ├── GameBoard.vue           ✅ F2
│   │   ├── CurrentSituation.vue    ✅ F2
│   │   ├── PlayByPlay.vue          ✅ F2
│   │   ├── BoxScore.vue            🎯 F7
│   │   ├── BattingLines.vue        🎯 F7
│   │   ├── PitchingLines.vue       🎯 F7
│   │   ├── GameCard.vue            🎯 F7
│   │   └── GameFilters.vue         🎯 F7
│   ├── Decisions/                  ✅ F3
│   ├── Gameplay/                   ✅ F4
│   ├── Substitutions/              ✅ F5
│   ├── UI/                         ✅ F3
│   └── ErrorBoundary.vue           🎯 F7
├── pages/
│   ├── games/
│   │   ├── [id].vue                ✅ F6 (INTEGRATED)
│   │   ├── index.vue               🎯 F7 (game list)
│   │   └── new.vue                 🎯 F7 (create game)
│   ├── demo*.vue                   ✅ F2-F5
├── composables/
│   ├── useGameState.ts             ✅ F1 (🔄 enhance for spectator)
│   ├── useGameEvents.ts            ✅ F1
│   ├── useGameActions.ts           ✅ F1
│   └── useWebSocket.ts             ✅ F1
├── store/
│   ├── game.ts                     ✅ F1
│   ├── auth.ts                     ✅ F1
│   └── ui.ts                       ✅ F1 (🔄 enhance toasts)
└── utils/
    └── errorLogger.ts              🎯 F7
```

---

## Success Criteria for Phase F7

Phase F7 will be **COMPLETE** when:

**Polish**:
- ✅ Smooth transitions between all panels
- ✅ Loading skeletons for async content
- ✅ Toast notifications for all actions
- ✅ Keyboard shortcuts working
- ✅ ARIA labels on interactive elements

**Advanced Features**:
- ✅ Game lobby shows all games
- ✅ Can create new game
- ✅ Spectator mode fully functional
- ✅ Box score displays all stats
- ✅ Error boundary catches crashes

**Performance**:
- ✅ Initial page load < 2 seconds
- ✅ Action responses feel instant
- ✅ No layout shifts during loading
- ✅ Smooth scrolling and animations

**Testing**:
- ✅ All 446 existing tests passing
- ✅ New tests for F7 features
- ✅ Manual testing checklist complete
- ✅ Mobile/tablet/desktop all tested

---

## Phase F7 → Production Transition

**After Phase F7**, we'll have:
- Complete gameplay (Phases F1-F6)
- Polished UI/UX (Phase F7)
- Advanced features (Phase F7)
- **Production-ready frontend**

**Production Checklist** (Future Phase F8):
- Environment configuration (.env.production)
- Discord OAuth integration (replace test tokens)
- Error tracking (Sentry or similar)
- Analytics (Google Analytics or similar)
- Performance monitoring
- Security audit
- Accessibility audit (WCAG 2.1 AA)
- Browser compatibility testing
- Load testing
- Deployment pipeline (CI/CD)
- Domain setup and SSL
- CDN configuration

---

## Quick Commands Reference

```bash
# Start backend (required)
cd /mnt/NV2/Development/strat-gameplay-webapp/backend
uv run python -m app.main

# Start frontend dev server
cd /mnt/NV2/Development/strat-gameplay-webapp/frontend-sba
npm run dev
# Visit: http://localhost:3000

# Run all frontend tests
npm run test

# Run specific test suite
npm run test -- "tests/unit/components/Game"

# Build for production
npm run build

# Preview production build
npm run preview
```

---

## Current Metrics

**Backend**:
- Tests: 739/739 passing (100%)
- Lines of Code: ~15,000
- Test Coverage: ~95%

**Frontend**:
- Tests: 446/446 passing (100%)
- Lines of Code: ~8,000
- Components: 24 production components
- Pages: 6 pages (1 integrated game page + 5 demos)

**Total Project**:
- ~23,000 lines of code
- ~1,185 tests (100% passing)
- 6 months of development
- 6 major phases complete

---

## Known Issues to Address in F7

### Current Limitations
1. **No game lobby** - Can't see list of games or create new ones
2. **Spectator mode basic** - No clear indicator, spectators could try to submit actions
3. **No box score** - Can't see detailed statistics
4. **Basic error handling** - Could be more user-friendly
5. **No keyboard shortcuts** - Everything requires clicking
6. **Performance** - Could optimize with lazy loading

### Nice-to-Haves (Future)
- Game chat/messaging
- Replay system
- Game recording/playback
- Advanced analytics and charts
- Player profiles
- League standings
- Season management
- Tournament brackets

---

## Context for AI Agent

**You are continuing work on the SBA frontend** (Strat-O-Matic Baseball Association web app).

**Current State**:
- Backend: 100% complete (739/739 tests)
- Frontend Phases F1-F6: 100% complete (446/446 tests)
- **Main game page fully functional** - Complete gameplay cycle working
- **WebSocket authentication working** - JWT token flow implemented
- **Your job**: Add polish and advanced features (Phase F7)

**Key Principles**:
- Mobile-first design (60% of traffic expected)
- Type safety (TypeScript strict mode)
- Composition API (`<script setup>`)
- Explicit imports (Nuxt 4 requirement)
- State-driven UI (reactive to WebSocket events)
- No emojis unless user requests

**Important Files**:
- `pages/games/[id].vue` - Main integrated game page (~500 lines)
- `store/game.ts` - Centralized game state
- `composables/useGameActions.ts` - Action wrappers
- `composables/useWebSocket.ts` - WebSocket connection

**Start Here**:
1. Review the completed Phase F6 integration
2. Test the complete gameplay flow
3. Choose a Phase F7 feature to implement
4. Follow existing patterns and testing practices

---

**Document Version**: 4.0
**Last Updated**: 2025-01-20
**Phase**: F7 (Polish & Advanced Features) - Starting
**Previous Phase**: F6 Complete (full game page integration)
**Total Tests**: 446 passing (100%)
**Contributors**: Claude (Jarvis), Cal Corum
