# Frontend Documentation

**NOTICE: The web frontend in this repository is DEPRECATED. All active development is on the iOS app.**

## Backend Architecture

BaoLife has two backend implementations:
- **Active**: Node.js/TypeScript backend in `server/` - all new development
- **Legacy**: Python backend in `ws/` - being phased out

Both backends use the same WebSocket message protocol, so the iOS app works with either.

## Active Frontend: iOS App

**Location**: `../lichunWebsocket/`

The iOS app is the primary and actively maintained frontend for BaoLife. For complete documentation, see:
- [iOS App Architecture (CLAUDE.md)](../lichunWebsocket/CLAUDE.md) - Complete iOS development guide
- [Backend Documentation (BACKEND.md)](../lichunWebsocket/BACKEND.md) - WebSocket protocol and backend architecture

---

## DEPRECATED: Web Frontend (This Repository)

**Status**: No longer maintained. Use the iOS app instead.

Location: `index.html`, `main.js` in repository root.

This web frontend is kept for historical reference only and should not be used for new development.

### Technology Stack

- **Vanilla JavaScript** with jQuery for DOM manipulation
- **Bootstrap 5** for UI components and styling
- **WebSocket API** for real-time server communication
- **Underscore.js** for utility functions
- **SweetAlert2** for modal dialogs

### Architecture

**Single-Page Application** structure with view-based navigation:
- All views contained in `index.html` with `.lichun-view` class (hidden by default)
- Navigation via bottom button bar toggles between views
- Modal overlays for questions, conversations, and character details

### Key Components

#### WebSocket Connection (`main.js:871-895`)

```javascript
// Auto-connects to appropriate endpoint
ws://localhost:8001/         // Development
wss://lichun.app/wss/        // Production

// Connection lifecycle
connectToWebsocket() → init(websocket) → receive(websocket)
```

**Connection Management:**
- UserID stored in `localStorage` (generated on first visit)
- Auto-reconnect after 7.5s on disconnect
- Manual reconnect via connection status button

#### Message Flow

**Sending to Server** (`main.js:828-840`):
```javascript
send(websocket, type, message)
// Example: send(websocket, 'command', 'start')
```

**Receiving from Server** (`main.js:72-105`):
```javascript
receive(websocket)
// Routes by event.type:
// - "playerObject" → updateClient()
// - "messageEvent" → showMessage()
// - "questionEvent" → showQuestion()
// - "conversationEvent" → showConversation()
// - "personObject" → displayPerson()
// - "u" → updateObject() // Lightweight updates
```

#### View System

**Main Views:**
1. **Welcome/Character Creation** (`#welcomeContainer`)
   - Character setup form: name, age, sex
   - Confirmation screen before starting game
   - Handler: `welcomePage()` (main.js:107-135)

2. **Home View** (`#home`)
   - Character stats and profile image
   - Game speed controls (1-5)
   - Activities section
   - Schedules and daily plan
   - Handler: `updateClient()` (main.js:289-418)

3. **Relationships View** (`#relationships`)
   - List of all NPCs with affinity indicators
   - Click to open person detail modal
   - Handler: `displayRelationships()` (main.js:566-621)

4. **Store View** (`#store`)
   - Available items for purchase
   - Handler: `displayStore()` (main.js:537-565)

**Navigation:**
```javascript
// Bottom bar with 3 navigation buttons
<a class="navButton" data-target="home">Home</a>
<a class="navButton" data-target="relationships">Relationships</a>
<a class="navButton" data-target="store">Store</a>
```

#### Admin Controls

Debug/admin bar (`#adminBar`) with game control buttons:
- **START**: Send "start" command to begin game loop
- **STOP**: Send "stop" command to pause game loop
- **RESTART**: Send "restart" command, clear character, return to welcome

**Note:** These are development controls, typically hidden in production.

#### Header Display

Real-time information bar (`#header`):
- Date and time: "January 15 14:00 Monday"
- Current status: Character's current activity message
- Dynamic background image based on game state

#### Game Speed Controls

Radio button group (1-5) maps to game speed values:
```javascript
1 → 1000ms  // Slowest
2 → 500ms
3 → 50ms
4 → 20ms
5 → 1ms     // Fastest
```

### Modal Systems

#### Question Modal (`#questionModal`)

Displays game events requiring player decisions.

