npm package: @sagegreytechnologies/ai-chat-widget
Description: A customizable AI chat widget for React applications with escalation support and modern UI
Author: Sagegrey Technologies
Latest version: 1.0.3

# 🤖 AI Chat Widget

A modern, customizable AI chat widget for React applications with advanced features including escalation support, session management, and beautiful UI.

[![npm version](https://badge.fury.io/js/@sagegreytechnologies%2Fai-chat-widget.svg)](https://badge.fury.io/js/@sagegreytechnologies%2Fai-chat-widget)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![React](https://img.shields.io/badge/React-18+-61DAFB.svg)](https://reactjs.org/)

## ✨ Features

- 🎨 **Fully Customizable** - Colors, positioning, messages, and styling
- 🚀 **TypeScript Support** - Complete type definitions included
- 📱 **Responsive Design** - Works perfectly on desktop and mobile
- 🔄 **Session Management** - Automatic session restoration and persistence
- 📈 **Escalation Support** - Seamless handoff to human agents
- 📊 **Chat History** - Built-in conversation history with grouping
- 🎯 **Smart Categorization** - Ticket categories for better organization
- 🔒 **Secure** - Built with security best practices
- ⚡ **Lightweight** - Minimal bundle size with tree-shaking support
- 🌐 **Modern UI** - Beautiful interface with smooth animations

## 📦 Installation

```bash
npm install @sagegreytechnologies/ai-chat-widget
```

Or with yarn:

```bash
yarn add @sagegreytechnologies/ai-chat-widget
```

## 🚀 Quick Start

### 1. Import the Component (Shadow DOM Version - Recommended)

```tsx
import React from 'react';
import ChatWidget from '@sagegreytechnologies/ai-chat-widget'; // This imports ShadowChatWidget
// Note: No CSS import needed - styles are encapsulated in Shadow DOM

function App() {
  return (
    <div className="App">
      {/* Your app content */}
      
      <ChatWidget
        apiUrl="https://your-api-endpoint.com"
        thirdPartyApiKey="your-api-key"
        companyName="Your Company"
        title="Customer Support"
        welcomeMessage="Hi! How can we help you today?"
      />
    </div>
  );
}

export default App;
```

### 2. Basic Configuration

```tsx
<ChatWidget
  // Required props
  apiUrl="https://your-backend.com"
  thirdPartyApiKey="your-api-key"
  companyName="Your Company Name"
  
  // Optional customization
  primaryColor="#3b82f6"
  position="bottom-right"
  title="Support Chat"
  subtitle="We're here to help"
  welcomeMessage="Hello! How can I assist you?"
  placeholder="Type your message..."
  userEmail="user@example.com"
  userName="John Doe"
/>
```

**✨ Shadow DOM Benefits:**
- 🔒 **Complete Style Isolation** - No CSS conflicts with your existing styles
- 🚀 **No CSS Import Required** - Styles are automatically encapsulated
- 🎯 **Better Performance** - Isolated rendering and styling
- 🛡️ **Encapsulation** - Widget styles won't affect your page and vice versa

## 🔍 Import Options Explained

| Import Method | Component | CSS Import | Style Isolation | Recommended |
|---------------|-----------|------------|-----------------|-------------|
| `import ChatWidget from '...'` | ShadowChatWidget | ❌ Not needed | ✅ Complete | ✅ Yes |
| `import { LegacyChatWidget } from '...'` | ChatWidget | ✅ Required | ❌ None | ⚠️ Legacy only |

### Default Import (Recommended - Shadow DOM)
```tsx
import ChatWidget from '@sagegreytechnologies/ai-chat-widget';
// ☝️ This gives you the Shadow DOM version (ShadowChatWidget)
// ✅ No CSS import needed
// ✅ Complete style isolation
// ✅ No conflicts with your existing CSS
```

### Named Import (Legacy - Without Shadow DOM)
```tsx
import { LegacyChatWidget } from '@sagegreytechnologies/ai-chat-widget';
import '@sagegreytechnologies/ai-chat-widget/style.css'; // CSS import required
// ☝️ This gives you the original version without Shadow DOM
// ⚠️ Requires CSS import
// ⚠️ May have style conflicts
```

### 3. Legacy Mode (Without Shadow DOM)

If you need the legacy version without Shadow DOM isolation, you can import the original component:

```tsx
import { LegacyChatWidget } from '@sagegreytechnologies/ai-chat-widget';
import '@sagegreytechnologies/ai-chat-widget/style.css'; // CSS import required for legacy mode

<LegacyChatWidget
  apiUrl="https://your-api-endpoint.com"
  thirdPartyApiKey="your-key"
  companyName="Your Company"
  // ... other props
/>
```

**Note:** Legacy mode requires manual CSS import and may have style conflicts with your existing CSS.

## 📋 API Reference

### Props

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `apiUrl` | `string` | ✅ | - | Backend API endpoint URL |
| `thirdPartyApiKey` | `string` | ✅ | - | Your API key for the chat service |
| `companyName` | `string` | ✅ | - | Your company name for branding |
| `primaryColor` | `string` | ❌ | `'#3b82f6'` | Primary color for the widget theme |
| `position` | `'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left'` | ❌ | `'bottom-right'` | Widget position on screen |
| `welcomeMessage` | `string` | ❌ | `'Hello! How can I help you today?'` | Initial bot message |
| `placeholder` | `string` | ❌ | `'Type your message...'` | Input field placeholder |
| `title` | `string` | ❌ | `'Chat Support'` | Widget header title |
| `subtitle` | `string` | ❌ | `'We\'re here to help'` | Widget header subtitle |
| `userEmail` | `string` | ❌ | - | Pre-fill user email |
| `userName` | `string` | ❌ | - | Pre-fill user name |

### TypeScript Interfaces

```tsx
interface ChatMessage {
  id: string;
  text: string;
  sender: 'user' | 'bot' | 'agent';
  timestamp: Date;
  intent?: string;
  confidence_score?: number;
  sentiment?: string;
  is_escalated?: boolean;
  sender_name?: string;
}

interface ChatWidgetProps {
  apiUrl: string;
  primaryColor?: string;
  position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
  welcomeMessage?: string;
  placeholder?: string;
  title?: string;
  subtitle?: string;
  userEmail?: string;
  userName?: string;
  thirdPartyApiKey: string;
  companyName: string;
}
```

## 🎨 Customization Examples

### Custom Styling

```tsx
<ChatWidget
  apiUrl="https://your-api-endpoint.com"
  thirdPartyApiKey="your-key"
  companyName="Acme Corp"
  primaryColor="#ff6b6b"
  title="Acme Support"
  subtitle="24/7 Customer Care"
  welcomeMessage="Welcome to Acme! How can we assist you today?"
  placeholder="Ask us anything..."
/>
```

### Different Positions

```tsx
// Top left corner
<ChatWidget
  apiUrl="https://your-api-endpoint.com"
  thirdPartyApiKey="your-key"
  companyName="Your Company"
  position="top-left"
/>

// Bottom left corner
<ChatWidget
  apiUrl="https://your-api-endpoint.com"
  thirdPartyApiKey="your-key"
  companyName="Your Company"
  position="bottom-left"
/>
```

### Pre-filled User Information

```tsx
<ChatWidget
  apiUrl="https://your-api-endpoint.com"
  thirdPartyApiKey="your-key"
  companyName="Your Company"
  userEmail="customer@example.com"
  userName="Jane Smith"
/>
```

## 🔧 Advanced Features

### Session Management

The widget automatically manages user sessions and persists conversations across page reloads:

- **Automatic Session Restoration** - Conversations resume where they left off
- **Local Storage Integration** - User preferences and history saved locally
- **Cross-tab Synchronization** - Sessions work across multiple browser tabs

### Escalation Support

The widget supports seamless escalation to human agents:

- **Automatic Detection** - AI determines when escalation is needed
- **Manual Escalation** - Users can request human assistance
- **Agent Handoff** - Smooth transition from bot to human agent
- **Status Indicators** - Clear visual feedback during escalation

### Chat History

Built-in conversation history with smart organization:

- **Grouped by Date** - Conversations organized by day
- **Searchable** - Easy to find previous conversations
- **Persistent** - History maintained across sessions

## 🌐 Backend Integration

### Expected API Endpoints

Your backend should implement these endpoints:

#### Start Chat
```
POST /api/chat/start
Content-Type: application/json

{
  "name": "User Name",
  "email": "user@example.com",
  "phone": "+1234567890",
  "message": "Initial message",
  "category": "general"
}
```

#### Send Message
```
POST /api/chat/send
Content-Type: application/json
Authorization: Bearer <session_token>

{
  "message": "User message",
  "conversation_id": "conv_123"
}
```

#### Get Chat History
```
GET /api/chat/history?conversation_id=conv_123
Authorization: Bearer <session_token>
```

### Response Format

```json
{
  "success": true,
  "message": "AI response message",
  "metadata": {
    "intent": "question",
    "sentiment": "neutral",
    "confidence_score": 0.95,
    "should_escalate": false,
    "suggested_actions": ["continue_conversation"],
    "timestamp": "2024-01-01T12:00:00Z"
  }
}
```

## 🎯 Best Practices

### Performance

- **Lazy Loading** - Import the widget only when needed
- **Code Splitting** - Use dynamic imports for better performance
- **Minimal Bundle** - Tree-shake unused features

```tsx
// Lazy load the widget
const ChatWidget = React.lazy(() => import('@sagegreytechnologies/ai-chat-widget'));

function App() {
  const props = {
    apiUrl: "https://your-api-endpoint.com",
    thirdPartyApiKey: "your-key",
    companyName: "Your Company"
  };
  
  return (
    <React.Suspense fallback={<div>Loading...</div>}>
      <ChatWidget {...props} />
    </React.Suspense>
  );
}
```

### Security

- **API Key Protection** - Never expose API keys in client-side code
- **Input Validation** - Always validate user inputs on the backend
- **Rate Limiting** - Implement rate limiting on your API endpoints

### User Experience

- **Clear Messaging** - Use descriptive welcome messages
- **Responsive Design** - Test on various screen sizes
- **Accessibility** - Ensure keyboard navigation works properly

## 🔍 Troubleshooting

### Common Issues

#### Widget Not Appearing
```tsx
// Ensure all required props are provided
<ChatWidget
  apiUrl="https://your-api-endpoint.com"  // Required
  thirdPartyApiKey="your-key"             // Required
  companyName="Your Company"              // Required
/>
```

#### API Connection Issues
```tsx
// Check your API URL and ensure CORS is configured
<ChatWidget
  apiUrl="https://your-api.com"  // Make sure this is correct and accessible
  thirdPartyApiKey="your-key"
  companyName="Your Company"
/>
```

#### TypeScript Errors
```bash
# Make sure you have the latest version
npm update @sagegreytechnologies/ai-chat-widget
```

#### Styling Conflicts
```css
/* Use CSS specificity to override styles */
.chat-widget-container {
  z-index: 9999 !important;
}
```

### Debug Mode

Enable debug logging in development:

```tsx
// Add to your development environment
if (process.env.NODE_ENV === 'development') {
  localStorage.setItem('chatWidgetDebug', 'true');
}
```

## 📱 Browser Support

- ✅ Chrome 90+
- ✅ Firefox 88+
- ✅ Safari 14+
- ✅ Edge 90+
- ✅ Mobile browsers (iOS Safari, Chrome Mobile)

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🆘 Support

- 📧 Email: contact@sagegreytech.com
- 🌐 Website: https://sagegreytech.com
- 📚 Documentation: [Full API Docs](https://docs.sagegreytech.com)

## 🔄 Changelog

### v1.0.0
- Initial release
- Core chat functionality
- Session management
- Escalation support
- TypeScript support
- Responsive design

---

Made with ❤️ by [Sagegrey Technologies](https://sagegreytech.com)