# Client SDK Documentation

The `@analytics/client` package provides browser and server-side analytics tracking.

## Installation

```bash
npm install @analytics/client
# or
yarn add @analytics/client
# or
bun add @analytics/client
```

## Quick Start

### Browser (Vanilla JavaScript)

```typescript
import { AnalyticsClient } from '@analytics/client';

const analytics = new AnalyticsClient({
  apiBaseUrl: 'https://analytics.example.com',
  appName: 'my-app',
});

// Track a page view
analytics.trackEngagement({
  type: 'navigation',
  action: 'page_view',
  metadata: { path: window.location.pathname },
});

// Track a custom event
analytics.trackEngagement({
  type: 'user_action',
  action: 'button_click',
  metadata: { buttonId: 'signup-cta' },
});

// Identify a user
analytics.identify('user-123', {
  email: 'user@example.com',
  plan: 'pro',
});
```

### Server-Side (Node.js)

```typescript
import { BackendAnalyticsClient } from '@analytics/client';

const analytics = new BackendAnalyticsClient({
  apiBaseUrl: 'http://analytics-collector:4001',
  appName: 'my-api',
});

// Track from server
analytics.trackEngagement({
  sessionId: req.headers['x-session-id'] || 'server',
  userId: req.user?.id,
  type: 'api_request',
  action: 'GET /users',
  metadata: {
    statusCode: 200,
    durationMs: 45,
  },
});
```

## Configuration

### AnalyticsConfig

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `apiBaseUrl` | `string` | required | Analytics collector URL |
| `appName` | `string` | required | Application identifier |
| `enabled` | `boolean` | `true` | Enable/disable tracking |
| `enableDebugLogging` | `boolean` | `false` | Log tracking calls |
| `batchSize` | `number` | `10` | Events per batch |
| `flushInterval` | `number` | `5000` | Batch flush interval (ms) |
| `autoCapture` | `object` | see below | Auto-capture settings |

### Auto-Capture Settings

```typescript
{
  autoCapture: {
    pageViews: true,      // Track page navigation
    clicks: true,         // Track click events
    scrollDepth: true,    // Track scroll percentage
    performance: true,    // Track Core Web Vitals
    errors: false,        // Track JavaScript errors
  }
}
```

## Core Methods

### trackEngagement()

Track user interactions and events.

```typescript
analytics.trackEngagement({
  type: string,           // Event category
  action: string,         // Event name
  metadata?: object,      // Additional data
  sessionId?: string,     // Override session ID
  userId?: string,        // User identifier
});
```

### identify()

Associate a user ID with the current session.

```typescript
analytics.identify(userId: string, traits?: object);
```

### setUserId() / clearUserId()

Manage user identity.

```typescript
analytics.setUserId('user-123');
analytics.clearUserId();
```

### flush()

Force send queued events immediately.

```typescript
await analytics.flush();
```

## Event Types

### Navigation Events

```typescript
// Page view
analytics.trackEngagement({
  type: 'navigation',
  action: 'page_view',
  metadata: {
    path: '/products',
    title: 'Products Page',
    referrer: document.referrer,
  },
});

// Route change (SPA)
analytics.trackEngagement({
  type: 'navigation',
  action: 'route_change',
  metadata: {
    from: '/home',
    to: '/products',
  },
});
```

### User Actions

```typescript
// Button click
analytics.trackEngagement({
  type: 'click',
  action: 'cta_button',
  metadata: {
    buttonText: 'Get Started',
    location: 'hero',
  },
});

// Form submission
analytics.trackEngagement({
  type: 'form',
  action: 'submit',
  metadata: {
    formName: 'contact',
    success: true,
  },
});
```

### E-commerce Events

```typescript
// Product view
analytics.trackEngagement({
  type: 'ecommerce',
  action: 'product_view',
  metadata: {
    productId: 'prod-123',
    productName: 'Blue Widget',
    price: 29.99,
  },
});

// Purchase
analytics.trackEngagement({
  type: 'ecommerce',
  action: 'purchase',
  metadata: {
    orderId: 'ord-456',
    total: 99.99,
    currency: 'USD',
    isConversion: true,
    conversionValue: 99.99,
  },
});
```

## Consent-Free Mode

The SDK uses in-memory session IDs by default, requiring no cookies or localStorage:

- Session IDs generated per page load
- No persistent storage used
- UTM parameters captured from URL only
- GDPR/ePrivacy compliant without consent banners

## Device Information

Automatically captured (no storage required):
- Screen resolution
- Viewport size
- Device type (mobile/tablet/desktop)
- Browser name and version
- Operating system
- Language preference
- Timezone

## Error Handling

The SDK silently handles errors to never break your application:

```typescript
// All tracking calls are fire-and-forget
analytics.trackEngagement({...}); // Never throws

// Enable debug logging to see issues
const analytics = new AnalyticsClient({
  apiBaseUrl: '...',
  appName: '...',
  enableDebugLogging: true, // Logs to console
});
```

## TypeScript Support

Full TypeScript support with exported types:

```typescript
import type {
  AnalyticsConfig,
  EngagementEvent,
  DeviceInfo,
  AttributionData,
} from '@analytics/client';
```
