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

# Gaplash Chat UI Kit

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

## 🚀 Features

✅ **Easy Integration** - Drop-in chat component with minimal setup  
✅ **Environment Isolation** - Users can only chat within their environment  
✅ **Real-time Messaging** - WebSocket and Firebase Cloud Messaging support  
✅ **One-on-One Conversations** - Direct messaging between users  
✅ **API Key Authentication** - Secure authentication using environment-scoped API keys  
✅ **Auto User Management** - Automatically creates/authenticates users  
✅ **File Attachments** - Support for file uploads (if backend supports)  
✅ **Typing Indicators** - Real-time typing status  
✅ **Online Presence** - See who's online  
✅ **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  
✅ **Error Handling** - Comprehensive error handling with retry logic  
✅ **Debug Mode** - Built-in debugging for development  

## 📦 Installation

```bash
npm install @gaplash/ui-kit-react socket.io-client
# or
yarn add @gaplash/ui-kit-react socket.io-client

# For Firebase real-time messaging (optional)
npm install firebase
```

## 🔧 Setup for Demod Frontend

### 1. Basic Integration

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

function App() {
  const config = {
    // Backend configuration
    apiUrl: 'https://your-gaplash-backend.com',
    apiKey: 'gaplash_your_environment_api_key', // Get from Gaplash dashboard
    environmentId: 'your-environment-id', // Your Demod environment ID
    
    // User from your Demod system
    externalUserId: 'demod_user_123', // User ID from Demod
    userEmail: 'user@example.com',
    userName: 'John Doe',
    userAvatar: 'https://example.com/avatar.jpg', // optional
    
    // Optional features
    debug: true, // Enable in development
    features: {
      enableFileUpload: true,
      enableTypingIndicators: true,
      enableEmojis: true,
    }
  };

  return (
    <div style={{ height: '600px', width: '800px' }}>
      <ChatContainer 
        config={config}
        onError={(error) => console.error('Chat error:', error)}
        onUserAuthenticated={(user) => console.log('User authenticated:', user)}
        onNewMessage={(message) => console.log('New message:', message)}
      />
    </div>
  );
}

export default App;
```

### 2. Advanced Integration with Error Handling

```tsx
import React, { useState, useCallback } from 'react';
import { ChatContainer, GaplashConfig } from '@gaplash/ui-kit-react';

function DemodChatComponent({ currentUser, environmentId }) {
  const [chatError, setChatError] = useState(null);
  const [isOnline, setIsOnline] = useState(true);

  const config: GaplashConfig = {
    apiUrl: process.env.REACT_APP_GAPLASH_API_URL,
    apiKey: process.env.REACT_APP_GAPLASH_API_KEY, // Environment variable
    environmentId: environmentId,
    
    // User data from your Demod application
    externalUserId: currentUser.id,
    userEmail: currentUser.email,
    userName: currentUser.name,
    userAvatar: currentUser.avatar,
    userMetadata: {
      // Any additional data you want to store
      demodRole: currentUser.role,
      department: currentUser.department,
    },
    
    // Real-time configuration
    wsUrl: process.env.REACT_APP_GAPLASH_WS_URL, // Optional WebSocket URL
    
    // Theme customization
    theme: {
      primaryColor: '#007bff',
      backgroundColor: '#f8f9fa',
      messageBackgroundColor: '#ffffff',
      userMessageBackgroundColor: '#007bff',
      borderRadius: '8px',
    },
    
    // Feature flags
    features: {
      enableFileUpload: true,
      enableTypingIndicators: true,
      enableEmojis: true,
      enableMessageReactions: false,
      enableSearch: false,
    },
    
    // Retry configuration
    retryConfig: {
      maxRetries: 3,
      retryDelay: 2000,
    },
    
    debug: process.env.NODE_ENV === 'development',
  };

  const handleError = useCallback((error) => {
    console.error('Gaplash Chat Error:', error);
    setChatError(error.message);
    
    // Report error to your error tracking system
    // reportError('gaplash_chat_error', error);
  }, []);

  const handleUserAuthenticated = useCallback((user) => {
    console.log('Gaplash user authenticated:', user);
    setIsOnline(true);
  }, []);

  const handleNewMessage = useCallback((message) => {
    console.log('New message received:', message);
    
    // Show browser notification
    if (Notification.permission === 'granted') {
      new Notification(`New message from ${message.user.name}`, {
        body: message.content,
        icon: message.user.avatar,
      });
    }
  }, []);

  if (chatError) {
    return (
      <div className="chat-error">
        <h3>Chat temporarily unavailable</h3>
        <p>{chatError}</p>
        <button onClick={() => setChatError(null)}>Try Again</button>
      </div>
    );
  }

  return (
    <div className="demod-chat-wrapper">
      <div className="chat-header">
        <h2>Team Chat</h2>
        {isOnline && <span className="online-badge">🟢 Online</span>}
      </div>
      
      <ChatContainer
        config={config}
        height="500px"
        width="100%"
        onError={handleError}
        onUserAuthenticated={handleUserAuthenticated}
        onNewMessage={handleNewMessage}
        className="demod-chat"
      />
    </div>
  );
}

