# Plan: Modern AI Chat UI Design

## Tổng quan kiến trúc UI

Dự án sẽ có 2 ứng dụng web chính với design language thống nhất:

### Web Client (User-facing)

- **Mục đích**: Chat interface cho end users tương tác với AI
- **Design inspiration**: x.ai Grok, OpenAI ChatGPT
- **Key features**:
  - Minimalistic và intuitive
  - Dark mode as default với light mode option
  - Real-time chat với typing indicators
  - Message history và conversation management
  - Multi-modal input (text, voice future)

### Web Admin (Admin-facing)

- **Mục đích**: Dashboard quản lý users, analytics, system settings
- **Design inspiration**: Modern admin dashboards với AI-powered insights
- **Key features**:
  - Analytics dashboard với charts/graphs
  - User management với advanced filtering
  - System monitoring và health checks
  - Content moderation tools
  - Configuration management
```mermaid
graph TB
    subgraph Design System
        Colors[Color Palette<br/>Dark + Light Mode]
        Typo[Typography<br/>System Fonts]
        Comp[Components<br/>Radix UI]
        Icons[Icons<br/>Lucide React]
    end

    subgraph Web Client
        Auth1[Authentication]
        Chat[Chat Interface]
        History[Conversation History]
        Settings1[User Settings]
    end

    subgraph Web Admin
        Dashboard[Analytics Dashboard]
        Users[User Management]
        Monitor[System Monitoring]
        Settings2[Admin Settings]
    end

    Colors --> Web Client
    Colors --> Web Admin
    Typo --> Web Client
    Typo --> Web Admin
    Comp --> Web Client
    Comp --> Web Admin
    Icons --> Web Client
    Icons --> Web Admin
```


## I. Design System Foundation

### 1.1 Color Palette

#### Dark Mode (Primary Theme)

Dựa trên research, dark mode giảm eye strain 67% và là xu hướng chính cho AI chat interfaces.

**Background Colors:**

```css
--bg-primary: #0A0A0A        /* Main background - Almost black */
--bg-secondary: #121212      /* Card/Panel background - Dark grey (better depth) */
--bg-tertiary: #1A1A1A       /* Hover states */
--bg-elevated: #242424       /* Elevated surfaces (modals, dropdowns) */
```

**Text Colors (WCAG Compliant):**

```css
--text-primary: #FAFAFA      /* Primary text - Off-white (4.5:1 contrast) */
--text-secondary: #E0E0E0    /* Secondary text - Light grey */
--text-tertiary: #A0A0A0     /* Tertiary/disabled text */
--text-inverse: #1A1A1A      /* Text on light backgrounds */
```

**Brand/Accent Colors:**

```css
--accent-primary: #3B82F6    /* Primary blue - CTAs, links */
--accent-secondary: #8B5CF6  /* Purple - Highlights */
--accent-success: #10B981    /* Green - Success states */
--accent-warning: #F59E0B    /* Amber - Warnings */
--accent-error: #EF4444      /* Red - Errors */
--accent-info: #06B6D4       /* Cyan - Info */
```

**Chat Specific Colors:**

```css
--chat-user-bubble: #2563EB        /* User message - Deep blue */
--chat-ai-bubble: #374151          /* AI message - Dark grey */
--chat-user-text: #FFFFFF          /* White text on blue */
--chat-ai-text: #F3F4F6            /* Light text on grey */
--chat-timestamp: #9CA3AF          /* Timestamp grey */
--chat-divider: #1F2937            /* Divider between messages */
```

**Border Colors:**

```css
--border-primary: #2A2A2A    /* Default borders */
--border-secondary: #3A3A3A  /* Hover borders */
--border-focus: #3B82F6      /* Focus state - Blue */
```

#### Light Mode (Secondary Theme)

```css
/* Light mode variants */
--bg-primary-light: #FFFFFF
--bg-secondary-light: #F9FAFB
--bg-tertiary-light: #F3F4F6
--text-primary-light: #111827
--text-secondary-light: #4B5563
--border-primary-light: #E5E7EB
```

**Semantic Color Usage:**

