npm package: @isharjeeldd/gen-analytics-sdk
Description: Generative Analytics SDK - Chat-based data visualization widget
Author: PolyX
Latest version: 0.1.0

# Generative Analytics Frontend SDK (PolyX Integration)

## 1. Overview
The Generative Analytics SDK is a **standalone embeddable chat and visualization interface** that allows users to converse with an AI assistant and request data-driven insights (graphs, tables, summaries).  
It can be integrated into any frontend application, primarily built using **React**, and optionally distributed as a **web component** for non-React environments.

The SDK connects to the **Generative Analytics Service (backend)** and relies on **Poly** for organization authentication, configuration, and logging.

---

## 2. Quick Start

### Installation

```bash
npm install @polyx/gen-analytics-sdk
```

### Basic Usage (Enhanced Floating Widget) ⭐ RECOMMENDED

```tsx
import { GenAnalyticsProvider, AnalyticsChatWidget } from "@polyx/gen-analytics-sdk";
import "@polyx/gen-analytics-sdk/style.css";

function App() {
  return (
    <GenAnalyticsProvider
      orgId="org_123"
      projectId="proj_main"
      token={polyJwt}
      endpoint="https://gen-analytics.api.polyx.com"
      theme={{ primary: "#5b99ff", radius: 10 }}
      features={{ floatingCharts: true, showSQL: true }}
    >
      {/* Your app content */}
      <AnalyticsChatWidget />
    </GenAnalyticsProvider>
  );
}
```

### Advanced Usage (Full Customization)

```tsx
import { GenAnalyticsProvider, FloatingChatWidget } from "@polyx/gen-analytics-sdk";

function App() {
  return (
    <GenAnalyticsProvider {...config}>
      <FloatingChatWidget
        position="bottom-right"
        buttonTheme="green"
        theme="dark"
        title="My Analytics Assistant"
        subtitle="Ask questions about your data"
        width="450px"
        height="700px"
      />
    </GenAnalyticsProvider>
  );
}
```

### Inline Widget (For Dashboards)

```tsx
import { GenAnalyticsProvider, ChatWidget } from "@polyx/gen-analytics-sdk";

function Dashboard() {
  return (
    <GenAnalyticsProvider {...config}>
      <div className="dashboard">
        <ChatWidget height={600} />
      </div>
    </GenAnalyticsProvider>
  );
}
```

---

## 3. Development

### Setup

```bash
# Install dependencies
npm install

# Run development server
npm run dev

# Build for production
npm run build

# Preview production build
npm run preview
```

The demo application will be available at `http://localhost:5173`

---

## 4. Core Features

1. **Floating Chat Widget** ⭐ NEW
   - Beautiful chat bubble in the corner
   - Slides-in panel with smooth animations
   - Click to open/close, ESC to dismiss
   - Unread message notifications
   - Fully responsive design

2. **Chat Interface**
   - Rich message types: text, chart, table, error, streaming responses.
   - Inline or floating display modes.
   - Message history with timestamps.

3. **Auto-Visualization**
   - Automatic chart type selection based on data structure.
   - Supports: Line, Bar, Pie, Area, Scatter, Histogram charts.
   - Fallback to table view for complex data.
   - Powered by Recharts for beautiful, responsive charts.

4. **Schema-Agnostic Design**
   - Works with any data structure.
   - No configuration needed for different schemas.
   - Flexible type inference system.

5. **Configurable Themes**
   - CSS variable-based theming.
   - Light/dark mode support.
   - Customizable colors, spacing, and border radius.

6. **Poly Integration** (Coming Soon)
   - Auth token verification using PolyAuth.
   - Config fetching: org/project info, visualization defaults.
   - Audit events sent to PolyLogs.

---

## 5. API Reference

### GenAnalyticsProvider Props

| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `orgId` | string | Yes | Organization identifier from PolyAuth |
| `projectId` | string | Yes | Active project identifier |
| `token` | string | Yes | PolyAuth JWT for authenticated sessions |
| `endpoint` | string | No | Backend API endpoint (default: mock) |
| `theme` | ThemeConfig | No | Theme configuration |
| `features` | FeatureFlags | No | Feature toggles |
| `children` | ReactNode | Yes | Child components |

### ThemeConfig

