import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { forwardRef, useState, useRef, useCallback, useMemo, useLayoutEffect } from 'react';
import { d as BreakpointSm } from './primitive-C3RFDRA8.js';
import { S as SrOnly } from './SrOnly-eUpYGpAT.js';
import { c as cx } from './index-De1g9FRV.js';
import { B as ButtonToggle } from './ButtonToggle-DaFQ3DBG.js';
import { S as SvgMoreHoriz } from './more_horiz-DJgdQiy0.js';
import { B as Button } from './Button-BdrrhBTI.js';
import { M as Menu } from './Menu-CCavGohP.js';
import { S as SvgKeyboardArrowDown } from './keyboard_arrow_down-C8WQ38p1.js';
import { F as Flex } from './Flex-WyyZm1bf.js';
import { T as Text } from './Text-3Tbp9SGi.js';
import { S as SvgKeyboardArrowLeft, a as SvgKeyboardArrowRight } from './keyboard_arrow_right-DZWNVytH.js';
import { useTrackingId } from './useTrackingId.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';

import './Pagination.css';const itemStyles = {
	"pagination-item": "_pagination-item_4ug3i_2",
	"pagination-item-button": "_pagination-item-button_4ug3i_15"
};

const PaginationItem = forwardRef(
  (props, ref) => {
    const { page, isActive, onClick, className, ...rest } = props;
    const paginationClassName = cx(itemStyles["pagination-item"], className);
    const paginationButtonClassName = cx(itemStyles["pagination-item-button"], {
      [itemStyles.active]: isActive
    });
    return /* @__PURE__ */ jsx("li", { ref, ...rest, className: paginationClassName, children: /* @__PURE__ */ jsx(
      ButtonToggle,
      {
        className: paginationButtonClassName,
        size: "small",
        onClick,
        "aria-current": isActive ? "page" : void 0,
        "aria-label": isActive ? `Current page, page ${page}` : `Go to page ${page}`,
        checked: isActive,
        children: page
      }
    ) });
  }
);
PaginationItem.displayName = "PaginationItem";

const styles$5 = {
	"pagination-item-overflow-menu": "_pagination-item-overflow-menu_ainsh_2",
	"pagination-item-overflow-menu-content": "_pagination-item-overflow-menu-content_ainsh_7"
};

