// Amili Kit: Click beacon. https://amili.ai/kit#kit-beacon
// SPDX-License-Identifier: MIT. Copyright (c) 2026 Amili (Paulo de Vries). Made by Amili.
// Tests and more parts: https://amili.ai/kit. The "brand" option shows a tiny "amili" mark linking to the kit; set
// brand: false to hide it.
//
//   import { beaconScript, makeBeaconHandler } from './kit/beacon.mjs';
//   html += `<script>${beaconScript({ endpoint: 'https://your-endpoint.example/c', site: 'example.com' })}</script>`
//   Mark links you care about: <a href="/go/x" data-from="hero">  (data-event-from works too)
//
// beaconScript opts = {
//   endpoint: 'https://your-endpoint.example/c', // required: where counts go (your Worker; see makeBeaconHandler)
//   site: 'example.com',                         // required: sent as s=, so one endpoint can count many sites
//   match: '/go/|amazon\\.|amzn\\.to',            // which links count (regex source, tested against the href)
//   bounty: 'purchaseType=MTRIAL|/go/audible',    // optional: links that are a different kind of click (t=b)
//   pages: [['^/$', 'home'], ['^/compare/', 'compare']], // optional page classes; default: first path segment
//   optOutParam: '__fa',                          // ?__fa=1 once marks this browser as yours (never counted)
// }
// Sends: s=<site>&f=<from label>&p=<page class>[&t=b]. Nothing else: no URL, no referrer, no time, no id.
//
// makeBeaconHandler({ record, sites }) -> (request) => Response. For a Cloudflare Worker or Pages Function:
// validates the four fields, adds the day (UTC) and the visitor's country from Cloudflare, calls record(point), answers
// 204. `record` is yours: Analytics Engine, D1, a queue, or kvCounter(env.KV) below for a quick start.


const LABEL = /^[a-z0-9][a-z0-9_-]{0,39}$/;

export function beaconScript(o = {}) {
  if (!o.endpoint || !/^https:\/\/[^/]+\/?/.test(o.endpoint) || /[?#'"\\<>]/.test(o.endpoint)) throw new Error('beaconScript: endpoint must be a plain https:// URL (no query)');
  if (!o.site || !/^[a-z0-9.-]+$/.test(o.site)) throw new Error('beaconScript: site must be a hostname like example.com');
  const match = new RegExp(o.match || '/go/|amazon\\.|amzn\\.to', 'i');
  const bounty = o.bounty ? new RegExp(o.bounty, 'i') : null;
  const pages = (o.pages || []).map(([re, label]) => {
    if (!LABEL.test(label)) throw new Error(`beaconScript: page label "${label}" must match ${LABEL}`);
    return [new RegExp(re), label];
  });
  const opt = /^[a-z_]{1,12}$/.test(o.optOutParam || '__fa') ? (o.optOutParam || '__fa') : '__fa';
  return `(function(){"use strict";var E=${JSON.stringify(o.endpoint)},S=${JSON.stringify(o.site)},M=${match},B=${bounty || 'null'},P=[${pages.map(([r, l]) => `[${r},${JSON.stringify(l)}]`).join(',')}],L=${LABEL};
var me=false;try{if(location.search.indexOf("${opt}=1")>-1)localStorage.setItem("ak-no-count","1");me=localStorage.getItem("ak-no-count")==="1"}catch(e){}
if(navigator.webdriver===true||/HeadlessChrome/.test(navigator.userAgent||""))me=true;
function page(){var p=location.pathname;for(var i=0;i<P.length;i++)if(P[i][0].test(p))return P[i][1];var s=p.split("/")[1]||"home";return L.test(s)?s:"other"}
function hit(e){try{if(me||!e.isTrusted)return;var a=e.target&&e.target.closest&&e.target.closest("a[href]");if(!a)return;var h=a.href||"";if(!M.test(h))return;
var f=(a.getAttribute("data-from")||a.getAttribute("data-event-from")||"untagged").toLowerCase();if(!L.test(f))f="other";
var q="s="+encodeURIComponent(S)+"&f="+encodeURIComponent(f)+"&p="+encodeURIComponent(page())+(B&&B.test(h)?"&t=b":"");
if(navigator.sendBeacon)navigator.sendBeacon(E+"?"+q)}catch(x){}}
document.addEventListener("click",hit,true);document.addEventListener("auxclick",function(e){if(e.button===1)hit(e)},true);})();`;
}

export function makeBeaconHandler({ record, sites } = {}) {
  if (typeof record !== 'function') throw new Error('makeBeaconHandler: record(point) is required');
  const allow = sites ? new Set(sites) : null;
  return async (request) => {
    const u = new URL(request.url);
    const s = u.searchParams.get('s') || '', f = u.searchParams.get('f') || '', p = u.searchParams.get('p') || '', t = u.searchParams.get('t');
    const ok = /^[a-z0-9.-]{3,80}$/.test(s) && LABEL.test(f) && LABEL.test(p) && (t === null || t === 'b') && (!allow || allow.has(s));
    if (!ok) return new Response(null, { status: 400 });
    const point = { day: new Date().toISOString().slice(0, 10), site: s, from: f, page: p, type: t === 'b' ? 'bounty' : 'click', country: /^[A-Z]{2}$/.test(request.cf?.country || '') ? request.cf.country : 'XX' };
    try { await record(point); } catch { return new Response(null, { status: 503 }); }
    return new Response(null, { status: 204, headers: { 'access-control-allow-origin': '*', 'cache-control': 'no-store' } });
  };
}

// Quick start counter on Workers KV: one key per (day, site, from, page, type, country). KV is eventually consistent,
// so two clicks in the same second can count once: fine for "which placement works", not for billing. Keys expire in 400 days.
export const kvCounter = (kv) => async (pt) => {
  const { day, site, from, page, type, country } = pt;
  const key = `c:${day}:${site}:${from}:${page}:${type}:${country}`;
  const n = Number(await kv.get(key)) || 0;
  await kv.put(key, String(n + 1), { expirationTtl: 400 * 86400 });
};

// The kit's common shape: every component exports { name, render(opts) -> html, css, js }. Here render() is the <script>.
export default { name: 'beacon', title: 'Click beacon', render: (o) => `<script>${beaconScript(o)}</script>`, css: '', js: '' };
