# ConversionIQ JavaScript SDK

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Bundle Size](https://img.shields.io/badge/minimal-1.0%20KB-brightgreen.svg)](https://bundlephobia.com/package/@conversioniq/sdk)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)

> **Behavioral psychology platform that detects visitor frustration, predicts abandonment, and helps you save at-risk conversions in real-time.**

Stop guessing why visitors leave. Know in real-time.

## 🎯 What Makes ConversionIQ Different

Unlike traditional analytics that tell you *what* happened after visitors leave, ConversionIQ detects *how* users are feeling while they're still on your site - giving you the chance to intervene before they abandon.

### Real-Time Behavioral Intelligence
- **Detect frustrated visitors** - Rage clicks, hesitation patterns, form anxiety
- **Calculate abandonment risk** - Real-time psychology scoring (0-100)
- **Get actionable alerts** - Know when high-value sessions are at risk

### Explainable Psychology Metrics
- **"4 rage clicks detected"** not "78.4% ML prediction"
- **Understand why** scores change with transparent metrics
- **Trust insights** you can explain to your team

### Privacy-First by Design
- **No session recording** or screen capture
- **Client-side analysis** - behavioral signals, not sensitive data
- **GDPR/CCPA compliant** - collect patterns, not PII

## 🧠 Core Capabilities

### 1. Micro-Interaction Detection
Track **HOW** users interact with your site, not just what they click:

```javascript
// Automatically detects:
// - Rage clicks (frustrated rapid clicking on non-responsive elements)
// - Hesitation duration (hovering 3+ seconds before acting)
// - Form anxiety (excessive backspaces, slow fill speed)
// - Error encounters (form validation failures, broken elements)
// - Cursor distance (erratic movements indicating confusion)
```

### 2. Session Psychology Profiling
Real-time behavioral analysis generates actionable scores:

```javascript
{
  frustrationScore: 0.85,      // High frustration (rage clicks, errors)
  confidenceScore: 0.32,       // Low confidence (hesitation, backspaces)
  engagementScore: 0.61,       // Moderate engagement (scroll patterns)
  abandonmentRisk: 0.78,       // 78% likely to abandon
  conversionProbability: 0.15  // 15% likely to convert
}
```

### 3. Real-Time Abandonment Alerts
Get notified when sessions need intervention:

```javascript
{
  alertType: 'frustration',
  riskScore: 0.85,
  triggerReason: '4 rage clicks, 3 errors encountered, high hesitation',
  suggestedIntervention: 'Show live chat offer',
  pageUrl: '/checkout',
  sessionId: 'session-123'
}
```

## 🚀 Quick Start (5 minutes)

### Installation

```bash
npm install @conversioniq/sdk
```

### Basic Setup

```html
<!-- Option 1: Direct script tag (minimal version - 1.0 KB gzipped) -->
<script src="https://cdn.conversioniq.com/sdk/conversioniq-minimal.min.js"
        data-api-key="your-api-key"
        data-website-id="your-website-id"></script>

<!-- Option 2: NPM/ES modules -->
<script type="module">
  import ConversionIQ from '@conversioniq/sdk/minimal';

  const ciq = new ConversionIQ({
    apiKey: 'your-api-key',
    websiteId: 'your-website-id'
  });

  // Page views and conversions tracked automatically
  // Micro-interactions detected automatically

  // Optional: Track custom events
  ciq.track('custom_event', { key: 'value' });
</script>
```

### Advanced Setup with Psychology Features

```javascript
import ConversionIQ from '@conversioniq/sdk';
import { MicroInteractionTracking } from '@conversioniq/sdk/features/MicroInteractionTracking';

const ciq = new ConversionIQ({
  apiKey: 'your-api-key',
  websiteId: 'your-website-id',

  // Enable behavioral psychology features
  enableMicroInteractions: true,
  batchInterval: 5000, // Send behavioral data every 5 seconds

  // Privacy settings
  enablePrivacyMode: true
});

// Initialize micro-interaction tracking
const microTracking = new MicroInteractionTracking(ciq);
microTracking.start({
  trackRageClicks: true,
  trackHesitation: true,
  trackFormAnxiety: true,
  trackScrollPatterns: true
});
```

## 📦 Bundle Options & Tree-Shaking

ConversionIQ offers multiple bundle options optimized for different use cases:

| Bundle | Size (Gzipped) | Features | Best For |
|--------|----------------|----------|----------|
| **Minimal** | 1.0 KB | Core tracking only | Basic event tracking |
| **Core** | 14.2 KB | Full SDK with behavioral features | Most applications |
| **Full** | 14.2 KB | All features pre-loaded | Feature-rich apps |
| **Micro-Interactions** | 10.8 KB | Psychology tracking module | E-commerce, SaaS |

### Tree-Shaking Examples

```javascript
// Import only what you need
import { MinimalConversionIQ } from '@conversioniq/sdk/minimal';
import { MicroInteractionTracking } from '@conversioniq/sdk/features/MicroInteractionTracking';

// Or use dynamic imports for code splitting
const loadPsychologyFeatures = async () => {
  const { MicroInteractionTracking } = await import('@conversioniq/sdk/features/MicroInteractionTracking');
  return new MicroInteractionTracking(config);
};
```

## 🎯 Framework Integration

### React

```jsx
// hooks/useConversionIQ.js
import { useEffect, useRef } from 'react';
import ConversionIQ from '@conversioniq/sdk';

export function useConversionIQ(config) {
  const sdk = useRef(null);

  useEffect(() => {
    sdk.current = new ConversionIQ({
      ...config,
      enableMicroInteractions: true // Enable behavioral psychology
    });

    return () => {
      // Cleanup if needed
    };
  }, [config]);

  return {
    track: (event, data) => sdk.current?.track(event, data),
    trackConversion: (value, currency, metadata) =>
      sdk.current?.trackConversion(value, currency, metadata)
  };
}

// Component usage
function CheckoutPage() {
  const { trackConversion } = useConversionIQ({
    apiKey: process.env.REACT_APP_CONVERSION_IQ_API_KEY,
    websiteId: process.env.REACT_APP_CONVERSION_IQ_WEBSITE_ID
  });

  const handlePurchase = async (orderData) => {
    // Process payment...

    // Track conversion
    await trackConversion(orderData.total, 'USD', {
      orderId: orderData.id,
      items: orderData.items
    });
  };

  return (
    <button onClick={() => handlePurchase(order)}>
      Complete Purchase
    </button>
  );
}
```

### Vue 3 (Composition API)

```javascript
// composables/useConversionIQ.js
import { ref, onMounted } from 'vue';
import ConversionIQ from '@conversioniq/sdk';

export function useConversionIQ(config) {
  const sdk = ref(null);

  onMounted(() => {
    sdk.value = new ConversionIQ({
      ...config,
      enableMicroInteractions: true
    });
  });

  const track = (event, data) => sdk.value?.track(event, data);
  const trackConversion = (value, currency = 'USD', metadata = {}) => {
    sdk.value?.trackConversion(value, currency, metadata);
  };

  return { track, trackConversion };
}
```

### Next.js

```javascript
// lib/conversioniq.js
import ConversionIQ from '@conversioniq/sdk';

let sdk = null;

export function initConversionIQ() {
  if (typeof window !== 'undefined' && !sdk) {
    sdk = new ConversionIQ({
      apiKey: process.env.NEXT_PUBLIC_CONVERSION_IQ_API_KEY,
      websiteId: process.env.NEXT_PUBLIC_CONVERSION_IQ_WEBSITE_ID,
      enableMicroInteractions: true, // Enable behavioral psychology
      debug: process.env.NODE_ENV === 'development'
    });
  }
  return sdk;
}

// pages/_app.js
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { initConversionIQ } from '../lib/conversioniq';

export default function App({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    const ciq = initConversionIQ();

    const handleRouteChange = () => {
      ciq?.trackPageView();
    };

    router.events.on('routeChangeComplete', handleRouteChange);
    handleRouteChange(); // Track initial page view

    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

  return <Component {...pageProps} />;
}
```

## 🧪 Real-World Use Cases

### E-commerce: Reduce Cart Abandonment

```javascript
import ConversionIQ from '@conversioniq/sdk';
import { MicroInteractionTracking } from '@conversioniq/sdk/features/MicroInteractionTracking';

const ciq = new ConversionIQ({
  apiKey: 'your-api-key',
  websiteId: 'your-website-id',
  enableMicroInteractions: true
});

const microTracking = new MicroInteractionTracking(ciq);

// Start tracking checkout behavior
microTracking.start();

// Listen for high-risk abandonment alerts
microTracking.on('abandonmentRisk', (alert) => {
  if (alert.riskScore > 0.7 && alert.pageUrl.includes('/checkout')) {
    // Show intervention
    showExitIntentPopup({
      message: 'Having trouble? Chat with us!',
      offer: '10% off if you complete your order now'
    });
  }
});
```

### SaaS: Improve Onboarding Completion

```javascript
// Detect users struggling with onboarding
microTracking.on('frustrationDetected', (session) => {
  if (session.frustrationScore > 0.8 && isOnboardingPage()) {
    // Trigger helpful intervention
    showContextualHelp({
      message: 'Need help getting started?',
      action: 'Schedule 15-min onboarding call'
    });
  }
});
```

### B2B: Save High-Value Leads

```javascript
// Track form hesitation on demo request
microTracking.on('formAnxiety', (data) => {
  if (data.backspaceCount > 5 && data.hesitationDuration > 3000) {
    // Reduce form friction
    showInlineChatAssist({
      message: 'Questions about the demo? Ask away!'
    });
  }
});
```

## 📊 Understanding Psychology Metrics

### Frustration Score (0-100)
Indicates user frustration based on:
- **Rage clicks**: Rapid repeated clicks on non-responsive elements
- **Error encounters**: Form validation failures, broken interactions
- **Excessive hesitation**: Long delays before actions
- **High backspace count**: Repeated corrections in forms

**Interpretation:**
- 0-30: Low frustration (normal behavior)
- 30-60: Moderate friction (watch closely)
- 60-100: High frustration (intervention recommended)

### Confidence Score (0-100)
Indicates user confidence based on:
- **Click speed**: Fast, decisive clicks vs. hesitant hovering
- **Form fill patterns**: Smooth entry vs. corrections
- **Navigation certainty**: Direct paths vs. backtracking
- **Error recovery**: Quick fixes vs. abandonment

**Interpretation:**
- 70-100: High confidence (likely to convert)
- 40-70: Moderate confidence (needs support)
- 0-40: Low confidence (high risk)

### Abandonment Risk (0-1 probability)
Predictive score based on:
- Frustration score > 70
- Confidence score < 30
- Multiple error encounters
- Extended hesitation on key actions
- Exit-intent signals

**Intervention Thresholds:**
- 0.0-0.3: Low risk (monitor)
- 0.3-0.7: Medium risk (prepare intervention)
- 0.7-1.0: High risk (intervene immediately)

## 🔧 Advanced Configuration

```javascript
import ConversionIQ from '@conversioniq/sdk';

const sdk = new ConversionIQ({
  // Required
  apiKey: 'your-api-key',
  websiteId: 'your-website-id',

  // Behavioral Psychology Features
  enableMicroInteractions: true,

  // Batching & Performance
  batchSize: 10,           // Events per batch
  batchInterval: 5000,     // Send behavioral data every 5s
  timeout: 5000,           // Request timeout (ms)

  // Privacy & Compliance
  enablePrivacyMode: true, // GDPR/CCPA compliance

  // Retry configuration
  retry: {
    maxAttempts: 3,
    baseDelay: 1000,
    maxDelay: 10000
  },

  // Debugging
  debug: false
});
```

## 🛡️ Privacy & GDPR Compliance

ConversionIQ is **privacy-first by design**:

### What We DON'T Collect
- ❌ No session recordings or screen captures
- ❌ No personally identifiable information (PII)
- ❌ No form field values or sensitive data
- ❌ No full-page screenshots

### What We DO Collect
- ✅ Behavioral signals (click patterns, scroll speed)
- ✅ Element selectors (which button, not what's in it)
- ✅ Interaction timing (hesitation, rage clicks)
- ✅ Psychology scores (calculated client-side)

### Privacy Controls

```javascript
// Check privacy status
const privacyStatus = sdk.getPrivacyStatus();
console.log(privacyStatus); // { analytics: false, microInteractions: true }

// Update consent
sdk.updatePrivacyConsent({
  essential: true,         // Always required
  analytics: true,         // Usage analytics
  microInteractions: true  // Behavioral psychology
});

// Conditional tracking based on consent
if (privacyStatus.microInteractions) {
  microTracking.start();
}
```

## 🆚 How ConversionIQ Compares

### vs. Google Analytics
**Google Analytics** tells you *what* happened after visitors leave.
**ConversionIQ** tells you *why* they're leaving and alerts you in real-time.

**Use together:** GA for traffic analytics, ConversionIQ for behavioral insights.

### vs. Hotjar / Crazy Egg
**Hotjar** shows *where* users click with heatmaps and session recordings.
**ConversionIQ** shows *how* they're feeling without privacy-invasive recordings.

**The difference:** Psychology signals vs. video surveillance.

### vs. FullStory / LogRocket
**FullStory** records everything for debugging.
**ConversionIQ** detects what matters without storing sensitive data.

**The difference:** Behavioral intelligence, not session replay.

### vs. Heap / Amplitude
**Heap** tracks feature usage and product analytics.
**ConversionIQ** detects emotional state and abandonment risk.

**The difference:** Product analytics vs. behavioral psychology.

## 🚨 Error Handling & Debugging

```javascript
// Enable debug mode
const sdk = new ConversionIQ({
  apiKey: 'your-api-key',
  websiteId: 'your-website-id',
  debug: true // Logs all SDK activity
});

// Handle errors gracefully
sdk.track('purchase', purchaseData).catch(error => {
  console.warn('ConversionIQ tracking failed:', error);
  // Continue with user flow - never block conversions
});

// Check SDK health
if (window.ConversionIQ) {
  console.log('ConversionIQ SDK loaded');
  console.log('Config:', window.ConversionIQ.config);
}
```

## 📝 TypeScript Support

```typescript
import ConversionIQ, {
  ConversionIQConfig,
  MicroInteractionEvent,
  SessionPsychologyProfile,
  AbandonmentAlert
} from '@conversioniq/sdk';

const config: ConversionIQConfig = {
  apiKey: 'your-api-key',
  websiteId: 'your-website-id',
  enableMicroInteractions: true
};

const sdk = new ConversionIQ(config);

// Type-safe event tracking
const eventData: MicroInteractionEvent = {
  type: 'rage_click',
  elementSelector: 'button#checkout',
  clickCount: 5,
  timestamp: Date.now()
};

sdk.track('micro_interaction', eventData);
```

## 📈 Performance Best Practices

### 1. Use the Right Bundle
- **Minimal** (1.0 KB): Basic tracking only
- **Core** (14.2 KB): Full SDK with behavioral features
- **Micro-Interactions** (10.8 KB): Psychology module only

### 2. Batch Behavioral Data
```javascript
const sdk = new ConversionIQ({
  apiKey: 'your-api-key',
  websiteId: 'your-website-id',
  batchSize: 10,        // Send 10 events at once
  batchInterval: 5000   // Or every 5 seconds
});
```

### 3. Lazy Load Advanced Features
```javascript
// Load psychology features only on key pages
if (isCheckoutPage()) {
  const { MicroInteractionTracking } = await import('@conversioniq/sdk/features/MicroInteractionTracking');
  const tracker = new MicroInteractionTracking(config);
  tracker.start();
}
```

## 🧪 Testing

### Unit Testing

```javascript
import ConversionIQ from '@conversioniq/sdk/minimal';

global.fetch = jest.fn();

describe('ConversionIQ SDK', () => {
  let sdk;

  beforeEach(() => {
    fetch.mockClear();
    sdk = new ConversionIQ({
      apiKey: 'test-key',
      websiteId: 'test-site'
    });
  });

  test('tracks micro-interactions with correct payload', async () => {
    fetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({ success: true })
    });

    await sdk.track('rage_click', {
      elementSelector: 'button#submit',
      clickCount: 5
    });

    expect(fetch).toHaveBeenCalledWith(
      expect.stringContaining('/micro-interactions'),
      expect.objectContaining({
        method: 'POST'
      })
    );
  });
});
```

## 🛠️ Troubleshooting

### Events not tracking
```javascript
// Check configuration
console.log('SDK Config:', sdk.config);

// Enable debug mode
const sdk = new ConversionIQ({
  apiKey: 'your-api-key',
  websiteId: 'your-website-id',
  debug: true // This will log all SDK activity
});

// Verify network requests in DevTools > Network tab
```

### Micro-interactions not detected
```javascript
// Ensure feature is enabled
const sdk = new ConversionIQ({
  apiKey: 'your-api-key',
  websiteId: 'your-website-id',
  enableMicroInteractions: true // Must be true
});

// Verify module is loaded
import { MicroInteractionTracking } from '@conversioniq/sdk/features/MicroInteractionTracking';
const tracker = new MicroInteractionTracking(sdk);
tracker.start(); // Must call start()
```

## 📚 API Reference

### Core Methods

#### `new ConversionIQ(config)`
Creates a new SDK instance with behavioral psychology features.

**Parameters:**
- `config.apiKey` (string, required): Your ConversionIQ API key
- `config.websiteId` (string, required): Your website ID
- `config.enableMicroInteractions` (boolean): Enable behavioral psychology (default: false)
- `config.batchInterval` (number): Batch send interval in ms (default: 5000)

#### `track(eventType, data)`
Track custom events or micro-interactions.

**Returns:** Promise<void>

#### `trackConversion(value, currency, metadata)`
Track conversion events with value.

**Returns:** Promise<void>

#### `updatePrivacyConsent(consents)`
Update privacy consent for behavioral tracking.

**Parameters:**
- `consents.microInteractions` (boolean): Allow micro-interaction tracking

For complete API documentation, visit [docs.conversioniq.com](https://docs.conversioniq.com).

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## 📄 License

MIT License. See [LICENSE](LICENSE) for details.

## 🆘 Support

- 📧 Email: support@conversioniq.com
- 💬 Community: [ConversionIQ Community](https://community.conversioniq.com)
- 📖 Documentation: [docs.conversioniq.com](https://docs.conversioniq.com)
- 🐛 Issues: [GitHub Issues](https://github.com/conversioniq/sdk/issues)

---

**Built with behavioral psychology by the ConversionIQ Team**
