# @renessence/web

Auto-initializing MindBody/Healcode integration for websites. Simply include the script and configure – link interception and modal management work automatically.

## Installation

### Via CDN (Recommended)

```html
<script defer src="https://cdn.jsdelivr.net/npm/@renessence/web@1"></script>
```

### Via pnpm

```bash
pnpm add @renessence/web
```

## Quick Start

Add the script to your HTML and configure via an inline script:

```html
<!DOCTYPE html>
<html>
<head>
  <script defer src="https://cdn.jsdelivr.net/npm/@renessence/web@1"></script>
  <script>
    // Config for MindBody Integration
    window.MindBodyConfig = {
      siteId: 'YOUR_SITE_ID',
      mbSiteId: 'YOUR_MB_SITE_ID',

      // Enable tracking parameter forwarding (UTM, gclid, fbclid, etc.)
      trackingParams: true,

      // Optional: adjust scroll for fixed headers
      scrollOffsetClass: 'header-fixed',

      // Define which URL paths to intercept
      interceptNamespaces: ['/buy', '/login', '/account'],

      // Simple URL mappings
      simplePatterns: {
        '/login': { type: 'login' },
        '/account': { type: 'account' },
      },

      // Dynamic URL patterns with slug extraction
      dynamicPatterns: [
        {
          pattern: /^\/buy\/packages\/(.+)$/,
          type: 'pricing',
          itemType: 'service',
        },
        {
          pattern: /^\/buy\/gift-cards\/(.+)$/,
          type: 'gift-card',
          itemType: 'item',
        },
      ],

      // Map friendly slugs to MindBody item IDs
      itemIdMap: {
        'package-slug': 'MB_SERVICE_ID',
        'gift-card-slug': 'MB_ITEM_ID',
      },

      // Optional: interception hook to customize behavior
      // Return false to cancel opening, or await async logic
      onIntercept: (evt, linkInfo, openFn) => {
        // Example: simple logging and allow default open
        console.debug('Intercepted', linkInfo)
        // Example: block certain link types
        // if (linkInfo.type === 'contract') return false
        // Or run async checks, then call openFn()
        return openFn()
      },
    }
  </script>
</head>
<body>
  <a href="/buy/packages/5x-floating">Buy 5x Floating Package</a>
  <a href="/login">Member Login</a>
</body>
</html>
```

## Configuration Options

### Required

| Option | Type | Description |
|--------|------|-------------|
| `siteId` | `string` | Your MindBody site ID (healcode site) |
| `mbSiteId` | `string` | Your MindBody business ID |

### Link Interception

| Option | Type | Description |
|--------|------|-------------|
| `interceptNamespaces` | `string[]` | URL path prefixes to intercept (e.g., `['/buy', '/login']`) |
| `simplePatterns` | `Record<string, LinkInfo>` | Exact URL to modal type mapping |
| `dynamicPatterns` | `DynamicPattern[]` | Regex patterns for extracting IDs from URLs |
| `itemIdMap` | `Record<string, string>` | Map slugs to MindBody item IDs |

### Tracking

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `trackingParams` | `boolean` | `false` | Forward URL parameters (UTM, gclid, fbclid, _ga, _gl) to Healcode |

### Optional Behavior

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `scrollOffsetClass` | `string` | `undefined` | CSS class to calculate fixed header offset |
| `identitySite` | `boolean` | Auto-detected | Override auto-detection of MindBody Identity enablement (rarely needed) |
| `debug` | `boolean` | `false` | Enable debug logging for initialization and modal interactions |
| `initTimeoutMs` | `number` | `20000` | Maximum time to wait for vendor script initialization (ms) |
| `modalTimeoutMs` | `number` | `20000` | Maximum time to wait for modal system readiness (ms) |
| `onIntercept` | `function` | `undefined` | Hook called when a link is intercepted; return `false` to cancel, or a Promise to defer opening |

## Link Types

The library supports intercepting these MindBody link types:

- **`login`** - Member login modal
- **`register`** - New member registration
- **`account`** - Member account management
- **`cart`** - Shopping cart
- **`pricing`** - Service/package pricing (requires `itemId`)
- **`gift-card`** - Gift card purchase (requires `itemId`)
- **`contract`** - Contract enrollment (requires `itemId`)

## URL Pattern Examples

### Simple Patterns

Direct URL to modal mapping:

```javascript
simplePatterns: {
  '/login': { type: 'login' },
  '/register': { type: 'register' },
  '/account': { type: 'account' },
  '/cart': { type: 'cart' },
}
```

### Dynamic Patterns

Extract IDs from URL paths:

```javascript
dynamicPatterns: [
  {
    // Matches: /buy/packages/anything
    // Extracts: "anything" as slug
    pattern: /^\/buy\/packages\/(.+)$/,
    type: 'pricing',
    itemType: 'service',
  },
  {
    // Matches: /buy/contracts/membership-gold
    // Extracts: "membership-gold" as slug
    pattern: /^\/buy\/contracts\/(.+)$/,
    type: 'contract',
    itemType: 'contract',
  },
]
```

### Item ID Mapping

Convert friendly slugs to MindBody IDs:

```javascript
itemIdMap: {
  '5x-floating': '100014',
  'membership-gold': '200045',
  'gift-card-50-eur': '100115',
}
```

**Result:** Clicking `/buy/packages/5x-floating` opens the pricing modal for item `100014`.

## Tracking Parameters

When `trackingParams: true`, these parameters are forwarded to Healcode URLs:

- **UTM Parameters**: `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`, `utm_id`
- **Google Ads**: `gclid`, `gbraid`, `wbraid`
- **Facebook Ads**: `fbclid`
- **Google Analytics**: `_ga`, `_gl`

This ensures analytics consistency across your site and MindBody.

## How It Works

1. Script loads and calls `initializeHealcode()` automatically
2. Detects any embedded Healcode widgets on the page
3. Sets up link interception based on your config
4. Clicks on matching links open modals instead of navigating
5. Tracking parameters are preserved for attribution

## Browser Support

Modern browsers with ES2020+ support (Chrome 80+, Firefox 72+, Safari 13.1+, Edge 80+).

## Advanced Usage

For more control (manual initialization, widget creation, TypeScript), use the lower-level [`mindbody-inject`](https://github.com/cwaring/renessence-lib/tree/main/packages/mindbody-inject) package.

## License

[PolyForm Noncommercial License 1.0.0](https://polyformproject.org/licenses/noncommercial/1.0.0)

Free for non-commercial use. Commercial use exclusively licensed to Renessence B.V.

## Support

- **Issues**: [GitHub Issues](https://github.com/cwaring/renessence-lib/issues)
- **Documentation**: [Full API Docs](https://github.com/cwaring/renessence-lib/tree/main/packages/mindbody-inject/docs)
