import {useLayoutEffect, useState} from 'react';
import {isE2E} from '@config/launchArguments';
import {ScreenOpenPerfTracker} from '@config/sentry';

/**
 * In my tests Android takes around 200ms, ios 500;
 */
const MAX_LOADING_TIME = 600;

/**
 * This hook is used to send Sentry metrics and show a marker in E2E tests if the screen was loaded in less than 600ms.
 */
export const usePerformanceMetrics = () => {
  const [isMarkerVisible, setIsMarkerVisible] = useState(false);

  useLayoutEffect(() => {
    const raf = requestAnimationFrame(() => {
      ScreenOpenPerfTracker.finish();
      if (
        isE2E &&
        ScreenOpenPerfTracker.lastDuration &&
        ScreenOpenPerfTracker.lastDuration < MAX_LOADING_TIME
      ) {
        setIsMarkerVisible(true);
      }
      ScreenOpenPerfTracker.reset();
    });

    return () => {
      cancelAnimationFrame(raf);
    };
  }, []);

  return isE2E && isMarkerVisible;
};
