npm package: @mofid-ai/floating-chatbot
Description: Production-ready floating AI chatbot with voice capabilities and Mofid API integration
Author: Mofid AI
Latest version: 2.3.5

# @mofid-ai/floating-chatbot

A production-ready, fully-featured floating AI chatbot widget with voice capabilities, real-time streaming, and Mofid API integration.

[![npm version](https://img.shields.io/npm/v/@mofid-ai/floating-chatbot.svg)](https://www.npmjs.com/package/@mofid-ai/floating-chatbot)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

## ✨ Features

- 🎯 **Fully Isolated Styles** - Works seamlessly with Tailwind, Bootstrap, and vanilla CSS
- 💬 **Text Chat** - Full conversational AI with message history
- 🎤 **Voice Messages** - Record and send voice messages with waveform visualization
- 📞 **Voice Calls** - Real-time voice conversations with WebSocket streaming
- 🎨 **Customizable** - Custom colors, logos, and positioning
- 📱 **Responsive** - Mobile-first design that works on all devices
- 🔒 **Type-Safe** - Written in TypeScript with full type definitions
- 🚀 **Production Ready** - Optimized, tested, and battle-tested

## 📦 Installation

```bash
npm install @mofid-ai/floating-chatbot
# or
yarn add @mofid-ai/floating-chatbot
# or
pnpm add @mofid-ai/floating-chatbot
```

### Peer Dependencies

```bash
npm install react react-dom framer-motion lucide-react
```

## 🚀 Quick Start

### Basic Usage

```tsx
import { FloatingChatbot } from '@mofid-ai/floating-chatbot';
import '@mofid-ai/floating-chatbot/styles.css';

function App() {
  return (
    <FloatingChatbot
      apiKey="your-mofid-api-key"
      apiBaseUrl="https://api.mofid.ai"
      position="bottom-right"
      primaryColor="#3B82F6"
      secondaryColor="#8B5CF6"
    />
  );
}
```

### With Custom Logo

```tsx
import { FloatingChatbot } from '@mofid-ai/floating-chatbot';
import '@mofid-ai/floating-chatbot/styles.css';

function App() {
  return (
    <FloatingChatbot
      apiKey="your-api-key"
      apiBaseUrl="https://api.mofid.ai"
      logo="/path/to/logo.png"
      logoText="/path/to/logo-text.png"
      position="bottom-right"
      primaryColor="#FF6B6B"
      secondaryColor="#4ECDC4"
      initialOpen={false}
    />
  );
}
```

### React Component Logo

```tsx
import { FloatingChatbot } from '@mofid-ai/floating-chatbot';
import '@mofid-ai/floating-chatbot/styles.css';
import { MessageCircle } from 'lucide-react';

function App() {
  return (
    <FloatingChatbot
      apiKey="your-api-key"
      apiBaseUrl="https://api.mofid.ai"
      logo={<MessageCircle size={32} color="white" />}
      logoText={<span style={{ fontWeight: 'bold' }}>AI Assistant</span>}
    />
  );
}
```

## 🎨 Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `apiKey` | `string` | **Required** | Your Mofid API key |
| `apiBaseUrl` | `string` | `'https://api.mofid.ai'` | Base URL for the Mofid API |
| `wsUrl` | `string` | Auto-generated | WebSocket URL for voice calls |
| `logo` | `string \| ReactNode` | Default logo | Logo to display in the button (URL or component) |
| `logoText` | `string \| ReactNode` | Default text | Logo text to display when expanded |
| `position` | `'bottom-right' \| 'bottom-left' \| 'bottom-center'` | `'bottom-right'` | Position of the chatbot |
| `primaryColor` | `string` | `'#3B82F6'` | Primary theme color |
| `secondaryColor` | `string` | `'#8B5CF6'` | Secondary theme color |
| `initialOpen` | `boolean` | `false` | Whether the chat starts open |

## 🎯 Framework Compatibility

### React + Vite

```tsx
// App.tsx
import { FloatingChatbot } from '@mofid-ai/floating-chatbot';
import '@mofid-ai/floating-chatbot/styles.css';

export default function App() {
  return (
    <div className="app">
      {/* Your app content */}
      <FloatingChatbot
        apiKey={import.meta.env.VITE_MOFID_API_KEY}
        apiBaseUrl="https://api.mofid.ai"
      />
    </div>
  );
}
```

### Next.js (App Router)

```tsx
// app/layout.tsx
'use client';

import { FloatingChatbot } from '@mofid-ai/floating-chatbot';
import '@mofid-ai/floating-chatbot/styles.css';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {children}
        <FloatingChatbot
          apiKey={process.env.NEXT_PUBLIC_MOFID_API_KEY!}
          apiBaseUrl="https://api.mofid.ai"
        />
      </body>
    </html>
  );
}
```

### Next.js (Pages Router)

```tsx
// pages/_app.tsx
import { FloatingChatbot } from '@mofid-ai/floating-chatbot';
import '@mofid-ai/floating-chatbot/styles.css';

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Component {...pageProps} />
      <FloatingChatbot
        apiKey={process.env.NEXT_PUBLIC_MOFID_API_KEY!}
        apiBaseUrl="https://api.mofid.ai"
      />
    </>
  );
}
```

### Tailwind CSS Project

```tsx
// The chatbot styles are completely isolated and won't conflict
import { FloatingChatbot } from '@mofid-ai/floating-chatbot';
import '@mofid-ai/floating-chatbot/styles.css';

function App() {
  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-4xl font-bold text-gray-900">My App</h1>
        {/* Your Tailwind-styled content */}
      </div>
      
      <FloatingChatbot
        apiKey="your-key"
        apiBaseUrl="https://api.mofid.ai"
        primaryColor="#0EA5E9" // Tailwind sky-500
        secondaryColor="#8B5CF6" // Tailwind violet-500
      />
    </div>
  );
}
```

### Bootstrap Project

```tsx
// Works perfectly with Bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';
import { FloatingChatbot } from '@mofid-ai/floating-chatbot';
import '@mofid-ai/floating-chatbot/styles.css';

function App() {
  return (
    <div className="container">
      <div className="row">
        <div className="col-12">
          <h1 className="display-4">Bootstrap + AI Chat</h1>
        </div>
      </div>
      
      <FloatingChatbot
        apiKey="your-key"
        apiBaseUrl="https://api.mofid.ai"
        primaryColor="#0d6efd" // Bootstrap primary
        secondaryColor="#6610f2" // Bootstrap indigo
      />
    </div>
  );
}
```

## 🔧 Advanced Usage

### Using API Utilities Directly

```tsx
import {
  sendTextMessage,
  sendVoiceMessage,
  setApiBaseUrl,
  storeChatroomId,
  getStoredChatroomId
} from '@mofid-ai/floating-chatbot';

// Set API base URL
setApiBaseUrl('https://api.mofid.ai');

// Send text message
async function sendMessage(text: string) {
  const chatroomId = getStoredChatroomId();
  
  const response = await sendTextMessage(
    text,
    chatroomId,
    false, // expectAudio
    'your-api-key',
    'https://api.mofid.ai'
  );
  
  console.log('Response:', response);
}

// Send voice message
async function sendVoice(audioBlob: Blob) {
  const chatroomId = getStoredChatroomId();
  
  const response = await sendVoiceMessage(
    audioBlob,
    chatroomId,
    true, // expectAudio - get audio response
    'your-api-key',
    'https://api.mofid.ai'
  );
  
  console.log('Voice response:', response);
}
```

### Custom Stream Client

```tsx
import { StreamClient } from '@mofid-ai/floating-chatbot';

const client = new StreamClient('wss://api.mofid.ai/v1/conversation/stream');

// Listen to events
client.on('connected', () => {
  console.log('Connected to stream');
});

client.on('message', (data) => {
  console.log('Received:', data);
});

client.on('error', (error) => {
  console.error('Stream error:', error);
});

// Connect and start session
await client.connect();
await client.setupAudio();
await client.startSession({ apiKey: 'your-key' });

// Start recording
await client.startRecording();

// Stop recording
client.stopRecording();

// Disconnect
await client.disconnect();
```

### Custom VAD Manager

```tsx
import { VADManager, VADPresets } from '@mofid-ai/floating-chatbot';

const vad = new VADManager();

await vad.initialize({
  ...VADPresets.sensitive, // or: default, strict, fast, quality
  onSpeechStart: () => {
    console.log('Speech detected');
  },
  onSpeechEnd: (audio) => {
    console.log('Speech ended, audio chunks:', audio.length);
  }
});

// Start VAD
vad.start();

// Pause VAD
vad.pause();

// Destroy VAD
vad.destroy();
```

## 🎨 Theming

### Custom Colors

```tsx
<FloatingChatbot
  apiKey="your-key"
  apiBaseUrl="https://api.mofid.ai"
  primaryColor="#FF6B6B"    // Custom primary
  secondaryColor="#4ECDC4"  // Custom secondary
/>
```

### Custom Positioning

```tsx
// Bottom right (default)
<FloatingChatbot position="bottom-right" {...props} />

// Bottom left
<FloatingChatbot position="bottom-left" {...props} />

// Bottom center
<FloatingChatbot position="bottom-center" {...props} />
```

## 📱 Mobile Responsiveness

The chatbot is fully responsive and automatically adjusts to mobile screens:

- On mobile: Full-width popover that covers most of the screen
- On desktop: Fixed-width popover positioned according to `position` prop
- Touch-friendly controls and buttons
- Optimized microphone access for mobile devices

## 🔐 Security

- API keys should be stored in environment variables
- Never commit API keys to version control
- Use server-side proxies for sensitive operations in production
- The chatbot uses secure WebSocket connections (WSS)

## 🐛 Troubleshooting

### Styles not working / Conflicting with my CSS

Make sure you import the CSS file:

```tsx
import '@mofid-ai/floating-chatbot/styles.css';
```

All styles are prefixed with `.mofid-chatbot-root` and use CSS custom properties, so they won't conflict with your existing styles.

### WebSocket keeps sending infinite packets

This has been fixed in the latest version. Make sure you're using version 2.1.0 or higher. The issue was caused by improper recording state management.

### Microphone not working

1. Check browser permissions
2. Ensure you're using HTTPS (required for microphone access)
3. Check console for errors
4. Verify the `wsUrl` is correct

### Voice call not connecting

1. Verify your `apiBaseUrl` is correct
2. Check that `wsUrl` is properly generated (should start with `ws://` or `wss://`)
3. Check browser console for WebSocket errors
4. Verify your API key is valid

## 📄 License

MIT © Mofid AI

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## 📞 Support

For issues and questions:
- GitHub Issues: https://github.com/mofid-ai/floating-chatbot/issues
- Email: support@mofid.ai
- Documentation: https://docs.mofid.ai

## 🎉 Changelog

### v2.1.0
- ✅ Fixed WebSocket infinite loop issue
- ✅ Complete style isolation for all frameworks
- ✅ Improved VAD (Voice Activity Detection)
- ✅ Better error handling
- ✅ Full TypeScript support
- ✅ Dynamic API base URL support
- ✅ Proper recording state management

### v2.0.0
- 🎉 Initial release
- ✨ Text chat support
- 🎤 Voice messages
- 📞 Real-time voice calls
- 🎨 Customizable theming