# Navigator SDK

## Overview

The Navigator SDK provides a unified widget for integrating AI-powered voice and chat conversations into your applications. With built-in support for contextual messaging, tool integration, and training capabilities.

## ✨ Key Features

- **🎙️ Voice & Chat Interface**: Support for both voice and text conversations
- **🛠️ Tool Integration**: Execute custom tools and actions from conversations
- **📊 Training Mode**: Capture user interactions for assistant training
- **📱 Responsive Design**: Works seamlessly on desktop and mobile
- **🎯 Contextual Messaging**: Send real-time context to enhance conversations
- **📍 Flexible Positioning**: Customizable widget placement and styling

## 🚀 Quick Start

### Installation

```bash
npm install navi-web
```

### Basic Usage

```typescript
import { initUnifiedWidget } from "navi-web";

// Voice-enabled widget
initUnifiedWidget({
  assistantId: "your-assistant-id",
  voiceEnabled: true,
  onReady: () => {
    /* Widget ready */
  },
  onCallEnded: (summary) => {
    /* Handle call end */
  },
  runTool: (toolName, args) => {
    /* Handle tool call */
  },
});

// Chat-enabled widget
initUnifiedWidget({
  assistantId: "your-assistant-id",
  chatEnabled: true,
  onReady: () => {
    /* Widget ready */
  },
});

// Both voice and chat
initUnifiedWidget({
  assistantId: "your-assistant-id",
  voiceEnabled: true,
  chatEnabled: true,
  user_identifier: "user@example.com",
  company: "Acme Corp", // Optional: track end user's company
});
```

## 📚 API Reference

### `initUnifiedWidget(config)`

Main initialization function for the Navigator SDK widget.

#### Configuration Interface

```typescript
interface UnifiedWidgetConfig {
  // Required
  assistantId: string;

  // User identification
  user_identifier?: string;
  company?: string; // Company name for end user tracking

  // Feature toggles
  chatEnabled?: boolean; // Enable chat interface (default: false)
  voiceEnabled?: boolean; // Enable voice interface (default: true)

  // Event handlers
  onReady?: () => void;
  onError?: (error: Error) => void;
  onCallEnded?: (summary: any) => void;
  runTool?: (toolName: string, args: any) => void;

  // Widget positioning
  position?: {
    alignment?:
      | "top-left"
      | "top-center"
      | "top-right"
      | "center-left"
      | "center"
      | "center-right"
      | "bottom-left"
      | "bottom-center"
      | "bottom-right";
    offsetX?: number; // Horizontal offset in pixels
    offsetY?: number; // Vertical offset in pixels
    margin?: number; // Margin from screen edges in pixels
  };

  // Styling
  className?: string;

  // Additional configuration
  model?: string; // AI model (default: "gpt-5")
  allowUserInteraction?: boolean; // Allow user interaction (default: true)
  orgId?: string;
  apiBaseUrl?: string;
  productId?: string;
  userId?: string;
}
```

## 🔧 Advanced Usage

### Tool Integration

The `runTool` callback allows your assistant to execute actions in your application:

```typescript
initUnifiedWidget({
  assistantId: "assistant-123",
  runTool: (toolName, args) => {
    switch (toolName) {
      case "navigate":
        // Handle navigation
        router.push(args.url);
        break;
      case "show_info":
        displayInfo(args.message);
        break;
      case "update_form":
        updateFormField(args.field, args.value);
        break;
      default:
        // Handle unknown tool
        break;
    }
  },
});
```

### Widget Positioning

Customize widget placement on your page:

```typescript
initUnifiedWidget({
  assistantId: "your-assistant-id",
  position: {
    alignment: "bottom-right", // Widget alignment
    margin: 40, // Distance from edges (px)
    offsetX: 0, // Horizontal offset (px)
    offsetY: 0, // Vertical offset (px)
  },
});
```

Available alignments: `top-left`, `top-center`, `top-right`, `center-left`, `center`, `center-right`, `bottom-left`, `bottom-center`, `bottom-right`

### User Context API

Send contextual information to enhance conversations:

