npm package: @gaplash/chat-ui
Description: Gaplash Chat UI Kit - Easy-to-integrate chat component for web applications
Author: Gaplash Team
Latest version: 1.0.0

# Gaplash Chat UI Kit

A powerful, easy-to-integrate chat component library for React applications. Similar to Weavy, but built specifically for the Gaplash ecosystem.

## Features

✅ **Easy Integration** - Drop-in chat component with minimal setup  
✅ **Real-time Messaging** - WebSocket and Firebase support  
✅ **One-on-One Conversations** - Direct messaging between users  
✅ **Environment Isolation** - Users can only chat within their environment  
✅ **File Attachments** - Support for file uploads (optional)  
✅ **Typing Indicators** - Real-time typing status  
✅ **Message Actions** - Edit, delete, and react to messages  
✅ **Responsive Design** - Works on desktop and mobile  
✅ **Customizable Themes** - Easy styling and theming  
✅ **TypeScript Support** - Full type safety  

## Quick Start

### Installation

```bash
npm install @gaplash/chat-ui
# or
yarn add @gaplash/chat-ui
```

### Basic Usage

```tsx
import React from 'react';
import { ChatContainer } from '@gaplash/chat-ui';

function App() {
  const config = {
    apiUrl: 'https://your-gaplash-backend.com',
    environmentId: 'your-environment-id',
    externalUserId: 'user-123', // User ID from your system
    userEmail: 'user@example.com',
    userName: 'John Doe',
    userAvatar: 'https://example.com/avatar.jpg', // optional
  };

  return (
    <div style={{ height: '600px', width: '800px' }}>
      <ChatContainer config={config} />
    </div>
  );
}

export default App;
```

## Configuration

### Required Configuration

```tsx
interface GaplashConfig {
  apiUrl: string;              // Your Gaplash backend URL
  environmentId: string;       // Environment ID from your Gaplash setup
  externalUserId: string;      // User ID from your application
  userEmail: string;           // User's email address
  userName: string;            // User's display name
  userAvatar?: string;         // User's avatar URL (optional)
}
```

### Optional Configuration

```tsx
interface GaplashConfig {
  // ... required fields ...
  
  userMetadata?: Record<string, any>;  // Custom user data
  
  // Firebase configuration for real-time features
  firebaseConfig?: {
    apiKey: string;
    authDomain: string;
    projectId: string;
    storageBucket: string;
    messagingSenderId: string;
    appId: string;
  };
  
  // Custom theme
  theme?: {
    primaryColor?: string;
    backgroundColor?: string;
    textColor?: string;
    borderColor?: string;
    messageBackgroundColor?: string;
    userMessageBackgroundColor?: string;
    borderRadius?: string;
    fontFamily?: string;
  };
  
  // Feature flags
  features?: {
    enableFileUpload?: boolean;
    enableEmojis?: boolean;
    enableTypingIndicators?: boolean;
    enableMessageReactions?: boolean;
    enableSearch?: boolean;
  };
}
```

## Integration Examples

### Basic Integration (Demod Example)

```tsx
// In your Demod application
import React from 'react';
import { ChatContainer } from '@gaplash/chat-ui';

const ChatPage = ({ user }) => {
  const chatConfig = {
    apiUrl: process.env.REACT_APP_GAPLASH_API_URL,
    environmentId: process.env.REACT_APP_GAPLASH_ENV_ID,
    externalUserId: user.id,
    userEmail: user.email,
    userName: user.displayName,
    userAvatar: user.profilePicture,
    userMetadata: {
      role: user.role,
      department: user.department,
    },
    features: {
      enableFileUpload: true,
      enableEmojis: true,
      enableTypingIndicators: true,
    },
  };

  return (
    <div className="chat-page">
      <h1>Team Chat</h1>
      <ChatContainer 
        config={chatConfig}
        height="calc(100vh - 100px)"
        width="100%"
      />
    </div>
  );
};
```

### Custom Styling

```tsx
const customTheme = {
  primaryColor: '#007bff',
  backgroundColor: '#f8f9fa',
  textColor: '#333333',
  borderRadius: '12px',
  fontFamily: 'Inter, sans-serif',
};

<ChatContainer 
  config={{ ...config, theme: customTheme }}
  className="my-custom-chat"
  style={{ border: '2px solid #007bff' }}
/>
```

### With Firebase Real-time

```tsx
const configWithFirebase = {
  ...baseConfig,
  firebaseConfig: {
    apiKey: "your-firebase-api-key",
    authDomain: "your-project.firebaseapp.com",
    projectId: "your-project",
    storageBucket: "your-project.appspot.com",
    messagingSenderId: "123456789",
    appId: "1:123456789:web:abcdef123456"
  }
};

<ChatContainer config={configWithFirebase} />
```

