# N8N Chat Widget

A customizable, embeddable chat widget with markdown support and modern styling. Perfect for integrating conversational AI into your website with n8n workflows.

[![NPM Version](https://img.shields.io/npm/v/marlonsantos)](https://www.npmjs.com/package/marlonsantos)
[![NPM Downloads](https://img.shields.io/npm/dm/marlonsantos)](https://www.npmjs.com/package/marlonsantos)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

✨ **Modern Design** - Clean, professional chat interface with gradient styling
🎨 **Customizable Theming** - Full control over colors, positioning, and branding
📝 **Markdown Support** - Rich text formatting with code blocks, lists, and links
🔒 **Security First** - Built-in HTML sanitization with DOMPurify
📱 **Responsive** - Works perfectly on desktop and mobile devices
⚡ **Lightweight** - Minimal dependencies with optimal performance
🔗 **N8N Integration** - Seamless webhook integration with n8n workflows

## Installation

### NPM

```bash
npm install marlonsantos
```

### CDN

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

### Direct Download

```html
<script src="./path/to/chat-widget.js"></script>
```

## Quick Start

### Basic Implementation

```html
<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>
<body>
    <!-- Your website content -->
    
    <!-- Chat Widget Configuration -->
    <script>
        window.ChatWidgetConfig = {
            webhook: {
                url: 'https://your-n8n-instance.com/webhook/chat',
                route: 'chat'
            },
            branding: {
                name: 'Support Chat',
                logo: 'https://your-site.com/logo.png',
                welcomeText: 'Hello! How can we help you today?',
                responseTimeText: 'We typically reply within a few minutes'
            }
        };
    </script>
    
    <!-- Load the chat widget -->
    <script src="https://cdn.jsdelivr.net/npm/marlonsantos@latest/chat-widget.js"></script>
</body>
</html>
```

## Configuration

### Complete Configuration Options

```javascript
window.ChatWidgetConfig = {
    webhook: {
        url: 'https://your-n8n-instance.com/webhook/chat',  // Required: Your n8n webhook URL
        route: 'chat'                                        // Required: Webhook route name
    },
    branding: {
        name: 'Support Chat',                               // Chat window title
        logo: 'https://your-site.com/logo.png',            // Logo URL (32x32 recommended)
        welcomeText: 'Hello! How can we help?',            // Welcome message
        responseTimeText: 'We reply within minutes',        // Response time text
        poweredBy: {
            text: 'Powered by n8n',                        // Footer attribution
            link: 'https://n8n.io'                         // Attribution link
        }
    },
    style: {
        primaryColor: '#854fff',                            // Main theme color
        secondaryColor: '#6b3fd4',                          // Secondary theme color
        backgroundColor: '#ffffff',                         // Chat background
        fontColor: '#333333',                               // Text color
        position: 'right'                                   // 'right' or 'left'
    }
};
```

## N8N Webhook Setup

### 1. Create N8N Workflow

Create a new workflow in n8n with a webhook trigger:

```json
{
    "httpMethod": "POST",
    "path": "chat",
    "responseMode": "responseNode"
}
```

### 2. Expected Request Format

The widget sends requests in this format:

```json
{
    "action": "loadPreviousSession",
    "sessionId": "uuid-v4-session-id",
    "route": "chat",
    "metadata": {
        "userId": ""
    }
}
```

For messages:

```json
{
    "action": "sendMessage",
    "sessionId": "uuid-v4-session-id",
    "route": "chat",
    "chatInput": "User message text",
    "metadata": {
        "userId": ""
    }
}
```

### 3. Expected Response Format

Your n8n workflow should return:

```json
{
    "output": "AI response message with **markdown** support"
}
```

Or as an array:

```json
[{
    "output": "AI response message with **markdown** support"
}]
```

## Styling & Theming

### CSS Variables

You can also customize the widget using CSS variables:

```css
:root {
    --n8n-chat-primary-color: #your-primary-color;
    --n8n-chat-secondary-color: #your-secondary-color;
    --n8n-chat-background-color: #your-bg-color;
    --n8n-chat-font-color: #your-text-color;
}
```

### Custom CSS

Target specific elements with these selectors:

```css
.n8n-chat-widget .chat-container { /* Main chat window */ }
.n8n-chat-widget .chat-toggle { /* Chat toggle button */ }
.n8n-chat-widget .chat-message.user { /* User messages */ }
.n8n-chat-widget .chat-message.bot { /* Bot messages */ }
.n8n-chat-widget .brand-header { /* Header with logo */ }
```

## Markdown Support

The widget supports full markdown rendering including:

- **Bold** and *italic* text
- `Inline code` and code blocks
- Lists (ordered and unordered)
- Links and images
- Tables
- Blockquotes
- Headings (H1-H6)
- Horizontal rules

### Code Blocks

````markdown
```javascript
function hello() {
    console.log('Hello from chat widget!');
}
```
````

## Security Features

- **HTML Sanitization**: All user input and bot responses are sanitized
- **XSS Protection**: Built-in protection against cross-site scripting
- **Safe Markdown**: Only safe HTML tags and attributes are allowed
- **HTTPS Only**: Secure communication with your n8n webhooks

## Browser Support

- ✅ Chrome (60+)
- ✅ Firefox (60+)
- ✅ Safari (12+)
- ✅ Edge (79+)
- ✅ Mobile browsers (iOS Safari, Chrome Mobile)

## Advanced Usage

### Multiple Widgets

You can have multiple chat widgets on the same page:

```javascript
// First widget
window.ChatWidgetConfig = { /* config */ };
// Load first widget script

// Second widget with different config
window.ChatWidgetConfig2 = { /* different config */ };
// Load second widget script with modified variable name
```

### Event Handling

```javascript
// Listen for widget events (if implemented)
document.addEventListener('chatWidgetReady', function(e) {
    console.log('Chat widget is ready!');
});
```

### Dynamic Configuration

```javascript
// Update configuration after loading
if (window.N8NChatWidget) {
    window.N8NChatWidget.updateConfig({
        style: {
            primaryColor: '#new-color'
        }
    });
}
```

## Troubleshooting

### Common Issues

1. **Widget not appearing**: Check console for JavaScript errors
2. **Messages not sending**: Verify webhook URL and n8n workflow setup
3. **Styling issues**: Ensure CSS variables are properly set
4. **CORS errors**: Configure your n8n instance to allow your domain

### Debug Mode

Add this to enable debug logging:

```javascript
window.ChatWidgetConfig.debug = true;
```

## Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/new-feature`
3. Commit your changes: `git commit -am 'Add new feature'`
4. Push to the branch: `git push origin feature/new-feature`
5. Submit a pull request

## License

MIT License - see the [LICENSE](LICENSE) file for details.

## Support

- 🐛 **Bug Reports**: [GitHub Issues](https://github.com/MarIonSantos/cdn/issues)
- 💬 **Questions**: [GitHub Discussions](https://github.com/MarIonSantos/cdn/discussions)
- 📧 **Contact**: [GitHub Profile](https://github.com/MarIonSantos)

## Changelog

### v1.0.1
- Initial release
- Basic chat widget functionality
- Markdown support with DOMPurify sanitization
- Customizable theming and branding
- N8N webhook integration
- Responsive design

---

Made with ❤️ for the n8n community