import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { forwardRef, useRef, useMemo, useState, useLayoutEffect } from 'react';
import { d as BreakpointSm } from './primitive-DXlHdTFb.js';
import { S as SrOnly } from './SrOnly-pnf8ajnh.js';
import { c as cx } from './index-De1g9FRV.js';
import { B as ButtonToggle } from './ButtonToggle-Ct9_5bhC.js';
import { S as SvgMoreHoriz } from './more_horiz-DJgdQiy0.js';
import { M as Menu } from './Menu-wpTyUDac.js';
import { S as SvgKeyboardArrowDown } from './keyboard_arrow_down-C8WQ38p1.js';
import { B as Button } from './Button-Bnt8XUI7.js';
import { F as Flex } from './Flex-DOUtHiPi.js';
import { T as Text } from './Text-J5YtSSXY.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_1vn7j_1",
	"pagination-item-button": "_pagination-item-button_1vn7j_16"
};

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$4 = {
	"pagination-item-overflow-menu": "_pagination-item-overflow-menu_mk7jj_1",
	"pagination-item-overflow-menu-content": "_pagination-item-overflow-menu-content_mk7jj_5"
};

const PaginationOverflowMenu = forwardRef((props, ref) => {
  const { startPage, endPage, length, onItemClick, ...rest } = props;
  return /* @__PURE__ */ jsx("li", { className: styles$4["pagination-item-overflow-menu"], ref, ...rest, children: /* @__PURE__ */ jsx(
    Menu,
    {
      icon: SvgMoreHoriz,
      size: "small",
      appearance: "ghost",
      maxHeight: 200,
      contentClassName: styles$4["pagination-item-overflow-menu-content"],
      "aria-label": "More pages",
      children: Array.from({ length }).map((_, index) => /* @__PURE__ */ jsx(
        Menu.Item,
        {
          label: `${startPage + index}`,
          onClick: () => {
            const selectedPage = startPage + index;
            onItemClick(selectedPage);
            setTimeout(() => {
              document.querySelector('[aria-current="page"]')?.focus();
            }, 100);
          }
        },
        index
      ))
    },
    `${startPage}-${endPage}`
  ) });
});
PaginationOverflowMenu.displayName = "PaginationOverflowMenu";

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

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$3["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$2 = {
	"pagination-list": "_pagination-list_1myx1_1"
};

const PaginationList = forwardRef(
  (props, ref) => {
    const {
      page,
      totalPages,
      hasTotalItemCount,
      children,
      onPageChange,
      className
    } = props;
    const paginationListClassName = cx(styles$2["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$1 = {
	"pagination-total-count": "_pagination-total-count_s9c4p_1"
};

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

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

const Pagination$1 = Object.assign(
  forwardRef(
    function PaginationInner(props, ref) {
      const { className, children, ...rest } = props;
      const paginationClassName = cx(styles.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 = 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,
        "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,
                    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-USDJM5vi.js.map
