> ## Documentation Index
> Fetch the complete documentation index at: https://docs.g-tateth.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Chat Widget Implementation

> Complete guide to implementing the G-Tateth chat widget on your website

The G-Tateth Chat Widget is a powerful, customizable customer support widget that you can embed on any website. It provides real-time messaging, AI-powered responses, file attachments, and seamless agent handoff.

## Quick Start

### Getting Your Tracking Code

1. Log in to your G-Tateth dashboard
2. Navigate to **Settings > Product > Chat Widget**
3. Go to the **Integration** tab
4. Copy the tracking code displayed in the "Tracking Code" field

### Basic Implementation

Add the tracking code to your website's `<head>` section. The tracking code will look like this:

```html theme={null}
<!DOCTYPE html>
<html>
<head>
  <title>My Website</title>
  
  <!-- G-Tateth Chat Widget -->
  <script 
    src="https://g-tateth.com/widget/script.iife.js" 
    data-account="your-domain.com"
    data-base-url="https://api.g-tateth.com"
  ></script>
</head>
<body>
  <!-- Your website content -->
</body>
</html>
```

**Important Notes:**

* Replace `your-domain.com` with your actual account domain (found in your dashboard settings)
* Replace `https://api.g-tateth.com` with your backend API URL (found in your dashboard settings)
* The script URL (`https://g-tateth.com/widget/script.iife.js`) may vary based on your environment
* The `data-account` attribute is required and tells the widget which account configuration to load (uses your domain for security)
* The `data-base-url` attribute specifies the backend API URL (defaults to `https://api.g-tateth.com` for production)
* Place the script in the `<head>` section for best performance
* **Security**: The tracking code uses your domain instead of internal IDs for better security

### React/Next.js Implementation

For React applications, you can use the widget script directly or use the programmatic API:

**Option 1: Using the Script Tag (Recommended)**

Add the tracking code to your `_document.tsx` or `_app.tsx`:

```tsx theme={null}
// pages/_document.tsx or app/layout.tsx
import Script from 'next/script';

export default function Document() {
  return (
    <html>
      <head>
        <Script 
          src="https://g-tateth.com/widget/script.iife.js" 
          data-account="your-domain.com"
          data-base-url="https://api.g-tateth.com"
          strategy="afterInteractive"
        />
      </head>
      <body>
        {/* Your app content */}
      </body>
    </html>
  );
}
```

**Option 2: Programmatic Mount**

```tsx theme={null}
// pages/index.tsx or app/page.tsx
import { useEffect } from 'react';

export default function MyPage() {
  useEffect(() => {
    // Load widget script
    const script = document.createElement('script');
    script.src = 'https://g-tateth.com/widget/script.iife.js';
    script.setAttribute('data-account', 'your-domain.com');
    script.setAttribute('data-base-url', 'https://api.g-tateth.com');
    script.async = true;
    document.head.appendChild(script);

    script.onload = () => {
      if (window.GTatethCRMWidget) {
        window.GTatethCRMWidget.mount({
          tenantDomain: 'your-domain.com', // or tenantId: 'your-tenant-id' (if needed)
          baseUrl: 'https://api.g-tateth.com',
          companyName: 'Your Company',
          primaryColor: '#2f4a6b'
        });
      }
    };
  }, []);

  return (
    <div>
      <h1>Welcome to My Site</h1>
    </div>
  );
}
```

## Configuration Options

### Widget Configuration

<ParamField body="tenantId" type="string" required>
  Your unique tenant identifier. Get this from your dashboard settings page. You can also use `tenantDomain` instead if you prefer.
</ParamField>

<ParamField body="tenantDomain" type="string">
  Your tenant domain (alternative to tenantId). Use this if you prefer to identify by domain instead of ID.
</ParamField>

<ParamField body="baseUrl" type="string">
  API base URL. Required when using the tracking code script tag. Default: `https://api.g-tateth.com` (or auto-detected as fallback when using programmatic mount)
</ParamField>

<ParamField body="companyName" type="string" required>
  Your company name displayed in the widget header.
</ParamField>