const SCROLLER_MAX_HEIGHT = 200;
const ITEM_HEIGHT = 32;
const OVERSCAN = 5;
const PaginationOverflowMenu = forwardRef((props, ref) => {
  const { startPage, endPage, length, currentPage, onItemClick, ...rest } = props;
  const [scrollTop, setScrollTop] = useState(0);
  const [pendingFocusPage, setPendingFocusPage] = useState(null);
  const scrollerRef = useRef(null);
  const getInitialFocusPage = useCallback(() => {
    return Math.min(endPage, Math.max(startPage, currentPage));
  }, [currentPage, endPage, startPage]);
  const getScrollTopForIndex = useCallback(
    (index, currentScrollTop) => {
      const itemTop = index * ITEM_HEIGHT;
      const itemBottom = itemTop + ITEM_HEIGHT;
      const viewportBottom = currentScrollTop + SCROLLER_MAX_HEIGHT;
      if (itemTop < currentScrollTop) {
        return itemTop;
      }
      if (itemBottom > viewportBottom) {
        return itemBottom - SCROLLER_MAX_HEIGHT;
      }
      return currentScrollTop;
    },
    []
  );
  const syncScrollTop = useCallback((nextScrollTop) => {
    setScrollTop(nextScrollTop);
    if (scrollerRef.current && scrollerRef.current.scrollTop !== nextScrollTop) {
      scrollerRef.current.scrollTop = nextScrollTop;
    }
  }, []);
  const focusLogicalPage = useCallback(
    (pageNumber) => {
      const targetIndex = pageNumber - startPage;
      const nextScrollTop = getScrollTopForIndex(targetIndex, scrollTop);
      if (nextScrollTop !== scrollTop) {
        syncScrollTop(nextScrollTop);
      }
      setPendingFocusPage(pageNumber);
    },
    [getScrollTopForIndex, scrollTop, startPage, syncScrollTop]
  );
  const handleScroll = useCallback((event) => {
    setScrollTop(event.currentTarget.scrollTop);
  }, []);
  const handleItemKeyDown = useCallback(
    (event, pageNumber) => {
      if (event.code !== "ArrowDown" && event.code !== "ArrowUp") {
        return;
      }
      event.preventDefault();
      event.stopPropagation();
      const nextPage = event.code === "ArrowDown" ? pageNumber === endPage ? startPage : pageNumber + 1 : pageNumber === startPage ? endPage : pageNumber - 1;
      focusLogicalPage(nextPage);
    },
    [endPage, focusLogicalPage, startPage]
  );
  const visibleCount = Math.ceil(SCROLLER_MAX_HEIGHT / ITEM_HEIGHT);
  const startIndex = Math.max(
    0,
    Math.floor(scrollTop / ITEM_HEIGHT) - OVERSCAN
  );
  const endIndex = Math.min(length, startIndex + visibleCount + OVERSCAN * 2);
  const totalSize = length * ITEM_HEIGHT;
  const visibleIndices = useMemo(() => {
    const indices = [];
    for (let i = startIndex; i < endIndex; i++) {
      indices.push(i);
    }
    return indices;
  }, [endIndex, startIndex]);
  useLayoutEffect(() => {
    if (pendingFocusPage === null) {
      return;
    }
    const targetElement = document.querySelector(
      `[data-pagination-page="${pendingFocusPage}"]`
    );
    if (!targetElement) {
      return;
    }
    targetElement.focus();
    setPendingFocusPage(null);
  }, [pendingFocusPage, visibleIndices]);
  return /* @__PURE__ */ jsx("li", { className: styles$5["pagination-item-overflow-menu"], ref, ...rest, children: /* @__PURE__ */ jsx(
    Menu,
    {
      trigger: (triggerProps) => {
        const isOpen = triggerProps["aria-expanded"] === true;
        return /* @__PURE__ */ jsx(
          Button,
          {
            ref: triggerProps.ref,
            onClick: () => {
              if (!isOpen) {
                focusLogicalPage(getInitialFocusPage());
              }
              triggerProps.onClick?.();
            },
            onKeyDown: (event) => {
              if (!isOpen && (event.code === "ArrowDown" || event.code === "ArrowUp")) {
                event.preventDefault();
                event.stopPropagation();
                focusLogicalPage(getInitialFocusPage());
                triggerProps.onClick?.();
                return;
              }
              triggerProps.onKeyDown?.(event);
            },
            "aria-haspopup": triggerProps["aria-haspopup"],
            "aria-controls": triggerProps["aria-controls"],
            "aria-expanded": triggerProps["aria-expanded"],
            "data-state": triggerProps["data-state"],
            icon: SvgMoreHoriz,
            size: "small",
            appearance: "ghost",
            "aria-label": "More pages"
          }
        );
      },
      contentClassName: styles$5["pagination-item-overflow-menu-content"],
      "aria-label": "More pages",
      children: /* @__PURE__ */ jsx(
        "div",
        {
          ref: scrollerRef,
          onScroll: handleScroll,
          style: {
            maxHeight: SCROLLER_MAX_HEIGHT,
            overflowY: "auto",
            position: "relative"
          },
          children: /* @__PURE__ */ jsx(
            "div",
            {
              style: {
                height: totalSize,
                position: "relative",
                width: "100%"
              },
              children: visibleIndices.map((index) => {
                const pageNumber = startPage + index;
                return /* @__PURE__ */ jsx(
                  Menu.Item,
                  {
                    "data-pagination-page": pageNumber,
                    label: `${pageNumber}`,
                    onKeyDown: (event) => handleItemKeyDown(event, pageNumber),
                    onClick: () => {
                      onItemClick(pageNumber);
                      setTimeout(() => {
                        document.querySelector('[aria-current="page"]')?.focus();
                      }, 100);
                    },
                    style: {
                      position: "absolute",
                      top: 0,
                      left: 0,
                      right: 0,
                      transform: `translateY(${index * ITEM_HEIGHT}px)`,
                      height: ITEM_HEIGHT
                    }
                  },
                  pageNumber
                );
              })
            }
          )
        }
      )
    },
    `${startPage}-${endPage}`
  ) });
});
PaginationOverflowMenu.displayName = "PaginationOverflowMenu";

