# Chat Widget

Embeddable AI chat widget that can be added to any website with a single script tag.

[![npm version](https://img.shields.io/npm/v/@fauzitech/chat-widget.svg)](https://www.npmjs.com/package/@fauzitech/chat-widget)
[![bundle size](https://img.shields.io/bundlephobia/minzip/@fauzitech/chat-widget?label=gzip)](https://bundlephobia.com/package/@fauzitech/chat-widget)
[![license](https://img.shields.io/badge/license-MIT-green)](https://github.com/muhfauziazhar/chat-widget/blob/main/LICENSE)

## Features

- 🎨 **Customizable** — colors, position, title, greeting
- 💬 **AI-powered** — real-time chat with any OpenAI-compatible API
- 📱 **Mobile responsive** — works on all screen sizes
- ⚡ **Lightweight** — ~15KB gzipped, no dependencies
- 🔒 **Rate limiting** — built-in 10 req/min per IP
- 📝 **Markdown support** — bold, italic, code, lists
- 🌙 **Dark mode** — auto-detects system preference

## Install

```bash
npm install @fauzitech/chat-widget
```

Or via CDN (recommended for most sites):

```html
<script src="https://cdn.jsdelivr.net/npm/@fauzitech/chat-widget@1/dist/widget.js"></script>
```

## Quick Start

Add these two lines to your HTML:

```html
<script src="https://cdn.jsdelivr.net/npm/@fauzitech/chat-widget@1/dist/widget.js"></script>
<script>
  FauziChat.init({
    serverUrl: 'https://your-server.vercel.app/api/chat',
    title: 'Chat with Me',
    subtitle: 'Ask me anything',
    primaryColor: '#3B82F6'
  });
</script>
```

That's it! The chat button will appear in the bottom-right corner.

## Framework Examples

### HTML (Plain)

```html
<!DOCTYPE html>
<html>
<head>
  <title>My Website</title>
</head>
<body>
  <h1>Welcome to my site</h1>
  
  <!-- Chat Widget -->
  <script src="https://cdn.jsdelivr.net/npm/@fauzitech/chat-widget@1/dist/widget.js"></script>
  <script>
    FauziChat.init({
      serverUrl: 'https://your-server.vercel.app/api/chat',
      title: 'Support Chat',
      subtitle: 'How can I help?',
      primaryColor: '#10B981',
      greeting: 'Hi! Need help? Ask me anything!'
    });
  </script>
</body>
</html>
```

### Next.js (App Router)

```tsx
// components/ChatWidget.tsx
'use client';

import { useEffect } from 'react';
import Script from 'next/script';

export default function ChatWidget() {
  useEffect(() => {
    const checkReady = setInterval(() => {
      if (window.FauziChat) {
        clearInterval(checkReady);
        window.FauziChat.init({
          serverUrl: 'https://your-server.vercel.app/api/chat',
          title: 'Chat with AI',
          primaryColor: '#3B82F6'
        });
      }
    }, 100);
    return () => clearInterval(checkReady);
  }, []);

  return (
    <Script
      src="https://cdn.jsdelivr.net/npm/@fauzitech/chat-widget@1/dist/widget.js"
      strategy="lazyOnload"
    />
  );
}
```

```tsx
// app/layout.tsx
import ChatWidget from '@/components/ChatWidget';

export default function Layout({ children }) {
  return (
    <html>
      <body>
        {children}
        <ChatWidget />
      </body>
    </html>
  );
}
```

### React (Vite / CRA)

```tsx
// ChatWidget.tsx
import { useEffect } from 'react';

declare global {
  interface Window {
    FauziChat: { init: (config: Record<string, unknown>) => void };
  }
}

export default function ChatWidget() {
  useEffect(() => {
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/@fauzitech/chat-widget@1/dist/widget.js';
    script.onload = () => {
      window.FauziChat.init({
        serverUrl: 'https://your-server.vercel.app/api/chat',
        title: 'Chat with AI',
        primaryColor: '#3B82F6'
      });
    };
    document.body.appendChild(script);
  }, []);

  return null;
}
```

### WordPress

Add to your theme's `footer.php` or use a plugin like "Insert Headers and Footers":

```html
<script src="https://cdn.jsdelivr.net/npm/@fauzitech/chat-widget@1/dist/widget.js"></script>
<script>
  FauziChat.init({
    serverUrl: 'https://your-server.vercel.app/api/chat',
    title: 'Chat with Support',
    primaryColor: '#0073AA'
  });
</script>
```

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `serverUrl` | string | `/api/chat` | Chat API endpoint (required) |
| `apiKey` | string | - | API key for authentication |
| `position` | string | `bottom-right` | Widget position: `bottom-right`, `bottom-left`, `top-right`, `top-left` |
| `primaryColor` | string | `#3B82F6` | Primary color (hex code) |
| `title` | string | `Chat with AI` | Header title |
| `subtitle` | string | `Ask me anything` | Header subtitle |
| `placeholder` | string | `Type your message...` | Input placeholder |
| `greeting` | string | `Hi! How can I help you today?` | Initial greeting message |
| `maxMessages` | number | `50` | Max messages in history |

## Deploy Your Own Server

### 1. Clone and configure

```bash
git clone https://github.com/muhfauziazhar/chat-widget.git
cd chat-widget/packages/server

cp .env.example .env
# Edit .env with your settings
```

### 2. Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `OPENAI_API_KEY` | Yes | API key for LLM provider (OpenAI, Anthropic, etc.) |
| `OPENAI_BASE_URL` | No | API base URL (default: `https://api.openai.com/v1`) |
| `CHAT_MODEL` | No | Model name (default: `gpt-4o-mini`) |
| `SYSTEM_PROMPT` | No | Custom system prompt for the AI |

### 3. Deploy to Vercel

```bash
npm install
vercel --prod
```

### 4. Other Hosting

The server is a standard Node.js API endpoint. You can host it on:
- Vercel (recommended)
- Netlify Functions
- AWS Lambda
- Railway
- Any Node.js server

## System Prompt Customization

The `SYSTEM_PROMPT` environment variable lets you customize the AI's behavior:

```
You are a helpful customer support agent for [Company Name].

About the company:
- We sell [products/services]
- Business hours: Mon-Fri 9am-5pm
- Email: support@company.com

Answer questions about our products, pricing, and policies.
For account-specific issues, direct them to support@company.com.
```

## API Response Format

The server returns:

```json
{
  "message": "AI response text here"
}
```

## Development

```bash
# Install dependencies
npm install

# Build widget
cd packages/widget
npm run build

# Run server locally
cd packages/server
npm run dev
```

## CDN URLs

**jsDelivr (npm — recommended):**
```
https://cdn.jsdelivr.net/npm/@fauzitech/chat-widget@1/dist/widget.js
```

**jsDelivr (latest):**
```
https://cdn.jsdelivr.net/npm/@fauzitech/chat-widget@latest/dist/widget.js
```

**unpkg:**
```
https://unpkg.com/@fauzitech/chat-widget@1/dist/widget.js
```

## Bundle Size

| File | Size | Gzipped |
|------|------|---------|
| `dist/widget.js` (UMD) | ~14 KB | ~4.2 KB |
| `dist/widget.esm.js` (ESM) | ~13 KB | ~4.0 KB |

Zero dependencies. Works in all modern browsers.

## Changelog

### 1.0.1
- Fixed markdown rendering (bold, italic, lists, headers, links, strikethrough)
- Improved code block handling

### 1.0.0
- Initial release
- Customizable theme, position, greeting
- AI-powered chat with any OpenAI-compatible API
- Mobile responsive
- Rate limiting built-in

## License

MIT
