import 'core-js/modules/es.object.assign.js';
import { __rest } from '../../../_virtual/_tslib.js';
import { jsx } from 'react/jsx-runtime';
import { Grid } from '@mui/material';
import { useEffect } from 'react';
import useCurrentBreakpoint from '../../hooks/useCurrentBreakpoint.js';

const ItemsPerRow = {
  sm: 2,
  md: 3,
  lg: 4,
  xl: 5,
  xxl: 6
};
const GridItem = ({
  children
}) => {
  return jsx(Grid, Object.assign({
    item: true,
    sm: 12 / ItemsPerRow.sm,
    md: 12 / ItemsPerRow.md,
    lg: 12 / ItemsPerRow.lg,
    xl: 12 / ItemsPerRow.xl,
    xxl: 12 / ItemsPerRow.xxl,
    component: "div"
  }, {
    children: children
  }));
};
const GridView = _a => {
  var {
      children,
      containerElement = document.body,
      scrollOffset = 0,
      onScrollEnd
    } = _a,
    props = __rest(_a, ["children", "containerElement", "scrollOffset", "onScrollEnd"]);
  const currentBreakPoint = useCurrentBreakpoint();
  const currentItemsPerRow = ItemsPerRow[currentBreakPoint];
  useEffect(() => {
    const handleScroll = event => {
      if (event.currentTarget instanceof HTMLDivElement) {
        const {
          scrollTop,
          scrollHeight,
          clientHeight
        } = event.currentTarget;
        if (scrollTop + clientHeight + scrollOffset >= scrollHeight) {
          // when responsive the column number will be changed during screen resizing.
          // The next page count should not be a fixed number but need to adjust to fulfill the full size of the page list.
          // eg: 6 columns in XXL, first page is 5 rows total 30 items. if down to MD then 4 columns,
          // there will be 7 rows + 2 columns for the last row. so the next paginate need to be 2 + 4x7 = 30.
          // then the following paginate will still be 28
          const nextColumnsGap = currentItemsPerRow - children.length % currentItemsPerRow;
          onScrollEnd === null || onScrollEnd === void 0 ? void 0 : onScrollEnd(nextColumnsGap, currentItemsPerRow);
        }
      }
    };
    containerElement === null || containerElement === void 0 ? void 0 : containerElement.addEventListener('scroll', handleScroll);
    return () => {
      containerElement === null || containerElement === void 0 ? void 0 : containerElement.removeEventListener('scroll', handleScroll);
    };
  }, [containerElement, scrollOffset, onScrollEnd, children.length, currentItemsPerRow]);
  return jsx(Grid, Object.assign({
    container: true,
    spacing: {
      xs: 1,
      md: 2
    }
  }, props, {
    children: children === null || children === void 0 ? void 0 : children.map((child, index) => jsx(GridItem, {
      children: child
    }, index))
  }));
};

export { GridItem, GridView, GridView as default };
