// KL-101: presence tracker — pings the backend whenever a human does
// something in the dashboard. The backend's director loop uses the
// last_user_interaction timestamp to detect AFK and auto-pause the
// AI Director (so we don't burn AI calls forever on an unattended
// laptop running endless audio).
//
// Debounced 5s — even a continuous mousemove storm only sends one
// ping per window. The backend's threshold is in minutes/hours, so
// 5s precision is plenty.

const DEBOUNCE_MS = 5000;

let lastPing = 0;
let pendingTimer = null;
let initialized = false;

function sendPing() {
    pendingTimer = null;
    lastPing = Date.now();
    fetch('/api/director/interaction', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: '{}',
    }).catch(() => {
        // Network blip — the next interaction will retry. No need to
        // surface a banner; the worst case is a slightly later pause.
    });
}

function noteInteraction() {
    const now = Date.now();
    // Already pinged within the debounce window? No-op.
    if (now - lastPing < DEBOUNCE_MS && pendingTimer === null) {
        return;
    }
    if (pendingTimer !== null) {
        return;  // already scheduled
    }
    const wait = Math.max(0, DEBOUNCE_MS - (now - lastPing));
    pendingTimer = setTimeout(sendPing, wait);
}

export function initPresenceTracker() {
    if (initialized) return;
    initialized = true;

    // Document-level listeners. `passive` so we never block scroll/UI.
    // mousemove and keydown cover most "human in the room" cases;
    // visibilitychange catches "user came back from another tab/app";
    // focus catches the window-regain case in pywebview.
    const opts = {passive: true, capture: true};
    document.addEventListener('mousemove', noteInteraction, opts);
    document.addEventListener('keydown', noteInteraction, opts);
    document.addEventListener('click', noteInteraction, opts);
    document.addEventListener('touchstart', noteInteraction, opts);
    window.addEventListener('focus', noteInteraction);
    document.addEventListener('visibilitychange', () => {
        if (!document.hidden) noteInteraction();
    });

    // Initial ping so the backend gets a first timestamp without
    // waiting for the user to wiggle the mouse.
    sendPing();
}
