'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from 'react';
const POLL_INTERVAL_MS = 30_000;
const ACTIVE_THRESHOLD_MS = 5 * 60 * 1000; // 5 minutes
const SessionsContext = createContext(null);
// ── Provider component ────────────────────────────────────────────────
export function SessionsProvider({ children }) {
    const [sessionsByPath, setSessionsByPath] = useState(new Map());
    const sessionsByPathRef = useRef(sessionsByPath);
    sessionsByPathRef.current = sessionsByPath;
    const fetchSessions = useCallback(async () => {
        if (document.hidden)
            return;
        try {
            const res = await fetch('/api/sessions-batch');
            if (!res.ok)
                return;
            const data = (await res.json());
            const next = new Map();
            for (const [path, sessions] of Object.entries(data.sessionsByPath)) {
                next.set(path, sessions);
            }
            setSessionsByPath(next);
        }
        catch {
            // Silent — stale data is better than no data
        }
    }, []);
    useEffect(() => {
        void fetchSessions();
        const timer = setInterval(() => void fetchSessions(), POLL_INTERVAL_MS);
        return () => clearInterval(timer);
    }, [fetchSessions]);
    const getSessionsForPath = useCallback((path) => sessionsByPathRef.current.get(path) ?? [], 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [sessionsByPath]);
    const hasActiveSessions = useCallback((path) => {
        const sessions = sessionsByPathRef.current.get(path);
        if (!sessions)
            return false;
        const now = Date.now();
        return sessions.some((s) => s.lastMessageAt && now - new Date(s.lastMessageAt).getTime() < ACTIVE_THRESHOLD_MS);
    }, 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [sessionsByPath]);
    const value = useMemo(() => ({ getSessionsForPath, hasActiveSessions }), [getSessionsForPath, hasActiveSessions]);
    return _jsx(SessionsContext.Provider, { value: value, children: children });
}
// ── Consumer hook ─────────────────────────────────────────────────────
export function useSessionsContext() {
    const ctx = useContext(SessionsContext);
    if (!ctx) {
        return { getSessionsForPath: () => [], hasActiveSessions: () => false };
    }
    return ctx;
}
