# JavaScript API

The widget exposes a global `window.MailAgent` object with methods to open, control, and close the widget programmatically.

## `MailAgent.open(options)`

Opens the widget and returns a handle for interacting with it.

```javascript
const widget = await MailAgent.open({
  bottom: "20px",
  right: "20px",
  width: "400px",
  height: "600px"
});
```

**Returns:** `Promise<WidgetHandle>`

See [Configuration](https://support.mailagent.email/widget/configuration) for all available options.

## Widget Handle

The object returned by `MailAgent.open()` provides the following interface:

### `widget.send(message)`

Send a message to the chat programmatically. This triggers the AI assistant to respond as if the user typed the message.

```javascript
// Send a text message
widget.send({ text: "Draft a follow-up email to the client" });
```

```javascript
// Send with file attachments
widget.send({
  text: "Summarize this document",
  files: [file]
});
```

### `widget.mounted`

A read-only boolean indicating whether the widget iframe is still attached to the DOM.

```javascript
if (widget.mounted) {
  widget.send({ text: "Hello!" });
}
```

### `widget.unmount()`

Closes and removes the widget from the page with a fade-out animation.

```javascript
widget.unmount();
```

## Full Example

```html
<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
</head>
<body>
  <button id="open-chat">Open Chat</button>
  <button id="close-chat" disabled>Close Chat</button>
  <button id="send-msg" disabled>Ask about pricing</button>

  <script
    src="https://widget.mailagent.email/connect/connect.js"
    data-user-id="YOUR_USER_ID"
    data-suggestions='[{"icon":"💬","text":"Help me write an email"}]'
  ></script>

  <script>
    let widget = null;

    document.getElementById('open-chat').addEventListener('click', async () => {
      widget = await MailAgent.open({
        bottom: '20px',
        right: '20px',
        width: '400px',
        height: '600px',
      });

      document.getElementById('close-chat').disabled = false;
      document.getElementById('send-msg').disabled = false;
    });

    document.getElementById('close-chat').addEventListener('click', () => {
      widget?.unmount();
      widget = null;
      document.getElementById('close-chat').disabled = true;
      document.getElementById('send-msg').disabled = true;
    });

    document.getElementById('send-msg').addEventListener('click', () => {
      widget?.send({ text: 'What are your pricing plans?' });
    });
  </script>
</body>
</html>
```

## Events

The widget communicates with the parent page via `postMessage`. You can listen for these events if you need deeper integration:

| Event Type          | Direction       | Description                            |
| ------------------- | --------------- | -------------------------------------- |
| `init`              | Parent ← Widget | Widget requests initialization data.   |
| `init`              | Parent → Widget | Parent sends config (userId, etc.).    |
| `initialized`       | Parent ← Widget | Widget is fully loaded and ready.      |
| `__widget_resize__` | Parent ← Widget | Widget reports its content dimensions. |
| `close`             | Parent ← Widget | Widget requests to be closed.          |
| `send`              | Parent → Widget | Parent sends a message to the chat.    |

> **Note:** You typically don't need to handle these events directly — the `MailAgent.open()` API manages them for you. These are documented for advanced use cases only.
