import 'react';

/**
 * Performance monitoring for smooth scroll engine
 * Tracks FPS, frame drops, and average frame time
 */
class PerformanceMonitor {
    constructor(targetFPS = 60) {
        this.frames = [];
        this.droppedFrames = 0;
        this.totalFrames = 0;
        this.lastReportTime = 0;
        this.onUpdate = null;
        this.reportInterval = 1000; // Report every second
        this.targetFPS = targetFPS;
        this.targetFrameTime = 1000 / targetFPS;
    }
    /**
     * Record a frame
     * @param timestamp - Current timestamp from RAF
     */
    recordFrame(timestamp) {
        this.frames.push(timestamp);
        this.totalFrames++;
        // Keep only last second of frames
        const oneSecondAgo = timestamp - 1000;
        this.frames = this.frames.filter((t) => t > oneSecondAgo);
        // Report metrics every interval
        if (timestamp - this.lastReportTime >= this.reportInterval) {
            this.report(timestamp);
            this.lastReportTime = timestamp;
        }
    }
    /**
     * Record a dropped frame
     */
    recordDroppedFrame() {
        this.droppedFrames++;
    }
    /**
     * Calculate and report metrics
     */
    report(timestamp) {
        if (!this.onUpdate || this.frames.length < 2)
            return;
        // Calculate FPS from frames in last second
        const fps = this.frames.length;
        // Calculate average frame time
        let totalFrameTime = 0;
        for (let i = 1; i < this.frames.length; i++) {
            totalFrameTime += this.frames[i] - this.frames[i - 1];
        }
        const avgFrameTime = this.frames.length > 1 ? totalFrameTime / (this.frames.length - 1) : 0;
        // Check if below target (within 10% tolerance)
        const isBelowTarget = fps < this.targetFPS * 0.9;
        const metrics = {
            fps,
            avgFrameTime,
            droppedFrames: this.droppedFrames,
            totalFrames: this.totalFrames,
            isBelowTarget,
        };
        this.onUpdate(metrics);
    }
    /**
     * Set callback for metrics updates
     */
    setOnUpdate(callback) {
        this.onUpdate = callback;
    }
    /**
     * Update target FPS
     */
    setTargetFPS(fps) {
        this.targetFPS = fps;
        this.targetFrameTime = 1000 / fps;
    }
    /**
     * Get target frame time
     */
    getTargetFrameTime() {
        return this.targetFrameTime;
    }
    /**
     * Reset all metrics
     */
    reset() {
        this.frames = [];
        this.droppedFrames = 0;
        this.totalFrames = 0;
        this.lastReportTime = 0;
    }
    /**
     * Destroy the monitor
     */
    destroy() {
        this.frames = [];
        this.onUpdate = null;
    }
}

export { PerformanceMonitor };
