import { useState, useEffect, useRef } from 'react';

export type NetworkQuality = 'good' | 'unstable' | 'offline';

export const useNetworkStatus = (): NetworkQuality => {
    const [quality, setQuality] = useState<NetworkQuality>(navigator.onLine ? 'good' : 'offline');
    const dropCountRef = useRef(0);
    const resetTimerRef = useRef<number | null>(null);

    useEffect(() => {
        const handleOffline = () => {
            console.log('[NETWORK] Offline');
            setQuality('offline');
        };

        const handleOnline = () => {
            console.log('[NETWORK] Back online');
            dropCountRef.current++;

            // 3+ drops in 2 minutes = unstable
            if (dropCountRef.current >= 3) {
                setQuality('unstable');
            } else {
                setQuality('good');
            }

            // Reset drop counter after 2 minutes of stability
            if (resetTimerRef.current) clearTimeout(resetTimerRef.current);
            resetTimerRef.current = window.setTimeout(() => {
                dropCountRef.current = 0;
                if (navigator.onLine) setQuality('good');
            }, 120000);
        };

        window.addEventListener('offline', handleOffline);
        window.addEventListener('online', handleOnline);

        return () => {
            window.removeEventListener('offline', handleOffline);
            window.removeEventListener('online', handleOnline);
            if (resetTimerRef.current) clearTimeout(resetTimerRef.current);
        };
    }, []);

    return quality;
};
