var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
  if (kind === "a" && !f)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _KlevuPagination_instances, _KlevuPagination_handlePageChange, _KlevuPagination_updateUrl;
import { h, Host } from "@stencil/core";
/**
 * Pagination component. Either provide numbers or query result to display the component.
 *
 * @csspart pagination-base The container for pagination
 * @csspart pagination-navigation-previous The previous page button
 * @csspart pagination-navigation-next The next page button
 */
export class KlevuPagination {
  constructor() {
    _KlevuPagination_instances.add(this);
    this.current = undefined;
    this.min = undefined;
    this.max = undefined;
    this.queryResult = undefined;
    this.shouldUpdateUrlForPage = undefined;
  }
  async watchPropHandler(newQueryResult, oldQueryResult) {
    if (newQueryResult.meta.offset !== oldQueryResult.meta.offset) {
      if (this.shouldUpdateUrlForPage && (!newQueryResult.meta.offset || newQueryResult.meta.offset === 0)) {
        const urlSearchParams = new URLSearchParams(window.location.search);
        urlSearchParams.delete("klevu_page");
        __classPrivateFieldGet(this, _KlevuPagination_instances, "m", _KlevuPagination_updateUrl).call(this, urlSearchParams);
      }
    }
  }
  componentDidLoad() {
    if (!this.shouldUpdateUrlForPage) {
      return;
    }
    const urlSearchParams = new URLSearchParams(window.location.search);
    const page = urlSearchParams.get("klevu_page");
    if (page && +page > 0) {
      this.klevuPaginationChange.emit(+page);
    }
  }
  render() {
    let min, max, current;
    if (this.queryResult) {
      min = 1;
      max = Math.floor(this.queryResult.meta.totalResultsFound / this.queryResult.meta.noOfResults) + 1;
      current = Math.floor(this.queryResult.meta.offset / this.queryResult.meta.noOfResults) + 1;
    }
    else {
      if ([this.current, this.max, this.min].some((i) => i === undefined)) {
        throw new Error("queryResult or current, min & max needs to be defined");
      }
      min = this.min;
      max = this.max;
      current = this.current;
    }
    let pages = [];
    for (let i = min; i <= max; i++) {
      pages.push(i);
    }
    if (pages.length > 8) {
      let startIndex = min + 1;
      let endIndex = max - 1;
      let currentStartIndex = current > 3 ? current - 1 : 0;
      let currentEndIndex = current < endIndex - 1 ? currentStartIndex + 2 : endIndex - 1;
      if (currentStartIndex < startIndex) {
        currentStartIndex = startIndex + 1;
        currentEndIndex = currentStartIndex + 2;
      }
      pages = [];
      for (let i = min; i <= startIndex; i++) {
        pages.push(i);
      }
      if (startIndex + 1 < currentStartIndex) {
        pages.push(-1);
      }
      for (let i = currentStartIndex; i <= currentEndIndex; i++) {
        pages.push(i);
      }
      if (currentEndIndex + 1 < endIndex) {
        pages.push(-1);
      }
      for (let i = endIndex; i <= max; i++) {
        pages.push(i);
      }
    }
    return (h(Host, null, h("div", { part: "pagination-base" }, h("klevu-icon", { class: {
        disabled: current === min,
      }, onClick: () => current !== min && __classPrivateFieldGet(this, _KlevuPagination_instances, "m", _KlevuPagination_handlePageChange).call(this, current - 1), name: "navigate_before", part: "pagination-navigation-previous" }), pages.map((i) => {
      if (i == -1) {
        return h("span", { class: "disabled dots" }, "...");
      }
      return (h("span", { class: {
          current: current === i,
        }, onClick: () => current !== i && __classPrivateFieldGet(this, _KlevuPagination_instances, "m", _KlevuPagination_handlePageChange).call(this, i), part: "pagination-page-number" }, i));
    }), h("klevu-icon", { class: {
        disabled: current === max,
      }, onClick: () => current !== max && __classPrivateFieldGet(this, _KlevuPagination_instances, "m", _KlevuPagination_handlePageChange).call(this, current + 1), name: "navigate_next", part: "pagination-navigation-next" }))));
  }
  static get is() { return "klevu-pagination"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["klevu-pagination.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["klevu-pagination.css"]
    };
  }
  static get properties() {
    return {
      "current": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Current page"
        },
        "attribute": "current",
        "reflect": false
      },
      "min": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Min page"
        },
        "attribute": "min",
        "reflect": false
      },
      "max": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Max page"
        },
        "attribute": "max",
        "reflect": false
      },
      "queryResult": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "KlevuQueryResult",
          "resolved": "undefined | { id: string; filters?: (KlevuFilterResultOptions | KlevuFilterResultSlider | KlevuFilterResultRating)[] | undefined; meta: { apiKey: string; isPersonalised: boolean; qTime: number; noOfResults: number; totalResultsFound: number; offset: number; typeOfSearch: KlevuTypeOfSearch; debuggingInformation: unknown; notificationCode: number; searchedTerm: string; klevuImageData?: { processed: { urls: string[]; }[]; } | undefined; tags: string[]; }; records: ({ id: string; } & KlevuRecord)[]; }",
          "references": {
            "KlevuQueryResult": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::KlevuQueryResult"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Query results used to build min, max and current"
        }
      },
      "shouldUpdateUrlForPage": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "To set the page selection value in the url"
        },
        "attribute": "should-update-url-for-page",
        "reflect": false
      }
    };
  }
  static get events() {
    return [{
        "method": "klevuPaginationChange",
        "name": "klevuPaginationChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Page that was changed into"
        },
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        }
      }];
  }
  static get watchers() {
    return [{
        "propName": "queryResult",
        "methodName": "watchPropHandler"
      }];
  }
}
_KlevuPagination_instances = new WeakSet(), _KlevuPagination_handlePageChange = function _KlevuPagination_handlePageChange(page) {
  this.klevuPaginationChange.emit(page);
  if (this.shouldUpdateUrlForPage) {
    const urlSearchParams = new URLSearchParams(window.location.search);
    urlSearchParams.set("klevu_page", `${page}`);
    __classPrivateFieldGet(this, _KlevuPagination_instances, "m", _KlevuPagination_updateUrl).call(this, urlSearchParams);
  }
}, _KlevuPagination_updateUrl = function _KlevuPagination_updateUrl(urlSearchParams) {
  window.history.pushState({}, "", "?" + urlSearchParams.toString());
};
//# sourceMappingURL=klevu-pagination.js.map
