# @bytelyst/broadcast-client

TypeScript client for the ByteLyst Broadcast & Messaging platform. Provides in-app message polling, read receipts, and push notification token management.

## Installation

```bash
npm install @bytelyst/broadcast-client
# or
pnpm add @bytelyst/broadcast-client
```

## Quick Start

```typescript
import { createBroadcastClient } from '@bytelyst/broadcast-client';

const client = createBroadcastClient({
  baseURL: 'https://api.bytelyst.io/v1',
  productId: 'lysnrai',
  getAuthToken: async () => {
    // Return your JWT token
    return localStorage.getItem('token');
  }
});

// Start polling for messages (every 60 seconds)
client.startPolling(60000, (messages) => {
  console.log('New messages:', messages);
});
```

## API Reference

### `createBroadcastClient(config)`

Creates a new broadcast client instance.

**Config:**
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `baseURL` | string | Yes | API base URL |
| `productId` | string | Yes | Product identifier |
| `getAuthToken` | () => Promise<string> | Yes | Function to retrieve JWT token |

### Methods

#### `getMessages()`
Fetch active in-app messages for the current user.

```typescript
const { data, error } = await client.getMessages();
// Returns: { messages: InAppMessage[] }
```

#### `markRead(messageId: string)`
Mark a message as read.

```typescript
await client.markRead('msg_123');
```

#### `markDismissed(messageId: string)`
Dismiss a message.

```typescript
await client.markDismissed('msg_123');
```

#### `trackClick(messageId: string)`
Track when user clicks/taps a message CTA.

```typescript
await client.trackClick('msg_123');
```

#### `startPolling(intervalMs: number, callback: (messages) => void)`
Start polling for new messages.

```typescript
client.startPolling(60000, (messages) => {
  // Called every 60 seconds with current messages
});
```

#### `stopPolling()`
Stop message polling.

```typescript
client.stopPolling();
```

#### `registerDeviceToken(token: string, platform: 'ios' | 'android' | 'web')`
Register push notification device token.

```typescript
await client.registerDeviceToken('fcm_token_xyz', 'android');
```

#### `unregisterDeviceToken(token: string)`
Unregister device token (e.g., on logout).

```typescript
await client.unregisterDeviceToken('fcm_token_xyz');
```

## React Integration

### Hook Usage

```typescript
import { useBroadcastClient } from './hooks/useBroadcastClient';

function App() {
  const { messages, unreadCount, markRead, markDismissed } = useBroadcastClient({
    pollingInterval: 60000
  });

  return (
    <div>
      {messages.map(msg => (
        <Banner
          key={msg.id}
          title={msg.title}
          body={msg.body}
          onDismiss={() => markDismissed(msg.id)}
          onClick={() => markRead(msg.id)}
        />
      ))}
    </div>
  );
}
```

### Provider Pattern

```typescript
// BroadcastProvider.tsx
import { createContext, useContext, useEffect, useState } from 'react';
import { createBroadcastClient, BroadcastClient, InAppMessage } from '@bytelyst/broadcast-client';

const BroadcastContext = createContext<BroadcastContextType | null>(null);

export function BroadcastProvider({ children, config }: { children: React.ReactNode; config: BroadcastConfig }) {
  const [client] = useState(() => createBroadcastClient(config));
  const [messages, setMessages] = useState<InAppMessage[]>([]);

  useEffect(() => {
    client.startPolling(60000, setMessages);
    return () => client.stopPolling();
  }, [client]);

  const value = {
    messages,
    unreadCount: messages.filter(m => m.status === 'unread').length,
    markRead: client.markRead.bind(client),
    markDismissed: client.markDismissed.bind(client),
    trackClick: client.trackClick.bind(client),
  };

  return (
    <BroadcastContext.Provider value={value}>
      {children}
    </BroadcastContext.Provider>
  );
}

export const useBroadcast = () => {
  const ctx = useContext(BroadcastContext);
  if (!ctx) throw new Error('useBroadcast must be used within BroadcastProvider');
  return ctx;
};
```

## Types

```typescript
interface InAppMessage {
  id: string;
  broadcastId: string;
  title: string;
  body?: string;
  style: 'banner' | 'modal' | 'fullscreen' | 'toast';
  priority: 'low' | 'normal' | 'high' | 'urgent';
  ctaText?: string;
  ctaUrl?: string;
  imageUrl?: string;
  deepLink?: {
    screen: string;
    params: Record<string, string>;
  };
  status: 'unread' | 'read' | 'dismissed';
  createdAt: string;
}

interface BroadcastConfig {
  baseURL: string;
  productId: string;
  getAuthToken: () => Promise<string>;
}
```

## Error Handling

All methods return a result tuple `[data, error]`:

```typescript
const [data, error] = await client.getMessages();

if (error) {
  console.error('Failed to fetch messages:', error.message);
  return;
}

// Use data.messages
```

## Browser Support

- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+

## License

MIT © ByteLyst
