# Floating Chat Widget Implementation

This document describes the implementation of the persistent floating chat widget for seamless team communication across the Jomblo dashboard.

## Overview

The floating chat widget provides real-time team communication with the following key features:

- **Persistent Position**: Fixed in bottom right corner, always visible across dashboard pages
- **Collapsible/Minimizable**: Can be minimized to show only unread count
- **Drag-and-Drop Positioning**: Users can reposition the widget
- **Real-time Updates**: Live presence indicators and message updates
- **Entity Mentions**: Context-aware entity quoting and mentions
- **Edit Locks**: Conflict prevention for concurrent editing
- **Presence Integration**: Shows who's online and their current location

## Architecture

### Database Schema

The chat system uses the following tables:

#### `team_presence`
Tracks user online status and last activity
- `user_id`: References users table
- `online`: Boolean indicating online status
- `last_seen`: Timestamp of last activity
- `created_at`, `updated_at`: Audit timestamps

#### `team_chat_messages`
Stores chat messages with entity context
- `sender_id`: References users table
- `message`: Text content
- `entity_type`, `entity_id`: Optional entity references
- `priority`: Message priority (normal, high)
- `is_mention`: Boolean for direct mentions
- `read_by`: Array of user IDs who read the message

#### `entity_mentions`
Tracks mentions within messages
- `message_id`: References team_chat_messages
- `entity_type`, `entity_id`: Referenced entity
- `mentioned_user_id`: User who was mentioned

#### `edit_locks`
Prevents edit conflicts
- `entity_type`, `entity_id`: Locked entity
- `user_id`: User who holds the lock
- `lock_type`: Type of lock (edit, view)
- `expires_at`: Lock expiration time

### API Endpoints

#### `/api/chat/messages`
- `GET`: Fetch chat messages with pagination
- `POST`: Send new message

#### `/api/presence`
- `GET`: Get current online users
- `POST`: Update user presence status

#### `/api/edit-locks`
- `GET`: List active edit locks
- `POST`: Create new edit lock
- `DELETE`: Release edit lock

### Components

#### Core Components
- `TeamChatWidget`: Main container component
- `ChatWidget`: Floating widget with drag-and-drop
- `ChatToggleButton`: Minimized state button
- `ChatHeader`: Widget header with controls
- `ChatMessages`: Message list display
- `ChatInput`: Message composition area

#### Feature Components
- `EntityMentions`: Entity search and quoting
- `EditLockIndicator`: Edit lock management
- `PresenceIndicator`: Online user display

#### State Management
- `useChatWidgetStore`: Widget state (minimized, position, visibility)
- `useChatStore`: Chat messages and operations
- `usePresenceStore`: User presence data

## Installation

### 1. Database Setup

Run the SQL schema setup:

```bash
# Set your database URL
export DATABASE_URL="postgresql://user:password@localhost:5432/jomblo"

# Execute the setup script
./scripts/setup-chat.sh
```

Or manually run the SQL:

```bash
psql "$DATABASE_URL" -f scripts/setup-chat-schema.sql
```

### 2. Environment Variables

Ensure your `.env` file includes:

```env
DATABASE_URL="postgresql://user:password@localhost:5432/jomblo"
```

### 3. Dependencies

The chat widget uses existing project dependencies:
- `pg`: PostgreSQL client
- `lucide-react`: Icons
- `zustand`: State management
- `@radix-ui/react-*`: UI components

## Usage

### Basic Chat

1. The widget appears in the bottom right corner of the dashboard
2. Click the widget to expand from minimized state
3. Type messages in the input field and press Enter to send
4. Messages appear in real-time for all online users

### Entity Mentions

1. Click the "Mentions" button in the widget
2. Search for entities (products, customers, orders, etc.)
3. Select an entity to quote it in your message
4. The message will include entity context for easy reference

### Edit Locks

1. When editing entities, locks are automatically created
2. The "Edit Locks" button shows active locks
3. Locks prevent concurrent editing conflicts
4. Locks expire after 30 minutes or can be manually released

### Presence Features

1. Online users are shown in the presence indicator
2. Real-time updates show who's currently active
3. User avatars and names are displayed
4. Click presence indicators to see who's online

## Configuration

### Widget Position

The widget defaults to bottom-right positioning but can be dragged to any position. Position is not persisted between sessions.

### Styling

The widget uses Tailwind CSS classes and follows the project's design system:
- `bg-background`: Matches theme background
- `border-border`: Consistent border styling
- `shadow-lg`: Subtle shadow for depth
- `rounded-lg`: Rounded corners

### Responsive Design

The widget is optimized for desktop use. On mobile devices, it may be hidden or adapted for smaller screens.

## Development

### Adding New Entity Types

To add support for new entity types in mentions:

1. Update the mock data in `EntityMentions.tsx`
2. Create API endpoints for entity search if needed
3. Update the database schema if new entity types require special handling

### Customizing Appearance

Modify the Tailwind classes in component files:

```tsx
// In ChatWidget.tsx
<div className="fixed bottom-6 right-6 z-50 w-96 bg-background border border-border rounded-lg shadow-lg">
```

### Adding Features

1. Create new components in `components/dashboard/`
2. Add state management to relevant stores
3. Update the widget layout as needed
4. Ensure proper TypeScript interfaces

## Testing

### Unit Tests

Test individual components and functions:

```bash
pnpm test:unit
```

### Integration Tests

Test API endpoints and database interactions:

```bash
pnpm test:integration
```

### E2E Tests

Test complete user workflows:

```bash
pnpm test:e2e
```

## Troubleshooting

### Widget Not Appearing

1. Check that `TeamChatWidget` is rendered in `app/(private)/dashboard/layout.tsx`
2. Verify user is authenticated and has dashboard access
3. Check browser console for JavaScript errors

### Messages Not Loading

1. Verify database tables exist and have proper permissions
2. Check API endpoints are accessible
3. Ensure user has proper authentication

### Presence Not Updating

1. Verify `team_presence` table has data
2. Check that presence API endpoints work
3. Ensure user presence is being tracked

### Edit Locks Not Working

1. Verify `edit_locks` table exists
2. Check that lock creation/deletion API works
3. Ensure proper error handling for conflicts

## Security

### Authentication

All chat endpoints require user authentication via the existing auth system.

### Authorization

- Users can only see their own presence data
- Edit locks respect user permissions
- Message history is accessible to authenticated users

### Data Validation

- All inputs are validated server-side
- SQL queries use parameterized statements
- Entity references are validated

## Performance

### Database Optimization

- Proper indexes on frequently queried columns
- Efficient queries with appropriate JOINs
- Pagination for message lists

### Frontend Optimization

- Virtualization for long message lists
- Debounced presence updates
- Efficient state updates

### Caching

- Browser caching for static assets
- Consider Redis caching for presence data in production

## Future Enhancements

### Planned Features

- **SSE/Real-time Updates**: Replace polling with Server-Sent Events
- **Desktop Notifications**: Browser notifications for mentions
- **Message Threads**: Nested conversations
- **File Sharing**: Upload and share files
- **Voice Messages**: Audio message support
- **Search**: Full-text search across messages

### Mobile Support

- Responsive design for mobile devices
- Touch-friendly interactions
- Mobile-specific features

### Advanced Features

- **Message Reactions**: Emoji reactions to messages
- **Message Editing**: Edit sent messages
- **Message Deletion**: Delete messages with proper permissions
- **Typing Indicators**: Show when users are typing