const styles$4 = {
	"pagination-items-per-page-button": "_pagination-items-per-page-button_1m1js_2"
};

const PaginationItemsPerPageMenu = forwardRef((props, ref) => {
  const {
    itemsPerPage,
    itemsPerPageOptions,
    onItemsPerPageChange,
    itemsPerPageLabel = "Rows per page"
  } = props;
  const handleKeyDown = (e) => {
    if (e.code === "ArrowDown" || e.code === "ArrowUp") {
      e.preventDefault();
      const menuId = e.currentTarget.getAttribute("aria-controls");
      setTimeout(() => {
        const menu = menuId ? document.getElementById(menuId) : null;
        const menuItems = menu?.querySelectorAll('[data-anv="menu-item"]') || document.querySelectorAll('[data-anv="menu-item"]');
        menuItems[0]?.focus();
      }, 100);
    }
  };
  return /* @__PURE__ */ jsxs(Flex, { alignItems: "center", gap: "2", ref, children: [
    /* @__PURE__ */ jsx(Text, { size: "small", children: itemsPerPageLabel }),
    /* @__PURE__ */ jsx(
      Menu,
      {
        trigger: ({ ref: ref2, ...rest }) => {
          return /* @__PURE__ */ jsx(
            Button,
            {
              ref: ref2,
              ...rest,
              onKeyDown: handleKeyDown,
              className: styles$4["pagination-items-per-page-button"],
              appearance: "ghost",
              icon: { after: SvgKeyboardArrowDown },
              size: "small",
              children: itemsPerPage
            }
          );
        },
        children: itemsPerPageOptions.map((option) => /* @__PURE__ */ jsx(
          Menu.Item,
          {
            label: option,
            onClick: () => {
              onItemsPerPageChange?.(option);
            }
          },
          option
        ))
      }
    )
  ] });
});
PaginationItemsPerPageMenu.displayName = "PaginationItemsPerPageMenu";

const styles$3 = {
	"pagination-list": "_pagination-list_1apvp_2"
};

const PaginationList = forwardRef(
  (props, ref) => {
    const {
      page,
      totalPages,
      hasTotalItemCount,
      children,
      onPageChange,
      className
    } = props;
    const paginationListClassName = cx(styles$3["pagination-list"], className);
    return /* @__PURE__ */ jsxs("ul", { ref, className: paginationListClassName, children: [
      /* @__PURE__ */ jsx("li", { className: itemStyles["pagination-item"], children: /* @__PURE__ */ jsx(
        Button,
        {
          appearance: "ghost",
          icon: SvgKeyboardArrowLeft,
          size: "small",
          "aria-label": "Previous page",
          disabled: page === 1,
          onClick: () => {
            if (page > 1) {
              onPageChange?.(page - 1);
            }
          }
        }
      ) }),
      children,
      /* @__PURE__ */ jsx("li", { className: itemStyles["pagination-item"], children: /* @__PURE__ */ jsx(
        Button,
        {
          appearance: "ghost",
          icon: SvgKeyboardArrowRight,
          size: "small",
          "aria-label": "Next page",
          disabled: hasTotalItemCount !== false && (totalPages === 0 || page === totalPages),
          onClick: () => {
            if (totalPages === 0 || page < totalPages) {
              onPageChange?.(page + 1);
            }
          }
        }
      ) })
    ] });
  }
);
PaginationList.displayName = "PaginationList";

const styles$2 = {
	"pagination-total-count": "_pagination-total-count_efq0t_2"
};

