// Privacy-respecting, first-party analytics. The visitor token is a random
// localStorage string — never email, IP, or a fingerprint. It only lets the
// admin dashboard tell "new vs returning" in aggregate. Server hashes it.
const VISITOR_KEY = 'goodnews:visitor';
const VISITDAY_KEY = 'goodnews:visitday';

export function visitorId() {
  try {
    let v = localStorage.getItem(VISITOR_KEY);
    if (!v) {
      v = crypto?.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2) + Date.now();
      localStorage.setItem(VISITOR_KEY, v);
    }
    return v;
  } catch {
    return '';
  }
}

export function track(kind, articleId = 0) {
  try {
    const body = JSON.stringify({ kind, article_id: articleId || 0, visitor: visitorId() });
    if (navigator.sendBeacon) {
      navigator.sendBeacon('/api/events', new Blob([body], { type: 'application/json' }));
    } else {
      fetch('/api/events', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body,
        keepalive: true,
      }).catch(() => {});
    }
  } catch {
    /* best-effort, never throws */
  }
}

// Deep link for a shared game result: full https:// URL straight to the exact game +
// variant (not generic /play), tagged so we can attribute arrivals to the share loop.
const SITE = 'https://upbeatbytes.com';
export function gameShareUrl(game, variant) {
  const v = variant ? `&v=${encodeURIComponent(variant)}` : '';
  return `${SITE}/play?game=${game}${v}&utm_source=game_share`;
}

// Per-game funnel: trackGame('word', 'started'|'completed'|'shared'). Kinds must mirror
// the backend allowlist (_GAME_EVENT_KINDS in api.py). Deduped per game/kind/day server-side.
const GAME_NAMES = ['word', 'wordsearch', 'bloom', 'match'];
const GAME_EVENTS = ['started', 'completed', 'shared', 'arrival'];
export function trackGame(game, event) {
  if (GAME_NAMES.includes(game) && GAME_EVENTS.includes(event)) track(`${game}_${event}`);
}

// Count a visit at most once per day per device.
export function trackVisit() {
  try {
    const today = new Date().toISOString().slice(0, 10);
    if (localStorage.getItem(VISITDAY_KEY) !== today) {
      localStorage.setItem(VISITDAY_KEY, today);
      track('visit');
    }
  } catch {
    /* ignore */
  }
}
