import {useEffect} from 'react';
import {
  cancelAnimation,
  makeMutable,
  withTiming,
} from 'react-native-reanimated';
import {useDeviceOrientation} from '@hooks/useDeviceOrientation';
import {OrientationValue} from '@shared/utils';

const getRotationFromOrientation = (orientation: OrientationValue): number => {
  switch (orientation) {
    case 'PORTRAIT':
      return 0;
    case 'LANDSCAPE-LEFT':
      return 90;
    case 'LANDSCAPE-RIGHT':
      return -90;
    case 'PORTRAIT-UPSIDEDOWN':
      return 180;
    default:
      return 0;
  }
};

// Global SharedValues - live outside React lifecycle
export const iconRotationSV = makeMutable(0); // Animated value
export const iconRotationTargetSV = makeMutable(0); // Target value without animation

/**
 * Hook to sync device orientation with the global SharedValue.
 * Call this once at the top level of the Camera screen.
 */
export const useSyncCameraOrientation = () => {
  const {orientation} = useDeviceOrientation();

  useEffect(() => {
    const rotation = getRotationFromOrientation(orientation);
    iconRotationTargetSV.value = rotation;
    iconRotationSV.value = withTiming(rotation, {duration: 400});

    return () => {
      cancelAnimation(iconRotationSV);
    };
  }, [orientation]);
};