const PaginationTotalCount = ({
  itemRangeText,
  className
}) => {
  const paginationTotalCountClassName = cx(
    styles$2["pagination-total-count"],
    className
  );
  return /* @__PURE__ */ jsx(
    Text,
    {
      size: "small",
      className: paginationTotalCountClassName,
      "aria-hidden": "true",
      children: itemRangeText
    }
  );
};

const pagination$1 = "_pagination_t09n5_2";
const styles$1 = {
	pagination: pagination$1
};

const Pagination$1 = Object.assign(
  forwardRef(
    function PaginationInner(props, ref) {
      const { className, children, ...rest } = props;
      const paginationClassName = cx(styles$1.pagination, className);
      return /* @__PURE__ */ jsx("nav", { ref, className: paginationClassName, ...rest, children });
    }
  ),
  {
    List: PaginationList,
    Item: PaginationItem,
    OverflowMenu: PaginationOverflowMenu,
    ItemsPerPageMenu: PaginationItemsPerPageMenu,
    TotalCount: PaginationTotalCount
  }
);
Pagination$1.displayName = "Pagination";

const usePaginationArray = ({
  page,
  totalPages,
  maxArrayLength = 7
}) => {
  const prevRef = useRef(null);
  return useMemo(() => {
    const maxPagesToShow = maxArrayLength - 2;
    let result = [];
    const addRange = (start, end) => {
      const count = end - start + 1;
      if (count === 1) {
        result.push({ type: "page", page: start });
      } else if (count >= 2) {
        result.push({
          type: "overflow",
          startPage: start,
          endPage: end,
          length: count
        });
      }
    };
    if (totalPages <= maxArrayLength) {
      result = Array.from({ length: totalPages }, (_, i) => ({
        type: "page",
        page: i + 1
      }));
    } else if (page <= maxPagesToShow) {
      for (let i = 1; i <= maxPagesToShow; i++) {
        result.push({ type: "page", page: i });
      }
      addRange(maxArrayLength - 1, totalPages - 1);
      result.push({ type: "page", page: totalPages });
    } else if (page >= totalPages - maxPagesToShow + 1) {
      result.push({ type: "page", page: 1 });
      addRange(2, totalPages - maxPagesToShow);
      for (let i = totalPages - (maxPagesToShow - 1); i <= totalPages; i++) {
        result.push({ type: "page", page: i });
      }
    } else {
      result.push({ type: "page", page: 1 });
      addRange(2, page - 2);
      result.push({ type: "page", page: page - 1 });
      result.push({ type: "page", page });
      result.push({ type: "page", page: page + 1 });
      addRange(page + 2, totalPages - 1);
      result.push({ type: "page", page: totalPages });
    }
    const prev = prevRef.current;
    let shouldRemakeForJump = false;
    if (prev && prev.totalPages === totalPages && prev.maxArrayLength === maxArrayLength) {
      const start = Math.min(prev.prevPage, page);
      const end = Math.max(prev.prevPage, page);
      const hasOverflowBetween = prev.array.some(
        (item) => item.type === "overflow" && // Check if overflow intersects with the range (not completely covers)
        !(item.endPage < start || item.startPage > end)
      );
      const newPageInOverflow = prev.array.some(
        (item) => item.type === "overflow" && item.startPage <= page && item.endPage >= page
      );
      shouldRemakeForJump = hasOverflowBetween || newPageInOverflow;
    }
    if (shouldRemakeForJump) {
      prevRef.current = {
        array: result,
        totalPages,
        maxArrayLength,
        prevPage: page
      };
      return result;
    }
    if (prev && prev.totalPages === totalPages && prev.maxArrayLength === maxArrayLength && prev.array.some((item) => item.type === "page" && item.page === page)) {
      return prev.array;
    }
    prevRef.current = {
      array: result,
      totalPages,
      maxArrayLength,
      prevPage: page
    };
    return result;
  }, [page, totalPages, maxArrayLength]);
};

const pagination = "_pagination_1pkjs_1";
const styles = {
	pagination: pagination
};

