import { useCallback, useState } from 'react';

import { type CoachMarkStep, type CoachMarkStepWithRef } from './types';

export const useCoachRefs = (steps: CoachMarkStep[]) => {
  const [stepsWithRefs, setStepsWithRefs] = useState<CoachMarkStepWithRef[]>(
    steps.map(step => ({ ...step, ref: null })),
  );

  const setRef = useCallback(
    (index: number) => (node: Element | null) => {
      setStepsWithRefs(previousSteps => {
        if (previousSteps[index]?.ref === node) return previousSteps;
        if (!previousSteps[index]?.ref) {
          const newRefs = [...previousSteps];
          newRefs[index] = { ...newRefs[index], ref: node };
          return newRefs;
        }
        return previousSteps;
      });
    },
    [],
  );

  return { stepsWithRefs, setRef };
};
