import {Easing, withRepeat, withTiming} from 'react-native-reanimated';

export const SPARKLE_STAR_COUNT = 3;

/** Full wave period — linear driver, no dead time between loops. */
export const SPARKLE_CYCLE_MS = 900;

/**
 * Each star's twinkle window as a fraction of the cycle.
 * > 1/3 guarantees overlap so one star is always easing.
 */
export const SPARKLE_TWINKLE_RATIO = 0.45;

export const TWINKLE_MIN_OPACITY = 0.58;

export const SPARKLE_CYCLE_EASING = Easing.linear;

export const buildSparkleCycle = () =>
  withRepeat(
    withTiming(1, {
      duration: SPARKLE_CYCLE_MS,
      easing: SPARKLE_CYCLE_EASING,
    }),
    -1,
    false,
  );

export const getSparkleOpacity = (
  cycleProgress: number,
  starIndex: number,
  isActive: boolean,
): number => {
  'worklet';

  if (!isActive) {
    return 1;
  }

  const starOffset = starIndex / SPARKLE_STAR_COUNT;
  let localPhase = cycleProgress - starOffset;

  if (localPhase < 0) {
    localPhase += 1;
  }

  if (localPhase >= SPARKLE_TWINKLE_RATIO) {
    return 1;
  }

  const t = localPhase / SPARKLE_TWINKLE_RATIO;
  const wave = Math.sin(t * Math.PI);

  return TWINKLE_MIN_OPACITY + (1 - TWINKLE_MIN_OPACITY) * (1 - wave);
};
