import { CSSProperties, useMemo } from 'react';
import { ARROW_DIMENSIONS, carouselMaxThumbnailPaddingPx } from '../components/consts';

const MAX_COMPACT_CONTENT_SIZE = 3;
const TARGET_ITEM_WIDTH = 260; //px
const INTER_ITEM_GAP = 24; // px between thumbnails
const MEDIUM_ARROW_WIDTH = ARROW_DIMENSIONS.medium.width + ARROW_DIMENSIONS.medium.padding * 2;
const ARROW_BUFFER = MEDIUM_ARROW_WIDTH * 2 + 16; // px to accommodate both arrows + padding
const MAX_ITEM_PADDING = carouselMaxThumbnailPaddingPx * 2; // per-item horizontal padding (left + right)

interface Options {
  widgetWidth: number;
  contentSize?: number;
  isMobile: boolean;
}

interface Result {
  width: number;
  isCompact: boolean;
}

export const useCompactDesktopWidth = ({ widgetWidth, contentSize, isMobile }: Options): Result =>
  useMemo(() => {
    const sanitizedWidth = Math.max(widgetWidth, 0);
    const declaredContentSize = Math.max(1, contentSize ?? 1);

    const canApplyCompactMode =
      !isMobile &&
      sanitizedWidth > 0 &&
      declaredContentSize <= MAX_COMPACT_CONTENT_SIZE;

    if (!canApplyCompactMode) {
      return { width: sanitizedWidth, isCompact: false };
    }

    const visibleItems = Math.min(declaredContentSize, MAX_COMPACT_CONTENT_SIZE);
    const gapCount = Math.max(visibleItems - 1, 0);
    const baseContentWidth = visibleItems * TARGET_ITEM_WIDTH;
    const gapWidth = gapCount * INTER_ITEM_GAP;
    const paddingWidth = visibleItems * MAX_ITEM_PADDING;
    const targetWidth = baseContentWidth + gapWidth + paddingWidth + ARROW_BUFFER;

    if (sanitizedWidth <= targetWidth) {
      return { width: sanitizedWidth, isCompact: false };
    }

    return { width: targetWidth, isCompact: true };
  }, [widgetWidth, contentSize, isMobile]);

export const getCompactContainerStyle = (
  isCompact: boolean,
  width: number,
): CSSProperties | undefined => (
  isCompact && width > 0
    ? {
        maxWidth: `${width}px`,
        marginLeft: 'auto',
        marginRight: 'auto',
        width: '100%',
      }
    : undefined
);

export default useCompactDesktopWidth;
