# AspireChat

A highly customizable React chatbot component with extensive configuration options for modern web applications.

[![npm version](https://img.shields.io/npm/v/aspirechat.svg)](https://www.npmjs.com/package/aspirechat)
[![license](https://img.shields.io/npm/l/aspirechat.svg)](https://github.com/aspiredev/aspirechat/blob/main/LICENSE)

## Features

- 🎨 **Highly Customizable**: Customize every aspect of the chatbot UI through extensive theme options
- 🔌 **Plug and Play**: Easy to integrate with any React application
- 📱 **Responsive**: Works seamlessly across devices and screen sizes
- 🔗 **API Integration**: Connect to any backend API for dynamic responses
- 🧩 **Plugin System**: Extend functionality through custom plugins
- 🌓 **Dark Mode Support**: Built-in dark theme and custom theme options
- 📊 **Button-Based Flows**: Guide users through conversations with predefined buttons
- 💬 **Typing Indicators**: Natural typing indicators for a more engaging experience
- 🔄 **Persistent Chat**: Option to persist chat history between sessions

## Installation

```bash
npm install aspirechat
# or
yarn add aspirechat
```

## Quick Start

### Button-Based Flows

```jsx
import React from "react";
import { Chatbot } from "aspirechat";
import { ChatContextProvider } from "aspirechat";

const App = () => {
  // Define your chat flows
  const chatFlows = {
    welcome: {
      id: "welcome",
      messages: [
        {
          text: "Welcome to our support chatbot! How can I help you today?",
          type: "bot",
        },
      ],
      options: [
        {
          id: "1",
          text: "Product Information",
          value: "",
          nextFlow: "products",
        },
        {
          id: "2",
          text: "Pricing Plans",
          value: "",
          nextFlow: "pricing",
        },
        {
          id: "3",
          text: "Contact Support",
          value: "",
          nextFlow: "contact",
        },
      ],
    },
    products: {
      id: "products",
      messages: [
        {
          text: "We offer the following products:",
          type: "bot",
        },
        {
          text: "<ul><li>Product A - Analytics Suite</li><li>Product B - CRM Solution</li><li>Product C - Marketing Automation</li></ul>",
          type: "bot",
          html: true,
        },
      ],
      options: [
        {
          id: "1",
          text: "Tell me about Product A",
          value: "",
          nextFlow: "productA",
        },
        {
          id: "2",
          text: "Tell me about Product B",
          value: "",
          nextFlow: "productB",
        },
        { id: "3", text: "Back to menu", value: "", nextFlow: "welcome" },
      ],
    },
    pricing: {
      id: "pricing",
      messages: [
        {
          text: "Our pricing starts at $49/month for the basic plan.",
          type: "bot",
        },
      ],
      options: [
        {
          id: "1",
          text: "See pricing details",
          value: "Here's our detailed pricing structure...",
          nextFlow: null,
        },
        { id: "2", text: "Back to menu", value: "", nextFlow: "welcome" },
      ],
    },
    contact: {
      id: "contact",
      messages: [
        {
          text: "You can reach our support team at support@example.com or by phone at 555-123-4567.",
          type: "bot",
        },
      ],
      options: [
        {
          id: "1",
          text: "Email Support",
          value: "I'll open your email client to contact support.",
          nextFlow: null,
        },
        {
          id: "2",
          text: "Call Support",
          value: "Connecting you with our support team...",
          nextFlow: null,
        },
        { id: "3", text: "Back to menu", value: "", nextFlow: "welcome" },
      ],
    },
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>My Website</h1>
      </header>

      <ChatContextProvider
        initialConfig={{
          headerTitle: "Support Bot",
          initiallyOpen: true,
        }}
        initialOptions={{
          flows: chatFlows,
          initialFlow: "welcome",
        }}
      >
        <Chatbot />
      </ChatContextProvider>
    </div>
  );
};

export default App;
```

## Advanced Configuration

AspireChat is designed to be highly customizable. Below are some examples of more advanced configurations.

### Connecting to an API endpoint

```jsx
import { Chatbot } from "aspirechat";

const App = () => {
  const api = {
    endpoint: "https://api.example.com/chat",
    headers: {
      Authorization: "Bearer YOUR_API_KEY",
    },
    transformRequest: (message) => ({
      query: message.text,
      userId: "user-123",
    }),
    transformResponse: (data) => ({
      text: data.response,
      type: "bot",
    }),
  };

  return <Chatbot api={api} />;
};
```

### Custom Theme

```jsx
import { Chatbot, darkTheme } from "aspirechat";

const App = () => {
  // Start with the built-in dark theme and customize it
  const customTheme = {
    ...darkTheme,
    primary: "#6d28d9", // purple-700
    secondary: "#8b5cf6", // purple-500
    userBubbleBackground: "#6d28d9", // purple-700
    userBubbleText: "#ffffff",
    botBubbleBackground: "#4c1d95", // purple-900
    botBubbleText: "#ffffff",
    fontFamily: "'Poppins', sans-serif",
  };

  return (
    <Chatbot
      config={{
        theme: customTheme,
        headerTitle: "Custom Support Bot",
      }}
    />
  );
};
```

### Customizing Chat Position

```jsx
import { Chatbot } from "aspirechat";

const App = () => {
  return (
    <Chatbot
      config={{
        position: {
          placement: "bottom-left", // "top-left", "top-right", "bottom-left", "bottom-right"
          offsetX: "30px",
          offsetY: "30px",
        },
        width: "400px",
        maxHeight: "700px",
      }}
    />
  );
};
```

### Persistent Chat History

```jsx
import { Chatbot } from "aspirechat";

const App = () => {
  return (
    <Chatbot
      config={{
        persistHistory: true,
        persistKey: "my-app-chat-history",
      }}
    />
  );
};
```

### Mobile Configuration

```jsx
import { Chatbot } from "aspirechat";

const App = () => {
  return (
    <Chatbot
      config={{
        mobile: {
          fullScreen: true, // Full screen on mobile
          bottomOffset: "60px", // Space for bottom navigation bar
        },
        fullScreenBreakpoint: "768px", // Switch to full screen below this width
      }}
    />
  );
};
```

## Using with Next.js

AspireChat is compatible with Next.js, but requires proper client component setup:

```jsx
"use client"; // This directive is important!

import React from "react";
import { Chatbot, ChatContextProvider } from "aspirechat";

export default function ChatWidget() {
  return (
    <ChatContextProvider
      initialConfig={{
        headerTitle: "Support Bot",
        initiallyOpen: true,
      }}
      initialOptions={{
        flows: {
          welcome: {
            id: "welcome",
            messages: [
              {
                text: "Welcome! How can I help you?",
                type: "bot",
              },
            ],
            options: [
              {
                id: "1",
                text: "Learn More",
                value: "Here's some information...",
                nextFlow: null,
              },
            ],
          },
        },
        initialFlow: "welcome",
      }}
    >
      <Chatbot />
    </ChatContextProvider>
  );
}
```

**Important**: Make sure to only use AspireChat components in client components (marked with 'use client').

## API Reference

### `<Chatbot>` Props

| Prop                   | Type      | Description                                   |
| ---------------------- | --------- | --------------------------------------------- |
| `config`               | `object`  | Configuration options for the chatbot         |
| `handlers`             | `object`  | Event handlers for various chatbot actions    |
| `responses`            | `array`   | Array of predefined response patterns         |
| `api`                  | `object`  | API configuration for connecting to a backend |
| `plugins`              | `array`   | Custom plugins to extend functionality        |
| `className`            | `string`  | Additional CSS class names                    |
| `disableDefaultStyles` | `boolean` | Disable default styled-components styles      |

### Configuration Options

#### Basic Configuration

| Option               | Type                 | Default             | Description                                              |
| -------------------- | -------------------- | ------------------- | -------------------------------------------------------- |
| `headerTitle`        | `string`             | "Chat Support"      | Title displayed in the header                            |
| `welcomeMessage`     | `string` or `object` | undefined           | Initial message sent by the bot                          |
| `placeholderText`    | `string`             | "Type a message..." | Placeholder text for the input field                     |
| `initiallyOpen`      | `boolean`            | `false`             | Whether the chat window should be open on initial render |
| `showMinimizeButton` | `boolean`            | `true`              | Display minimize button in the header                    |
| `showCloseButton`    | `boolean`            | `true`              | Display close button in the header                       |
| `logo`               | `string`             | undefined           | URL to the logo image displayed in the header            |

#### Appearance

| Option           | Type      | Default                         | Description                                  |
| ---------------- | --------- | ------------------------------- | -------------------------------------------- |
| `theme`          | `object`  | `defaultTheme`                  | Theme configuration object                   |
| `position`       | `object`  | `{ placement: 'bottom-right' }` | Positioning of the chat window               |
| `width`          | `string`  | "350px"                         | Width of the chat window                     |
| `height`         | `string`  | undefined                       | Height of the chat window                    |
| `maxHeight`      | `string`  | "600px"                         | Maximum height of the chat window            |
| `minHeight`      | `string`  | "300px"                         | Minimum height of the chat window            |
| `roundedCorners` | `boolean` | `true`                          | Use rounded corners for the chat window      |
| `boxShadow`      | `boolean` | `true`                          | Apply box shadow to the chat window          |
| `floatingButton` | `object`  | undefined                       | Configuration for the floating toggle button |

#### Behavior

| Option                   | Type      | Default   | Description                                       |
| ------------------------ | --------- | --------- | ------------------------------------------------- |
| `enableTypingIndicator`  | `boolean` | `true`    | Show typing indicator when the bot is "typing"    |
| `typingIndicatorTimeout` | `number`  | 1000      | Duration of the typing indicator in milliseconds  |
| `autoFocus`              | `boolean` | `true`    | Auto focus the input field when the chat opens    |
| `persistHistory`         | `boolean` | `false`   | Persist chat history in localStorage              |
| `persistKey`             | `string`  | undefined | Key for localStorage when persisting chat history |
| `showTimestamp`          | `boolean` | `true`    | Show timestamps for messages                      |
| `timestampFormat`        | `string`  | "HH:mm"   | Format for timestamps (HH:mm:ss)                  |
| `enableAutoScroll`       | `boolean` | `true`    | Auto scroll to the latest message                 |

### Event Handlers

| Handler         | Parameters               | Description                              |
| --------------- | ------------------------ | ---------------------------------------- |
| `onMessage`     | `(message: ChatMessage)` | Called when a message is added           |
| `onSendMessage` | `(text: string)`         | Called when a user sends a message       |
| `onOpen`        | none                     | Called when the chat window is opened    |
| `onClose`       | none                     | Called when the chat window is closed    |
| `onMinimize`    | none                     | Called when the chat window is minimized |
| `onMaximize`    | none                     | Called when the chat window is maximized |
| `onFileUpload`  | `(file: File)`           | Called when a file is uploaded           |
| `onError`       | `(error: Error)`         | Called when an error occurs              |

## Creating Custom Plugins

You can extend AspireChat's functionality with custom plugins:

```jsx
import { Chatbot } from "aspirechat";

// Analytics plugin example
const analyticsPlugin = {
  id: "analytics",
  name: "Analytics Tracker",
  initialize: (chat) => {
    // Plugin initialization
    console.log("Analytics plugin initialized");
  },
  middleware: (message, next) => {
    // Track all messages
    if (message.type === "user") {
      console.log("User message tracked:", message.text);
      // You could send to analytics service here
    }
    // Continue processing
    next();
  },
  destroy: () => {
    console.log("Analytics plugin destroyed");
  },
};

const App = () => {
  return <Chatbot plugins={[analyticsPlugin]} />;
};
```

## TypeScript Support

AspireChat is built with TypeScript and exports all types for excellent developer experience:

```tsx
import { Chatbot, ChatConfig, ChatResponse, ChatAPI } from "aspirechat";

const config: ChatConfig = {
  headerTitle: "TypeScript Chat",
  welcomeMessage: "Welcome to our TypeScript-powered chat!",
};

const responses: ChatResponse[] = [
  {
    pattern: /hello/i,
    response: "Hi there!",
  },
];

const api: ChatAPI = {
  endpoint: "/api/chat",
};

const App = () => {
  return <Chatbot config={config} responses={responses} api={api} />;
};
```

## License

MIT © [AspireDev](https://aspiredev.in/)