```typescript
import { sendUserContext } from "navi-web";

// Silent contextual message (provides background context)
sendUserContext("User viewing order #12345, status: pending, total: $299.99");

// User message (appears in chat conversation)
sendUserContext("I need help with this order", { silent: false });
```

#### React Examples

```typescript
import React, { useEffect } from "react";
import { sendUserContext } from "navi-web";

const ProductPage = ({ product }) => {
  // Send context when user views a product
  useEffect(() => {
    if (product) {
      sendUserContext(
        `User viewing product: ${product.name}, price: $${product.price}`
      );
    }
  }, [product]);

  const handleAddToCart = () => {
    sendUserContext(`User added ${product.name} to cart`);
    // ... your add to cart logic
  };

  return (
    <div>
      <h1>{product.name}</h1>
      <button onClick={handleAddToCart}>Add to Cart</button>
    </div>
  );
};
```

### Training Mode

Enable training mode to capture user interactions:

```typescript
initUnifiedWidget({
  assistantId: "your-assistant-id",
  trainingMode: true,
  trainingAgentId: "training-agent-id",
  onCaptureCompleted: (data) => {
    // Handle training capture completion
  },
  onTrainingError: (error) => {
    console.error("Training error:", error);
  },
});
```

## 🔄 Framework Integration

### React Integration

```typescript
import { useEffect } from "react";
import { initUnifiedWidget } from "navi-web";

const App = () => {
  useEffect(() => {
    initUnifiedWidget({
      assistantId: "your-assistant-id",
      chatEnabled: true,
      voiceEnabled: true,
      user_identifier: "user@example.com",
      onReady: () => {
        /* Widget ready */
      },
      runTool: (toolName, args) => {
        switch (toolName) {
          case "navigate":
            router.push(args.url);
            break;
          default:
            // Handle unknown tool
            break;
        }
      },
    });
  }, []);

  return <div id="app">{/* Your app content */}</div>;
};
```

### Vue.js Integration

```typescript
import { onMounted } from "vue";
import { initUnifiedWidget } from "navi-web";

export default {
  setup() {
    const router = useRouter();

    onMounted(async () => {
      initUnifiedWidget({
        assistantId: "your-assistant-id",
        chatEnabled: true,
        voiceEnabled: true,
        runTool: (toolName, args) => {
          switch (toolName) {
            case "navigate":
              router.push(args.url);
              break;
            default:
              // Handle unknown tool
              break;
          }
        },
      });
    });

    return {};
  },
};
```

## 🛠️ Utility Functions

### Unmounting

```typescript
import { unmountUnifiedWidget } from "navi-web";

// Clean up when component unmounts
unmountUnifiedWidget();
```

### Component Usage (React)

```tsx
import { UnifiedWidget } from "navi-web";

function MyApp() {
  return (
    <UnifiedWidget
      assistantId="my-assistant"
      chatEnabled={true}
      voiceEnabled={true}
      onCallEnded={(summary) => {
        /* Handle call end */
      }}
    />
  );
}
```

### User Context Status

Get the current status of context dispatchers:

```typescript
import { getUserContextStatus } from "navi-web";

const status = getUserContextStatus();
// Handle status: { chatActive: boolean, voiceActive: boolean }
```

## 💡 Best Practices

1. **Initialize Once**: Initialize the widget only once when your component mounts

2. **Error Handling**: Always implement `onError` and `onReady` callbacks for robust error handling

3. **Tool Implementation**: Implement all tools that your assistant might call via the `runTool` callback

4. **Navigation**: Use your framework's router for navigation to avoid page refreshes

5. **User Context Usage**: Leverage the user context API to provide rich context:
   - Send context for important user actions and state changes
   - Use descriptive messages that help the AI understand user intent
   - Default to silent messages unless the user explicitly wants to send a message
   - Include relevant data like IDs, amounts, statuses, and names

6. **Widget Positioning**: Consider your application's layout when positioning the widget:
   - Use `bottom-right` for chat-focused experiences
   - Use `bottom-center` for voice-focused experiences
   - Test positioning with different screen sizes
   - Use offsets to avoid overlapping important UI elements

7. **Cleanup**: The SDK handles cleanup automatically when the page unloads, but you can manually unmount if needed

## 🤝 Support

For issues and questions, please contact support or check the documentation.