- Primary blue (#3B82F6): CTAs, primary buttons, active states
- Purple (#8B5CF6): Premium features, AI-related highlights
- Success green (#10B981): Confirmations, success messages
- Warning amber (#F59E0B): Warnings, caution states
- Error red (#EF4444): Errors, destructive actions

### 1.2 Typography

Theo OpenAI guidelines, sử dụng **system fonts** để ensure readability và accessibility.

**Font Stack:**

```css
--font-sans:
  -apple-system,
  BlinkMacSystemFont,
  "SF Pro Display",    /* iOS/macOS */
  "Segoe UI",          /* Windows */
  Roboto,              /* Android */
  "Helvetica Neue",
  Arial,
  sans-serif;

--font-mono:
  "SF Mono",
  Consolas,
  "Liberation Mono",
  Menlo,
  monospace;
```

**Type Scale (Tailwind-based):**

```css
/* Display - Headers */
--text-6xl: 3.75rem / 1      /* 60px - Hero titles */
--text-5xl: 3rem / 1         /* 48px - Page titles */
--text-4xl: 2.25rem / 1.1    /* 36px - Section headers */
--text-3xl: 1.875rem / 1.2   /* 30px - Card headers */

/* Body */
--text-2xl: 1.5rem / 1.3     /* 24px - Large body */
--text-xl: 1.25rem / 1.4     /* 20px - Emphasized text */
--text-lg: 1.125rem / 1.5    /* 18px - Large body */
--text-base: 1rem / 1.5      /* 16px - Default body */
--text-sm: 0.875rem / 1.5    /* 14px - Small text */
--text-xs: 0.75rem / 1.5     /* 12px - Captions */
```

**Font Weights:**

```css
--font-light: 300     /* Light text */
--font-normal: 400    /* Body text */
--font-medium: 500    /* Emphasized */
--font-semibold: 600  /* Headings */
--font-bold: 700      /* Strong emphasis */
```

**Chat Typography:**

- Message text: 16px (text-base), regular weight
- Timestamps: 12px (text-xs), light weight
- User names: 14px (text-sm), medium weight
- System messages: 14px (text-sm), italic

### 1.3 Spacing & Layout

**Base Unit: 4px (0.25rem)**

**Spacing Scale:**

```css
--space-0: 0           /* 0px */
--space-1: 0.25rem     /* 4px */
--space-2: 0.5rem      /* 8px */
--space-3: 0.75rem     /* 12px */
--space-4: 1rem        /* 16px */
--space-5: 1.25rem     /* 20px */
--space-6: 1.5rem      /* 24px */
--space-8: 2rem        /* 32px */
--space-10: 2.5rem     /* 40px */
--space-12: 3rem       /* 48px */
--space-16: 4rem       /* 64px */
--space-20: 5rem       /* 80px */
```

**Container Widths:**

```css
--container-sm: 640px    /* Small devices */
--container-md: 768px    /* Medium devices */
--container-lg: 1024px   /* Large devices */
--container-xl: 1280px   /* Extra large */
--container-2xl: 1536px  /* 2X large */

/* Chat specific */
--chat-max-width: 768px  /* Max width for chat messages */
--sidebar-width: 280px   /* Conversation history sidebar */
```

**Border Radius:**

```css
--radius-sm: 0.25rem    /* 4px - Small elements */
--radius-md: 0.5rem     /* 8px - Buttons, inputs */
--radius-lg: 0.75rem    /* 12px - Cards */
--radius-xl: 1rem       /* 16px - Large cards */
--radius-2xl: 1.5rem    /* 24px - Modals */
--radius-full: 9999px   /* Full round - Avatars, pills */
```

**Shadows (Dark Mode Optimized):**

```css
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.5);
--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.5);
--shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.6);
--shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.7);
--shadow-glow: 0 0 20px rgba(59, 130, 246, 0.3); /* Blue glow for focus */
```

### 1.4 Grid System

**Responsive Breakpoints:**

```css
--screen-sm: 640px   /* Mobile landscape */
--screen-md: 768px   /* Tablet */
--screen-lg: 1024px  /* Desktop */
--screen-xl: 1280px  /* Large desktop */
--screen-2xl: 1536px /* Extra large desktop */
```

**Layout Patterns:**

- **Single Column (Mobile)**: < 768px - Full width content
- **Two Column (Tablet)**: 768px - 1024px - Sidebar + Main
- **Three Column (Desktop)**: > 1024px - Sidebar + Main + Panel

### 1.5 Animation & Transitions

**Timing Functions:**

```css
--ease-in: cubic-bezier(0.4, 0, 1, 1);
--ease-out: cubic-bezier(0, 0, 0.2, 1);
--ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);
--ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
```

**Duration:**

```css
--duration-fast: 150ms      /* Hover effects */
--duration-normal: 250ms    /* Default transitions */
--duration-slow: 350ms      /* Complex animations */
--duration-slower: 500ms    /* Page transitions */
```

**Common Transitions:**

```css
/* Smooth hover */
transition: all var(--duration-fast) var(--ease-out);

/* Button press */
transition: transform var(--duration-fast) var(--ease-in-out);

/* Modal open */
transition: opacity var(--duration-normal) var(--ease-in-out),
            transform var(--duration-normal) var(--ease-spring);
```

**Micro-interactions (2026 Trend):**

- Button hover: Subtle scale (1.02) + brightness
- Card hover: Lift effect (translateY -2px) + shadow
- Input focus: Glow effect (box-shadow) + border color
- Message send: Slide up + fade in
- Typing indicator: Pulsing dots animation

## II. Component Library

### 2.1 Core Components (Radix UI based)

#### Button

**Variants:**

```typescript
// Primary - Main CTAs
<Button variant="primary" size="md">
  Send Message
</Button>

// Secondary - Less emphasis
<Button variant="secondary" size="md">
  Cancel
</Button>

// Ghost - Minimal
<Button variant="ghost" size="sm">
  Edit
</Button>

// Danger - Destructive actions
<Button variant="danger" size="md">
  Delete
</Button>
```

**Sizes:**

- `xs`: 28px height, 12px text, 12px padding
- `sm`: 32px height, 14px text, 16px padding
- `md`: 40px height, 16px text, 20px padding (default)
- `lg`: 48px height, 18px text, 24px padding
- `xl`: 56px height, 20px text, 28px padding

**States:**

- Default: Normal appearance
- Hover: Brightness 110%, slight scale (1.02)
- Active: Brightness 90%, scale (0.98)
- Focus: Blue glow shadow
- Disabled: Opacity 50%, cursor not-allowed
- Loading: Spinner icon, disabled state

**Implementation:**

```css
/* Primary Button */
.btn-primary {
  background: var(--accent-primary);
  color: white;
  border-radius: var(--radius-md);
  padding: var(--space-3) var(--space-5);
  font-weight: var(--font-medium);
  transition: all var(--duration-fast) var(--ease-out);
}

.btn-primary:hover {
  filter: brightness(1.1);
  transform: scale(1.02);
}

.btn-primary:focus-visible {
  outline: none;
  box-shadow: var(--shadow-glow);
}
```

#### Input Fields

**Types:**

- Text Input
- Textarea
- Select
- Multi-select
- Date Picker
- Search (with icon)

**Structure:**

```tsx
<div className="input-group">
  <label htmlFor="email">Email Address</label>
  <input
    id="email"
    type="email"
    placeholder="you@example.com"
    className="input"
  />
  <span className="input-hint">We'll never share your email</span>
</div>
```

**Styles:**

```css
.input {
  background: var(--bg-secondary);
  border: 1px solid var(--border-primary);
  color: var(--text-primary);
  border-radius: var(--radius-md);
  padding: var(--space-3) var(--space-4);
  font-size: var(--text-base);
  transition: all var(--duration-fast) var(--ease-out);
}

.input:focus {
  border-color: var(--accent-primary);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  outline: none;
}

.input::placeholder {
  color: var(--text-tertiary);
}

.input-hint {
  color: var(--text-tertiary);
  font-size: var(--text-sm);
  margin-top: var(--space-1);
}
```

**States:**

- Default
- Focus (blue border + glow)
- Error (red border + error message)
- Success (green border + checkmark)
- Disabled (grey + cursor not-allowed)

#### Card

**Variants:**

```tsx
// Default Card
<Card>
  <CardHeader>
    <CardTitle>Card Title</CardTitle>
    <CardDescription>Card description</CardDescription>
  </CardHeader>
  <CardContent>
    Content goes here
  </CardContent>
  <CardFooter>
    Footer actions
  </CardFooter>
</Card>

// Interactive Card (hover effect)
<Card hover>
  ...
</Card>

// Bordered Card
<Card bordered>
  ...
</Card>
```

**Styles:**

```css
.card {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  padding: var(--space-6);
  transition: all var(--duration-normal) var(--ease-out);
}

.card.hover:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.card-header {
  margin-bottom: var(--space-4);
}

.card-title {
  font-size: var(--text-xl);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
}

.card-description {
  font-size: var(--text-sm);
  color: var(--text-secondary);
  margin-top: var(--space-1);
}
```

#### Modal/Dialog

**Structure:**

```tsx
<Dialog open={isOpen} onOpenChange={setIsOpen}>
  <DialogTrigger asChild>
    <Button>Open Dialog</Button>
  </DialogTrigger>
  <DialogContent>
    <DialogHeader>
      <DialogTitle>Dialog Title</DialogTitle>
      <DialogDescription>
        Dialog description text
      </DialogDescription>
    </DialogHeader>
    <div className="dialog-body">
      {/* Content */}
    </div>
    <DialogFooter>
      <Button variant="secondary" onClick={() => setIsOpen(false)}>
        Cancel
      </Button>
      <Button variant="primary">
        Confirm
      </Button>
    </DialogFooter>
  </DialogContent>
</Dialog>
```

**Animation:**

```css
/* Overlay fade in */
@keyframes overlay-fade {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* Content scale + fade */
@keyframes content-show {
  from {
    opacity: 0;
    transform: translate(-50%, -48%) scale(0.96);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

.dialog-overlay {
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(8px);
  animation: overlay-fade var(--duration-normal) var(--ease-out);
}

.dialog-content {
  background: var(--bg-elevated);
  border-radius: var(--radius-2xl);
  box-shadow: var(--shadow-xl);
  animation: content-show var(--duration-normal) var(--ease-spring);
}
```

#### Avatar

**Sizes:**

- `xs`: 24px
- `sm`: 32px
- `md`: 40px (default)
- `lg`: 48px
- `xl`: 64px

**States:**

- Image loaded
- Fallback (initials)
- Loading (skeleton)
- Status indicator (online/offline/away)
```tsx
<Avatar size="md" status="online">
  <AvatarImage src="/user.jpg" alt="John Doe" />
  <AvatarFallback>JD</AvatarFallback>
</Avatar>
```


### 2.2 Chat-Specific Components

#### Message Bubble

**Structure:**

```tsx
<div className="message user">
  <div className="message-header">
    <span className="message-author">You</span>
    <span className="message-time">2:30 PM</span>
  </div>
  <div className="message-bubble">
    <p className="message-text">Hello, how can I help you?</p>
  </div>
</div>

<div className="message ai">
  <Avatar size="sm" src="/ai-avatar.png" />
  <div className="message-content">
    <div className="message-header">
      <span className="message-author">AI Assistant</span>
      <span className="message-time">2:31 PM</span>
    </div>
    <div className="message-bubble">
      <p className="message-text">I can help you with...</p>
    </div>
  </div>
</div>
```

**Styles:**

```css
/* User Message (Right aligned, blue) */
.message.user {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-bottom: var(--space-4);
}

.message.user .message-bubble {
  background: var(--chat-user-bubble);
  color: var(--chat-user-text);
  border-radius: var(--radius-lg) var(--radius-lg) var(--radius-sm) var(--radius-lg);
  padding: var(--space-3) var(--space-4);
  max-width: 70%;
  word-wrap: break-word;
}

/* AI Message (Left aligned, grey) */
.message.ai {
  display: flex;
  gap: var(--space-3);
  margin-bottom: var(--space-4);
}

.message.ai .message-bubble {
  background: var(--chat-ai-bubble);
  color: var(--chat-ai-text);
  border-radius: var(--radius-lg) var(--radius-lg) var(--radius-lg) var(--radius-sm);
  padding: var(--space-3) var(--space-4);
  max-width: 70%;
}

/* Message Header */
.message-header {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  margin-bottom: var(--space-1);
}

.message-author {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-secondary);
}

.message-time {
  font-size: var(--text-xs);
  color: var(--chat-timestamp);
}
```

**Message Animations:**

```css
/* Slide up + fade in */
@keyframes message-in {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message {
  animation: message-in var(--duration-normal) var(--ease-out);
}
```

#### Typing Indicator

```tsx
<div className="typing-indicator">
  <div className="typing-dot"></div>
  <div className="typing-dot"></div>
  <div className="typing-dot"></div>
</div>
```
```css
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: var(--space-3);
}

.typing-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--text-tertiary);
  animation: typing 1.4s infinite;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    opacity: 0.3;
    transform: scale(0.8);
  }
  30% {
    opacity: 1;
    transform: scale(1);
  }
}
```

#### Chat Input

```tsx
<div className="chat-input-container">
  <div className="chat-input-wrapper">
    <button className="chat-input-action" aria-label="Attach file">
      <PaperclipIcon />
    </button>

    <textarea
      className="chat-input"
      placeholder="Type a message..."
      rows={1}
      onKeyDown={handleKeyDown}
    />

    <button className="chat-input-send" aria-label="Send message">
      <SendIcon />
    </button>
  </div>

  <div className="chat-input-hint">
    Press Enter to send, Shift+Enter for new line
  </div>
</div>
```
```css
.chat-input-container {
  position: sticky;
  bottom: 0;
  background: var(--bg-primary);
  border-top: 1px solid var(--border-primary);
  padding: var(--space-4);
}

.chat-input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: var(--space-2);
  background: var(--bg-secondary);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-xl);
  padding: var(--space-2);
  transition: border-color var(--duration-fast) var(--ease-out);
}

.chat-input-wrapper:focus-within {
  border-color: var(--accent-primary);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.chat-input {
  flex: 1;
  background: transparent;
  border: none;
  color: var(--text-primary);
  font-size: var(--text-base);
  resize: none;
  max-height: 120px;
  padding: var(--space-2);
}

.chat-input:focus {
  outline: none;
}

.chat-input-action,
.chat-input-send {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: var(--radius-md);
  background: transparent;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--duration-fast) var(--ease-out);
}

.chat-input-action:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.chat-input-send {
  background: var(--accent-primary);
  color: white;
}

.chat-input-send:hover {
  filter: brightness(1.1);
  transform: scale(1.05);
}

.chat-input-send:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.chat-input-hint {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
  margin-top: var(--space-2);
  text-align: center;
}
```

#### Conversation Sidebar

```tsx
<aside className="conversation-sidebar">
  <div className="sidebar-header">
    <h2>Conversations</h2>
    <button className="new-chat-btn">
      <PlusIcon />
      New Chat
    </button>
  </div>

  <div className="sidebar-search">
    <SearchIcon />
    <input type="search" placeholder="Search conversations..." />
  </div>

  <div className="conversation-list">
    <button className="conversation-item active">
      <div className="conversation-title">Project Discussion</div>
      <div className="conversation-preview">Last message preview...</div>
      <div className="conversation-time">2m ago</div>
    </button>

    <button className="conversation-item">
      <div className="conversation-title">Design Review</div>
      <div className="conversation-preview">Can you check...</div>
      <div className="conversation-time">1h ago</div>
    </button>
  </div>
</aside>
```
```css
.conversation-sidebar {
  width: var(--sidebar-width);
  height: 100vh;
  background: var(--bg-secondary);
  border-right: 1px solid var(--border-primary);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: var(--space-4);
  border-bottom: 1px solid var(--border-primary);
}

.sidebar-header h2 {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  margin-bottom: var(--space-3);
}

.new-chat-btn {
  width: 100%;
  display: flex;
  align-items: center;
  gap: var(--space-2);
  padding: var(--space-3);
  background: var(--accent-primary);
  color: white;
  border: none;
  border-radius: var(--radius-md);
  font-weight: var(--font-medium);
  cursor: pointer;
  transition: all var(--duration-fast) var(--ease-out);
}

.new-chat-btn:hover {
  filter: brightness(1.1);
}

.sidebar-search {
  padding: var(--space-4);
  border-bottom: 1px solid var(--border-primary);
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.sidebar-search input {
  flex: 1;
  background: var(--bg-tertiary);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-md);
  padding: var(--space-2) var(--space-3);
  color: var(--text-primary);
  font-size: var(--text-sm);
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: var(--space-2);
}

.conversation-item {
  width: 100%;
  padding: var(--space-3);
  background: transparent;
  border: none;
  border-radius: var(--radius-md);
  text-align: left;
  cursor: pointer;
  transition: background var(--duration-fast) var(--ease-out);
  margin-bottom: var(--space-1);
}

.conversation-item:hover {
  background: var(--bg-tertiary);
}

.conversation-item.active {
  background: var(--bg-tertiary);
  border-left: 3px solid var(--accent-primary);
}

.conversation-title {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-primary);
  margin-bottom: var(--space-1);
}

.conversation-preview {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-time {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
  margin-top: var(--space-1);
}
```

### 2.3 Admin Components

#### Data Table

```tsx
<DataTable
  columns={columns}
  data={data}
  searchable
  filterable
  sortable
  pagination
/>
```

**Features:**

- Column sorting
- Global search
- Column filters
- Pagination
- Row selection
- Bulk actions
- Export to CSV/Excel
- Column visibility toggle

#### Analytics Card

```tsx
<AnalyticsCard
  title="Total Users"
  value="12,345"
  change="+12.5%"
  trend="up"
  icon={<UsersIcon />}
/>
```

**Variants:**

- Metric card (single value)
- Chart card (with graph)
- Progress card (with progress bar)
- Comparison card (multiple metrics)

#### Charts

Using Recharts or Tremor library:

- Line Chart (Trends over time)
- Bar Chart (Comparisons)
- Pie/Donut Chart (Distributions)
- Area Chart (Cumulative data)
- Heatmap (Activity patterns)

## III. Web Client - Detailed Screens

### 3.1 Authentication Pages

#### Login Page

**Layout:**

```
┌─────────────────────────────────────┐
│                                     │
│           [Logo]                    │
│                                     │
│       Sign in to GoodGo            │
│                                     │
│   ┌───────────────────────────┐   │
│   │ Email                      │   │
│   │ [                    ]     │   │
│   └───────────────────────────┘   │
│                                     │
│   ┌───────────────────────────┐   │
│   │ Password                   │   │
│   │ [                    ]     │   │
│   └───────────────────────────┘   │
│                                     │
│   [ ] Remember me    Forgot password? │
│                                     │
│   ┌───────────────────────────┐   │
│   │      Sign in              │   │
│   └───────────────────────────┘   │
│                                     │
│   ─────── OR ───────               │
│                                     │
│   ┌───────────────────────────┐   │
│   │  🔵 Continue with Google  │   │
│   └───────────────────────────┘   │
│                                     │
│   Don't have an account? Sign up   │
│                                     │
└─────────────────────────────────────┘
```

**Key Elements:**

- Centered card (max-width: 400px)
- Logo at top
- H1: "Sign in to GoodGo"
- Email input (with validation)
- Password input (with show/hide toggle)
- Remember me checkbox
- Forgot password link
- Primary button: "Sign in"
- Divider: "OR"
- OAuth buttons (Google, optionally GitHub)
- Sign up link at bottom

**Validation:**

- Real-time email format validation
- Password strength indicator (on sign up)
- Error messages below inputs
- Success message on successful login
- Loading state on button during auth

#### Register Page

Similar to login with additional fields:

- Full Name
- Email
- Password
- Confirm Password
- Terms & Conditions checkbox
- Password strength meter
- Sign up button
- Already have account? Sign in link

**Password Strength Indicator:**

```tsx
<div className="password-strength">
  <div className="strength-bar">
    <div className="strength-fill" style={{ width: `${strength}%` }} />
  </div>
  <span className="strength-text">{strengthLabel}</span>
</div>
```

Levels:

- Weak (0-25%): Red
- Fair (26-50%): Orange
- Good (51-75%): Yellow
- Strong (76-100%): Green

#### Forgot Password Page

**Flow:**

1. Enter email → Send reset link
2. Check email → Click link
3. Enter new password → Confirm
4. Success → Redirect to login

### 3.2 Main Chat Interface

**Layout (Desktop):**

```
┌──────────┬─────────────────────────────────────────┬────────────┐
│          │                                         │            │
│  SIDEBAR │           MAIN CHAT AREA               │   PANEL    │
│          │                                         │  (optional) │
│  Convos  │                                         │            │
│          │  ┌─────────────────────────────────┐   │  Settings  │
│  [+New]  │  │ AI: How can I help you?        │   │  or        │
│          │  └─────────────────────────────┘   │  Info      │
│  • Chat1 │                                         │            │
│  • Chat2 │  ┌─────────────────────────────────┐   │            │
│  • Chat3 │  │           You: Hello           │   │            │
│          │  └─────────────────────────────────┘   │            │
│          │                                         │            │
│          │  ┌─────────────────────────────────┐   │            │
│          │  │ AI: Hi! I'm here to help...    │   │            │
│          │  └─────────────────────────────────┘   │            │
│          │                                         │            │
│  [User]  │  ┌─────────────────────────────────┐   │            │
│  Avatar  │  │  [Type a message...]      [Send]│   │            │
│  Settings│  └─────────────────────────────────┘   │            │
│          │                                         │            │
└──────────┴─────────────────────────────────────────┴────────────┘
```

**Components Breakdown:**

1. **Left Sidebar** (280px wide)

   - New Chat button (sticky top)
   - Search conversations
   - Conversation list (scrollable)
   - User profile (sticky bottom)

2. **Main Chat Area** (flex-1, max 768px centered)

   - Header (conversation title, options)
   - Messages container (scrollable, auto-scroll to bottom)
   - Typing indicator
   - Input area (sticky bottom)

3. **Right Panel** (320px, optional, collapsible)

   - Conversation settings
   - Participants
   - Shared files
   - Quick actions

**Message Types:**

1. **Text Message**

   - Plain text with markdown support
   - Code blocks with syntax highlighting
   - Links with preview cards

2. **System Message**

   - Centered, grey text
   - Used for timestamps, status updates

3. **Error Message**

   - Red border, error icon
   - Retry button

4. **Loading Message**

   - Skeleton or typing indicator
   - Shown while AI is generating

**Message Actions (on hover):**

- Copy message
- Edit (user messages only)
- Delete (user messages only)
- Regenerate (AI messages)
- Like/Dislike (feedback)
- Share

### 3.3 User Settings

**Navigation Tabs:**

- Profile
- Preferences
- Security
- Notifications
- Billing (if applicable)
- API Keys (for developers)

**Profile Tab:**

```
Avatar Upload
┌──────────┐
│  [👤]    │  Change avatar
└──────────┘

Full Name:    [John Doe              ]
Email:        [john@example.com      ] (verified ✓)
Username:     [@johndoe              ]
Bio:          [Software developer... ]
              [                       ]

[Save Changes]  [Cancel]
```

**Preferences Tab:**

- Language selection
- Theme (Dark/Light/Auto)
- Chat settings
  - Auto-scroll to new messages
  - Show timestamps
  - Message grouping
  - Font size
- Accessibility
  - High contrast mode
  - Screen reader optimizations

**Security Tab:**

- Change password
- Two-factor authentication (2FA)
  - Enable/Disable
  - QR code for setup
- Active sessions
  - List of devices
  - Revoke access option
- Delete account (danger zone)

## IV. Web Admin - Detailed Screens

### 4.1 Dashboard (Overview)

**Layout:**

```
┌─────────────────────────────────────────────────────────────┐
│  HEADER: Dashboard                        [User] [Settings] │
├────────────┬────────────────────────────────────────────────┤
│            │                                                 │
│  SIDEBAR   │  METRICS ROW                                   │
│            │  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │
│ • Dashboard│  │ Users  │ │Messages│ │ Active │ │Revenue │ │
│ • Users    │  │ 12.3K  │ │  45K   │ │  892   │ │ $1.2K  │ │
│ • Analytics│  │ +12%   │ │  +8%   │ │  +5%   │ │ +15%   │ │
│ • Messages │  └────────┘ └────────┘ └────────┘ └────────┘ │
│ • Settings │                                                 │
│            │  CHARTS ROW                                    │
│ Admin      │  ┌─────────────────────┐ ┌──────────────────┐ │
│            │  │                     │ │                  │ │
│ [Logout]   │  │  User Growth Chart  │ │  Revenue Chart   │ │
│            │  │                     │ │                  │ │
│            │  └─────────────────────┘ └──────────────────┘ │
│            │                                                 │
│            │  RECENT ACTIVITY TABLE                         │
│            │  ┌──────────────────────────────────────────┐ │
│            │  │ User  │ Action  │ Time    │ Status      │ │
│            │  ├──────────────────────────────────────────┤ │
│            │  │ John  │ Signed  │ 2m ago  │ Success     │ │
│            │  │ Jane  │ Message │ 5m ago  │ Completed   │ │
│            │  └──────────────────────────────────────────┘ │
│            │                                                 │
└────────────┴────────────────────────────────────────────────┘
```

**Metric Cards (Top Row):**

Each card shows:

- Icon (relevant to metric)
- Label (e.g., "Total Users")
- Large number value
- Percentage change (with trend arrow)
- Sparkline chart (mini trend)
- Time period (e.g., "vs last month")

**Charts:**

1. **User Growth Chart** (Line Chart)

   - X-axis: Time (days/weeks/months)
   - Y-axis: User count
   - Multiple lines (total, active, new)
   - Interactive tooltip on hover

2. **Revenue Chart** (Area Chart)

   - Cumulative revenue over time
   - Color gradient fill
   - Comparison to previous period

3. **Message Activity Heatmap**

   - Days of week vs hours
   - Color intensity = activity level

**Recent Activity Table:**

- User avatar + name
- Action performed
- Timestamp (relative)
- Status badge
- Quick actions (view, edit)
- Pagination at bottom

### 4.2 User Management

**Features:**

- User list with search/filter
- User details modal
- Bulk actions (activate, deactivate, delete)
- User roles management
- Activity logs

**User List Table:**

```
┌────────────────────────────────────────────────────────────┐
│ Users                                    [+ Add User]       │
├────────────────────────────────────────────────────────────┤
│ 🔍 Search users...          🔽 Filter    📊 Export         │
├────────────────────────────────────────────────────────────┤
│ ☐ │Avatar│ Name      │ Email          │ Role  │ Status  │ │
├────────────────────────────────────────────────────────────┤
│ ☐ │ [👤] │ John Doe  │ john@mail.com  │ Admin │ Active  │ │
│ ☐ │ [👤] │ Jane Doe  │ jane@mail.com  │ User  │ Active  │ │
│ ☐ │ [👤] │ Bob Smith │ bob@mail.com   │ User  │ Inactive│ │
├────────────────────────────────────────────────────────────┤
│ Showing 1-10 of 150              [< 1 2 3 4 5 >]          │
└────────────────────────────────────────────────────────────┘
```

**Filters:**

- Role (Admin, User, Moderator)
- Status (Active, Inactive, Banned)
- Date range (Created, Last active)
- Sort by (Name, Email, Date, Activity)

**User Details Modal:**

- Profile information
- Activity timeline
- Message history
- Edit user button
- Deactivate/Delete buttons

### 4.3 Analytics

**Tabs:**

- Overview
- Users
- Messages
- Performance
- Custom Reports

**Overview Tab:**

- Key metrics summary
- Trends visualization
- Comparison charts (day/week/month/year)
- Export to PDF/CSV

**Users Tab:**

- User acquisition funnel
- Retention chart
- Cohort analysis
- Geographic distribution map
- Device/browser breakdown

**Messages Tab:**

- Total messages sent
- Average messages per user
- Peak activity times
- Popular topics/keywords
- Sentiment analysis

**Performance Tab:**

- API response times
- Error rates
- Uptime statistics
- Server resources (CPU, Memory, Disk)

### 4.4 System Settings

**Categories:**

- General
- Email
- Security
- API
- Advanced

**General Settings:**

- Site name
- Site logo
- Default language
- Timezone
- Maintenance mode toggle

**Email Settings:**

- SMTP configuration
- Email templates
- Test email function

**Security Settings:**

- Password policy
- Session timeout
- IP whitelist/blacklist
- Rate limiting
- CORS settings

**API Settings:**

- API keys management
- Webhooks configuration
- Rate limits
- Documentation link

## V. Responsive Design

### 5.1 Breakpoints Strategy

**Mobile First Approach:**

```css
/* Mobile (default) */
/* < 640px */

/* Tablet */
@media (min-width: 768px) {
  /* Tablet styles */
}

/* Desktop */
@media (min-width: 1024px) {
  /* Desktop styles */
}

/* Large Desktop */
@media (min-width: 1280px) {
  /* Large desktop styles */
}
```

### 5.2 Mobile Layout (< 768px)

**Web Client Mobile:**

```
┌──────────────────┐
│  [☰] GoodGo [⚙] │ ← Header (fixed)
├──────────────────┤
│                  │
│  ┌────────────┐  │
│  │ AI: Hello  │  │
│  └────────────┘  │
│                  │
│  ┌────────────┐  │
│  │ You: Hi    │  │
│  └────────────┘  │
│                  │
│                  │
│                  │ ← Messages (scrollable)
│                  │
├──────────────────┤
│ [Type...] [Send] │ ← Input (fixed)
└──────────────────┘
```

**Mobile Adaptations:**

- Hide sidebar by default (hamburger menu)
- Full-width messages
- Sticky header + input
- Swipe gestures (back, delete)
- Bottom tab navigation (optional)

**Web Admin Mobile:**

```
┌──────────────────┐
│ [☰] Dashboard    │ ← Header with menu
├──────────────────┤
│                  │
│ ┌──────────────┐ │
│ │ Users: 12.3K │ │
│ │ +12% ↗       │ │
│ └──────────────┘ │
│                  │
│ ┌──────────────┐ │ ← Stacked metrics
│ │ Messages:45K │ │
│ │ +8% ↗        │ │
│ └──────────────┘ │
│                  │
│ [View Details]   │
│                  │
└──────────────────┘
```

**Admin Mobile Adaptations:**

- Collapsible sidebar
- Stacked metric cards
- Horizontal scroll for tables
- Simplified charts
- Touch-friendly buttons (min 44px)

### 5.3 Tablet Layout (768px - 1024px)

**Two-column layout:**

- Show sidebar (toggleable)
- Medium-width messages (60%)
- Side-by-side charts (admin)

### 5.4 Touch Interactions

**Touch Targets:**

- Minimum size: 44x44px (iOS HIG)
- Spacing between: 8px minimum
- Active state feedback (scale down on press)

**Gestures:**

- Swipe left: Delete message/conversation
- Swipe right: Archive/mark as read
- Pull down: Refresh
- Long press: Context menu

## VI. Accessibility (WCAG 2.1 AA)

### 6.1 Color Contrast

**Requirements:**

- Normal text (< 18px): 4.5:1 minimum
- Large text (≥ 18px): 3:1 minimum
- UI components: 3:1 minimum

**Testing Tools:**

- WebAIM Contrast Checker
- Chrome DevTools Accessibility tab
- WAVE browser extension

### 6.2 Keyboard Navigation

**Focus Indicators:**

```css
*:focus-visible {
  outline: 2px solid var(--accent-primary);
  outline-offset: 2px;
}
```

**Tab Order:**

Logical flow:

1. Skip to main content link
2. Header navigation
3. Main content
4. Sidebar
5. Footer

**Keyboard Shortcuts:**

- `Tab`: Next element
- `Shift + Tab`: Previous element
- `Enter`: Activate button/link
- `Space`: Toggle checkbox/select
- `Escape`: Close modal/dropdown
- `Arrow keys`: Navigate lists/menus

**Custom Shortcuts (Chat):**

- `Ctrl/Cmd + K`: Open search
- `Ctrl/Cmd + N`: New conversation
- `Ctrl/Cmd + /`: Show shortcuts help
- `Alt + ↑/↓`: Navigate conversations

### 6.3 Screen Reader Support

**Semantic HTML:**

```html
<header>
<nav aria-label="Main navigation">
<main>
<aside aria-label="Conversation history">
<footer>
```

**ARIA Labels:**

```html
<!-- Button with icon only -->
<button aria-label="Send message">
  <SendIcon aria-hidden="true" />
</button>

<!-- Status indicator -->
<span role="status" aria-live="polite">
  AI is typing...
</span>

<!-- Form validation -->
<input
  type="email"
  aria-required="true"
  aria-invalid="true"
  aria-describedby="email-error"
/>
<span id="email-error" role="alert">
  Please enter a valid email
</span>
```

**Live Regions:**

```html
<!-- Announcement for new messages -->
<div role="status" aria-live="polite" aria-atomic="true">
  New message from AI Assistant
</div>
```

### 6.4 Visual Accessibility

**Font Size:**

- Minimum base: 16px
- User can zoom up to 200% without breaking layout

**Text Spacing:**

- Line height: 1.5 minimum
- Paragraph spacing: 2x font size
- Letter spacing: 0.12x font size (for headings)

**Focus Management:**

- Trap focus in modals
- Return focus after modal close
- Skip to main content link

**Alternative Text:**

- All images have alt text
- Decorative images: `alt=""`
- Avatar images: `alt="John Doe's avatar"`

## VII. Performance Optimization

### 7.1 Loading Strategy

**Critical Rendering Path:**

1. Inline critical CSS (above fold)
2. Defer non-critical CSS
3. Async load JavaScript
4. Lazy load images

**Code Splitting:**

```typescript
// Route-based splitting
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Chat = lazy(() => import('./pages/Chat'));

// Component-based splitting
const HeavyChart = lazy(() => import('./components/HeavyChart'));
```

**Image Optimization:**

- Next.js Image component (automatic optimization)
- WebP format with fallback
- Responsive images (srcset)
- Lazy loading (loading="lazy")
- Blur placeholder (base64)

### 7.2 Perceived Performance

**Skeleton Screens:**

Show content structure while loading:

```tsx
<div className="skeleton">
  <div className="skeleton-avatar" />
  <div className="skeleton-text" />
  <div className="skeleton-text short" />
</div>
```

**Optimistic UI:**

Show immediate feedback before API response:

- Message appears instantly when sent
- Update UI immediately on action
- Revert if API call fails

**Loading States:**

- Button loading (spinner inside)
- Page loading (full-screen or top bar)
- Partial loading (specific sections)

### 7.3 Caching

**Browser Caching:**

- Static assets: 1 year
- API responses: Vary by endpoint
- User data: Session storage

**Service Worker:**

- Cache static assets
- Offline support (basic)
- Background sync for messages

## VIII. Tech Stack Implementation

### 8.1 Frontend Stack

**Core:**

- Next.js 14+ (App Router)
- TypeScript 5+
- React 18+

**Styling:**

- Tailwind CSS 4
- CSS Variables (theme tokens)
- clsx / cn utility (conditional classes)

**UI Components:**

- Radix UI (unstyled primitives)
- Lucide React (icons)
- Framer Motion (animations)

**State Management:**

- Zustand (global state)
- React Query (server state)
- Context API (theme, auth)

**Forms:**

- React Hook Form
- Zod (validation)

**Charts:**

- Recharts or Tremor

**Utilities:**

- date-fns (date formatting)
- clsx (conditional classes)
- nanoid (unique IDs)

### 8.2 Project Structure

```
apps/web-client/
├── public/
│   ├── fonts/
│   ├── images/
│   └── icons/
├── src/
│   ├── app/                    # Next.js App Router
│   │   ├── (auth)/
│   │   │   ├── login/
│   │   │   └── register/
│   │   ├── (dashboard)/
│   │   │   ├── chat/
│   │   │   └── settings/
│   │   ├── layout.tsx
│   │   └── page.tsx
│   ├── components/
│   │   ├── ui/                 # Base components
│   │   │   ├── button.tsx
│   │   │   ├── input.tsx
│   │   │   ├── card.tsx
│   │   │   └── ...
│   │   ├── chat/               # Chat components
│   │   │   ├── message-bubble.tsx
│   │   │   ├── chat-input.tsx
│   │   │   └── typing-indicator.tsx
│   │   ├── layouts/
│   │   │   ├── header.tsx
│   │   │   ├── sidebar.tsx
│   │   │   └── footer.tsx
│   │   └── features/
│   ├── hooks/
│   │   ├── use-chat.ts
│   │   ├── use-auth.ts
│   │   └── use-theme.ts
│   ├── lib/
│   │   ├── api.ts
│   │   ├── utils.ts
│   │   └── constants.ts
│   ├── stores/
│   │   ├── auth-store.ts
│   │   ├── chat-store.ts
│   │   └── theme-store.ts
│   ├── styles/
│   │   ├── globals.css
│   │   └── theme.css
│   └── types/
│       ├── api.ts
│       └── models.ts
├── .env.local
├── next.config.js
├── tailwind.config.js
├── tsconfig.json
└── package.json
```

### 8.3 Component Example

**Button Component:**

```typescript
// components/ui/button.tsx
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"

const buttonVariants = cva(
  "inline-flex items-center justify-center rounded-md text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
  {
    variants: {
      variant: {
        primary: "bg-blue-600 text-white hover:bg-blue-700",
        secondary: "bg-gray-600 text-white hover:bg-gray-700",
        ghost: "hover:bg-gray-800 text-gray-300",
        danger: "bg-red-600 text-white hover:bg-red-700",
      },
      size: {
        xs: "h-7 px-3 text-xs",
        sm: "h-8 px-4 text-sm",
        md: "h-10 px-5 text-base",
        lg: "h-12 px-6 text-lg",
        xl: "h-14 px-7 text-xl",
      },
    },
    defaultVariants: {
      variant: "primary",
      size: "md",
    },
  }
)

export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof buttonVariants> {
  asChild?: boolean
  loading?: boolean
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, asChild = false, loading, children, ...props }, ref) => {
    const Comp = asChild ? Slot : "button"
    return (
      <Comp
        className={cn(buttonVariants({ variant, size, className }))}
        ref={ref}
        disabled={loading || props.disabled}
        {...props}
      >
        {loading && <Spinner className="mr-2" />}
        {children}
      </Comp>
    )
  }
)
Button.displayName = "Button"

export { Button, buttonVariants }
```

**Usage:**

```tsx
<Button variant="primary" size="md">
  Send Message
</Button>

<Button variant="ghost" size="sm" loading={isLoading}>
  Loading...
</Button>
```

## IX. Implementation Phases

### Todo System for Multi-Agent Development

This plan includes **60+ granular todos** organized by phase and designed for parallel development by multiple agents. Each todo:

- Has a unique ID (e.g., `design-system-1`, `chat-3`)
- Is independent and can be worked on in parallel with others
- Includes specific file paths and implementation details
- Maps to a phase but can be started as soon as dependencies are met

**How to Use:**

1. **View Todos**: Check the workspace todo list to see all pending tasks
2. **Assign Work**: Agents can pick todos based on their expertise and dependencies
3. **Track Progress**: Mark todos as `in_progress` when starting, `completed` when done
4. **Parallel Execution**: Multiple agents can work simultaneously on different todos within the same phase

**Dependency Guidelines:**

- **Phase 1 (Design System)** must be started first - provides base components
- **Phase 2 (Auth)** can start after `design-system-3` (Button) and `design-system-4` (Input) are done
- **Phase 3 (Chat)** requires `design-system-1` through `design-system-7` to be complete
- **Phase 5-7 (Admin)** can run in parallel with Phase 3-4 (Client) after Phase 1
- **Phase 8-10** (Responsive, Performance, Testing) can start once core features are implemented

**Example Parallel Workflow:**

```
Week 1: Design System
├─ Agent 1: design-system-1, design-system-2 (Tailwind + CSS vars)
├─ Agent 2: design-system-3, design-system-4 (Button + Input)
├─ Agent 3: design-system-5, design-system-6, design-system-7 (Card + Dialog + Avatar)
└─ Agent 4: design-system-8, design-system-9 (Theme + Storybook)

Week 2: Authentication (after Button + Input are done)
├─ Agent 1: auth-1, auth-2 (Login + Register pages)
├─ Agent 2: auth-3 (Forgot password)
├─ Agent 3: auth-4 (OAuth)
└─ Agent 4: auth-5 (Auth store)
```

### Complete Todo List Reference

All 60+ todos are tracked in the workspace todo system. Below is a quick reference organized by phase:

**Phase 1: Design System (9 todos)**

- `design-system-1`: Initialize Tailwind CSS 4 in web-client
- `design-system-2`: Create CSS variables file with theme tokens
- `design-system-3`: Build Button component with variants
- `design-system-4`: Build Input component with validation states
- `design-system-5`: Build Card component with subcomponents
- `design-system-6`: Build Modal/Dialog component using Radix UI
- `design-system-7`: Build Avatar component with sizes
- `design-system-8`: Setup theme switching system
- `design-system-9`: Initialize Storybook for documentation

**Phase 2: Authentication (5 todos)**

- `auth-1`: Create Login page with validation
- `auth-2`: Create Register page with password strength
- `auth-3`: Implement Forgot Password flow
- `auth-4`: Integrate OAuth with Google
- `auth-5`: Create auth store with Zustand

**Phase 3: Chat Interface (8 todos)**

- `chat-1`: Build Chat layout component
- `chat-2`: Build MessageBubble component
- `chat-3`: Build ChatInput component with auto-resize
- `chat-4`: Build TypingIndicator component
- `chat-5`: Build ConversationSidebar component
- `chat-6`: Implement message actions menu
- `chat-7`: Integrate WebSocket client
- `chat-8`: Create chat store with Zustand

**Phase 4: Settings & Profile (5 todos)**

- `settings-1`: Create User Profile page
- `settings-2`: Create Settings layout with tabs
- `settings-3`: Implement Preferences tab
- `settings-4`: Implement Security tab with 2FA
- `settings-5`: Implement API Keys management page

**Phase 5-7: Admin Dashboard (14 todos)**

- `admin-1`: Create Admin Dashboard layout
- `admin-2`: Build AnalyticsCard component
- `admin-3`: Create Dashboard overview page
- `admin-4`: Integrate Recharts and create UserGrowthChart
- `admin-5`: Create RevenueChart component
- `admin-6`: Build RecentActivityTable component
- `admin-7`: Create UserManagement page
- `admin-8`: Build DataTable component
- `admin-9`: Create UserDetailsModal component
- `admin-10`: Implement bulk actions for users
- `admin-11`: Create SystemSettings page
- `admin-12`: Build GeneralSettings form
- `admin-13`: Build EmailSettings form
- `admin-14`: Build SecuritySettings form

**Phase 8: Responsive & Accessibility (8 todos)**

- `responsive-1`: Mobile responsive for web-client
- `responsive-2`: Mobile responsive for web-admin
- `responsive-3`: Tablet optimizations
- `responsive-4`: Touch-friendly interactions
- `accessibility-1`: Keyboard navigation
- `accessibility-2`: ARIA labels and semantic HTML
- `accessibility-3`: Screen reader support
- `accessibility-4`: WCAG 2.1 AA compliance verification

**Phase 9: Performance (5 todos)**

- `performance-1`: Code splitting implementation
- `performance-2`: Image optimization
- `performance-3`: Lazy loading
- `performance-4`: Caching strategy
- `performance-5`: Lighthouse optimization

**Phase 10: Testing & Polish (6 todos)**

- `testing-1`: Unit tests for UI components
- `testing-2`: Unit tests for hooks/stores
- `testing-3`: E2E tests for critical flows
- `testing-4`: Cross-browser testing
- `testing-5`: Performance testing
- `testing-6`: Bug fixes and polish

> **Note:** Detailed todos for multi-agent development are tracked in the workspace todo system. Each phase below maps to specific todo items that can be worked on in parallel by multiple agents.

### Phase 1: Design System Setup (Week 1)

**Todos:** `design-system-1` through `design-system-9`

- Initialize Tailwind CSS 4 configuration
- Create CSS variables for theme tokens
- Build base UI components (Button, Input, Card, Dialog, Avatar)
- Setup theme switching system
- Initialize Storybook

**Parallel Work Opportunities:**

- Agent 1: Tailwind setup + CSS variables
- Agent 2: Button + Input components
- Agent 3: Card + Dialog + Avatar components
- Agent 4: Theme system + Storybook setup

### Phase 2: Web Client - Authentication (Week 2)

**Todos:** `auth-1` through `auth-5`

- Login page with form validation
- Register page with password strength
- Forgot password flow
- OAuth integration (Google)
- Auth state management

**Parallel Work Opportunities:**

- Agent 1: Login + Register pages
- Agent 2: Forgot password flow
- Agent 3: OAuth integration
- Agent 4: Auth store implementation

### Phase 3: Web Client - Chat Interface (Week 3-4)

**Todos:** `chat-1` through `chat-8`

- Chat layout structure
- Message bubble components
- Chat input with auto-resize
- Typing indicator
- Conversation sidebar
- Message actions menu
- WebSocket integration
- Chat store

**Parallel Work Opportunities:**

- Agent 1: Chat layout + Message bubbles
- Agent 2: Chat input + Typing indicator
- Agent 3: Conversation sidebar + Message actions
- Agent 4: WebSocket client + Chat store

### Phase 4: Web Client - Settings & Profile (Week 5)

**Todos:** `settings-1` through `settings-5`

- User profile page
- Settings layout with tabs
- Preferences tab
- Security tab (2FA)
- API keys management

**Parallel Work Opportunities:**

- Agent 1: Profile page + Settings layout
- Agent 2: Preferences tab
- Agent 3: Security tab
- Agent 4: API keys management

### Phase 5: Web Admin - Dashboard (Week 6-7)

**Todos:** `admin-1` through `admin-6`

- Admin dashboard layout
- Analytics card component
- Dashboard overview with metrics
- User growth chart
- Revenue chart
- Recent activity table

**Parallel Work Opportunities:**

- Agent 1: Dashboard layout + Analytics cards
- Agent 2: User growth chart
- Agent 3: Revenue chart
- Agent 4: Recent activity table

### Phase 6: Web Admin - User Management (Week 8)

**Todos:** `admin-7` through `admin-10`

- User management page
- DataTable component
- User details modal
- Bulk actions

**Parallel Work Opportunities:**

- Agent 1: User management page + DataTable
- Agent 2: User details modal
- Agent 3: Bulk actions implementation

### Phase 7: Web Admin - System Settings (Week 9)

**Todos:** `admin-11` through `admin-14`

- System settings page with tabs
- General settings form
- Email settings form
- Security settings form

**Parallel Work Opportunities:**

- Agent 1: Settings page + General settings
- Agent 2: Email settings
- Agent 3: Security settings

### Phase 8: Responsive & Accessibility (Week 10)

**Todos:** `responsive-1` through `responsive-4`, `accessibility-1` through `accessibility-4`

- Mobile responsive layouts
- Tablet optimizations
- Touch interactions
- Keyboard navigation
- ARIA labels and semantic HTML
- Screen reader support
- WCAG compliance verification

**Parallel Work Opportunities:**

- Agent 1: Mobile responsive (web-client)
- Agent 2: Mobile responsive (web-admin) + Tablet
- Agent 3: Accessibility (keyboard + ARIA)
- Agent 4: Screen reader + WCAG testing

### Phase 9: Performance & Optimization (Week 11)

**Todos:** `performance-1` through `performance-5`

- Code splitting
- Image optimization
- Lazy loading
- Caching strategy
- Lighthouse optimization

**Parallel Work Opportunities:**

- Agent 1: Code splitting + Lazy loading
- Agent 2: Image optimization
- Agent 3: Caching strategy
- Agent 4: Lighthouse optimization

### Phase 10: Testing & Polish (Week 12)

**Todos:** `testing-1` through `testing-6`

- Unit tests for components
- Unit tests for hooks/stores
- E2E tests for critical flows
- Cross-browser testing
- Performance testing
- Bug fixes and polish

**Parallel Work Opportunities:**

- Agent 1: Component unit tests
- Agent 2: Hooks/stores unit tests
- Agent 3: E2E tests
- Agent 4: Cross-browser + Performance testing
- Agent 5: Bug fixes and polish

## X. Design Resources & References

### 10.1 Inspiration Sources

- [x.ai Grok UI](https://grok.x.ai/) - Minimalistic, intuitive chat interface
- [OpenAI ChatGPT](https://chat.openai.com/) - Industry-standard AI chat
- [Claude.ai](https://claude.ai/) - Clean, professional design
- [Vercel AI Chat](https://sdk.vercel.ai/) - Modern chat SDK examples
- [Linear App](https://linear.app/) - Beautiful dark mode UI

### 10.2 Design Tools

- **Figma**: UI design and prototyping
- **Storybook**: Component development and documentation
- **Chromatic**: Visual regression testing
- **Tailwind UI**: Premium component examples
- **Shadcn UI**: High-quality component library

### 10.3 Color Tools

- **Coolors**: Color palette generation
- **Contrast Checker**: WCAG compliance
- **ColorBox**: Dark mode palette creation
- **Palettte**: Color scheme explorer

### 10.4 Typography Resources

- **Fontsource**: Self-hosted fonts
- **Modern Font Stacks**: System font combinations
- **Type Scale**: Typography scale generator

### 10.5 Icon Libraries

- **Lucide React**: Modern icon set (recommended)
- **Heroicons**: Tailwind's icon library
- **Phosphor Icons**: Flexible icon family
- **Feather Icons**: Minimalist icons

## XI. Common Patterns & Best Practices

### 11.1 Component Patterns

**Compound Components:**

```tsx
<Card>
  <CardHeader>
    <CardTitle>Title</CardTitle>
  </CardHeader>
  <CardContent>Content</CardContent>
</Card>
```

**Render Props:**

```tsx
<DataTable
  data={users}
  renderRow={(user) => (
    <UserRow user={user} />
  )}
/>
```

**Controlled Components:**

```tsx
const [value, setValue] = useState("")
<Input value={value} onChange={setValue} />
```

### 11.2 State Management Patterns

**Zustand Store:**

```typescript
// stores/chat-store.ts
import { create } from 'zustand'

interface ChatState {
  messages: Message[]
  isTyping: boolean
  addMessage: (message: Message) => void
  setTyping: (typing: boolean) => void
}

export const useChatStore = create<ChatState>((set) => ({
  messages: [],
  isTyping: false,
  addMessage: (message) =>
    set((state) => ({ messages: [...state.messages, message] })),
  setTyping: (typing) => set({ isTyping: typing }),
}))
```

**Usage:**

```tsx
const { messages, addMessage } = useChatStore()
```

### 11.3 API Integration Pattern

**React Query:**

```typescript
// hooks/use-chat.ts
import { useQuery, useMutation } from '@tanstack/react-query'

export function useMessages(conversationId: string) {
  return useQuery({
    queryKey: ['messages', conversationId],
    queryFn: () => api.getMessages(conversationId),
  })
}

export function useSendMessage() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: api.sendMessage,
    onSuccess: () => {
      queryClient.invalidateQueries(['messages'])
    },
  })
}
```

### 11.4 Error Handling

**Error Boundary:**

```tsx
<ErrorBoundary fallback={<ErrorPage />}>
  <App />
</ErrorBoundary>
```

**Toast Notifications:**

```tsx
import { toast } from 'sonner'

try {
  await sendMessage(text)
  toast.success('Message sent')
} catch (error) {
  toast.error('Failed to send message')
}
```

## XII. Deployment Considerations

### 12.1 Build Optimization

**Next.js Config:**

```javascript
// next.config.js
module.exports = {
  images: {
    domains: ['cdn.example.com'],
    formats: ['image/webp', 'image/avif'],
  },
  compiler: {
    removeConsole: process.env.NODE_ENV === 'production',
  },
  experimental: {
    optimizeCss: true,
  },
}
```

### 12.2 Environment Variables

```bash
# .env.local (development)
NEXT_PUBLIC_API_URL=http://localhost:5001/api/v1
NEXT_PUBLIC_WS_URL=ws://localhost:5001
NEXT_PUBLIC_ENV=development

# .env.production
NEXT_PUBLIC_API_URL=https://api.goodgo.vn/api/v1
NEXT_PUBLIC_WS_URL=wss://api.goodgo.vn
NEXT_PUBLIC_ENV=production
```

### 12.3 Performance Metrics

**Target Lighthouse Scores:**

- Performance: 90+
- Accessibility: 95+
- Best Practices: 95+
- SEO: 100

**Core Web Vitals:**

- LCP (Largest Contentful Paint): < 2.5s
- FID (First Input Delay): < 100ms
- CLS (Cumulative Layout Shift): < 0.1

---

## Research Sources

Based on research from:

- [xAI UI & Management Console](https://cobusgreyling.medium.com/xai-ui-management-console-35500fa967fe)
- [Grok UI Figma Community](https://www.figma.com/community/file/1514056350765003193/grok-ui)
- [OpenAI Apps SDK UI](https://developers.openai.com/apps-sdk/build/chatgpt-ui/)
- [OpenAI UI Guidelines](https://developers.openai.com/apps-sdk/concepts/ui-guidelines/)
- [16 Chat UI Design Patterns](https://bricxlabs.com/blogs/message-screen-ui-deisgn)
- [UI/UX Design Trends 2026](https://www.index.dev/blog/ui-ux-design-trends)
- [Modern Web Experience Design](https://digitalhouse.ae/blog/ui-and-ux-design/)

---

**Document Version:** 1.0

**Last Updated:** 2026-01-02

**Status:** Ready for Implementation