# Mazaal Chat Widget

An embeddable AI chat widget that connects any website to a Mazaal agent. Lightweight, themeable, and framework-agnostic — drop one `<script>` tag and you're live.

## Prerequisites

Before you embed the widget, you need:

1. A **Mazaal account** at [app.mazaal.ai](https://app.mazaal.ai).
2. A **published agent**. If you don't have one yet, create it from the dashboard — give it a system prompt, attach knowledge or tools, and publish.
3. The **Chatbot (web widget) channel** enabled on that agent.

## Connect an agent — the easy way

The dashboard generates a ready-to-paste embed script for you. This is the recommended flow for almost all users; you never have to hand-write a snippet.

1. Open [app.mazaal.ai](https://app.mazaal.ai) and select your agent.
2. Go to **Channels → Chatbot (web widget)**.
3. Configure appearance (title, colour, position, welcome message) and identification fields.
4. Click **Save** — the dashboard will show an **Embed script** block with a `<script>…</script>` snippet.
5. Copy that snippet and paste it immediately before `</body>` on every page that should show the widget.

That's it. The generated script already contains your `agentId`, the correct `apiUrl`, and all the appearance settings you just picked. Re-open the Channels screen any time to regenerate with new settings.

## Connect an agent — manual integration

If you prefer to wire up the script yourself (for example to drive it from a server-side template or a custom build step), initialise `ChatWidget` directly:

```html
<!-- Mazaal AI Chat Widget -->
<script
  src="https://cdn.jsdelivr.net/npm/@mazaal-dev/widget@latest/dist/mazaal-widget.iife.js"
  async
  onload='window.mazaalWidget = window.ChatWidget?.init({
    agentId: "YOUR_AGENT_ID",
    apiUrl: "https://app.mazaal.ai",
    title: "Demo Agent",
    subtitle: "We are here to help",
    primaryColor: "#FF6A2A",
    position: "bottom-right",
    theme: "light",
    welcomeMessage: "Hi! How can I help you today?",
    placeholder: "Type your message here...",
    enableIdentification: true,
    identifyAfterMessages: 3,
    identificationFields: { name: true, email: true, phone: false, company: false }
  })'>
</script>
<!-- End Mazaal AI Chat Widget -->
```

**Where to find your `agentId`**: in the dashboard, open your agent and copy the ID shown in the URL (`/agents/<agentId>`) or inside the **Channels → Chatbot** page.

**What to pass for `apiUrl`**: the origin of the Mazaal backend your account lives on — `https://app.mazaal.ai` for production. Always pass this explicitly when integrating manually; only omit it if you're pointing at the default production origin and know your deployment matches.

## Configuration

```typescript
interface WidgetConfig {
  // Required
  agentId: string;                   // Your Mazaal agent ID

  // Connectivity
  apiUrl?: string;                   // Mazaal backend origin (default: https://app.mazaal.ai)

  // Appearance
  theme?: 'light' | 'dark';          // default: light
  position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
  primaryColor?: string;             // default: #FF6A2A
  logo?: string;                     // Logo URL for the header
  title?: string;                    // Widget title
  subtitle?: string;                 // Widget subtitle
  agentName?: string;                // Agent name for display
  showAvatar?: boolean;              // default: true
  maxHeight?: number;                // default: 600
  maxWidth?: number;                 // default: 400
  zIndex?: number;                   // default: 1000

  // Messaging
  welcomeMessage?: string;           // Initial bot message
  placeholder?: string;              // Input placeholder text
  enableMarkdown?: boolean;          // default: true
  enableAttachments?: boolean;       // default: false
  enableNotifications?: boolean;     // Browser notifications (default: true)

  // Identification (collect visitor info after N messages)
  enableIdentification?: boolean;    // default: false
  identifyAfterMessages?: number;    // default: 3
  identificationFields?: {
    name?: boolean;
    email?: boolean;
    phone?: boolean;
    company?: boolean;
  };
  identificationRequired?: boolean;  // default: false
  identificationMessage?: string;    // Custom ID request message
}
```

## Dynamic configuration updates

Change config at runtime without re-mounting:

```javascript
if (window.mazaalWidget) {
  window.mazaalWidget.updateConfig({
    primaryColor: '#e91e63',
    title: 'New Title',
    welcomeMessage: 'Updated welcome message!',
  });
}
```

## Multiple widget instances

Run separate widgets on the same page — for example a support bubble and a sales bubble — by initialising `ChatWidget` more than once with distinct `agentId`s and positions:

```javascript
const supportWidget = ChatWidget.init({
  agentId: 'support-agent-id',
  apiUrl: 'https://app.mazaal.ai',
  position: 'bottom-right',
  primaryColor: '#007bff',
  title: 'Customer Support',
  enableIdentification: true,
  identificationRequired: true,
});

const salesWidget = ChatWidget.init({
  agentId: 'sales-agent-id',
  apiUrl: 'https://app.mazaal.ai',
  position: 'bottom-left',
  primaryColor: '#28a745',
  title: 'Sales Team',
  enableIdentification: true,
  identifyAfterMessages: 1,
});
```

## Defensive loader

If you want to guard against double-init or handle load failures gracefully:

```javascript
(function () {
  if (window.mazaalWidgetInitialized) return;

  const script = document.createElement('script');
  script.src = 'https://cdn.jsdelivr.net/npm/@mazaal-dev/widget@latest/dist/mazaal-widget.iife.js';
  script.async = true;

  script.onload = function () {
    if (window.ChatWidget) {
      window.mazaalWidget = window.ChatWidget.init({
        agentId: 'your-agent-id',
        apiUrl: 'https://app.mazaal.ai',
      });
      window.mazaalWidgetInitialized = true;
    }
  };

  script.onerror = function () {
    console.error('Failed to load Mazaal widget');
  };

  document.head.appendChild(script);
})();
```

## Troubleshooting

- **The bubble never appears.** Check the browser console — a CSP violation or a 404 on the bundle URL is the usual cause. Confirm your site's CSP allows `cdn.jsdelivr.net` under `script-src`.
- **Messages don't send.** Open DevTools → Network and look for the `POST /api/agents/public/chat` call. A 404 points at a wrong `apiUrl`; a 403 means the agent isn't published or the embedding domain isn't in the allow-list for that agent.
- **`agentId` not found.** Re-open your agent in the dashboard and copy the ID from the URL.

## Related docs

- [`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md) — design patterns, Shadow DOM isolation, CSP notes.
- [`docs/DEPLOYMENT.md`](./docs/DEPLOYMENT.md) — how the IIFE bundle is built and published.