const Pagination = forwardRef(
  (props, ref) => {
    const {
      "aria-label": ariaLabel,
      page,
      itemsPerPage,
      itemsPerPageOptions,
      totalItemCount: totalItemCountProp,
      showCount,
      onPageChange,
      onItemsPerPageChange,
      itemsPerPageLabel,
      className,
      ...rest
    } = props;
    const data = {
      "aria-label": ariaLabel
    };
    const trackingId = useTrackingId({
      name: "Pagination",
      data,
      hasOverride: !!rest["data-tracking-id"]
    });
    const totalItemCount = totalItemCountProp ?? 0;
    const totalPages = Math.ceil(totalItemCount / itemsPerPage);
    const elRef = useRef(null);
    const combinedRef = useMergeRefs([elRef, ref]);
    const [isNarrow, setIsNarrow] = useState(false);
    const pageArray = usePaginationArray({
      page,
      totalPages,
      maxArrayLength: 7
    });
    const isPageAvailable = pageArray.some(
      (item) => item.type === "page" && item.page === page
    );
    if (!isPageAvailable && page !== 1 && totalPages > 0) {
      requestAnimationFrame(() => {
        onPageChange?.(1);
      });
    }
    const firstItem = totalItemCount > 0 ? 1 + (page - 1) * itemsPerPage : 0;
    const lastItem = Math.min(firstItem - 1 + itemsPerPage, totalItemCount);
    const itemRangeText = totalItemCountProp === 0 ? "0 items" : `${firstItem} - ${lastItem} of ${totalItemCount} items`;
    useLayoutEffect(() => {
      const resizeObserver = new ResizeObserver((entries) => {
        const entry = entries[0];
        if (entry) {
          setIsNarrow(
            entry.contentRect.width < Number(BreakpointSm.value.replace("px", ""))
          );
        }
      });
      if (elRef.current) {
        resizeObserver.observe(elRef.current);
      }
      return () => {
        resizeObserver.disconnect();
      };
    }, []);
    return /* @__PURE__ */ jsxs(
      Pagination$1,
      {
        ref: combinedRef,
        "data-tracking-id": trackingId,
        className: cx(styles.pagination, className),
        "aria-label": ariaLabel || "Pagination navigation",
        ...rest,
        children: [
          /* @__PURE__ */ jsx(
            Pagination$1.List,
            {
              page,
              totalPages,
              hasTotalItemCount: totalItemCountProp !== void 0,
              onPageChange: (page2) => onPageChange?.(page2),
              children: pageArray.map((item) => {
                if (item.type === "page") {
                  return /* @__PURE__ */ jsx(
                    Pagination$1.Item,
                    {
                      page: item.page,
                      isActive: item.page === page,
                      onClick: () => onPageChange?.(item.page)
                    },
                    item.page
                  );
                }
                return /* @__PURE__ */ jsx(
                  Pagination$1.OverflowMenu,
                  {
                    startPage: item.startPage,
                    endPage: item.endPage,
                    length: item.length,
                    currentPage: page,
                    onItemClick: (item2) => onPageChange?.(item2)
                  },
                  item.startPage
                );
              })
            }
          ),
          isNarrow === false && /* @__PURE__ */ jsxs(Fragment, { children: [
            itemsPerPageOptions && /* @__PURE__ */ jsx(
              Pagination$1.ItemsPerPageMenu,
              {
                itemsPerPage,
                itemsPerPageOptions,
                onItemsPerPageChange: (itemsPerPage2) => onItemsPerPageChange?.(itemsPerPage2),
                itemsPerPageLabel
              }
            ),
            showCount && totalItemCountProp !== void 0 && /* @__PURE__ */ jsx(Pagination$1.TotalCount, { itemRangeText })
          ] }),
          /* @__PURE__ */ jsxs(SrOnly, { "aria-live": "polite", "aria-atomic": "true", children: [
            "Page ",
            page,
            " of ",
            totalPages,
            ", ",
            itemRangeText
          ] })
        ]
      }
    );
  }
);
Pagination.displayName = "Pagination";

export { Pagination as P };
//# sourceMappingURL=Pagination-YO69lIlZ.js.map
