# Analytics Events - Quick Start Guide

Get started with event tracking in 5 minutes.

## Step 1: Run Database Migration (1 minute)

```bash
cd mawidi-site
npm run check:schema
npx prisma migrate dev --name add_analytics_events
node scripts/sync-all-prisma-to-supabase.mjs
```

## Step 2: Server-Side Tracking (30 seconds)

Track events in API routes or server components:

```typescript
// app/api/bookings/route.ts
import { trackAppointmentCreated } from "@/lib/analytics/events";

export async function POST(req: Request) {
  const booking = await createBooking(data);

  // Track the event
  await trackAppointmentCreated({
    service: booking.service,
    source: "api",
  });

  return Response.json({ success: true });
}
```

## Step 3: Client-Side Tracking (30 seconds)

Track events in React components:

```typescript
'use client';

import { trackPricingPlanSelected } from '@/lib/analytics/client';

export function PricingCard({ plan, price }: Props) {
  const handleSelect = () => {
    // Track plan selection
    trackPricingPlanSelected(plan, price, {
      ctaLocation: 'pricing_page'
    });
  };

  return (
    <button onClick={handleSelect}>
      Select {plan}
    </button>
  );
}
```

## Step 4: Track Page Views (1 minute)

Add to any page component:

```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>;
}
```

## Step 5: Track Forms (2 minutes)

Add to form submissions:

```typescript
'use client';

import { trackContactFormSubmitted, trackFormValidationError } from '@/lib/analytics/client';

export function ContactForm() {
  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();

    try {
      const response = await fetch('/api/contact', {
        method: 'POST',
        body: JSON.stringify(formData)
      });

      if (!response.ok) throw new Error('Failed');

      // Track success
      trackContactFormSubmitted({
        topic: formData.topic,
        ctaLocation: 'contact_page'
      });
    } catch (error) {
      // Track error
      trackFormValidationError('contact_form', error.message);
    }
  };

  return <form onSubmit={handleSubmit}>...</form>;
}
```

## Common Events Quick Reference

### CTA Events

```typescript
import {
  trackDemoBookingCompleted,
  trackContactFormSubmitted,
  trackPricingPlanSelected,
  trackFreeTrialClicked,
} from "@/lib/analytics/client";

// Demo booking
trackDemoBookingCompleted({ ctaLocation: "hero" });

// Contact form
trackContactFormSubmitted({ topic: "sales" });

// Plan selection
trackPricingPlanSelected("Professional", 299);

// Free trial
trackFreeTrialClicked({ planName: "pro" });
```

### Feature Events

```typescript
import {
  trackDashboardViewed,
  trackAppointmentCreated,
  trackSubscriptionUpgraded,
} from "@/lib/analytics/client";

// Dashboard view
trackDashboardViewed();

// Create appointment
trackAppointmentCreated({ service: "consultation" });

// Upgrade subscription
trackSubscriptionUpgraded({ fromPlan: "basic", toPlan: "pro" });
```

### User Journey

```typescript
import {
  trackSignupCompleted,
  trackLoginSuccess,
  trackOnboardingCompleted,
} from "@/lib/analytics/client";

// Signup
trackSignupCompleted("user_123", { source: "google" });

// Login
trackLoginSuccess("user_123", { method: "email" });

// Onboarding
trackOnboardingCompleted("user_123");
```

### Error Tracking

```typescript
import {
  trackFormValidationError,
  trackApiError,
  trackPaymentError,
} from "@/lib/analytics/client";

// Form error
trackFormValidationError("signup", "Invalid email");

// API error
trackApiError("Request failed", "API_001");

// Payment error
trackPaymentError("Card declined");
```

### Engagement

```typescript
import {
  trackVideoPlayed,
  trackResourceDownloaded,
  trackCaseStudyViewed,
} from "@/lib/analytics/client";

// Video
trackVideoPlayed("demo_video");

// Download
trackResourceDownloaded("guide_123", "pdf");

// Case study
trackCaseStudyViewed("healthcare_study");
```

## Verify Events

### Check Database

```sql
-- View recent events
SELECT eventName, category, createdAt
FROM analytics_events
ORDER BY createdAt DESC
LIMIT 20;
```

### Check API Endpoint

```bash
# Test with curl
curl -X POST http://localhost:9000/api/analytics/events \
  -H "Content-Type: application/json" \
  -d '{
    "eventName": "navigation_page_view",
    "category": "navigation",
    "properties": { "page": "/test" }
  }'
```

### Monitor in Browser

Open browser DevTools → Network tab → Filter for "events"

## Optional: Add PostHog (5 minutes)

1. Get PostHog API key from https://app.posthog.com

2. Add to `.env.local`:

```env
NEXT_PUBLIC_POSTHOG_KEY=phc_xxxxx
NEXT_PUBLIC_POSTHOG_HOST=https://app.posthog.com
```

3. Add provider to `app/layout.tsx`:

```typescript
import { PostHogProvider } from '@/lib/analytics/posthog';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <PostHogProvider>
          {children}
        </PostHogProvider>
      </body>
    </html>
  );
}
```

4. Events will automatically send to PostHog!

## That's it! 🎉

You're now tracking user events across your application.

## Next Steps

1. **Add more tracking**:
   - Add to key conversion points
   - Track errors consistently
   - Monitor feature usage

2. **Analyze data**:
   - Review conversion funnels
   - Identify drop-off points
   - Optimize user journey

3. **Read full docs**:
   - `README.md` - Complete guide
   - `EVENT_CATALOG.md` - All 36 events
   - `examples.tsx` - More examples

## Need Help?

- Check `README.md` for detailed documentation
- See `examples.tsx` for more usage patterns
- Review `EVENT_CATALOG.md` for all available events