export default DemodChatComponent;
```

### 3. Integration with Firebase for Push Notifications

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

function ChatWithFirebase() {
  const config = {
    apiUrl: 'https://your-gaplash-backend.com',
    apiKey: 'your-api-key',
    environmentId: 'your-environment-id',
    externalUserId: 'user-123',
    userEmail: 'user@example.com',
    userName: 'John Doe',
    
    // Firebase configuration for push notifications
    firebaseConfig: {
      apiKey: "your-firebase-api-key",
      authDomain: "your-project.firebaseapp.com",
      projectId: "your-project-id",
      storageBucket: "your-project.appspot.com",
      messagingSenderId: "123456789",
      appId: "your-app-id",
      vapidKey: "your-vapid-key" // For web push notifications
    },
  };

  return <ChatContainer config={config} />;
}
```

## 🛠 Backend Setup

### 1. Create Organization and Environment

```bash
# Register your organization
curl -X POST https://your-gaplash-backend.com/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "organizationName": "Demod",
    "organizationDescription": "Demod platform chat",
    "ownerEmail": "admin@demod.com",
    "ownerName": "Demod Admin",
    "password": "secure-password"
  }'
```

### 2. Create Environment

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

### 3. Generate API Key

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

## 🎨 Customization

### CSS Styling

```css
/* Override default styles */
.gaplash-chat-container {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.gaplash-chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.gaplash-message {
  border-radius: 18px;
  padding: 12px 16px;
}

.gaplash-message.own {
  background: #007bff;
  color: white;
}

.gaplash-message.other {
  background: #f1f3f4;
  color: #333;
}

/* Dark theme */
.gaplash-chat-container.dark-theme {
  background: #1a1a1a;
  color: #ffffff;
}

.dark-theme .gaplash-sidebar {
  background: #2d2d2d;
}

.dark-theme .gaplash-message.other {
  background: #404040;
  color: #ffffff;
}
```

### Theme Configuration

```tsx
const darkTheme = {
  primaryColor: '#bb86fc',
  backgroundColor: '#121212',
  textColor: '#ffffff',
  borderColor: '#333333',
  messageBackgroundColor: '#1e1e1e',
  userMessageBackgroundColor: '#bb86fc',
  headerBackgroundColor: '#1f1f1f',
  sidebarBackgroundColor: '#1e1e1e',
  inputBackgroundColor: '#2d2d2d',
  borderRadius: '8px',
  fontFamily: 'Inter, system-ui, sans-serif',
};

<ChatContainer 
  config={{
    ...config,
    theme: darkTheme
  }}
/>
```

## 🔌 API Reference

### Configuration Options

```typescript
interface GaplashConfig {
  // Required
  apiUrl: string;              // Your Gaplash backend URL
  apiKey: string;              // Environment API key
  environmentId: string;       // Environment ID
  externalUserId: string;      // User ID from your app
  userEmail: string;           // User's email
  userName: string;            // User's display name
  
  // Optional
  userAvatar?: string;         // User's avatar URL
  userMetadata?: Record<string, any>; // Custom user data
  wsUrl?: string;              // WebSocket URL (defaults to apiUrl)
  
  // Firebase for push notifications
  firebaseConfig?: {
    apiKey: string;
    authDomain: string;
    projectId: string;
    storageBucket: string;
    messagingSenderId: string;
    appId: string;
    vapidKey?: string;
  };
  
  // Customization
  theme?: GaplashTheme;
  features?: {
    enableFileUpload?: boolean;
    enableEmojis?: boolean;
    enableTypingIndicators?: boolean;
    enableMessageReactions?: boolean;
    enableSearch?: boolean;
  };
  
  // Debugging & Error handling
  debug?: boolean;
  retryConfig?: {
    maxRetries?: number;
    retryDelay?: number;
  };
}
```

