// rule: effect-needs-cleanup
// file-path: src/victory-animation/victory-animation.tsx
// audit-verdict: pass
// weakness: react-bench-exact-callsite
// source: React Bench 0.9.11 exhaustive audit 3269b60ea7d5d28fa1517e25c42834d5fb7d6f5d743d8706d1d885a2d1206f33
import React from "react";
import * as d3Ease from "victory-vendor/d3-ease";
import { victoryInterpolator } from "./util";
import TimerContext from "../victory-util/timer-context";

/**
 * Single animation object to interpolate
 */
export type AnimationStyle = { [key: string]: string | number };
/**
 * Animation styles to interpolate
 */

export type AnimationData = AnimationStyle | AnimationStyle[];

export type AnimationEasing =
  | "back"
  | "backIn"
  | "backOut"
  | "backInOut"
  | "bounce"
  | "bounceIn"
  | "bounceOut"
  | "bounceInOut"
  | "circle"
  | "circleIn"
  | "circleOut"
  | "circleInOut"
  | "linear"
  | "linearIn"
  | "linearOut"
  | "linearInOut"
  | "cubic"
  | "cubicIn"
  | "cubicOut"
  | "cubicInOut"
  | "elastic"
  | "elasticIn"
  | "elasticOut"
  | "elasticInOut"
  | "exp"
  | "expIn"
  | "expOut"
  | "expInOut"
  | "poly"
  | "polyIn"
  | "polyOut"
  | "polyInOut"
  | "quad"
  | "quadIn"
  | "quadOut"
  | "quadInOut"
  | "sin"
  | "sinIn"
  | "sinOut"
  | "sinInOut";

export interface VictoryAnimationProps {
  children: (style: AnimationStyle, info: AnimationInfo) => React.ReactElement;
  duration?: number;
  easing?: AnimationEasing;
  delay?: number;
  onEnd?: () => void;
  data: AnimationData;
}

export interface VictoryAnimationState {
  data: AnimationStyle;
  animationInfo: AnimationInfo;
}

export interface AnimationInfo {
  progress: number;
  animating: boolean;
  terminating?: boolean;
}

export interface VictoryAnimation {
  context: React.ContextType<typeof TimerContext>;
}

/** d3-ease changed the naming scheme for ease from "linear" -> "easeLinear" etc. */
const formatAnimationName = (name: AnimationEasing) => {
  const capitalizedName = name.charAt(0).toUpperCase() + name.slice(1);
  return `ease${capitalizedName}`;
};

const DEFAULT_DURATION = 1000;

export const VictoryAnimation = ({
  duration = DEFAULT_DURATION,
  easing = "quadInOut",
  delay = 0,
  data,
  children,
  onEnd,
}: VictoryAnimationProps) => {
  const [state, setState] = React.useState<VictoryAnimationState>({
    data: Array.isArray(data) ? data[0] : data,
    animationInfo: {
      progress: 0,
      animating: false,
    },
  });

  const timer = React.useContext(TimerContext).animationTimer;
  const queue = React.useRef<AnimationStyle[]>(
    Array.isArray(data) ? data.slice(1) : [],
  );
  const interpolator = React.useRef<null | ((value: number) => AnimationStyle)>(
    null,
  );
  const loopID = React.useRef<number | undefined>(undefined);

  // Keep the currently visible style so that a run started later (e.g. after a
  // mid-flight `data` change, or the next step in an array queue) always
  // continues from what's on screen rather than a stale closure value.
  const currentData = React.useRef<AnimationStyle>(
    Array.isArray(data) ? data[0] : data,
  );

  // Latest props, so that an already-subscribed timer callback adopts the most
  // recent `duration`, `easing`, and `onEnd` instead of the values captured
  // when the run started.
  const durationRef = React.useRef(duration);
  const easeRef = React.useRef(d3Ease[formatAnimationName(easing)]);
  const delayRef = React.useRef(delay);
  const onEndRef = React.useRef(onEnd);
  durationRef.current = duration;
  easeRef.current = d3Ease[formatAnimationName(easing)];
  delayRef.current = delay;
  onEndRef.current = onEnd;

  // Identifies the active run. Any run whose generation no longer matches has
  // been superseded and must not render or complete.
  const generation = React.useRef(0);
  const isFirstRender = React.useRef(true);

  const commit = (
    nextData: AnimationStyle,
    animationInfo: AnimationInfo,
  ): void => {
    currentData.current = nextData;
    setState({ data: nextData, animationInfo });
  };

  React.useEffect(() => {
    // Length check prevents us from triggering `onEnd` in `traverseQueue`.
    if (queue.current.length) {
      traverseQueue(generation.current);
    }

    // Clean up the animation loop
    return () => {
      // Invalidate any in-flight or delayed run so it can't fire after unmount.
      generation.current += 1;
      if (loopID.current) {
        timer.unsubscribe(loopID.current);
      } else {
        timer.stop();
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  React.useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }

    // Supersede any run in progress (including a delayed start or a queued
    // step) so it stops rendering and never completes.
    generation.current += 1;
    if (loopID.current) {
      timer.unsubscribe(loopID.current);
      loopID.current = undefined;
    }

    // Continue from the currently visible style toward the new data. Copy the
    // array so the queue's `shift` never mutates the caller's prop.
    queue.current = Array.isArray(data) ? data.slice() : [data];
    traverseQueue(generation.current);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  const traverseQueue = (runID: number) => {
    if (runID !== generation.current) {
      return;
    }
    if (queue.current.length) {
      const nextData = queue.current[0];

      // Interpolate from what's currently on screen to the next target.
      interpolator.current = victoryInterpolator(currentData.current, nextData);

      const start = () => {
        // A `data` change or unmount during the delay may have superseded us.
        if (runID !== generation.current) {
          return;
        }
        loopID.current = timer.subscribe(
          (elapsed: number) => functionToBeRunEachFrame(elapsed, runID),
          durationRef.current,
        );
      };

      if (delayRef.current) {
        setTimeout(start, delayRef.current);
      } else {
        start();
      }
    } else if (onEndRef.current) {
      onEndRef.current();
    }
  };

  const functionToBeRunEachFrame = (elapsed: number, runID: number) => {
    // A superseded run must not render or complete.
    if (runID !== generation.current || !interpolator.current) {
      return;
    }

    // Step can generate imprecise values, sometimes greater than 1
    // if this happens set the state to 1 and return, cancelling the timer
    const duration = durationRef.current;
    const step = duration ? elapsed / duration : 1;

    if (step >= 1) {
      commit(interpolator.current(1), {
        progress: 1,
        animating: false,
        terminating: true,
      });
      if (loopID.current) {
        timer.unsubscribe(loopID.current);
      }
      queue.current.shift();
      traverseQueue(runID);
      return;
    }

    // If we're not at the end of the timer, set the state by passing
    // current step value that's transformed by the ease function to the
    // interpolator, which is cached for performance whenever props are received
    commit(interpolator.current(easeRef.current(step)), {
      progress: step,
      animating: step < 1,
    });
  };

  return children(state.data, state.animationInfo);
};
