# Google Analytics 4 Integration - Implementation Guide

## ✅ Completed Setup

### 1. GA4 Script Integration
- **Location**: `/apps/storefront/src/app/layout.tsx`
- **ID**: G-LYGFMS3PJS
- **What it does**: Automatically loads Google Analytics 4 on all pages

### 2. Analytics Utilities (`/apps/storefront/src/lib/analytics.ts`)
Created comprehensive event tracking functions:
- `trackViewItem()` - Product page views
- `trackAddToCart()` - Adding items to cart
- `trackRemoveFromCart()` - Removing items from cart
- `trackViewCart()` - Viewing cart page
- `trackBeginCheckout()` - Starting checkout
- `trackPurchase()` - Order completion
- `trackSearch()` - Search functionality
- `trackPageView()` - Manual page tracking

### 3. Component Integration

#### Product Page (`/app/produits/[handle]/page.tsx`)
- ✅ Added `AnalyticsViewItemScript` component
- Tracks: Product views with title, price, category
- Trigger: When product page loads

#### Shopping Cart (`/app/panier/page.tsx`)
- ✅ Added `AnalyticsViewCartScript` component
- Tracks: Cart items with quantities and prices
- Trigger: When cart page is viewed
- Also: Remove from cart events (via form actions)

#### Order Success (`/app/commande/succes/page.tsx`)
- ✅ Added `AnalyticsPurchaseScript` component
- Tracks: Purchase event with all order details
- Trigger: When payment succeeds (session.line_items)
- Includes: Order ID, total amount, all line items

#### Product Detail Component (`product-detail-dynamic.tsx`)
- ✅ Added GA4 import and tracking
- Modified `handleAddToCartSubmit()` to call `trackAddToCart()`
- Tracks: Product ID, title, price, quantity before form submission

## 📊 React Components Created

### 1. `analytics-view-item-script.tsx`
- Tracks product page views
- Props: productId, productTitle, price, category, image
- Type: Client component with useEffect

### 2. `analytics-view-cart-script.tsx`
- Tracks shopping cart visualization
- Props: array of cart items
- Type: Client component with useEffect

### 3. `analytics-purchase-script.tsx`
- Tracks purchase completion
- Props: orderId, totalAmount, currency, items array
- Type: Client component with useEffect

## 🔄 Event Flow Tracking

```
User Flow → GA4 Event
┌─────────────────────────────────┐
│ View Product → view_item        │
│ Add to Cart → add_to_cart       │
│ View Cart → view_cart           │
│ Begin Checkout → begin_checkout │
│ Purchase → purchase             │
└─────────────────────────────────┘
```

## 🚀 Next Steps (Production)

### Immediate (Week 1)
1. **Deploy to production**
   ```bash
   # Build and deploy your app
   npm run build:storefront
   # Verify GA4 script loads:
   # https://stylunique.fr → Should include gtag.js
   ```

2. **Verify GA4 is working**
   - Go to: https://analytics.google.com/analytics/web/
   - Select "Stylunique" property
   - Go to **Real-time** → **Overview**
   - Visit your site and check if you see active users

3. **Check event tracking**
   - In GA4: **Realtime** → **Events**
   - Look for: `page_view`, `view_item`, `add_to_cart`, `purchase`
   - Click product → should see `view_item`
   - Add to cart → should see `add_to_cart`

### Week 2
1. **Configure conversion events**
   - GA4 Dashboard → **Admin** → **Conversions**
   - Mark `purchase` as conversion goal
   - Consider marking `add_to_cart` as secondary goal

2. **Set up audiences**
   - Create audiences for:
     - Recent purchasers (last 7 days)
     - Cart abandoners (viewed cart but no purchase)
     - High-value customers (total value > €100)

3. **Link to Google Ads** (if running ads)
   - Admin → **Google Ads links**
   - Link your Google Ads account
   - Enables conversion tracking in Ads

### Week 3
1. **Review data in GA4**
   - **Acquisition** → Where users come from
   - **Engagement** → Popular pages, bounce rate
   - **Monetization** → Revenue by product, by user
   - **Retention** → Repeat purchase rates

2. **Check for issues**
   - Look for high bounce rates (>70%)
   - Check drop-off in checkout funnel
   - Verify all products are being tracked

## 🎯 E-Commerce Reports to Create

In GA4, go to **Reports** and look for:
- **Commerce Overview** - Total revenue, transactions, AOV
- **Product Performance** - Best sellers, top revenue products
- **Shopping Behavior** - Add to cart rate, checkout abandonment
- **Purchase Journey** - Multi-touch attribution

## 📝 Testing Checklist

Before marking as complete:
- [ ] Deploy code to production
- [ ] GA4 real-time shows active users within 30 seconds
- [ ] View a product → `view_item` event appears
- [ ] Add product to cart → `add_to_cart` event appears
- [ ] Complete a test purchase → `purchase` event appears with order details
- [ ] Cart page shows → `view_cart` event appears
- [ ] Events show in **GA4** → **Real-time** → **Events**

## 🔗 Important Links

- GA4 Property: https://analytics.google.com/analytics/web/ (ID: G-LYGFMS3PJS)
- Documentation: https://support.google.com/analytics/answer/10089681
- Event reference: https://support.google.com/analytics/answer/9322688

## 💡 Notes

- All events use EUR currency by default
- Prices are stored in cents in Medusa, converted to euros in GA4
- Cart view tracks all items in cart at viewing moment
- Purchase event fires only if payment_status = "paid"
- Test with your own account before sharing credentials

---

**Last Updated**: April 7, 2026
**Status**: ✅ Development Complete → Ready for Production Deployment