<ParamField body="companyLogo" type="string">
  URL to your company logo. Supports SVG, PNG, or JPG.
</ParamField>

<ParamField body="welcomeMessage" type="string">
  Initial message shown when widget opens. Default: "Welcome! How can we help you?"
</ParamField>

<ParamField body="primaryColor" type="string">
  Primary brand color (hex code). Default: `#2f4a6b`
</ParamField>

<ParamField body="position" type="string">
  Widget position: `bottom-right`, `bottom-left`, `top-right`, or `top-left`. Default: `bottom-right`
</ParamField>

<ParamField body="businessHours" type="object">
  Business hours configuration:

  ```json theme={null}
  {
    "enabled": true,
    "timezone": "America/New_York",
    "schedule": {
      "monday": { "open": "09:00", "close": "17:00" },
      "tuesday": { "open": "09:00", "close": "17:00" },
      "wednesday": { "open": "09:00", "close": "17:00" },
      "thursday": { "open": "09:00", "close": "17:00" },
      "friday": { "open": "09:00", "close": "17:00" },
      "saturday": { "open": null, "close": null },
      "sunday": { "open": null, "close": null }
    },
    "offlineMessage": "We're currently offline. Leave a message and we'll get back to you!"
  }
  ```
</ParamField>

<ParamField body="features" type="object">
  Feature flags:

  ```json theme={null}
  {
    "fileAttachments": true,
    "voiceMessages": true,
    "screenSharing": false,
    "videoCalls": false,
    "aiEnabled": true,
    "agentHandoff": true
  }
  ```
</ParamField>

## API Integration

<Note>
  All widget API endpoints are documented in the [API Reference](/api-reference) tab. This section provides integration examples and workflows.
</Note>

### Public Widget Settings Endpoint

The widget automatically fetches its configuration from the public settings endpoint:

**Endpoint:** `GET /api/widget/settings`

**Query Parameters:**

* `tenantId` (required if tenantDomain not provided) - Your tenant ID
* `tenantDomain` (required if tenantId not provided) - Your tenant domain

**Response:**
Returns widget configuration including appearance, behavior, availability, and chatbot settings.

**Example:**

```bash theme={null}
GET https://api.g-tateth.com/api/widget/settings?tenantId=YOUR_TENANT_ID
```

### Initialize Widget Session

Use the [Initialize Widget Session](/api-reference/widget/init) endpoint to create a new widget session.

**Required Parameters:**

* `tenantId` or `tenantDomain` - Your tenant identifier

**Optional Parameters:**

* `customerInfo` - Customer information object:
  ```json theme={null}
  {
    "name": "John Doe",
    "email": "john@example.com",
    "phone": "+1234567890",
    "metadata": {
      "plan": "premium",
      "signupDate": "2024-01-15"
    }
  }
  ```

**Response:**

* `sessionId` - Unique session identifier
* `conversationId` - Conversation ID if continuing existing conversation
* `config` - Widget configuration including business hours, features, etc.

### Send Message

Send messages from the widget using the [Send Message](/api-reference/widget/messages) endpoint.

**Required Parameters:**

* `conversationId` - Conversation ID
* `tenantId` - Tenant ID
* `text` - Message text content

**Optional Parameters:**

* `attachments` - Array of file attachments

### Get Messages

Retrieve conversation messages using the [Get Messages](/api-reference/widget/messages/\{conversationId}) endpoint.

**Query Parameters:**

* `limit` - Number of messages to return (default: 50)
* `before` - Message ID to fetch messages before (for pagination)

### Get Online Agents

Get list of online agents using the [Get Online Agents](/api-reference/widget/agents/online) endpoint.

**Query Parameters:**

* `tenantId` - Tenant ID (required)

## Advanced Features

### Custom Styling

Customize the widget appearance with CSS:

```css theme={null}
/* Override widget styles */
.gtateth-widget {
  --gtateth-primary-color: #2f4a6b;
  --gtateth-font-family: 'Inter', sans-serif;
  --gtateth-border-radius: 12px;
}

.gtateth-launcher {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
```

### Event Handlers

Listen to widget events:

