# Autotracking Documentation

The Engage browser widget includes comprehensive autotracking functionality that automatically captures user interactions without requiring manual event tracking calls.

## Configuration

Autotracking is configured during initialization:

```javascript
window.engage.queue.push(['init', {
  key: 'your-api-key',
  autotrack: {
    pageviews: true,  // Track page views and navigation
    buttons: true,    // Track button and link clicks
    forms: true       // Track form submissions and interactions
  }
}]);
```

You can also enable all autotracking features at once:

```javascript
window.engage.queue.push(['init', {
  key: 'your-api-key',
  autotrack: true  // Enables all tracking features
}]);
```

## Tracked Events

### 1. Pageview Tracking (`pageviews: true`)

**Event Name:** `pageview`

**Automatically tracks:**
- Initial page load
- Single Page Application (SPA) navigation
- Browser back/forward navigation
- Hash changes

**Data Captured:**
```javascript
{
  url: "https://example.com/page",
  title: "Page Title",
  referrer: "https://google.com",
  timestamp: "2024-01-01T00:00:00.000Z",
  viewport: { width: 1920, height: 1080 },
  screen: { width: 1920, height: 1080 },
  user_agent: "Mozilla/5.0...",
  utm: {  // Only if UTM parameters are present
    utm_source: "google",
    utm_medium: "cpc",
    utm_campaign: "spring_sale"
  }
}
```

### 2. Button Click Tracking (`buttons: true`)

**Event Name:** `button_click`

**Automatically tracks clicks on:**
- `<button>` elements
- `<a>` elements (links)
- Elements with `role="button"`
- Elements with `onclick` attributes
- Elements with CSS classes `btn` or `button`
- Input elements with `type="submit"` or `type="button"`

**Data Captured:**
```javascript
{
  element_type: "button",
  element_id: "submit-btn",
  element_classes: "btn btn-primary",
  element_text: "Submit Form",
  element_href: null, // For links
  element_data_attributes: {
    "data-action": "submit",
    "data-category": "form"
  },
  coordinates: { x: 150, y: 300 },
  url: "https://example.com/page",
  timestamp: "2024-01-01T00:00:00.000Z"
}
```

### 3. Form Submission Tracking (`forms: true`)

**Event Name:** `form_submission`

**Automatically tracks:**
- Form submission events
- Form field interactions (change events)
- Form field focus events

**Data Captured:**
```javascript
{
  form_id: "contact-form",
  form_name: "contact",
  form_action: "/submit",
  form_method: "post",
  form_classes: "contact-form",
  field_count: 5,
  field_data: {  // Non-sensitive fields only
    "name": "John Doe",
    "email": "john@example.com",
    "newsletter": true,
    "country": "US"
  },
  field_types: {
    "text": 2,
    "email": 1,
    "checkbox": 1,
    "select": 1
  },
  submission_method: "submit",
  url: "https://example.com/page",
  timestamp: "2024-01-01T00:00:00.000Z"
}
```

### 4. Form Field Interaction Tracking

**Event Name:** `form_field_interaction`

**Data Captured:**
```javascript
{
  field_name: "email",
  field_type: "email",
  field_id: "user-email",
  field_value: "john@example.com", // Sanitized and limited
  form_id: "signup-form",
  form_name: "signup",
  url: "https://example.com/page",
  timestamp: "2024-01-01T00:00:00.000Z"
}
```

**Event Name:** `form_field_focus`

**Data Captured:**
```javascript
{
  field_name: "email",
  field_type: "email",
  form_id: "signup-form",
  url: "https://example.com/page",
  timestamp: "2024-01-01T00:00:00.000Z"
}
```

## Privacy and Security

### Sensitive Field Filtering

The autotracker automatically excludes sensitive fields from tracking. The following patterns are considered sensitive and **will not be tracked**:

- **Password fields**: `type="password"`
- **Field names containing**: password, passwd, pwd, secret, token, api_key, credit_card, cvv, ccv, ssn, social_security, bank_account, routing_number, pin, security_code
- **File inputs**: `type="file"`

### Data Sanitization

All captured text data is:
- HTML sanitized to prevent XSS
- Limited in length (100 chars for text, 500 chars for form values)
- Validated for proper formats (e.g., email validation)

### Opt-out Mechanisms

Users can opt out of tracking in several ways:

1. **Element-level opt-out** using `data-engage-ignore`:
```html
<button data-engage-ignore>This won't be tracked</button>
```

2. **Container-level opt-out**:
```html
<div data-engage-ignore>
  <!-- Nothing inside this div will be tracked -->
  <button>Not tracked</button>
  <form><!-- Not tracked --></form>
</div>
```

3. **Engage widget elements** are automatically excluded from tracking

4. **Anonymous user control**:
```javascript
window.engage.queue.push(['init', {
  key: 'your-api-key',
  ignore_anonymous: true,  // Only track identified users
  autotrack: true
}]);
```

## Performance Considerations

- **Throttling**: Click events are throttled to 100ms, form events to 200-500ms
- **Debouncing**: Page navigation events are debounced to prevent duplicate tracking
- **Efficient DOM**: Uses event delegation for optimal performance
- **Memory management**: Automatic cleanup of tracked element references

## Testing Autotracking

Use the included test page to verify autotracking functionality:

```bash
npm run test:autotrack
```

This will open a test page located at `tests/test-autotrack.html` with various interactive elements and real-time tracking event display.

## API Integration

All autotracking events are sent using the standard `Engage.track()` method:

```javascript
// Pageview
Engage.track('pageview', { url: '...', title: '...' });

// Button click
Engage.track('button_click', { element_type: 'button', ... });

// Form submission
Engage.track('form_submission', { form_id: '...', field_data: {...} });
```

## Best Practices

1. **Enable gradually**: Start with pageviews, then add buttons and forms
2. **Test thoroughly**: Use the test page to verify expected behavior
3. **Monitor data**: Check your analytics dashboard for tracked events
4. **Respect privacy**: Ensure compliance with GDPR, CCPA, and other regulations
5. **Use opt-outs**: Provide clear opt-out mechanisms for users
6. **Validate data**: The autotracker includes built-in validation, but verify in your analytics

## Troubleshooting

### Common Issues

1. **Events not appearing**: Check browser console for errors
2. **Sensitive data leaked**: Verify field names don't match sensitive patterns
3. **Too many events**: Consider adjusting throttling or adding more specific opt-outs
4. **Missing events**: Ensure elements match the tracking selectors

### Debug Mode

Enable debug logging:

```javascript
window.engage.queue.push(['init', {
  key: 'your-api-key',
  debug: true,
  autotrack: true
}]);
```

This will log all tracking attempts to the browser console.
