# Analytics Events System

Comprehensive event tracking system for Mawidi platform with 36+ custom events across 7 categories.

## Overview

This analytics system provides:

- **36+ custom events** tracking key user actions
- **7 event categories** for organized analysis
- **Dual integration** with PostHog and Google Analytics
- **Privacy-friendly** session tracking
- **Server and client-side** tracking support
- **Conversion funnel** analysis

## Event Categories

### 1. CTA Events (7 events)

Track call-to-action interactions:

- `cta_demo_booking_started` - User opens demo booking form
- `cta_demo_booking_completed` - Demo booking successfully submitted
- `cta_contact_form_opened` - Contact form modal/page opened
- `cta_contact_form_submitted` - Contact form successfully submitted
- `cta_pricing_viewed` - Pricing page viewed
- `cta_pricing_plan_selected` - Specific pricing plan selected
- `cta_free_trial_clicked` - Free trial CTA clicked

### 2. Feature Usage Events (8 events)

Track product feature engagement:

- `feature_dashboard_viewed` - Dashboard page visited
- `feature_appointment_created` - New appointment booked
- `feature_appointment_cancelled` - Appointment cancelled
- `feature_billing_viewed` - Billing/subscription page viewed
- `feature_subscription_upgraded` - Subscription plan upgraded
- `feature_subscription_cancelled` - Subscription cancelled
- `feature_settings_updated` - User settings modified
- `feature_team_member_invited` - Team invitation sent

### 3. User Journey Events (6 events)

Track authentication and onboarding:

- `user_signup_started` - Signup form opened/started
- `user_signup_completed` - Account successfully created
- `user_login_success` - Successful login
- `user_login_failed` - Failed login attempt
- `user_logout` - User logged out
- `user_onboarding_completed` - Onboarding flow finished

### 4. Error Events (5 events)

Track errors and issues:

- `error_form_validation` - Form validation failed
- `error_api_request` - API request failed
- `error_payment_failed` - Payment processing failed
- `error_page_not_found` - 404 error encountered
- `error_session_expired` - Session timeout

### 5. Engagement Events (5 events)

Track content engagement:

- `engagement_video_played` - Video content started
- `engagement_resource_downloaded` - Resource (PDF, etc.) downloaded
- `engagement_case_study_viewed` - Case study page viewed
- `engagement_faq_expanded` - FAQ item expanded
- `engagement_chatbot_opened` - Chatbot/support widget opened

### 6. Conversion Events (3 events)

Track conversion funnel:

- `conversion_lead_captured` - Lead form submitted
- `conversion_trial_started` - Free trial activated
- `conversion_paid_customer` - First payment completed

### 7. Navigation Events (2 events)

Track navigation patterns:

- `navigation_page_view` - Page viewed
- `navigation_external_link_clicked` - External link clicked

## Usage

### Server-Side Tracking

```typescript
import {
  trackDemoBookingCompleted,
  trackSignupCompleted,
  trackPaidCustomer,
} from "@/lib/analytics/events";

// Track demo booking
await trackDemoBookingCompleted({
  userId: "user_123",
  language: "en",
  ctaLocation: "pricing_page",
});

// Track signup
await trackSignupCompleted("user_123", {
  source: "google",
  campaign: "summer_2024",
});

// Track conversion
await trackPaidCustomer("user_123", 299.0, {
  planName: "Professional",
  billingPeriod: "monthly",
});
```

### Client-Side Tracking

```typescript
"use client";

import {
  trackPricingPlanSelected,
  trackContactFormOpened,
  trackVideoPlayed,
} from "@/lib/analytics/client";

// Track pricing interaction
function handlePlanSelect(plan: string, price: number) {
  trackPricingPlanSelected(plan, price, {
    ctaLocation: "pricing_page",
  });
}

// Track form interaction
function openContactForm() {
  trackContactFormOpened({
    ctaLocation: "hero_section",
  });
}

// Track video engagement
function handleVideoPlay(videoId: string) {
  trackVideoPlayed(videoId, {
    videoTitle: "Product Demo",
    videoDuration: 120,
  });
}
```

### React Component Example

```typescript
'use client';

import { useEffect } from 'react';
import { trackPageView } from '@/lib/analytics/client';

export default function PricingPage() {
  useEffect(() => {
    trackPageView('/pricing');
  }, []);

  return <div>Pricing content...</div>;
}
```

## Event Properties

All events support these common properties:

| Property    | Type         | Description                 |
| ----------- | ------------ | --------------------------- |
| `userId`    | string       | User ID (if authenticated)  |
| `sessionId` | string       | Browser session ID          |
| `page`      | string       | Current page path           |
| `language`  | 'en' \| 'ar' | User's language             |
| `source`    | string       | Traffic source (utm_source) |
| `medium`    | string       | Traffic medium (utm_medium) |
| `campaign`  | string       | Campaign ID (utm_campaign)  |

Event-specific properties:

| Event Category    | Additional Properties                                   |
| ----------------- | ------------------------------------------------------- |
| CTA Events        | `ctaType`, `ctaLocation`, `formName`                    |
| Feature Events    | `featureName`, `actionType`, `resourceType`             |
| Error Events      | `errorMessage`, `errorCode`, `stackTrace`               |
| Engagement Events | `videoId`, `videoDuration`, `resourceId`, `caseStudyId` |
| Conversion Events | `value`, `planName`, `planPrice`                        |

## API Endpoint

Events from client-side are sent to:

```
POST /api/analytics/events
```

Request body:

```json
{
  "eventName": "cta_demo_booking_completed",
  "category": "cta",
  "properties": {
    "userId": "user_123",
    "ctaLocation": "hero_section",
    "language": "en"
  }
}
```

Rate limited to **100 events per minute** per IP address.

## Analytics Queries

### Get Event Counts by Category

```typescript
import { getEventCountByCategory } from "@/lib/analytics/events";

const startDate = new Date("2024-01-01");
const endDate = new Date("2024-01-31");

const counts = await getEventCountByCategory(startDate, endDate);
// { cta: 150, feature_usage: 420, engagement: 230, ... }
```

### Get Top Events

```typescript
import { getTopEvents } from "@/lib/analytics/events";

const topEvents = await getTopEvents(10);
// [
//   { eventName: 'navigation_page_view', count: 15234 },
//   { eventName: 'feature_dashboard_viewed', count: 3421 },
//   ...
// ]
```

### Get Conversion Funnel

```typescript
import { getConversionFunnel } from "@/lib/analytics/events";

const funnel = await getConversionFunnel(startDate, endDate);
// {
//   signupStarted: 500,
//   signupCompleted: 350,
//   trialStarted: 200,
//   paidCustomer: 75,
//   conversionRates: {
//     signupToTrial: 57.14,
//     trialToPaid: 37.50,
//     overallConversion: 15.00
//   }
// }
```

## Database Schema

```sql
CREATE TABLE analytics_events (
  id VARCHAR PRIMARY KEY,
  eventName VARCHAR NOT NULL,
  category VARCHAR NOT NULL,
  properties JSON,
  userId VARCHAR,
  sessionId VARCHAR,
  page VARCHAR,
  createdAt TIMESTAMP DEFAULT NOW()
);

CREATE INDEX idx_analytics_events_name ON analytics_events(eventName);
CREATE INDEX idx_analytics_events_category ON analytics_events(category);
CREATE INDEX idx_analytics_events_user ON analytics_events(userId);
CREATE INDEX idx_analytics_events_session ON analytics_events(sessionId);
CREATE INDEX idx_analytics_events_created ON analytics_events(createdAt);
```

## Integration with PostHog

Events are automatically sent to PostHog if configured:

```typescript
// Client-side PostHog integration
if (window.posthog) {
  window.posthog.capture(eventName, {
    category,
    ...properties,
  });
}
```

## Integration with Google Analytics

Events are automatically sent to GA4 if configured:

```typescript
// Client-side GA4 integration
if (window.gtag) {
  window.gtag("event", eventName, {
    event_category: category,
    ...properties,
  });
}
```

## Best Practices

### 1. Always Include Context

```typescript
// Good - includes context
trackContactFormSubmitted({
  ctaLocation: "pricing_page",
  formName: "enterprise_inquiry",
  language: "en",
});

// Bad - no context
trackContactFormSubmitted();
```

### 2. Track Conversion Value

```typescript
// Good - includes monetary value
trackPaidCustomer("user_123", 299.0, {
  planName: "Professional",
  billingPeriod: "monthly",
});

// Bad - missing value
trackPaidCustomer("user_123", 0);
```

### 3. Error Tracking with Details

```typescript
// Good - actionable error info
trackApiError("Failed to create appointment", "BOOKING_001", {
  endpoint: "/api/bookings",
  statusCode: 500,
});

// Bad - generic error
trackApiError("Error occurred");
```

### 4. Use Descriptive IDs

```typescript
// Good - descriptive IDs
trackVideoPlayed("product_demo_overview", {
  videoTitle: "Mawidi Platform Overview",
  videoDuration: 120,
});

// Bad - cryptic IDs
trackVideoPlayed("vid_123");
```

