# User Flow: Login

> **Goal**: Người dùng đăng nhập thành công vào hệ thống

## 📋 Flow Overview

**Entry Points**:
- Direct URL: `/login`
- From landing page
- After logout
- After session expiry
- From protected route redirect

**Exit Points**:
- Success → Dashboard (`/`)
- Forgot Password → `/forgot-password`
- Sign Up → `/register`

---

## 🗺️ Flow Diagram

```
┌─────────────┐
│ Entry Point │
└──────┬──────┘
       │
       v
┌──────────────────────────────┐
│   Login Page Loads           │
│   - Email input (empty)      │
│   - Password input (empty)   │
│   - Remember me (unchecked)  │
│   - Theme/Language controls  │
└──────┬───────────────────────┘
       │
       v
┌──────────────────────────────┐
│  User Enters Email           │
│  - Validation on blur        │
│  - Error if invalid format   │
└──────┬───────────────────────┘
       │
       v
┌──────────────────────────────┐
│  User Enters Password        │
│  - Show/hide toggle          │
│  - Validation on blur        │
└──────┬───────────────────────┘
       │
       v
┌──────────────────────────────┐
│  User Clicks "Sign In"       │
└──────┬───────────────────────┘
       │
       v
┌──────────────────────────────┐
│  Client-side Validation      │
│  - Check all fields filled   │
│  - Check valid email format  │
└──────┬───────────────────────┘
       │
       ├─ Invalid → Show errors inline
       │
       v Valid
┌──────────────────────────────┐
│  Show Loading State          │
│  - Disable button            │
│  - Show spinner              │
└──────┬───────────────────────┘
       │
       v
┌──────────────────────────────┐
│  Send API Request            │
│  POST /api/auth/login        │
└──────┬───────────────────────┘
       │
       ├─────────────────┬──────────────────┐
       │                 │                  │
       v Success         v Invalid Creds   v Server Error
┌─────────────┐   ┌──────────────────┐ ┌──────────────────┐
│ Save Token  │   │ Show Error:      │ │ Show Error:      │
│ Set Cookie  │   │ "Invalid email   │ │ "Something went  │
│ Update Auth │   │  or password"    │ │  wrong"          │
│ State       │   │ - Clear password │ │ - Keep form data │
└──────┬──────┘   │ - Focus email    │ │ - Enable retry   │
       │          └──────────────────┘ └──────────────────┘
       v
┌─────────────┐
│ Redirect to │
│ Dashboard   │
└─────────────┘
```

---

## 📝 Detailed Steps

### Step 1: Page Load
**Action**: User lands on `/login`

**UI State**:
- Clean form with empty fields
- "Sign In" button enabled
- Theme toggle (top-right)
- Language switcher (top-right)

**Technical**:
- Check if already authenticated → redirect to `/`
- Load theme preference from localStorage
- Load language preference from localStorage

---

### Step 2: Email Input
**Action**: User types email address

**Validation** (on blur):
- ✅ Required field
- ✅ Valid email format (`/^[^\s@]+@[^\s@]+\.[^\s@]+$/`)

**Error Messages**:
- Empty: "Email is required"
- Invalid: "Please enter a valid email address"

