npm package: @iconictech/ai-chat-widget
Description: Production-ready AI chat widget for customer support. Embeddable React component with configurable theming, multi-tenant support, and comprehensive error handling.
Author: Iconic Tech
Latest version: 1.0.0

# AI Chat Widget

A production-ready, embeddable React chat widget component for integrating AI-powered customer support into your tenant applications. Built with TypeScript, Tailwind CSS, and React 18+.

## Features

- ✨ **Fully Customizable UI** - Theme colors, alignment, border radius, and branding
- 🔐 **Secure API Integration** - Bearer token authentication for tenant isolation
- 🔄 **Auto-Retry Logic** - Configurable retry attempts with exponential backoff
- ❌ **Error Handling** - Comprehensive error states and user feedback
- ⚡ **Lightweight** - Minimal dependencies, optimized for performance
- 📱 **Responsive Design** - Works seamlessly on mobile and desktop
- 🌙 **Dark Mode Support** - Built-in dark mode styling
- ♿ **Accessibility Ready** - ARIA labels and keyboard navigation
- 📦 **TypeScript Support** - Full type safety and IntelliSense

## Installation

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

### Prerequisites

- React 18 or higher
- React DOM 18 or higher
- Tailwind CSS 3 or higher

Ensure your project has Tailwind CSS configured. Add to your `tailwind.config.js`:

```javascript
module.exports = {
  content: [
    './node_modules/@iconictech/ai-chat-widget/dist/**/*.{js,jsx,ts,tsx}'
  ]
};
```

## Usage

### Basic Setup

```tsx
import { ChatWidget } from '@iconictech/ai-chat-widget';

export default function App() {
  return (
    <ChatWidget
      apiKey={import.meta.env.VITE_API_KEY}
      apiBaseUrl={import.meta.env.VITE_API_BASE_URL}
    />
  );
}
```

### With Full Configuration

```tsx
import { ChatWidget } from '@iconictech/ai-chat-widget';

export default function App() {
  const handleError = (error: Error) => {
    console.error('Widget error:', error);
    // Send to error tracking service
  };

  const handleLoading = (isLoading: boolean) => {
    console.log('Widget loading:', isLoading);
  };

  return (
    <ChatWidget
      apiKey="your-tenant-api-key"
      apiBaseUrl="https://api.yourdomain.com"
      configEndpoint="/v1/widget-config"
      chatEndpoint="/v1/chat"
      onError={handleError}
      onLoading={handleLoading}
      maxRetries={3}
    />
  );
}
```

## Props Reference

```typescript
interface ChatWidgetProps {
  // Required
  apiKey: string;
  // Your tenant's unique API key for authentication

  // Optional
  apiBaseUrl?: string;
  // Base URL of your AI support API
  // Default: 'https://api.yourdomain.com'

  configEndpoint?: string;
  // Relative endpoint to fetch widget configuration
  // Default: '/v1/widget-config'

  chatEndpoint?: string;
  // Relative endpoint to send chat messages
  // Default: '/v1/chat'

  onError?: (error: Error) => void;
  // Callback fired when an error occurs (config loading or chat)

  onLoading?: (loading: boolean) => void;
  // Callback fired when loading state changes

  maxRetries?: number;
  // Maximum retry attempts for configuration loading with exponential backoff
  // Default: 3
}
```

## API Integration

The widget communicates with your backend via two main endpoints:

### 1. Widget Configuration Endpoint

**Endpoint:** `GET {apiBaseUrl}{configEndpoint}`

**Headers:**
```
Authorization: Bearer {apiKey}
Content-Type: application/json
```

**Response:**
```json
{
  "aiName": "Support Assistant",
  "greeting": "Hello! How can I help you today?",
  "theme": {
    "primaryColor": "#3b82f6",
    "bubbleColor": "#e5e7eb"
  },
  "alignment": "right",
  "corners": "rounded",
  "quickPrompts": [
    "How do I reset my password?",
    "What are your hours?"
  ]
}
```

**Field Details:**
- `aiName` (string): Display name of your AI assistant
- `greeting` (string): Initial greeting message shown when chat opens
- `theme.primaryColor` (string): Hex color for buttons, headers, and user messages
- `theme.bubbleColor` (string): Hex color for AI response bubbles
- `alignment` (string): Widget position on screen - `'left'` or `'right'`
- `corners` (string): Border radius style - `'rounded'` or `'soft'`
- `quickPrompts` (array): Array of suggested prompts for users (max 3 shown)