## Privacy & GDPR Compliance

- **No PII**: Never track email addresses, phone numbers, or names in event properties
- **Session IDs**: Hashed from IP + User Agent for privacy
- **User IDs**: Only for authenticated users (anonymous otherwise)
- **Data Retention**: Configure retention policies in PostHog/GA4
- **Opt-out**: Respect user tracking preferences

## Testing

```typescript
// In tests, events fail silently (console.error only)
import { trackDemoBookingCompleted } from "@/lib/analytics/events";

// Will log error but not throw
await trackDemoBookingCompleted({
  userId: "test_user",
});
```

## Monitoring

Check event tracking health:

```sql
-- Events in last 24 hours
SELECT category, COUNT(*)
FROM analytics_events
WHERE createdAt > NOW() - INTERVAL '24 hours'
GROUP BY category;

-- Most common events
SELECT eventName, COUNT(*) as count
FROM analytics_events
WHERE createdAt > NOW() - INTERVAL '7 days'
GROUP BY eventName
ORDER BY count DESC
LIMIT 20;

-- Error event trends
SELECT
  DATE(createdAt) as date,
  COUNT(*) as error_count
FROM analytics_events
WHERE category = 'error'
GROUP BY DATE(createdAt)
ORDER BY date DESC;
```

## Complete Event List (36 Events)

| #   | Event Name                         | Category     | Description              |
| --- | ---------------------------------- | ------------ | ------------------------ |
| 1   | `cta_demo_booking_started`         | CTA          | Demo booking form opened |
| 2   | `cta_demo_booking_completed`       | CTA          | Demo booking submitted   |
| 3   | `cta_contact_form_opened`          | CTA          | Contact form opened      |
| 4   | `cta_contact_form_submitted`       | CTA          | Contact form submitted   |
| 5   | `cta_pricing_viewed`               | CTA          | Pricing page viewed      |
| 6   | `cta_pricing_plan_selected`        | CTA          | Pricing plan selected    |
| 7   | `cta_free_trial_clicked`           | CTA          | Free trial CTA clicked   |
| 8   | `feature_dashboard_viewed`         | Feature      | Dashboard viewed         |
| 9   | `feature_appointment_created`      | Feature      | Appointment created      |
| 10  | `feature_appointment_cancelled`    | Feature      | Appointment cancelled    |
| 11  | `feature_billing_viewed`           | Feature      | Billing page viewed      |
| 12  | `feature_subscription_upgraded`    | Feature      | Subscription upgraded    |
| 13  | `feature_subscription_cancelled`   | Feature      | Subscription cancelled   |
| 14  | `feature_settings_updated`         | Feature      | Settings updated         |
| 15  | `feature_team_member_invited`      | Feature      | Team member invited      |
| 16  | `user_signup_started`              | User Journey | Signup started           |
| 17  | `user_signup_completed`            | User Journey | Signup completed         |
| 18  | `user_login_success`               | User Journey | Login successful         |
| 19  | `user_login_failed`                | User Journey | Login failed             |
| 20  | `user_logout`                      | User Journey | User logged out          |
| 21  | `user_onboarding_completed`        | User Journey | Onboarding completed     |
| 22  | `error_form_validation`            | Error        | Form validation error    |
| 23  | `error_api_request`                | Error        | API request error        |
| 24  | `error_payment_failed`             | Error        | Payment failed           |
| 25  | `error_page_not_found`             | Error        | 404 error                |
| 26  | `error_session_expired`            | Error        | Session expired          |
| 27  | `engagement_video_played`          | Engagement   | Video played             |
| 28  | `engagement_resource_downloaded`   | Engagement   | Resource downloaded      |
| 29  | `engagement_case_study_viewed`     | Engagement   | Case study viewed        |
| 30  | `engagement_faq_expanded`          | Engagement   | FAQ expanded             |
| 31  | `engagement_chatbot_opened`        | Engagement   | Chatbot opened           |
| 32  | `conversion_lead_captured`         | Conversion   | Lead captured            |
| 33  | `conversion_trial_started`         | Conversion   | Trial started            |
| 34  | `conversion_paid_customer`         | Conversion   | Paid customer            |
| 35  | `navigation_page_view`             | Navigation   | Page viewed              |
| 36  | `navigation_external_link_clicked` | Navigation   | External link clicked    |

## Support

For issues or questions about event tracking:

- Check PostHog dashboard for event delivery
- Review `/api/analytics/events` API logs
- Verify database `analytics_events` table
- Contact: analytics@mawidi.com