**UI Behavior**:
- Focus ring: X.ai blue (#1D9BF0)
- Error: Red border + error text below

---

### Step 3: Password Input
**Action**: User types password

**Features**:
- Password visibility toggle (eye icon)
- Masked by default

**Validation** (on blur):
- ✅ Required field
- ✅ Minimum length (8 characters)

**Error Messages**:
- Empty: "Password is required"
- Too short: "Password must be at least 8 characters"

---

### Step 4: Remember Me (Optional)
**Action**: User checks "Remember me"

**Behavior**:
- If checked: Session persists 30 days
- If unchecked: Session expires on browser close

---

### Step 5: Form Submission
**Action**: User clicks "Sign In" button

**Client-side Validation**:
```typescript
// Validation rules
{
  email: {
    required: true,
    pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  },
  password: {
    required: true,
    minLength: 8
  }
}
```

**If Invalid**:
- Show all errors
- Focus first invalid field
- Don't send API request

**If Valid**:
- Proceed to API call

---

### Step 6: Loading State
**UI Changes**:
- Button shows spinner
- Button text: "Signing in..."
- Button disabled
- Form fields disabled

**Duration**: Until API responds (typically 500ms-2s)

---

### Step 7: API Response Handling

#### ✅ Success (200 OK)
**API Response**:
```json
{
  "success": true,
  "data": {
    "token": "jwt_token_here",
    "user": {
      "id": "123",
      "email": "user@example.com",
      "name": "John Doe"
    }
  }
}
```

**Actions**:
1. Save token to localStorage/cookie
2. Update auth state (Zustand)
3. Show success toast (optional)
4. Redirect to `/` (dashboard)

---

#### ❌ Invalid Credentials (401 Unauthorized)
**API Response**:
```json
{
  "success": false,
  "error": {
    "code": "INVALID_CREDENTIALS",
    "message": "Invalid email or password"
  }
}
```

**Actions**:
1. Show error message below form
2. Clear password field
3. Focus email field
4. Keep email value
5. Enable retry

**Error Display**:
```
⚠️ Invalid email or password. Please try again.
```

---

#### ⚠️ Account Locked (403 Forbidden)
**API Response**:
```json
{
  "success": false,
  "error": {
    "code": "ACCOUNT_LOCKED",
    "message": "Too many failed attempts. Try again in 15 minutes."
  }
}
```

**Actions**:
1. Show specific error
2. Disable form for 15 minutes (optional)
3. Show countdown timer

---

#### 💥 Server Error (500)
**API Response**:
```json
{
  "success": false,
  "error": {
    "code": "SERVER_ERROR",
    "message": "Something went wrong. Please try again."
  }
}
```

**Actions**:
1. Show generic error message
2. Keep form data
3. Enable retry button

---

## 🔀 Alternative Paths

### Path A: Forgot Password
**Trigger**: User clicks "Forgot password?" link

**Action**: Navigate to `/forgot-password`

---

### Path B: Sign Up
**Trigger**: User clicks "Don't have an account? Sign up" link

**Action**: Navigate to `/register`

---

### Path C: Social Login (Future)
**Trigger**: User clicks "Continue with Google" button

**Action**:
1. Open OAuth popup
2. Handle callback
3. Same success flow as email/password

---

## ✅ Success Criteria

Flow is successful when:
- ✅ User is authenticated
- ✅ Token is stored
- ✅ User is redirected to dashboard
- ✅ Dashboard loads with user data

---

## 🧪 Testing Checklist

**Functional Tests**:
- [ ] Can submit with valid credentials
- [ ] Cannot submit with empty fields
- [ ] Cannot submit with invalid email
- [ ] Error shown for wrong password
- [ ] Loading state appears during API call
- [ ] Remember me persists session
- [ ] Forgot password link works
- [ ] Sign up link works

**Edge Cases**:
- [ ] Already authenticated user redirected
- [ ] Network error handled gracefully
- [ ] API timeout handled (> 10s)
- [ ] Special characters in password work
- [ ] Copy-paste email works
- [ ] Browser autofill works

**Accessibility**:
- [ ] Keyboard navigation works (Tab, Enter)
- [ ] Screen reader announces errors
- [ ] Focus management correct
- [ ] Error messages have role="alert"

**Performance**:
- [ ] Page loads < 1s
- [ ] API response < 2s
- [ ] No layout shift during loading

---

## 📱 Responsive Behavior

**Mobile (< 640px)**:
- Stack form vertically
- Full-width button
- Touch-friendly input size (min 44px height)
- Virtual keyboard doesn't hide submit button

**Tablet (640-1024px)**:
- Same as mobile, centered

**Desktop (> 1024px)**:
- Centered form (max-width: 448px)
- Ample padding around form

---

## 🎨 Figma Prototype

[Add link to Figma prototype here]

---

## 📊 Analytics Events

Track these events:
- `login_page_viewed`
- `login_form_submitted`
- `login_success`
- `login_failed` (with error code)
- `forgot_password_clicked`
- `sign_up_clicked`

---

**Maintained by**: UX Team
**Last Updated**: 2026-01-04
**Version**: 2.0 (X.ai Minimal Redesign)