**Structure:**
- Full-screen modal with blurred background
- Question text centered
- Button grid (2 columns) for answer options
- Each button can show costs (energy, diamonds, money)

**Flow** (`main.js:183-250`):
1. Server sends `questionEvent` with message and answers array
2. `showQuestion()` renders modal with options
3. User clicks answer button
4. Sends `questionEvent` type with id and response
5. Modal closes, game resumes

#### Activity Modal (`#activityModal`)

Shows detailed information about activities when clicked.

**Handler:** `displayActivityPage()` (main.js:637-729)
- Activity image and description
- Performance stats and level
- Focus options (Balanced, Skills, Social)
- Activity-specific actions

#### Person Modal (`#personModal`)

Displays character profile and relationship info.

**Handler:** `displayPerson()` (main.js:730-786)
- Character image (via Dicebear API)
- Stats: age, occupation, location, affinity
- Action buttons: Start Conversation, View Activities
- Relationship type indicator

#### Conversation System

**Handler:** `showConversation()` (main.js:787-827)
- Displays conversation history
- Text input for player responses
- Energy cost indicator
- Sends messages with type "conversation"

### Data Management

**Global Variables:**
```javascript
var websocket = false;   // WebSocket connection
var player = false;      // Full player object
var person = false;      // Player's character (player.c)
var reconnectTimeout;    // Reconnection timer
var questionTimeout;     // Question display timer
```

**State Updates:**
- Full state: `updateClient()` processes entire `playerObject`
- Partial updates: `updateObject()` handles selective property updates via "u" messages
- Comparison: `compareObjects()` detects changes between old and new state

### Key Functions Reference

| Function | Purpose | Location |
|----------|---------|----------|
| `connectToWebsocket()` | Initialize WebSocket connection | main.js:871 |
| `init(websocket)` | Setup event listeners and button handlers | main.js:15 |
| `receive(websocket)` | Route incoming messages by type | main.js:72 |
| `send(websocket, type, message)` | Send message to server | main.js:828 |
| `updateClient(event, websocket)` | Process full player state update | main.js:289 |
| `updateObject(event, websocket)` | Apply partial state changes | main.js:137 |
| `showQuestion(event, websocket)` | Display question modal | main.js:183 |
| `showMessage(event)` | Show toast notification | main.js:251 |
| `displayRelationships(player, old, ws)` | Render relationships list | main.js:566 |
| `displayPerson(person, websocket)` | Show person detail modal | main.js:730 |
| `showConversation(event, websocket)` | Display chat interface | main.js:787 |
| `welcomePage(event, websocket)` | Character creation flow | main.js:107 |

### Styling Notes

**Custom CSS Patterns:**
- Fixed header and bottom bars with `env(safe-area-inset-bottom)` for mobile
- Max width 500px for mobile-first design
- Custom button styles with `.activityButton`, `.focusButton` classes
- Gradient animations on question buttons (`.lichun-question-button`)
- Blurred background effects for modals

**Color Scheme:**
- Background: `#F1FAEE` (light teal)
- Primary accent: `#C46E72` (rose)
- Secondary: `#A8DADC` (light blue)
- Dark elements: `black` for bars

### Development Workflow

**Local Development:**
1. Ensure backend is running: `cd ws && ./startServer.sh`
2. Open `index.html` directly in browser (no build step required)
3. WebSocket automatically connects to `ws://localhost:8001/`

**Testing:**
- Use browser DevTools console for WebSocket message inspection
- Admin controls (START/STOP/RESTART) for game state testing
- Speed controls for accelerated testing

**Common Debugging:**
```javascript
// Check connection state
console.log(websocket.readyState); // 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED

// Inspect current player state
console.log(player);
console.log(person); // player.c

// Monitor WebSocket messages
websocket.addEventListener("message", ({data}) => console.log(JSON.parse(data)));
```

### Browser Compatibility

**Requirements:**
- WebSocket API support (all modern browsers)
- localStorage support
- ES6 JavaScript features

**Tested On:**
- Chrome/Edge (Chromium)
- Safari (iOS + macOS)
- Firefox

### Performance Considerations

- Minimal DOM manipulation via jQuery for speed
- State comparison (`compareObjects()`) prevents unnecessary re-renders
- Relationship list only updates when relationships change
- Image loading deferred until visible
- No framework overhead (vanilla JS)

