npm package: @jangkeyte/chat-module
Description: Real-time chat module with SSE support, emoji picker, file upload, and auto-scroll for Next.js applications
Author: PlayTiMi
Latest version: 1.1.0

# @jangkeyte/chat-module

Real-time chat module with SSE support, emoji picker, file upload, and auto-scroll for Next.js applications.

## 🚀 Features

- ✅ **Real-time messaging** with Server-Sent Events
- ✅ **Emoji picker** with 32 common emojis
- ✅ **File & image upload** with preview (JPG, PNG, GIF, WebP)
- ✅ **Online status** tracking
- ✅ **Auto-scroll** to latest messages
- ✅ **Responsive design** for mobile & desktop
- ✅ **Internationalization** (Japanese/English)
- ✅ **Toast notifications** for errors
- ✅ **Drag & drop** file upload

## 📖 Documentation

See [INTEGRATION_GUIDE.md](./INTEGRATION_GUIDE.md) for complete setup instructions.

## Features

- ✅ Real-time messaging using Server-Sent Events (SSE)
- ✅ User-to-user chat
- ✅ Online/Offline status indicators
- ✅ Message history
- ✅ Responsive design (mobile & desktop)
- ✅ Minimize/Maximize functionality
- ✅ Auto-scroll to latest message
- ✅ Keepalive mechanism
- ✅ Auto-reconnect on connection loss

## Installation

```bash
npm install @jangkeyte/chat-module
```

## Setup

### 1. Add ChatProvider to your app layout

```tsx
// app/layout.tsx
import { ChatProvider } from '@jangkeyte/chat-module'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <ChatProvider>
          {children}
        </ChatProvider>
      </body>
    </html>
  )
}
```

### 2. Add ChatWrapper to your layout

```tsx
// app/layout.tsx or components/Layout.tsx
import { ChatWrapper } from '@jangkeyte/chat-module'
import { useAuth } from '@/contexts/AuthContext' // Your auth context

export default function Layout({ children }) {
  const { user } = useAuth()
  
  return (
    <div>
      {children}
      <ChatWrapper 
        currentUser={user}
        apiBaseUrl="/api" // Optional, defaults to '/api'
      />
    </div>
  )
}
```

### 3. Use chat in your components

```tsx
// components/UserCard.tsx
import { openChatModal } from '@jangkeyte/chat-module'

export default function UserCard({ user }) {
  return (
    <div>
      <h3>{user.name}</h3>
      <button onClick={() => openChatModal(user.id)}>
        Chat with {user.name}
      </button>
    </div>
  )
}
```

## API Requirements

Your backend needs to implement these endpoints:

### 1. Messages API

#### GET `/api/messages/user/:userId`
Get messages between current user and specific user.

**Response:**
```json
{
  "success": true,
  "data": [
    {
      "id": "msg_123",
      "content": "Hello",
      "senderId": "user_1",
      "receiverId": "user_2",
      "createdAt": "2025-01-01T00:00:00Z",
      "sender": {
        "id": "user_1",
        "username": "john",
        "displayName": "John Doe",
        "avatar": "/avatar.jpg"
      },
      "receiver": { /* ... */ }
    }
  ]
}
```

#### POST `/api/messages/user`
Send a new message.

**Request:**
```json
{
  "content": "Hello",
  "receiverId": "user_2"
}
```

**Response:**
```json
{
  "success": true,
  "data": {
    "id": "msg_123",
    "content": "Hello",
    "senderId": "user_1",
    "receiverId": "user_2",
    "createdAt": "2025-01-01T00:00:00Z",
    "sender": { /* ... */ },
    "receiver": { /* ... */ }
  }
}
```

### 2. User Status API

#### POST `/api/user/status`
Update user online status.

**Request:**
```json
{
  "status": "online" // or "busy", "away"
}
```

#### PUT `/api/user/status`
Keepalive ping to maintain online status.

#### GET `/api/user/status?userId=xxx`
Get online status of specific user.

**Response:**
```json
{
  "success": true,
  "data": {
    "userId": "user_1",
    "status": "online",
    "isOnline": true,
    "lastSeen": 1234567890
  }
}
```

### 3. SSE API

#### GET `/api/chat/sse`
Server-Sent Events endpoint for real-time updates.

**Events:**
```javascript
// New message event
{
  "type": "new_message",
  "message": { /* UserMessage object */ }
}

// Online status event
{
  "type": "user_online_status",
  "userId": "user_1",
  "isOnline": true
}
```

### 4. User Info API

#### GET `/api/users/:id`
Get user information.

**Response:**
```json
{
  "success": true,
  "data": {
    "id": "user_1",
    "username": "john",
    "displayName": "John Doe",
    "avatar": "/avatar.jpg"
  }
}
```

## Database Schema

### UserMessage Table

```sql
CREATE TABLE UserMessage (
  id TEXT PRIMARY KEY,
  content TEXT NOT NULL,
  senderId TEXT NOT NULL,
  receiverId TEXT NOT NULL,
  messageType TEXT DEFAULT 'TEXT',
  attachmentUrl TEXT,
  isRead BOOLEAN DEFAULT false,
  createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
  updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (senderId) REFERENCES User(id),
  FOREIGN KEY (receiverId) REFERENCES User(id)
);

CREATE INDEX idx_sender ON UserMessage(senderId);
CREATE INDEX idx_receiver ON UserMessage(receiverId);
CREATE INDEX idx_created ON UserMessage(createdAt);
```

## Configuration

### Props

#### ChatWrapper Props

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| currentUser | `{ id: string; username: string; displayName?: string }` | Yes | - | Current logged-in user |
| apiBaseUrl | `string` | No | `/api` | Base URL for API endpoints |

## Styling

The module uses Tailwind CSS classes. Make sure your project has Tailwind CSS configured.

## Browser Support

- Chrome/Edge (latest)
- Firefox (latest)
- Safari (latest)
- Mobile browsers

## License

MIT

## Support

For issues and questions, please open an issue on GitHub.