### Component Props

```typescript
interface ChatContainerProps {
  config: GaplashConfig;
  className?: string;
  style?: Record<string, any>;
  height?: string | number;
  width?: string | number;
  
  // Event handlers
  onError?: (error: Error) => void;
  onUserAuthenticated?: (user: User) => void;
  onConversationChange?: (conversation: Conversation | null) => void;
  onNewMessage?: (message: Message) => void;
}
```

## 🚀 Best Practices

### 1. Environment Variables

```bash
# .env.local
REACT_APP_GAPLASH_API_URL=https://your-backend.com
REACT_APP_GAPLASH_API_KEY=gaplash_your_api_key
REACT_APP_GAPLASH_WS_URL=wss://your-backend.com
```

### 2. Error Handling

```tsx
const [chatStatus, setChatStatus] = useState('loading');

<ChatContainer
  config={config}
  onError={(error) => {
    setChatStatus('error');
    // Log to error tracking service
    errorTracker.captureException(error);
  }}
  onUserAuthenticated={() => {
    setChatStatus('ready');
  }}
/>

{chatStatus === 'error' && (
  <div className="chat-fallback">
    <p>Chat is temporarily unavailable.</p>
    <button onClick={() => window.location.reload()}>
      Retry
    </button>
  </div>
)}
```

### 3. Performance Optimization

```tsx
import React, { Suspense, lazy } from 'react';

// Lazy load chat component
const ChatContainer = lazy(() => 
  import('@gaplash/ui-kit-react').then(module => ({
    default: module.ChatContainer
  }))
);

function App() {
  return (
    <Suspense fallback={<div>Loading chat...</div>}>
      <ChatContainer config={config} />
    </Suspense>
  );
}
```

### 4. Mobile Responsive

```css
@media (max-width: 768px) {
  .gaplash-chat-container {
    height: 100vh !important;
    width: 100vw !important;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
  }
  
  .gaplash-sidebar {
    width: 100% !important;
  }
  
  .gaplash-main-area {
    width: 100% !important;
  }
}
```

## 🐛 Troubleshooting

### Common Issues

1. **Authentication Failed**
   ```
   Error: Authentication failed
   ```
   - Check your API key is correct
   - Verify environmentId exists
   - Ensure user email is valid

2. **Connection Timeout**
   ```
   Error: Backend API is not accessible
   ```
   - Verify apiUrl is correct and accessible
   - Check network connectivity
   - Confirm backend is running

3. **WebSocket Connection Failed**
   ```
   Warning: Real-time connection failed
   ```
   - This is non-fatal, chat will work with polling
   - Check wsUrl configuration
   - Verify WebSocket endpoint is accessible

### Debug Mode

Enable debug mode to see detailed logs:

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

This will log:
- API requests and responses
- WebSocket connection status
- Message events
- Error details

## 📚 Examples

Check out the `/examples` directory for complete integration examples:

- **Basic Integration** - Simple chat setup
- **Demod Integration** - Complete Demod platform integration
- **Firebase Push** - With push notifications
- **Custom Theme** - Branded chat interface
- **Mobile App** - React Native integration

## 🔐 Security

- All communication uses HTTPS/WSS
- API keys provide environment-scoped access
- Users are isolated by environment
- No sensitive data is stored in localStorage except auth tokens
- JWT tokens have expiration and auto-refresh

## 📈 Performance

- Lazy loading of components
- Efficient WebSocket connection management
- Automatic reconnection with exponential backoff
- Message pagination to handle large conversations
- Optimized bundle size (~150KB gzipped)

## 🆘 Support

For issues and questions:

1. Check the troubleshooting section
2. Enable debug mode for detailed logs
3. Check browser console for errors
4. Create an issue with reproduction steps

## 📄 License

MIT License - see LICENSE file for details.