"use client";
import { BASE_PATH } from "@/lib/base";

/** Clickstream + session write-back for the funnel. All best-effort: failures
 *  never affect the user. Events are buffered and flushed in batches. */

type Ev = { step: string; stepNumber: number; answer?: string; timeSpentSec: number };

let buffer: Ev[] = [];
let sid: string | null = null;

function uuid() {
  return "ds_" + Date.now().toString(36) + "_" + Math.random().toString(36).slice(2, 10);
}

export function sessionId(): string {
  if (sid) return sid;
  if (typeof window === "undefined") return "";
  try {
    sid = localStorage.getItem("qs_disco_sid");
    if (!sid) { sid = uuid(); localStorage.setItem("qs_disco_sid", sid); }
  } catch { sid = uuid(); }
  return sid;
}

function meta() {
  if (typeof window === "undefined") return {};
  const q = new URLSearchParams(window.location.search);
  const ua = navigator.userAgent || "";
  return {
    deviceType: /Mobi|Android|iPhone|iPad/i.test(ua) ? "mobile" : "desktop",
    // Channel comes from the link (email/push set utm_*). Absent → undefined → NULL
    // (matches chatbot's clean clickstream convention; no fabricated defaults, no blanks).
    source: q.get("utm_source") || q.get("source") || undefined,
    medium: q.get("utm_medium") || q.get("medium") || undefined,
    campaign: q.get("utm_campaign") || q.get("campaign") || undefined,
  };
}

export function trackStep(step: string, stepNumber: number, answer: string | undefined, timeSpentSec: number) {
  buffer.push({ step, stepNumber, answer: answer || undefined, timeSpentSec });
  if (buffer.length >= 6) flush();
}

export function flush(useBeacon = false) {
  if (typeof window === "undefined" || buffer.length === 0) return;
  const payload = JSON.stringify({ sessionId: sessionId(), meta: meta(), events: buffer });
  buffer = [];
  const url = `${BASE_PATH}/api/track-batch`;
  try {
    if (useBeacon && navigator.sendBeacon) {
      navigator.sendBeacon(url, new Blob([payload], { type: "application/json" }));
    } else {
      fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: payload, keepalive: true }).catch(() => {});
    }
  } catch { /* ignore */ }
}

export function postSession(data: Record<string, unknown>) {
  if (typeof window === "undefined") return;
  const m = meta();
  try {
    fetch(`${BASE_PATH}/api/session`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        sessionId: sessionId(),
        data: {
          vDeviceType: m.deviceType, vSource: m.source, vMedium: m.medium, vCampaign: m.campaign,
          vOnBoardPlatform: "web",
          ...data,
        },
      }),
      keepalive: true,
    }).catch(() => {});
  } catch { /* ignore */ }
}

if (typeof window !== "undefined") {
  window.addEventListener("pagehide", () => flush(true));
  window.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") flush(true); });
}
