# GymFlow Application Requirements Specification

## 1. Introduction
This document serves as the authoritative source of truth for the GymFlow application functionality. It is derived from a deep analysis of the production codebase (React frontend + Node.js/Prisma backend). These requirements are intended to guide future development and serve as the basis for automated test generation (Playwright).

## 2. System Actors
*   **Guest**: An unauthenticated user (restricted to Login/Register).
*   **User**: A standard authenticated user with access to tracking, plans, and capabilities.
*   **Admin**: A super-user with additional privileges to manage other users (block, delete, reset passwords).

---

## 3. Functional Requirements

### 3.1. Authentication & Integrity
The system relies on JWT-based authentication.

*   **3.1.1 Login**
    *   **Input**: Email, Password.
    *   **Logic**:
        *   Must validate email existence.
        *   Must validate password matches hash.
        *   **Block Check**: Must prevent login if `User.isBlocked` is true, returning a 403 error.
    *   **UI**:
        *   Show "Invalid credentials" on failure.
        *   Redirect to Tracker upon success.
        *   **Language Toggle**: User must be able to switch between English (EN) and Russian (RU) before logging in.
*   **3.1.2 Registration**
    *   **Input**: Email, Password.
    *   **Logic**:
        *   Email must be unique.
        *   Creates a `UserProfile` with default values (e.g., default weight 70kg, default rest timer 120s) upon account creation.
        *   Sets `isFirstLogin` to true.
*   **3.1.3 First-Time Setup (Password Change)**
    *   **Trigger**: If `User.isFirstLogin` is true.
    *   **Requirement**: User must be forced to change password immediately after initial login.
    *   **Effect**: Updates `User.password` and sets `isFirstLogin` to false.
*   **3.1.4 Profile Management**
    *   **Fields**: Weight, Height, Gender, Birth Date.
    *   **Logic**:
        *   Updates to `UserProfile` table.
        *   Dates are handled as ISO strings or timestamps.

### 3.2. Workout Management (Plans)
Users can structure their training via Plans.

*   **3.2.1 Plan Creation/Editing**
    *   **Data**: Name (required), Description (optional).
    *   **Exercises**: 
        *   User selects exercises from the global/personal library.
        *   **Ordering**: Exercises must be ordered (0-indexed).
        *   **Weighted Flag**: specific exercises in a plan can be marked as `isWeighted` (visual indicator).
        *   **Rest Time**: specific exercises can have a defined `restTime` (seconds).
    *   **Logic**: Supports reordering capabilities via drag-and-drop in UI.
*   **3.2.2 Plan Deletion**
    *   Standard soft or hard delete (Cascades to PlanExercises).

### 3.3. Exercise Library
*   **3.3.1 Exercise Types**
    The system supports distinct exercise types which dictate valid data entry fields:
    *   `STRENGTH`: Requires **Weight (kg)** and **Reps**.
    *   `BODYWEIGHT`: Requires **Reps** (and optional added Weight).
    *   `CARDIO`: Requires **Duration (s)** and **Distance (m)**.
    *   `STATIC`: Requires **Duration (s)**.
    *   `HIGH_JUMP`: Requires **Height (cm)**.
    *   `LONG_JUMP`: Requires **Distance (m)**.
    *   `PLYOMETRIC`: Requires **Reps**.
*   **3.3.2 Custom Exercises**
    *   User can create new exercises.
    *   **Unilateral Flag**: Boolean flag `isUnilateral`. If true, sets recorded for this exercise can specify a `side` (LEFT/Right/ALTERNATELY or L/R/A in UI).
    *   **Side Editing**: Users must be able to edit the side (checking L/A/R) in Active Session, History, and Quick Log modes.
    *   **Bodyweight %**: For bodyweight-based calculations.

### 3.4. Workout Tracking (The "Tracker")
The core feature. States: **Idle**, **Active Session**, **Sporadic Mode**.