```javascript theme={null}
window.addEventListener('gtateth:widget:opened', (event) => {
  console.log('Widget opened', event.detail);
});

window.addEventListener('gtateth:widget:message:sent', (event) => {
  console.log('Message sent', event.detail);
});

window.addEventListener('gtateth:widget:agent:joined', (event) => {
  console.log('Agent joined', event.detail);
});

window.addEventListener('gtateth:widget:conversation:created', (event) => {
  console.log('Conversation created', event.detail);
});
```

### File Attachments

Enable file uploads in the widget:

```javascript theme={null}
window.gtatethWidget = {
  // ... other config
  features: {
    fileAttachments: true,
    maxFileSize: 10485760, // 10MB
    allowedFileTypes: ['pdf', 'jpg', 'png', 'doc', 'docx']
  }
};
```

### AI-Powered Responses

The widget includes built-in AI that can:

* Answer common questions automatically
* Escalate to human agents when needed
* Learn from your knowledge base
* Provide 24/7 support

AI is enabled by default. Configure it in your dashboard under **Settings > AI**.

### Agent Handoff

When AI can't help, conversations automatically escalate to human agents:

```javascript theme={null}
// Listen for agent handoff
window.addEventListener('gtateth:widget:agent:joined', (event) => {
  const { agentId, agentName } = event.detail;
  console.log(`${agentName} has joined the conversation`);
});
```

## WebSocket Integration

For real-time updates, connect to the WebSocket:

```javascript theme={null}
const ws = new WebSocket(`wss://api.g-tateth.com?sessionId=${sessionId}&type=widget`);

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  switch(data.type) {
    case 'new-message':
      // Handle new message
      break;
    case 'agent-joined':
      // Handle agent joining
      break;
    case 'typing-indicator':
      // Show typing indicator
      break;
    case 'read-receipt':
      // Update read status
      break;
  }
};
```

## Best Practices

### Performance

* Load the widget script asynchronously
* Use lazy loading for non-critical features
* Minimize custom CSS overrides
* Cache widget configuration

### Security

* Always use HTTPS in production
* Validate customer data before sending
* Implement rate limiting on your side
* Use secure WebSocket connections (WSS)

### User Experience

* Show clear offline/online status
* Provide helpful welcome messages
* Enable file attachments for better support
* Use business hours to set expectations

### Analytics

Track widget usage:

```javascript theme={null}
window.addEventListener('gtateth:widget:message:sent', (event) => {
  // Track in your analytics
  analytics.track('Widget Message Sent', {
    conversationId: event.detail.conversationId,
    messageLength: event.detail.text.length
  });
});
```

## Troubleshooting

### Widget Not Loading

1. Check browser console for errors
2. Verify `tenantId` is correct
3. Ensure API URL is accessible
4. Check CORS settings

### Messages Not Sending

1. Verify WebSocket connection
2. Check network tab for failed requests
3. Ensure authentication is working
4. Check rate limits

### Styling Issues

1. Check for CSS conflicts
2. Verify custom CSS is loading
3. Use browser dev tools to inspect
4. Clear browser cache

## Examples

### E-commerce Integration

```javascript theme={null}
window.gtatethWidget = {
  tenantId: 'your-tenant-id',
  companyName: 'My Store',
  welcomeMessage: 'Need help with your order? We\'re here to help!',
  customerInfo: {
    email: customerEmail,
    metadata: {
      orderId: currentOrderId,
      cartValue: cartTotal
    }
  }
};
```

### SaaS Application

```javascript theme={null}
window.gtatethWidget = {
  tenantId: 'your-tenant-id',
  companyName: 'My SaaS',
  features: {
    aiEnabled: true,
    agentHandoff: true,
    fileAttachments: true
  },
  customerInfo: {
    email: userEmail,
    metadata: {
      plan: userPlan,
      feature: currentFeature
    }
  }
};
```

## Support

Need help? Contact us:

* **Email**: [support@g-tateth.com](mailto:support@g-tateth.com)
* **Documentation**: [https://docs.g-tateth.com](https://docs.g-tateth.com)
* **Dashboard**: [https://app.g-tateth.com](https://app.g-tateth.com)
