function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import React, { useState, forwardRef, Fragment, useRef, useEffect } from "react";
import { cx, isNumber } from "../../utils";
import { useForkRef } from "../../hooks";
import { PaginationPages, PaginationActions, PaginationButton, PaginationSection, PaginationButtonGroup, PaginationRoot, PaginationShorter, PaginationActionsLeft, PaginationHelperText } from "./Pagination.styles";
import { getSections, defaultValues } from "./utils";
import { base as viewCSS } from "./variations/_view/base";
import { base as typeCSS } from "./variations/_type/base";
import { base as sizeCSS } from "./variations/_size/base";
import { classes } from "./Pagination.tokens";
import { PaginationQuickJumpToPage } from "./ui/PaginationQuickJumpToPage/PaginationQuickJumpToPage";
import { PaginationSelectPerPage } from "./ui/PaginationSelectPerPage/PaginationSelectPerPage";
export var paginationRoot = function paginationRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), outerValue = _ref2.value, defaultValue = _ref2.defaultValue, helperText = _ref2.helperText, singleLine = _ref2.singleLine, outerPerPage = _ref2.perPage, defaultPerPage = _ref2.defaultPerPage, _ref_slots = _ref2.slots, slots = _ref_slots === void 0 ? defaultValues.slots : _ref_slots, view = _ref2.view, viewCurrentPage = _ref2.viewCurrentPage, _ref_type = _ref2.type, type = _ref_type === void 0 ? defaultValues.type : _ref_type, size = _ref2.size, _ref_pilled = _ref2.pilled, pilled = _ref_pilled === void 0 ? defaultValues.pilled : _ref_pilled, _ref_square = _ref2.square, square = _ref_square === void 0 ? defaultValues.square : _ref_square, _ref_disabledPages = _ref2.disabledPages, disabledPages = _ref_disabledPages === void 0 ? defaultValues.disabledPages : _ref_disabledPages, _ref_count = _ref2.count, count = _ref_count === void 0 ? defaultValues.value : _ref_count, _ref_hasQuickJump = _ref2.hasQuickJump, hasQuickJump = _ref_hasQuickJump === void 0 ? defaultValues.hasQuickJump : _ref_hasQuickJump, _ref_hasPerPage = _ref2.hasPerPage, hasPerPage = _ref_hasPerPage === void 0 ? defaultValues.hasPerPage : _ref_hasPerPage, _ref_perPageList = _ref2.perPageList, perPageList = _ref_perPageList === void 0 ? defaultValues.perPageList : _ref_perPageList, _ref_isCommonButtonStyles = _ref2.isCommonButtonStyles, isCommonButtonStyles = _ref_isCommonButtonStyles === void 0 ? defaultValues.isCommonButtonStyles : _ref_isCommonButtonStyles, _ref_placeholderQuickJump = _ref2.placeholderQuickJump, placeholderQuickJump = _ref_placeholderQuickJump === void 0 ? defaultValues.placeholderQuickJump : _ref_placeholderQuickJump, _ref_textQuickJump = _ref2.textQuickJump, textQuickJump = _ref_textQuickJump === void 0 ? defaultValues.textQuickJump : _ref_textQuickJump, _ref_textPerPage = _ref2.textPerPage, textPerPage = _ref_textPerPage === void 0 ? defaultValues.textPerPage : _ref_textPerPage, leftContent = _ref2.leftContent, rightContent = _ref2.rightContent, _ref_listWidth = _ref2.listWidth, listWidth = _ref_listWidth === void 0 ? 'fit-content' : _ref_listWidth, onChangePageValue = _ref2.onChangePageValue, onChangePerPageValue = _ref2.onChangePerPageValue, onChange = _ref2.onChange, rest = _object_without_properties(_ref2, [
            "value",
            "defaultValue",
            "helperText",
            "singleLine",
            "perPage",
            "defaultPerPage",
            "slots",
            "view",
            "viewCurrentPage",
            "type",
            "size",
            "pilled",
            "square",
            "disabledPages",
            "count",
            "hasQuickJump",
            "hasPerPage",
            "perPageList",
            "isCommonButtonStyles",
            "placeholderQuickJump",
            "textQuickJump",
            "textPerPage",
            "leftContent",
            "rightContent",
            "listWidth",
            "onChangePageValue",
            "onChangePerPageValue",
            "onChange"
        ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
        var _useState = _sliced_to_array(useState(defaultValue || defaultValues.value), 2), pageInner = _useState[0], setPageInner = _useState[1];
        var pageValue = outerValue !== null && outerValue !== void 0 ? outerValue : pageInner;
        var _useState1 = _sliced_to_array(useState(hasPerPage ? defaultPerPage || defaultValues.perPage : undefined), 2), perPageInner = _useState1[0], setPerPageInner = _useState1[1];
        var perPageValue = outerPerPage !== null && outerPerPage !== void 0 ? outerPerPage : perPageInner;
        var pagesRef = useRef(null);
        var _useState2 = _sliced_to_array(useState(0), 2), pagesWidth = _useState2[0], setPagesWidth = _useState2[1];
        var _useState3 = _sliced_to_array(useState(0), 2), rootWidth = _useState3[0], setRootWidth = _useState3[1];
        var rootRef = useRef(null);
        var forkRef = useForkRef(rootRef, ref);
        var pages = Math.ceil(count / (perPageValue || 1));
        var sections = getSections(pageValue, pages, slots);
        var typeClass = classes["".concat(type, "Type")];
        var roundedClass = pilled ? 'circle-circle' : 'square-square';
        var withHasPerPageSelect = hasPerPage && !helperText ? classes.withHasPerPageSelect : undefined;
        var withHasQuickJump = hasQuickJump ? classes.withHasQuickJump : undefined;
        var disabled = disabledPages.map(function(el) {
            return isNumber(el) ? Number(el) : null;
        });
        var pageSetter = function pageSetter(pageValueCandidate) {
            var newPageValue = pageValueCandidate !== null && pageValueCandidate !== void 0 ? pageValueCandidate : defaultValues.value;
            if (newPageValue > pages) {
                newPageValue = pages;
            }
            if (newPageValue < 1) {
                newPageValue = 1;
            }
            if (disabled.includes(newPageValue)) {
                return;
            }
            setPageInner(newPageValue);
            return newPageValue;
        };
        var handleSetPage = function handleSetPage(pageValueCandidate) {
            var newValue = pageSetter(pageValueCandidate);
            onChange === null || onChange === void 0 ? void 0 : onChange(newValue, perPageValue);
            onChangePageValue === null || onChangePageValue === void 0 ? void 0 : onChangePageValue(newValue);
        };
        var handlerSetPerPage = function handlerSetPerPage(newPerPageValue) {
            setPerPageInner(newPerPageValue);
            onChange === null || onChange === void 0 ? void 0 : onChange(pageValue, newPerPageValue);
            onChangePerPageValue === null || onChangePerPageValue === void 0 ? void 0 : onChangePerPageValue(newPerPageValue);
        };
        var handleClick = function handleClick(currentPage) {
            if (isActiveButton(currentPage)) {
                return;
            }
            handleSetPage(currentPage);
        };
        var isActiveButton = function isActiveButton(checkPage) {
            return pageValue === checkPage ? classes.paginationPageButtonActive : '';
        };
        useEffect(function() {
            var observers = [];
            if (pagesRef.current) {
                var pagesObserver = new ResizeObserver(function(entries) {
                    var newWidth = entries[0].contentRect.width;
                    setPagesWidth(newWidth);
                });
                pagesObserver.observe(pagesRef.current);
                observers.push(pagesObserver);
            }
            if (rootRef.current) {
                var rootObserver = new ResizeObserver(function(entries) {
                    var newWidth = entries[0].contentRect.width;
                    setRootWidth(newWidth);
                });
                rootObserver.observe(rootRef.current);
                observers.push(rootObserver);
            }
            return function() {
                observers.forEach(function(observer) {
                    return observer.disconnect();
                });
            };
        }, [
            type
        ]);
        return /*#__PURE__*/ React.createElement(Root, _object_spread({
            size: size,
            view: view,
            viewCurrentPage: viewCurrentPage,
            className: cx(classes.wrapper, typeClass),
            ref: forkRef
        }, rest), /*#__PURE__*/ React.createElement(PaginationRoot, {
            className: typeClass
        }, /*#__PURE__*/ React.createElement(PaginationPages, {
            ref: pagesRef
        }, leftContent && /*#__PURE__*/ React.createElement(PaginationButtonGroup, {
            isCommonButtonStyles: isCommonButtonStyles
        }, leftContent), sections && sections.map(function(section, indexSection) {
            return /*#__PURE__*/ React.createElement(Fragment, {
                key: indexSection
            }, indexSection !== 0 && /*#__PURE__*/ React.createElement(PaginationShorter, {
                stretching: "fixed",
                disabled: true,
                className: classes.buttonDisabled
            }, "..."), /*#__PURE__*/ React.createElement(PaginationSection, null, section.map(function(currentPage, index) {
                return /*#__PURE__*/ React.createElement(PaginationButton, {
                    key: "".concat(currentPage, "_").concat(index),
                    className: cx(classes.paginationPageButton, isActiveButton(currentPage), disabled.includes(currentPage) ? classes.buttonDisabled : ''),
                    pin: roundedClass,
                    disabled: disabled.includes(currentPage),
                    square: square,
                    onClick: function onClick() {
                        return handleClick(currentPage);
                    }
                }, currentPage);
            })));
        }), rightContent && /*#__PURE__*/ React.createElement(PaginationButtonGroup, {
            isCommonButtonStyles: isCommonButtonStyles
        }, rightContent)), /*#__PURE__*/ React.createElement(PaginationActions, {
            style: type === 'compact' ? {
                minWidth: '0px'
            } : {
                width: "calc(100% - ".concat(pagesWidth, "px)")
            },
            className: cx(classes.actions, typeClass, withHasPerPageSelect, withHasQuickJump)
        }, /*#__PURE__*/ React.createElement(PaginationActionsLeft, {
            className: typeClass
        }, hasQuickJump && /*#__PURE__*/ React.createElement(PaginationQuickJumpToPage, {
            placeholderQuickJump: placeholderQuickJump,
            textQuickJump: textQuickJump,
            onChangeValue: handleSetPage
        }), helperText && /*#__PURE__*/ React.createElement(PaginationHelperText, {
            className: cx(typeClass, singleLine ? classes.ellipsisText : ''),
            style: {
                maxWidth: rootWidth
            }
        }, helperText)), hasPerPage && /*#__PURE__*/ React.createElement(PaginationSelectPerPage, {
            textPerPage: textPerPage,
            perPageValue: perPageValue,
            perPageList: perPageList,
            onChangeValue: handlerSetPerPage,
            size: size,
            listWidth: listWidth
        }))));
    });
};
export var paginationConfig = {
    name: 'Pagination',
    tag: 'div',
    layout: paginationRoot,
    base: '',
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        },
        type: {
            css: typeCSS
        }
    },
    defaults: {
        view: 'clear',
        size: 'm'
    }
};
