You are helping integrate LinkJolt affiliate tracking into a product that takes payment through Polar (polar.sh).

## Context
- Merchant ID: YOUR_MERCHANT_ID
- Platform: Polar
- Tracking Script: https://www.linkjolt.io/api/tracking.js?id=YOUR_MERCHANT_ID
- Webhook: none to configure. The merchant connected Polar from LinkJolt → Integrations → Polar, and LinkJolt created a webhook endpoint named "LinkJolt" in their Polar organization. Sales, renewals and refunds arrive on it automatically. Do NOT ask the user to add a webhook or paste a secret.

## How attribution works
When a visitor arrives from an affiliate link (`?tc=...&aff=...`), the tracking script stores the affiliate identity in the browser and exposes it as `window.linkjolt.referral`, a string of the form `tc_<code>_aff_<id>_cid_<click>`.

Polar copies a checkout's `metadata.reference_id` onto the order it creates AND onto every renewal order of the subscription, so the one thing the integration must do is put `window.linkjolt.referral` into `reference_id` on the checkout. LinkJolt's webhook reads `metadata.reference_id` off every paid order.

Pick the ONE case that matches how this site sells:

### Case A: Polar checkout links on the site (buttons or links to buy.polar.sh, or the Polar embed)
Nothing beyond the tracking script. The script rewrites every Polar checkout link and every `data-polar-checkout` embed on the page to carry `?reference_id=<window.linkjolt.referral>`, and Polar merges that query parameter into the checkout metadata. Verify by opening a page with `?tc=TEST&aff=TEST` and inspecting a checkout link's href: it must end in `reference_id=tc_TEST_aff_TEST`.

### Case B: the site's own code creates the checkout (Polar SDK or API)
Read the referral in the browser and send it to the server with the checkout request, then set it as `metadata.reference_id` when creating the checkout:

```typescript
// Browser (the page that starts the checkout)
const referral = window.linkjolt?.referral || '';
fetch('/api/checkout', { method: 'POST', body: JSON.stringify({ productId, referral }) });

// Server (Polar SDK)
import { Polar } from '@polar-sh/sdk';
const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN });

const checkout = await polar.checkouts.create({
  products: [productId],
  successUrl: 'https://example.com/thanks',
  metadata: referral ? { reference_id: referral } : {},   // ← THIS is the whole integration
});
// redirect the customer to checkout.url
```

If `reference_id` is already used for something else in this codebase, put the referral under `metadata.linkjolt` instead; LinkJolt reads that key as an alias. Never put it anywhere else and never rename the value.

### Case C: coupon codes only
The merchant gives each affiliate a Polar discount code registered in LinkJolt. No code change: LinkJolt matches the code on the paid order.

---

### Add Tracking Script

Add this to your website's `<head>` tag:

**HTML:**
```html
<script src="https://www.linkjolt.io/api/tracking.js?id=YOUR_MERCHANT_ID" async></script>
```

**Next.js / React:**
```tsx
import Script from 'next/script'

// Add this in your layout.tsx or _app.tsx
<Script
  src="https://www.linkjolt.io/api/tracking.js?id=YOUR_MERCHANT_ID"
  strategy="afterInteractive"
/>
```

## Tracking Script API Reference

```javascript
// Format: "tc_CAMPAIGN123_aff_AFFILIATE456_cid_CLICK789"
window.linkjolt.referral

// Returns: { trackingCode, affiliateId, clickId }
window.linkjolt.getTrackingInfo()

// Returns boolean
window.linkjolt.isAffiliateVisit()

// Browser-side conversion reporting (used by Squarespace / Teachable / BigCommerce paths)
window.linkjolt.trackPurchase(amount, { orderId: 'ORDER_ID' })
```

---

## Test it
1. Open the site with `?tc=TEST&aff=TEST` and confirm `window.linkjolt.referral` is `tc_TEST_aff_TEST` in the console.
2. Start a checkout and confirm the created checkout carries `metadata.reference_id` (case B: log the object you create; case A: inspect the link's href before clicking).
3. Complete a purchase. The sale appears in LinkJolt → Commissions within a few seconds of Polar marking the order paid.

## Common issues
- Sale recorded with no affiliate → the checkout had no `metadata.reference_id` (case B: the referral was empty or never reached the server; case A: the link was not on the page when the script ran, or was built by script AFTER our rewriter; call `window.linkjolt.referral` when building it).
- Renewals not recording → renewals inherit the reference from the subscription automatically; check the FIRST order carried it. LinkJolt attributes renewals from its own record of the first payment, so nothing is needed on later orders.
- Trials → a trial start arrives as a zero-amount paid order and is recorded as a trial; the first real charge turns it into the commission.
- Refunds → Polar's order.refunded event reverses the commission proportionally. Nothing to build.