## Backend Setup

### 1. Register Your Organization

```bash
curl -X POST https://your-gaplash-backend.com/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "organizationName": "Demod Inc",
    "organizationDescription": "Our awesome company",
    "ownerEmail": "admin@demod.com",
    "ownerName": "Admin User",
    "password": "secure_password"
  }'
```

### 2. Create an Environment

```bash
curl -X POST https://your-gaplash-backend.com/environments \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "name": "Demod Production",
    "description": "Production environment for Demod users"
  }'
```

### 3. Get Environment API Key

```bash
curl -X POST https://your-gaplash-backend.com/auth/environments/ENV_ID/api-key \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "name": "Demod Frontend Key"
  }'
```

## Advanced Usage

### Using Individual Components

```tsx
import { 
  ConversationList, 
  MessageList, 
  MessageInput,
  GaplashAPI,
  chatStoreFactory 
} from '@gaplash/chat-ui';

const CustomChatApp = () => {
  const [store, setStore] = useState(null);
  const [api, setApi] = useState(null);

  useEffect(() => {
    const initChat = async () => {
      const storeInstance = await chatStoreFactory.initStore();
      const apiInstance = new GaplashAPI(config);
      
      setStore(storeInstance);
      setApi(apiInstance);
    };
    
    initChat();
  }, []);

  return (
    <div className="custom-chat">
      <ConversationList 
        conversations={conversations}
        onConversationSelect={handleSelect}
      />
      <MessageList 
        messages={messages}
        currentUser={currentUser}
      />
      <MessageInput 
        onSendMessage={handleSend}
      />
    </div>
  );
};
```

### Event Handling

```tsx
const ChatWithEvents = () => {
  const handleMessageSent = (message) => {
    console.log('Message sent:', message);
    // Analytics, notifications, etc.
  };

  const handleUserOnline = (userId) => {
    console.log('User came online:', userId);
    // Update UI, send notifications
  };

  return (
    <ChatContainer 
      config={config}
      onMessageSent={handleMessageSent}
      onUserOnline={handleUserOnline}
    />
  );
};
```

## API Reference

### ChatContainer Props

```tsx
interface ChatContainerProps {
  config: GaplashConfig;
  className?: string;
  style?: React.CSSProperties;
  height?: string | number;
  width?: string | number;
  onMessageSent?: (message: Message) => void;
  onConversationStarted?: (conversation: Conversation) => void;
  onError?: (error: string) => void;
}
```

### GaplashAPI Methods

```tsx
class GaplashAPI {
  // Authentication
  authenticateUser(): Promise<AuthResponse>
  
  // Conversations
  getConversations(): Promise<Conversation[]>
  getOrCreateConversation(recipientId: string): Promise<Conversation>
  
  // Messages
  sendDirectMessage(recipientId: string, content: string, attachments?: File[]): Promise<Message>
  getConversationMessages(conversationId: string, limit?: number, offset?: number): Promise<Message[]>
  editMessage(messageId: string, content: string): Promise<Message>
  deleteMessage(messageId: string): Promise<void>
  
  // Users
  getEnvironmentUsers(): Promise<User[]>
  
  // Real-time
  sendTypingIndicator(isTyping: boolean): Promise<void>
}
```

## Troubleshooting

### Common Issues

**1. Authentication Failed**
```
Error: User not found
```
Make sure the user exists in your Gaplash environment. Users are automatically created when they first access the chat.

**2. Environment Not Found**
```
Error: Environment not found
```
Verify your `environmentId` is correct and the environment exists in your organization.

**3. Real-time Not Working**
- Check if WebSocket connection is established
- Verify Firebase configuration if using Firebase
- Ensure your backend supports WebSocket/Socket.IO

**4. Styling Issues**
- Import the CSS: `import '@gaplash/chat-ui/styles.css'`
- Check for CSS conflicts with your application styles
- Use custom themes for consistent styling

### Debug Mode

```tsx
// Enable debug logging
localStorage.setItem('gaplash-debug', 'true');

<ChatContainer 
  config={{ ...config, debug: true }}
/>
```

## Support

- **Documentation**: [https://docs.gaplash.com](https://docs.gaplash.com)
- **Issues**: [GitHub Issues](https://github.com/gaplash/chat-ui/issues)
- **Discord**: [Join our community](https://discord.gg/gaplash)
- **Email**: support@gaplash.com

## License

MIT License - see [LICENSE](LICENSE) for details.

---

Made with ❤️ by the Gaplash team