### 2. Chat Endpoint

**Endpoint:** `POST {apiBaseUrl}{chatEndpoint}`

**Headers:**
```
Authorization: Bearer {apiKey}
Content-Type: application/json
```

**Request Body:**
```json
{
  "message": "How do I update my billing information?"
}
```

**Response:**
```json
{
  "reply": "You can update your billing information in your account settings under the Billing section."
}
```

**Response Requirements:**
- Must include `reply` field with the AI response
- Reply field must be a non-empty string

## Environment Configuration

Create a `.env.local` file (copy from `.env.example`):

```env
VITE_API_BASE_URL=https://api.yourdomain.com
VITE_CONFIG_ENDPOINT=/v1/widget-config
VITE_CHAT_ENDPOINT=/v1/chat
VITE_MAX_RETRIES=3
```

## Security Best Practices

### ⚠️ API Key Handling

- **Never hardcode API keys** in your code
- Store API keys in environment variables
- Use tenant-specific API keys for isolation
- Rotate keys regularly
- Monitor key usage and access logs

### Request Authentication

All requests use Bearer token authentication:

```
Authorization: Bearer {apiKey}
```

Ensure your backend:
- Validates the API key on every request
- Checks tenant ownership of resources
- Implements rate limiting per API key
- Logs all API accesses for audit trails

### HTTPS/TLS

- Always use HTTPS in production
- Implement certificate pinning if needed
- Monitor SSL/TLS certificate expiration

### Content Security

- Sanitize all API responses before display
- Implement CSP headers on your application
- Validate and sanitize user input on backend
- Never trust client-side validation alone

## Error Handling

The widget provides two error feedback mechanisms:

### 1. Error Display in UI

- Configuration load errors show no widget (silent fail)
- Chat errors display error message in the conversation
- All errors are dismissible

### 2. onError Callback

Implement the `onError` callback to:
- Log errors to your monitoring service
- Show custom error notifications
- Trigger user support workflows

```tsx
<ChatWidget
  apiKey={apiKey}
  onError={(error) => {
    // Send to error tracking
    Sentry.captureException(error);
    
    // Show custom notification
    toast.error('Chat widget unavailable. Please refresh.');
  }}
/>
```

## Styling & Customization

The widget is built with Tailwind CSS. All colors and layout are configurable via the API response. For advanced customization:

1. **Colors** - Control via `theme.primaryColor` and `theme.bubbleColor` in widget config
2. **Size** - Widget dimensions are fixed (w-96, h-500px) - modify via CSS if needed
3. **Dark Mode** - Automatically supports dark mode with `dark:` classes
4. **Position** - Control via `alignment` setting (left/right)
5. **Border Radius** - Control via `corners` setting (rounded/soft)

## Troubleshooting

### Widget not appearing

1. Check that `apiKey` is valid and tenant has access
2. Verify `apiBaseUrl` is correct and accessible
3. Check browser console for errors
4. Ensure Tailwind CSS is properly configured in your project

### Chat messages not sending

1. Verify chat endpoint URL is correct
2. Check API key has chat permissions
3. Ensure request payload includes `message` field
4. Check response includes `reply` field

### Styling issues

1. Ensure Tailwind CSS node_modules path includes the widget in `content`
2. Rebuild Tailwind CSS: `npm run build`
3. Clear browser cache
4. Check for CSS class conflicts

## TypeScript Support

Full TypeScript types are included. Import types for custom implementations:

```tsx
import type {
  ChatWidgetProps,
  WidgetConfig,
  ChatWidgetError
} from '@iconictech/ai-chat-widget';
```

## Browser Support

- Chrome/Chromium 90+
- Firefox 88+
- Safari 14+
- Edge 90+

## Performance

- Initial bundle size: ~15KB (gzipped)
- No external API calls before user interaction
- Lazy configuration loading
- Optimized re-renders with React hooks

## Changelog

### v1.0.0 (2026-01-11)

- Initial release
- Configurable API endpoints
- Error handling with retry logic
- Dark mode support
- Comprehensive TypeScript types

## License

MIT © 2026 Iconic Tech

## Support

For issues and questions:
- Open an issue on GitHub
- Email support@iconictech.com
- Check documentation at https://docs.iconictech.com