import { useMemo } from 'react';

export type Unit = 'percent' | 'pixel';

export const useSnapCalculator = (snaps: number[], maxHeight: number, unit: Unit) => {
  const viewportHeightPx = document.documentElement.clientHeight;
  const swipeviewHeightPx =
    unit === 'percent' ? Math.floor(viewportHeightPx * (maxHeight / 100)) : maxHeight;

  const snapsToPixels = useMemo(
    () =>
      snaps?.map(snap =>
        Math.abs(
          (unit === 'percent' ? Math.floor(swipeviewHeightPx * (snap / 100)) : snap) -
            swipeviewHeightPx,
        ),
      ),
    [viewportHeightPx],
  );

  const getPixelToSnap = (pixels: number) => {
    const snapIdx = snapsToPixels?.indexOf(pixels) || 0;
    return snaps?.[snapIdx] || 0;
  };

  const getSnapToPixel = (snap: number) => {
    const snapIdx = snaps?.indexOf(snap) || 0;
    return snapsToPixels?.[snapIdx] || 0;
  };

  return {
    viewportHeightPx,
    snapsToPixels,
    swipeviewHeightPx,
    getPixelToSnap,
    getSnapToPixel,
  };
};
