import { renderHook } from '@testing-library/react';
import { describe, it, expect, vi, afterEach } from 'vitest';

import { useWebVitals, getRating } from './useWebVitals';

describe('useWebVitals', () => {
    afterEach(() => {
        vi.unstubAllGlobals();
    });

    it('does not throw when mounted without a callback', () => {
        expect(() => renderHook(() => useWebVitals())).not.toThrow();
    });

    it('does not throw when mounted with an onMetric callback', () => {
        const onMetric = vi.fn();
        expect(() => renderHook(() => useWebVitals(onMetric))).not.toThrow();
    });

    it('is SSR-safe when PerformanceObserver is undefined', () => {
        vi.stubGlobal('PerformanceObserver', undefined);
        expect(() => renderHook(() => useWebVitals())).not.toThrow();
    });

    it('getRating returns correct rating for LCP values', () => {
        // Under 2500ms = good
        expect(getRating('LCP', 1000)).toBe('good');
        expect(getRating('LCP', 2500)).toBe('good');
        // 2501–4000ms = needs-improvement
        expect(getRating('LCP', 2501)).toBe('needs-improvement');
        expect(getRating('LCP', 4000)).toBe('needs-improvement');
        // Over 4000ms = poor
        expect(getRating('LCP', 4001)).toBe('poor');
    });

    it('getRating returns correct rating for CLS values', () => {
        expect(getRating('CLS', 0.05)).toBe('good');
        expect(getRating('CLS', 0.15)).toBe('needs-improvement');
        expect(getRating('CLS', 0.3)).toBe('poor');
    });

    it('unmounts cleanly without errors', () => {
        const { unmount } = renderHook(() => useWebVitals());
        expect(() => unmount()).not.toThrow();
    });
});
