/*!
 * KoliBri - The accessible HTML-Standard
 */
'use strict';

var index = require('./index-DBbl8tEq.js');
var common = require('./common-DAAt5YQ7.js');
var customClass = require('./custom-class-C8GDf7By.js');
var label = require('./label-VzToxIES.js');
var tooltipAlign = require('./tooltip-align-C2v_joNk.js');
var componentNames = require('./component-names-5KS_pYRF.js');
var i18n = require('./i18n-DL7vJXNn.js');
var dev_utils = require('./dev.utils-Cdn-EtYb.js');
var events = require('./events-DN9qldnr.js');
var uniqueNavLabels = require('./unique-nav-labels-ZxWa1D5d.js');
require('./align-e4FQ7dUp.js');
require('./i18n-CgUN6lev.js');

const validateMax = (component, value, options) => {
    common.watchNumber(component, '_max', value, options);
};

const leftDoubleArrowIcon = {
    left: 'kolicon-chevron-double-left',
};
const leftSingleArrow = {
    left: 'kolicon-chevron-left',
};
const rightSingleArrowIcon = {
    right: 'kolicon-chevron-right',
};
const rightDoubleArrowIcon = {
    right: 'kolicon-chevron-double-right',
};
function getUserLanguage() {
    const userLanguage = navigator.language || 'de-DE';
    const normalizedLanguage = userLanguage.includes('-') ? userLanguage : `${userLanguage}-${userLanguage.toUpperCase()}`;
    return normalizedLanguage;
}
const userLanguage = getUserLanguage();
const NUMBER_FORMATTER = new Intl.NumberFormat(userLanguage, {
    style: 'decimal',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
});
const KolPaginationWc = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.translatePageFirst = i18n.translate('kol-page-first');
        this.translatePageBack = i18n.translate('kol-page-back');
        this.translatePageNext = i18n.translate('kol-page-next');
        this.translatePageLast = i18n.translate('kol-page-last');
        this.translateEntriesPerSite = i18n.translate('kol-entries-per-site');
        this.translatePage = i18n.translate('kol-page');
        this.translatePagination = i18n.translate('kol-pagination');
        this.calcCount = (total, pageSize = 1) => Math.ceil(total / pageSize);
        this.getCount = () => this.calcCount(this.state._max, this.state._pageSize);
        this._boundaryCount = 1;
        this._hasButtons = true;
        this._pageSize = 1;
        this._pageSizeOptions = [];
        this._siblingCount = 1;
        this._tooltipAlign = 'top';
        this.state = {
            _boundaryCount: 1,
            _label: this.translatePagination,
            _hasButtons: {
                first: true,
                last: true,
                next: true,
                previous: true,
            },
            _on: {
                onClick: () => null,
            },
            _page: 0,
            _pageSize: 1,
            _pageSizeOptions: [],
            _siblingCount: 1,
            _max: 0,
        };
        this.onClick = (event, page) => {
            if (typeof this.state._on.onClick === 'function') {
                this.state._on.onClick(event, page);
            }
            if (this.host) {
                events.dispatchDomEvent(this.host, events.KolEvent.click, page);
            }
            this.onChangePage(event, page);
        };
        this.onChangePage = (event, page) => {
            const timeout = setTimeout(() => {
                clearTimeout(timeout);
                if (typeof this.state._on.onChangePage === 'function') {
                    this.state._on.onChangePage(event, page);
                }
                if (this.host) {
                    events.dispatchDomEvent(this.host, events.KolEvent.changePage, page);
                }
            });
        };
        this.onChangePageSize = (event, value) => {
            value = parseInt(value);
            if (typeof value === 'number' && value > 0 && this._pageSize !== value) {
                this._pageSize = value;
                const timeout = setTimeout(() => {
                    clearTimeout(timeout);
                    if (typeof this.state._on.onChangePageSize === 'function') {
                        this.state._on.onChangePageSize(event, this._pageSize);
                    }
                    if (this.host) {
                        events.dispatchDomEvent(this.host, events.KolEvent.changePageSize, this._pageSize);
                    }
                });
            }
        };
        this.onGoToFirst = {
            onClick: (event) => {
                this.onClick(event, 1);
            },
        };
        this.onGoToEnd = {
            onClick: (event) => {
                this.onClick(event, this.getCount());
            },
        };
        this.onGoBackward = {
            onClick: (event) => {
                this.onClick(event, this.state._page - 1);
            },
        };
        this.onGoForward = {
            onClick: (event) => {
                this.onClick(event, this.state._page + 1);
            },
        };
        this.beforePageSize = (_nextValue, nextState) => {
            let pageSize = nextState.has('_pageSize') ? nextState.get('_pageSize') : this.state._pageSize;
            const pageSizeOptions = nextState.has('_pageSizeOptions') ? nextState.get('_pageSizeOptions') : this.state._pageSizeOptions;
            if (Array.isArray(pageSizeOptions) && pageSizeOptions.length > 0) {
                const find = pageSizeOptions.find((option) => option.value === pageSize);
                if (find === undefined) {
                    pageSize = pageSizeOptions[0].value;
                }
                else {
                    pageSize = find.value;
                }
                nextState.set('_pageSize', pageSize);
            }
            const page = nextState.has('_page') ? nextState.get('_page') : this.state._page;
            const total = nextState.has('_max') ? nextState.get('_max') : this.state._max;
            this.syncPage(nextState, page, nextState.get('_pageSize'), total);
        };
        this.syncPage = (nextState, page, pageSize, total) => {
            if (total > 0) {
                const count = this.calcCount(total, pageSize);
                if (count > 0) {
                    if (page > count) {
                        nextState.set('_page', count);
                        this.onChangePage(common.STATE_CHANGE_EVENT, count);
                    }
                    else if (page < 1) {
                        nextState.set('_page', 1);
                        this.onChangePage(common.STATE_CHANGE_EVENT, 1);
                    }
                }
            }
        };
        this.beforePageSizeOptions = (nextValue, nextState) => {
            const options = [];
            if (Array.isArray(nextValue)) {
                for (const value of nextValue) {
                    if (typeof value === 'number') {
                        options.push({
                            label: `${value}`,
                            value: value,
                        });
                    }
                }
            }
            nextState.set('_pageSizeOptions', options);
            this.beforePageSize(options, nextState);
        };
    }
    getPageStart() {
        return Math.max(0, (this.state._page - 1) * this.state._pageSize + 1);
    }
    getPageEnd() {
        const highest = this.state._page * this.state._pageSize;
        if (this.state._max < highest) {
            return this.state._max;
        }
        return highest;
    }
    render() {
        var _a;
        let ellipsis = false;
        const count = this.getCount();
        const pageButtons = Array.from({ length: count }, (_, i) => i + 1).map((page) => {
            if (page <= this.state._boundaryCount ||
                page > count - this.state._boundaryCount ||
                (page >= this.state._page - this.state._siblingCount && page <= this.state._page + this.state._siblingCount)) {
                ellipsis = true;
                if (this.state._page === page) {
                    return this.getSelectedPageButton(page);
                }
                else {
                    return this.getUnselectedPageButton(page);
                }
            }
            else if (ellipsis === true) {
                ellipsis = false;
                return (index.h("li", { key: dev_utils.nonce() }, index.h("span", { class: "kol-pagination__separator", "aria-hidden": "true" })));
            }
            else {
                return null;
            }
        });
        return (index.h(index.Host, { class: "kol-pagination" }, index.h("span", { role: "status", "aria-live": "polite", class: "kol-pagination__entries" }, i18n.translate('kol-table-visible-range', {
            placeholders: {
                start: NUMBER_FORMATTER.format(this.getPageStart()),
                end: NUMBER_FORMATTER.format(this.getPageEnd()),
                total: NUMBER_FORMATTER.format(this.state._max),
            },
        })), index.h("nav", { class: "kol-pagination__navigation", "aria-label": this.state._label }, index.h("ul", { class: "kol-pagination__navigation-list" }, this.state._hasButtons.first && (index.h("li", null, index.h(componentNames.KolButtonWcTag, { class: "kol-pagination__button kol-pagination__button--first", _customClass: this.state._customClass, _disabled: this.state._page <= 1, _icons: leftDoubleArrowIcon, _hideLabel: true, _label: this.translatePageFirst, _on: this.onGoToFirst, _tooltipAlign: this.state._tooltipAlign }))), this.state._hasButtons.previous && (index.h("li", null, index.h(componentNames.KolButtonWcTag, { class: "kol-pagination__button kol-pagination__button--previous", _customClass: this.state._customClass, _disabled: this.state._page <= 1, _icons: leftSingleArrow, _hideLabel: true, _label: this.translatePageBack, _on: this.onGoBackward, _tooltipAlign: this.state._tooltipAlign }))), pageButtons, this.state._hasButtons.next && (index.h("li", null, index.h(componentNames.KolButtonWcTag, { class: "kol-pagination__button kol-pagination__button--next", _customClass: this.state._customClass, _disabled: count <= this.state._page, _icons: rightSingleArrowIcon, _hideLabel: true, _label: this.translatePageNext, _on: this.onGoForward, _tooltipAlign: this.state._tooltipAlign }))), this.state._hasButtons.last && (index.h("li", null, index.h(componentNames.KolButtonWcTag, { class: "kol-pagination__button kol-pagination__button--last", _customClass: this.state._customClass, _disabled: count <= this.state._page, _icons: rightDoubleArrowIcon, _hideLabel: true, _label: this.translatePageLast, _on: this.onGoToEnd, _tooltipAlign: this.state._tooltipAlign }))))), ((_a = this.state._pageSizeOptions) === null || _a === void 0 ? void 0 : _a.length) > 0 && (index.h("div", { class: "page-size" }, index.h(componentNames.KolSelectWcTag, { class: "kol-pagination__page-size-select", _label: this.translateEntriesPerSite, _options: this.state._pageSizeOptions, _on: {
                onChange: this.onChangePageSize,
            }, _value: this.state._pageSize })))));
    }
    getUnselectedPageButton(page) {
        const pageText = NUMBER_FORMATTER.format(page);
        const ariaDescription = `${this.translatePage} ${pageText}`;
        return (index.h("li", { key: dev_utils.nonce() }, index.h(componentNames.KolButtonWcTag, { class: "kol-pagination__button kol-pagination__button--numbers", _ariaDescription: ariaDescription, _customClass: this.state._customClass, _label: pageText, _on: {
                onClick: (event) => {
                    this.onClick(event, page);
                },
            } })));
    }
    getSelectedPageButton(page) {
        const pageText = NUMBER_FORMATTER.format(page);
        const ariaDescription = `${this.translatePage} ${pageText}`;
        return (index.h("li", { key: dev_utils.nonce() }, index.h(componentNames.KolButtonWcTag, { "aria-current": "page", class: "kol-pagination__button kol-pagination__button--selected selected", _ariaDescription: ariaDescription, _customClass: this.state._customClass, _label: pageText })));
    }
    validateBoundaryCount(value) {
        common.watchNumber(this, '_boundaryCount', Math.max(0, value !== null && value !== void 0 ? value : 1));
    }
    validateCustomClass(value) {
        customClass.validateCustomClass(this, value);
    }
    validateLabel(label$1, _oldValue, initial = false) {
        if (!initial) {
            uniqueNavLabels.removeNavLabel(this.state._label);
        }
        label.validateLabel(this, label$1);
        uniqueNavLabels.addNavLabel(this.state._label);
    }
    validateHasButtons(value) {
        common.watchValidator(this, '_hasButtons', (value) => typeof value === 'boolean' || typeof value === 'string' || (typeof value === 'object' && value !== null), new Set(['Boolean', 'PaginationHasButton']), value, {
            hooks: {
                beforePatch: (nextValue, nextState) => {
                    if (typeof nextValue === 'boolean') {
                        nextState.set('_hasButtons', {
                            first: nextValue,
                            last: nextValue,
                            next: nextValue,
                            previous: nextValue,
                        });
                    }
                    else {
                        if (typeof nextValue === 'string') {
                            try {
                                nextValue = common.parseJson(nextValue);
                            }
                            catch (_a) {
                                nextState.delete('_hasButtons');
                            }
                        }
                        if (typeof nextValue === 'object' && nextValue !== null) {
                            nextState.set('_hasButtons', Object.assign(Object.assign({}, this.state._hasButtons), { first: typeof nextValue.first === 'boolean'
                                    ? nextValue.first === true
                                    : this.state._hasButtons.first, last: typeof nextValue.last === 'boolean'
                                    ? nextValue.last === true
                                    : this.state._hasButtons.last, next: typeof nextValue.next === 'boolean'
                                    ? nextValue.next === true
                                    : this.state._hasButtons.next, previous: typeof nextValue.previous === 'boolean'
                                    ? nextValue.previous === true
                                    : this.state._hasButtons.previous }));
                        }
                    }
                },
            },
        });
    }
    validateOn(value) {
        if (typeof value === 'object' && value !== null) {
            this.state = Object.assign(Object.assign({}, this.state), { _on: value });
        }
    }
    validatePage(value) {
        common.watchNumber(this, '_page', value, {
            hooks: {
                beforePatch: (_nextValue, nextState) => {
                    const pageSize = nextState.has('_pageSize') ? nextState.get('_pageSize') : this.state._pageSize;
                    const total = nextState.has('_max') ? nextState.get('_max') : this.state._max;
                    this.syncPage(nextState, _nextValue, pageSize, total);
                },
            },
        });
    }
    validatePageSize(value) {
        common.watchNumber(this, '_pageSize', value, {
            hooks: {
                beforePatch: this.beforePageSize,
            },
        });
    }
    validatePageSizeOptions(value) {
        common.watchJsonArrayString(this, '_pageSizeOptions', (value) => typeof value === 'number', value, undefined, {
            hooks: {
                beforePatch: this.beforePageSizeOptions,
            },
        });
    }
    validateSiblingCount(value) {
        common.watchNumber(this, '_siblingCount', Math.max(0, value !== null && value !== void 0 ? value : 1));
    }
    validateMax(value) {
        validateMax(this, value, {
            hooks: {
                beforePatch: (_nextValue, nextState) => {
                    const page = nextState.has('_page') ? nextState.get('_page') : this.state._page;
                    const pageSize = nextState.has('_pageSize') ? nextState.get('_pageSize') : this.state._pageSize;
                    this.syncPage(nextState, page, pageSize, _nextValue);
                },
            },
        });
    }
    validateTooltipAlign(value) {
        tooltipAlign.validateTooltipAlign(this, value);
    }
    componentWillLoad() {
        this.validateBoundaryCount(this._boundaryCount);
        this.validateCustomClass(this._customClass);
        this.validateHasButtons(this._hasButtons);
        this.validateLabel(this._label, undefined, true);
        this.validateOn(this._on);
        this.validatePage(this._page);
        this.validatePageSize(this._pageSize);
        this.validatePageSizeOptions(this._pageSizeOptions);
        this.validateSiblingCount(this._siblingCount);
        this.validateTooltipAlign(this._tooltipAlign);
        this.validateMax(this._max);
        this.validatePage(this._page);
    }
    disconnectedCallback() {
        uniqueNavLabels.removeNavLabel(this.state._label);
    }
    get host() { return index.getElement(this); }
    static get watchers() { return {
        "_boundaryCount": ["validateBoundaryCount"],
        "_customClass": ["validateCustomClass"],
        "_label": ["validateLabel"],
        "_hasButtons": ["validateHasButtons"],
        "_on": ["validateOn"],
        "_page": ["validatePage"],
        "_pageSize": ["validatePageSize"],
        "_pageSizeOptions": ["validatePageSizeOptions"],
        "_siblingCount": ["validateSiblingCount"],
        "_max": ["validateMax"],
        "_tooltipAlign": ["validateTooltipAlign"]
    }; }
};

exports.kol_pagination_wc = KolPaginationWc;
//# sourceMappingURL=kol-pagination-wc.entry.cjs.js.map
