import { jsx as _jsx } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { createContext, useCallback, useContext, useRef, useState, useMemo, useEffect, } from 'react';
import { uiTelemetryService, } from '@vybestack/llxprt-code-core';
// --- Context Definition ---
const SessionStatsContext = createContext(undefined);
// --- Provider Component ---
export const SessionStatsProvider = ({ children, }) => {
    const [stats, setStats] = useState({
        sessionId: `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        sessionStartTime: new Date(),
        metrics: uiTelemetryService.getMetrics(),
        lastPromptTokenCount: 0,
        historyTokenCount: 0,
        promptCount: 0,
    });
    useEffect(() => {
        const handleUpdate = ({ metrics, lastPromptTokenCount, }) => {
            setStats((prevState) => ({
                ...prevState,
                metrics,
                lastPromptTokenCount,
            }));
        };
        uiTelemetryService.on('update', handleUpdate);
        // Set initial state
        handleUpdate({
            metrics: uiTelemetryService.getMetrics(),
            lastPromptTokenCount: uiTelemetryService.getLastPromptTokenCount(),
        });
        return () => {
            uiTelemetryService.off('update', handleUpdate);
        };
    }, []);
    const startNewPrompt = useCallback(() => {
        setStats((prevState) => ({
            ...prevState,
            promptCount: prevState.promptCount + 1,
        }));
    }, []);
    const updateHistoryTokenCount = useCallback((count) => {
        setStats((prevState) => ({
            ...prevState,
            historyTokenCount: count,
        }));
    }, []);
    // FIX: Use a ref to provide stable callback that always returns latest value
    // This prevents components from re-rendering when promptCount changes
    const promptCountRef = useRef(stats.promptCount);
    // Keep ref updated with latest value
    useEffect(() => {
        promptCountRef.current = stats.promptCount;
    }, [stats.promptCount]);
    const getPromptCount = useCallback(() => promptCountRef.current, []);
    const value = useMemo(() => ({
        stats,
        startNewPrompt,
        getPromptCount,
        updateHistoryTokenCount,
    }), [stats, startNewPrompt, getPromptCount, updateHistoryTokenCount]);
    return (_jsx(SessionStatsContext.Provider, { value: value, children: children }));
};
// --- Consumer Hook ---
export const useSessionStats = () => {
    const context = useContext(SessionStatsContext);
    if (context === undefined) {
        throw new Error('useSessionStats must be used within a SessionStatsProvider');
    }
    return context;
};
//# sourceMappingURL=SessionContext.js.map