## iOS App Architecture Overview

**Platform**: iOS/iPadOS (SwiftUI)
**Repository**: `../lichunWebsocket/`
**Language**: Swift 5
**Minimum iOS**: 17.0+

### Key Features

- **Native SwiftUI Interface**: Modern, responsive UI with card-based design
- **Real-time WebSocket Communication**: Connects to `wss://lichun.app/wss/`
- **In-App Purchases**: Diamond packages via StoreKit
- **Push Notifications**: Life event notifications on iOS devices
- **Claimable Events System**: Gamified reward claiming with animations
- **Relationship Management**: Dating, conversations, and NPC interactions
- **Activity Enrollment**: Schools, jobs, extracurriculars with progress tracking
- **Store System**: In-game purchases with energy, money, diamond costs

### Architecture Highlights

**State Management**:
- `WebSocketService`: Central observable object managing all game state
- `StoreManager`: Handles in-app purchase transactions
- `AppViewModel`: UI navigation and modal coordination

**Feature Modules**:
```
Features/
├── Home/           # Main dashboard with stats, timeline, controls
├── Activities/     # Activity enrollment and management
├── Dating/         # Relationship interactions
├── Messaging/      # Conversations with NPCs
├── Store/          # In-app purchases
├── Events/         # Game event modals and questions
├── Onboarding/     # Character creation flow
└── Settings/       # App settings and account management
```

**Key Components**:
- **StatusHeaderCard**: Time, season, resources (energy, money, diamonds, health)
- **LifeTimelineCard**: Scrollable event feed with claimable rewards
- **LifeEventCard**: Individual events with 3 states (unclaimed/claiming/claimed)
- **EventModalView**: Question/choice system for game decisions
- **ConversationView**: Chat interface with NPCs

### WebSocket Message Flow

The iOS app uses the same message protocol as the deprecated web frontend:

**Client → Server**:
```swift
["type": "init", "userID": userID]
["type": "command", "value": "start"|"stop"|"restart"]
["type": "speed", "value": speedValue]
["type": "questionEvent", "id": eventId, "response": answer]
["type": "conversation", "message": ["id": conversationId, "message": text]]
["type": "claimEvent", "message": ["eventId": id, "timestamp": timestamp]]
```

**Server → Client**:
- `playerObject`: Full game state with all characters, activities, items
- `u`: Lightweight updates (energy, money, time progression)
- `messageEvent`: Life events and notifications
- `questionEvent`: Choices and decisions
- `conversationEvent`: Chat messages with sentiment analysis
- `personObject`: NPC/relationship updates

### Development Setup

1. **Open Project**:
   ```bash
   cd ../lichunWebsocket
   open lichunWebsocket.xcodeproj
   ```

2. **Dependencies** (Swift Package Manager):
   - SDWebImage + SDWebImageSVGCoder (image loading)
   - Alamofire (network monitoring)
   - AlertToast (toast notifications)
   - StoreKit (in-app purchases)

3. **Run in Simulator**:
   - Select target: iPhone 15 or later
   - Press ⌘R to build and run
   - Backend must be running at `ws://localhost:8001/` or `wss://lichun.app/wss/`

4. **Testing**:
   ```bash
   # Unit tests
   xcodebuild test -project lichunWebsocket.xcodeproj \
     -scheme BaoLife \
     -destination 'platform=iOS Simulator,name=iPhone 15'

   # UI tests
   xcodebuild test -project lichunWebsocket.xcodeproj \
     -scheme BaoLife \
     -destination 'platform=iOS Simulator,name=iPhone 15' \
     -only-testing:lichunWebsocketUITests
   ```

### Complete Documentation

For detailed architecture, component documentation, and development guides, see:
- [../lichunWebsocket/CLAUDE.md](../lichunWebsocket/CLAUDE.md) - iOS app architecture
- [../lichunWebsocket/BACKEND.md](../lichunWebsocket/BACKEND.md) - Backend WebSocket protocol

---

## WebSocket Message Protocol

For complete message protocol documentation including all message types, event handling, and backend implementation details, see:
- [CLAUDE.md - WebSocket Communication](./CLAUDE.md#websocket-communication) - Quick reference
- [../lichunWebsocket/BACKEND.md](../lichunWebsocket/BACKEND.md) - Comprehensive protocol documentation