*   **3.4.1 Active Session (Standard)**
    *   **Initiation**:
        *   Can start "Free Workout" (no plan).
        *   Can start from a "Plan".
        *   **Input**: User confirms current Body Weight before starting.
        *   **Constraint**: User cannot have more than one active standard session (where `endTime` is null). API returns 400 if one exists.
    *   **The "Active" State**:
        *   **Persistence**: Session remains active in DB if browser is closed. `GET /sessions/active` restores state.
        *   **Timer**: Client-side logic calculates `now - startTime`.
    *   **Logging Sets**:
        *   **Input**: Exercise, Metrics (Weight/Reps/etc. based on Type), Side (if unilateral).
        *   **Smart Matching**: If a Plan is active, the system attempts to match the logged set to the current step in the plan based on the exercise ID and the number of sets already performed vs. planned.
        *   **Response**: Returns the created set and the `activeExerciseId` (for UI to auto-advance focus in plan).
    *   **Session Termination**:
        *   **Finish**: Updates `endTime` to now.
            *   **Profile Sync**: If the session had a `userBodyWeight` set, it updates the `UserProfile.weight`.
        *   **Quit (No Save)**:
            *   **Destructive Action**: Hard deletes the `WorkoutSession` and all associated `WorkoutSets` from the DB.
*   **3.4.2 Active Session (Quick Log)**
    *   **Concept**: A special session type (`QUICK_LOG`) that aggregates all sporadic sets for a single day.
    *   **Logic**:
        *   `GET /sessions/quick-log`: Finds strictly one session for the current calendar day (00:00-23:59 local server time) of type `QUICK_LOG`.
        *   `POST /sessions/quick-log/set`:
            *   Finds OR Creates the daily Quick Log session.
            *   Appends the set.
    *   **UI**: Separate "Sporadic Mode" view specialized for fast, one-off entries without a timer or plan context. Matches "Free Session" timer logic (see 3.4.3).

*   **3.4.3 Rest Timer**
    *   **Concept**: A configurable timer to track rest periods between sets.
    *   **Contexts**:
        *   **Free Session / Quick Log**:
            *   Manual setup.
            *   Default value: 2 minutes (120s).
            *   **Persistence**: The last manually set value becomes the new default for the user.
        *   **Planned Session**:
            *   **Config**: Each step in a plan can have a specific `restTime` (seconds).
            *   **Auto-Set**: When a set is logged, the timer RESETS (updates duration) to the value defined for the *current* step, but does **NOT** start automatically.
            *   **Fallback**: If plan step has no `restTime`, use User's default.
    *   **Behavior**:
        *   **Start**: Manual trigger by user (NEVER auto-starts).
        *   **Edit Value**:
            *   **Input**: Manual entry via FAB expand menu.
            *   **Format**: Strict "MM:SS" format (digits and colon only).
            *   **Constraints**: Max value `99:59`. Seconds > 59 are automatically clamped to 59.
            *   **Alignment**: Digits are right-aligned; input width is fixed to tightly fit `00:00`.
        *   **Countdown**: Visual display.
        *   **Completion**:
            *   Audio signal (3 seconds).
            *   Visual alert (Red color for 3 seconds).
            *   Auto-reset to next expected rest time.
    *   **UI Component**:
        *   Floating Action Button (FAB).
        *   **Idle**: Green Icon.
        *   **Running**: Shows digits.
        *   **Finished**: Red animation.


### 3.5. History & Analysis
*   **3.5.1 Session History**
    *   Displays all finished sessions.
    *   Groups by Date.
    *   **Quick Logs**: Displayed alongside standard workouts, identifiable by type.
*   **3.5.2 Statistics**
    *   Visualizes progress over time.
    *   **Key Metrics**: Volume (Weight * Reps), Frequency, Body Weight trends.

### 3.6. User Interface Logic
*   **3.6.1 Navigation**
    *   **Mobile**: Bottom navigation bar.
    *   **Desktop**: Side rail navigation.
    *   **Responsiveness**: Main layout container adapts padding/margins based on viewport breakpoint.
*   **3.6.2 Input Behavior**
    *   **Search**: Exercise selectors must support text search filtering.
    *   **Auto-Clear**: Search inputs should clear/select text on focus for rapid entry.

### 3.7. Admin Capabilities
Accessible only if `User.role === 'ADMIN'`.

*   **User List**: View all registered users (showing Block status, First Login status).
*   **Actions**:
    *   **Toggle Block**: Ban/Unban access.
    *   **Delete User**: Permanent removal.
    *   **Reset Password**: Admin can manually trigger password reset flows.

## 4. Technical Constants & Constraints
*   **Database**: SQLite (via Prisma).
*   **API Schema**: REST-like (JSON).
*   **Timezones**: Dates stored as UTC in DB, displayed in Local Time on client.
*   **Offline Mode**: Currently NOT supported (requires active connection for mutations).
