# Mori Widget

A modern, embeddable AI-powered chat widget built with React 19 and Chakra UI, designed for seamless integration into e-commerce websites. The widget provides intelligent customer support with product-aware conversations in Persian/Farsi (RTL).

## 🚀 Features

- **AI-Powered Chat**: Intelligent conversation capabilities with streaming responses
- **Product Context Awareness**: Automatically detects current product for contextual assistance
- **Dual Widget Mode**: Floating action button + optional embedded PDP (Product Detail Page) widget
- **WooCommerce Integration**: Native session tracking and product detection
- **Persian/Farsi Support**: Full RTL support with Persian UI elements
- **Shadow DOM Isolation**: Styles won't conflict with your website's CSS
- **Session Persistence**: Maintains chat history across page navigations
- **TypeScript**: Built with TypeScript for better development experience
- **Error Tracking**: Integrated Sentry monitoring for production reliability

## 📦 Installation

### Quick Start

Add this script tag to your website:

```html
<script
  src="https://cdn.jsdelivr.net/npm/mori-widget@latest/dist/widget.js"
  data-sharing-id="your-sharing-id"
></script>
```

### Embedded Widget (Optional)

For product detail pages, add this container:

```html
<div class="mori-embedded-widget"></div>
```

## 🎨 Customization

The widget's branding, colors, and behavior are configured via the bot configuration API (associated with your `data-sharing-id`). Customization includes:

- **Colors**: Primary and accent colors for branding
- **Welcome Message**: Custom greeting text
- **Suggestions**: Quick action buttons for common queries
- **Theming**: Light/dark theme support via `next-themes`

## 🔧 Development

### Prerequisites

- **Node.js**: 18+ recommended
- **pnpm**: 10.6.2+ (package manager)

### Local Development

1. Clone the repository:

```bash
git clone <repository-url>
cd mori-widget
```

2. Install dependencies:

```bash
pnpm install
```

3. Start development server:

```bash
pnpm dev
```

4. Open your browser to `http://localhost:3000`

### Building for Production

```bash
pnpm build
```

This creates an optimized `dist/widget.js` bundle with:
- Shadow DOM isolation
- CSS injected into JS
- Console logs stripped
- Font URLs rewritten for CDN
- Sentry release tracking

### Development vs Production

| Mode | Command | Entry | Shadow DOM | Use Case |
|------|---------|-------|------------|----------|
| **Development** | `pnpm dev` | `index.html` | ❌ Disabled | Local debugging with HMR |
| **Production** | `pnpm build` | `unified-widget.ts` | ✅ Enabled | CDN distribution |

**Why different modes?**
- Dev mode disables Shadow DOM for easier DOM inspection and debugging
- Production mode enables Shadow DOM to prevent CSS conflicts with host websites

## 📱 Widget Architecture

### Screen Flow

The widget follows a progressive disclosure pattern:

1. **Welcome Screen**: Animated greeting with bot avatar
2. **Suggestions Screen**: Quick action buttons for common queries
3. **Chat Screen**: Full conversation interface with streaming responses

### Widget Modes

**Floating Widget** (default):
- Floating Action Button (FAB) in bottom-right corner
- Expands to modal overlay when clicked
- Controlled via `window.moriWidget.open()` / `close()` / `toggle()`

**Embedded Widget** (optional):
- Inline widget for product detail pages
- Renders inside `.mori-embedded-widget` containers
- Independent state from floating widget

### Technical Stack

- **React 19.1**: Latest React with concurrent features
- **Chakra UI 3.25**: Modern component library with accessibility
- **TypeScript 5.6**: Full type safety
- **Vite 7**: Lightning-fast build tooling
- **Framer Motion 12**: Smooth animations
- **react-shadow**: Shadow DOM encapsulation
- **Sentry**: Error tracking and monitoring

## 🌐 Browser Support

Modern browsers with ES2020+ support:
- Chrome 88+
- Firefox 85+
- Safari 14+
- Edge 88+

**Requirements:**
- Shadow DOM support
- ES Modules support
- Fetch API with streaming (ReadableStream)

## 🔌 Programmatic Control

### Global API

The widget exposes a global API for programmatic control:

```javascript
// Open the floating widget
window.moriWidget.open()

// Close the floating widget
window.moriWidget.close()

// Toggle the floating widget
window.moriWidget.toggle()
```

### Custom Events

You can also control the widget via custom events:

```javascript
// Open widget
window.dispatchEvent(new CustomEvent('mori:open-widget'))

// Close widget
window.dispatchEvent(new CustomEvent('mori:close-widget'))

// Toggle widget
window.dispatchEvent(new CustomEvent('mori:toggle-widget'))
```

## 📊 Session Persistence

The widget maintains conversation state across page navigations using `sessionStorage`:

- **Chat history**: All messages preserved during session
- **Thread continuity**: Conversations resume after page reload
- **Cross-tab sync**: Widget state shared across browser tabs
- **Product context**: Current product tracked automatically

Sessions are identified by:
- `data-sharing-id` (bot identifier)
- WooCommerce session ID (if available)
- Browser session ID (fallback)

## 🔒 Security & Privacy

- **Shadow DOM Isolation**: Widget styles and DOM completely isolated from host page
- **Secure Communication**: HTTPS-only API endpoints
- **Error Tracking**: Sentry integration with privacy-safe context
- **No Global Pollution**: Minimal global scope footprint (`window.moriWidget` only)

## 🚀 Performance

- **Optimized Bundle**: Single JS file with CSS injected (~500KB gzipped)
- **Prefetching**: Bot configuration loaded early for instant chat
- **Streaming Responses**: Real-time message display as AI generates content
- **CDN Delivery**: Fast global distribution via jsDelivr NPM CDN
- **Code Splitting**: Dynamic imports for optimal loading
- **Tree-Shaking**: Unused code removed during build

## 🛠️ Development Tools

### Code Quality

```bash
pnpm lint         # Check code quality with ESLint
pnpm lint:fix     # Auto-fix linting issues
pnpm format       # Format code with Prettier
pnpm type-check   # TypeScript validation
```

### Linting Rules

- **ESLint 9** with flat config format
- **TypeScript**, **React**, and **accessibility** plugins
- **Strict formatting**: No trailing spaces, consistent blank lines
- **Auto-removal**: Unused imports automatically removed

## 📄 License

This project is licensed under the MIT License.

## 🔄 Version Management

### Using Latest Version (Auto-Updates)

```html
<script
  src="https://cdn.jsdelivr.net/npm/mori-widget@latest/dist/widget.js"
  data-sharing-id="your-id"
></script>
```

### Pinning Specific Version

```html
<script
  src="https://cdn.jsdelivr.net/npm/mori-widget@2.0.2/dist/widget.js"
  data-sharing-id="your-id"
></script>
```

**Current Version:** 2.0.2

---

**Mori Widget** - AI-powered customer support for e-commerce, in Persian.