```typescript
interface ThemeConfig {
  primary?: string;        // Primary color (default: #5b99ff)
  secondary?: string;      // Secondary color
  background?: string;     // Background color
  surface?: string;        // Surface color for cards
  text?: string;          // Text color
  textSecondary?: string; // Secondary text color
  border?: string;        // Border color
  error?: string;         // Error color
  success?: string;       // Success color
  radius?: number;        // Border radius in pixels
  darkMode?: boolean;     // Enable dark mode
}
```

### FeatureFlags

```typescript
interface FeatureFlags {
  floatingCharts?: boolean;   // Enable floating chart windows
  showSQL?: boolean;          // Show SQL queries (if supported)
  allowExport?: boolean;      // Enable data export
  showTimestamp?: boolean;    // Show message timestamps
  markdown?: boolean;         // Enable markdown in messages
}
```

### ChatWidget Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `className` | string | '' | Additional CSS classes |
| `height` | string \| number | '600px' | Widget height |
| `showHeader` | boolean | true | Show header bar |
| `title` | string | 'Generative Analytics' | Widget title |

---

## 6. Hooks API

### useChat

```typescript
const { messages, isLoading, error, sendMessage, clearMessages } = useChat();
```

Manages chat state and message sending.

### useVisualization

```typescript
const { inferChartType, prepareChartData, getDataFieldTypes } = useVisualization();
```

Provides chart type inference and data transformation utilities.

### useGenAnalytics

```typescript
const { orgId, projectId, token, endpoint, theme, features } = useGenAnalytics();
```

Access SDK configuration from context.

---

## 7. Architecture Overview

### Project Structure

```
src/
├── components/
│   ├── ChatWidget.tsx          # Main chat interface
│   ├── MessageList.tsx         # Message display
│   ├── ChartRenderer.tsx       # Auto-visualization
│   └── InputBox.tsx           # User input
├── lib/
│   ├── types.ts               # TypeScript interfaces
│   ├── chartHeuristics.ts     # Chart type inference
│   └── mockBackend.ts         # Mock API (for demo)
├── context/
│   └── GenAnalyticsProvider.tsx # React context
├── hooks/
│   ├── useChat.ts             # Chat state management
│   └── useVisualization.ts    # Chart utilities
├── theme/
│   └── theme.css              # CSS variables & styles
└── index.ts                   # Public API exports
```

### Chart Type Inference

The SDK automatically determines the best chart type based on data structure:

| Data Pattern | Chart Type |
|--------------|-----------|
| Temporal field + numeric | Line/Area Chart |
| Categorical + numeric | Bar Chart |
| Single categorical + numeric (≤6 categories) | Pie Chart |
| Multiple numeric fields | Scatter Plot |
| Single numeric field | Histogram |
| Complex/unclear | Table |

---

## 8. Example Queries (Demo)

The demo includes a mock backend that responds to various queries:

- "Show income tax returns for 2024-2025" → Time series line chart
- "Display tax revenue by province" → Bar chart
- "Show filing status breakdown" → Pie chart
- "Compare tax collections by quarter" → Grouped bar chart
- "Show income distribution by tax bracket" → Bar/histogram

---

## 9. Tech Stack

| Layer | Technology | Purpose |
|-------|------------|----------|
| Framework | React 18 + TypeScript | Core SDK |
| Styling | TailwindCSS | Theming and responsiveness |
| Charts | Recharts | Visualization engine |
| Build System | Vite + Rollup | Bundling (ESM + CJS) |
| Distribution | NPM Package | Deployment & consumption |

---

## 10. Roadmap

### Current (v0.1.0 - MVP)
- ✅ Chat interface with streaming
- ✅ Auto-visualization (Line, Bar, Pie, Area, Scatter)
- ✅ Schema-agnostic data handling
- ✅ Theme customization
- ✅ Mock backend for testing

### Next (v0.2.0)
- [ ] Real backend integration
- [ ] PolyAuth authentication
- [ ] Message persistence
- [ ] Export/download functionality
- [ ] Advanced chart options
- [ ] Markdown support in messages

### Future (v0.3.0+)
- [ ] Web component wrapper
- [ ] Chart editing/customization UI
- [ ] Multi-language support
- [ ] Voice input
- [ ] Chart annotations

---

## 11. Contributing

This SDK is part of the PolyX ecosystem. For development:

1. Clone the repository
2. Run `npm install`
3. Make your changes
4. Test with `npm run dev`
5. Build with `npm run build`

---

## 12. License

MIT

---

## 13. Support

For issues and questions:
- GitHub Issues: [Repository URL]
- Documentation: [Docs URL]
- Email: support@polyx.com