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 __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var _KlevuQuery_instances, _KlevuQuery_stopFilterListening, _KlevuQuery_lastResult, _KlevuQuery_fetch;
import { applyFilterWithManager, categoryMerchandising, FilterManager, KlevuDomEvents, KlevuFetch, KlevuListenDomEvent, kmcRecommendation, listFilters, search, sendMerchandisingViewEvent, sendSearchEvent, suggestions, } from "@klevu/core";
import { h, Host } from "@stencil/core";
import { KlevuInit } from "../klevu-init/klevu-init";
/**
 * __klevu-query__ component is a special kind of component that makes queries to Klevu defined by the
 * __type__ parameter. It also listens to clicks to __klevu-product__ -component and sends analytical data to Klevu
 * based on that. This components gives you ability to create any kind of UI with Klevu components or by using your own
 * components! Just use __klevu-query__ to fetch the data and __klevu-product__ to render the product
 * cards. Whole content of __klevu-product__ can be replaced with your content.
 */
export class KlevuQuery {
  constructor() {
    _KlevuQuery_instances.add(this);
    _KlevuQuery_stopFilterListening.set(this, void 0);
    _KlevuQuery_lastResult.set(this, void 0);
    this.type = undefined;
    this.disableInitialFetch = undefined;
    this.searchSuggestions = undefined;
    this.sendSearchViewEvent = undefined;
    this.options = undefined;
    this.sort = undefined;
    this.limit = undefined;
    this.offset = undefined;
    this.filterGet = undefined;
    this.filterCount = undefined;
    this.filterWithPrices = undefined;
    this.category = undefined;
    this.categoryTitle = undefined;
    this.searchTerm = undefined;
    this.recommendationId = undefined;
    this.recommendationCartProductIds = undefined;
    this.recommendationCurrentProductId = undefined;
    this.recommendationItemGroupId = undefined;
    this.recommendationCategoryPath = undefined;
    this.manager = new FilterManager();
    this.updateOnFilterChange = undefined;
    this.overrideModifiers = undefined;
  }
  onPropertyChange() {
    this.fetch();
  }
  /**
   * Force component to fetch results. This is called automatically when properties change.
   */
  async fetch() {
    await __classPrivateFieldGet(this, _KlevuQuery_instances, "m", _KlevuQuery_fetch).call(this);
  }
  async connectedCallback() {
    await KlevuInit.ready();
    if (!this.disableInitialFetch) {
      await __classPrivateFieldGet(this, _KlevuQuery_instances, "m", _KlevuQuery_fetch).call(this);
    }
    if (this.updateOnFilterChange) {
      __classPrivateFieldSet(this, _KlevuQuery_stopFilterListening, KlevuListenDomEvent(KlevuDomEvents.FilterSelectionUpdate, async () => {
        await __classPrivateFieldGet(this, _KlevuQuery_instances, "m", _KlevuQuery_fetch).call(this);
      }), "f");
    }
  }
  disconnectedCallback() {
    if (__classPrivateFieldGet(this, _KlevuQuery_stopFilterListening, "f")) {
      __classPrivateFieldGet(this, _KlevuQuery_stopFilterListening, "f").call(this);
    }
  }
  onProductClick(event) {
    var _a, _b, _c, _d, _e, _f;
    const product = event.detail.product;
    if (!__classPrivateFieldGet(this, _KlevuQuery_lastResult, "f") || !product.id) {
      return;
    }
    switch (this.type) {
      case "merchandising":
        if (this.categoryTitle) {
          (_b = (_a = __classPrivateFieldGet(this, _KlevuQuery_lastResult, "f")).categoryMerchandisingClickEvent) === null || _b === void 0 ? void 0 : _b.call(_a, {
            productId: product.id,
            categoryTitle: this.categoryTitle,
            variantId: product.itemGroupId,
          });
        }
        break;
      case "recommendation":
        (_d = (_c = __classPrivateFieldGet(this, _KlevuQuery_lastResult, "f")).recommendationClickEvent) === null || _d === void 0 ? void 0 : _d.call(_c, { productId: product.id, variantId: product.itemGroupId });
        break;
      case "search":
        (_f = (_e = __classPrivateFieldGet(this, _KlevuQuery_lastResult, "f")).searchClickEvent) === null || _f === void 0 ? void 0 : _f.call(_e, { productId: product.id, variantId: product.itemGroupId });
        break;
      default:
        const e = this.type;
        throw new Error(e);
    }
  }
  render() {
    return (h(Host, null, h("slot", null)));
  }
  static get is() { return "klevu-query"; }
  static get properties() {
    return {
      "type": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "\"search\" | \"merchandising\" | \"recommendation\"",
          "resolved": "\"merchandising\" | \"recommendation\" | \"search\"",
          "references": {}
        },
        "required": true,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "What kind of query"
        },
        "attribute": "type",
        "reflect": false
      },
      "disableInitialFetch": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "By default component will fetch results on init or on property change. This can be disabled with this prop."
        },
        "attribute": "disable-initial-fetch",
        "reflect": false
      },
      "searchSuggestions": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "When searching should search suggestions be fetched"
        },
        "attribute": "search-suggestions",
        "reflect": false
      },
      "sendSearchViewEvent": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Should search view event be sent. View event is important for analytical cases.\nIn case of a search this should be used only when creating a landing page for search."
        },
        "attribute": "send-search-view-event",
        "reflect": false
      },
      "options": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "AllQueryOptions",
          "resolved": "undefined | { id: string; categoryPath?: string | undefined; currentProductId?: string | undefined; itemGroupId?: string | undefined; cartProductIds?: string[] | undefined; } | { id: string; searchTerm: string; } & Omit<KlevuBaseQuerySettings, \"query\"> | { id: string; typeOfRecords: KlevuAnyTypeOfRecord[]; } & Omit<KlevuBaseQuerySettings, \"query\">",
          "references": {
            "AllQueryOptions": {
              "location": "local",
              "path": "/home/runner/work/frontend-sdk/frontend-sdk/packages/klevu-ui/src/components/klevu-query/klevu-query.tsx",
              "id": "src/components/klevu-query/klevu-query.tsx::AllQueryOptions"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Object to override and settings on search options"
        }
      },
      "sort": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "KlevuSearchSorting",
          "resolved": "KlevuSearchSorting.AdvancedSorting | KlevuSearchSorting.NameAsc | KlevuSearchSorting.NameDesc | KlevuSearchSorting.NewArrivalAsc | KlevuSearchSorting.NewArrivalDesc | KlevuSearchSorting.PriceAsc | KlevuSearchSorting.PriceDesc | KlevuSearchSorting.RatingAsc | KlevuSearchSorting.RatingDesc | KlevuSearchSorting.Relevance | undefined",
          "references": {
            "KlevuSearchSorting": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::KlevuSearchSorting"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "How to sort"
        },
        "attribute": "sort",
        "reflect": false
      },
      "limit": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "What's the limit on page"
        },
        "attribute": "limit",
        "reflect": false
      },
      "offset": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Offset of results"
        },
        "attribute": "offset",
        "reflect": false
      },
      "filterGet": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Fetch filters on the request"
        },
        "attribute": "filter-get",
        "reflect": false
      },
      "filterCount": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "To how many filters limit results to"
        },
        "attribute": "filter-count",
        "reflect": false
      },
      "filterWithPrices": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Should get price filters"
        },
        "attribute": "filter-with-prices",
        "reflect": false
      },
      "category": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Which category to do merchandising. Required for \"merchandising\" type"
        },
        "attribute": "category",
        "reflect": false
      },
      "categoryTitle": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Which category title to have on page. Required for \"merchandising\" type"
        },
        "attribute": "category-title",
        "reflect": false
      },
      "searchTerm": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "What to search. Required for \"search\" type."
        },
        "attribute": "search-term",
        "reflect": false
      },
      "recommendationId": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Which recommendation to fetch from Klevu Merchant Center. Required for \"recommendation\" type"
        },
        "attribute": "recommendation-id",
        "reflect": false
      },
      "recommendationCartProductIds": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "string[]",
          "resolved": "string[] | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Which products are in cart. Required for some recommendation types"
        }
      },
      "recommendationCurrentProductId": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Which product is currently being viewed. Required for some recommendation types"
        },
        "attribute": "recommendation-current-product-id",
        "reflect": false
      },
      "recommendationItemGroupId": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "What is the item group id of the product being viewed. Required for some recommendation types"
        },
        "attribute": "recommendation-item-group-id",
        "reflect": false
      },
      "recommendationCategoryPath": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Which category path to use for recommendation. Required for some recommendation types"
        },
        "attribute": "recommendation-category-path",
        "reflect": false
      },
      "manager": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "FilterManager",
          "resolved": "FilterManager",
          "references": {
            "FilterManager": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::FilterManager"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "klevu",
              "text": "/core FilterManager used for filters. If none is set, new one is created"
            }],
          "text": ""
        },
        "defaultValue": "new FilterManager()"
      },
      "updateOnFilterChange": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Should component listen to changes to filters"
        },
        "attribute": "update-on-filter-change",
        "reflect": false
      },
      "overrideModifiers": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "KlevuFetchModifer[]",
          "resolved": "KlevuFetchModifer[] | undefined",
          "references": {
            "KlevuFetchModifer": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::KlevuFetchModifer"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Override default modifiers. This will disable default modifiers and ones set by filter props"
        }
      }
    };
  }
  static get events() {
    return [{
        "method": "klevuQueryResult",
        "name": "klevuQueryResult",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "{\n    result: KlevuQueryResult\n    suggestions?: KlevuSuggestionResult\n    manager: FilterManager\n  }",
          "resolved": "{ result: KlevuQueryResult; suggestions?: KlevuSuggestionResult | undefined; manager: FilterManager; }",
          "references": {
            "KlevuQueryResult": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::KlevuQueryResult"
            },
            "KlevuSuggestionResult": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::KlevuSuggestionResult"
            },
            "FilterManager": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::FilterManager"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "fetch": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Force component to fetch results. This is called automatically when properties change.",
          "tags": []
        }
      }
    };
  }
  static get watchers() {
    return [{
        "propName": "manager",
        "methodName": "onPropertyChange"
      }, {
        "propName": "recommendationId",
        "methodName": "onPropertyChange"
      }, {
        "propName": "searchTerm",
        "methodName": "onPropertyChange"
      }, {
        "propName": "categoryTitle",
        "methodName": "onPropertyChange"
      }, {
        "propName": "category",
        "methodName": "onPropertyChange"
      }, {
        "propName": "filterCount",
        "methodName": "onPropertyChange"
      }, {
        "propName": "offset",
        "methodName": "onPropertyChange"
      }, {
        "propName": "limit",
        "methodName": "onPropertyChange"
      }, {
        "propName": "sort",
        "methodName": "onPropertyChange"
      }, {
        "propName": "options",
        "methodName": "onPropertyChange"
      }, {
        "propName": "type",
        "methodName": "onPropertyChange"
      }];
  }
  static get listeners() {
    return [{
        "name": "klevuProductClick",
        "method": "onProductClick",
        "target": "body",
        "capture": true,
        "passive": false
      }];
  }
}
_KlevuQuery_stopFilterListening = new WeakMap(), _KlevuQuery_lastResult = new WeakMap(), _KlevuQuery_instances = new WeakSet(), _KlevuQuery_fetch = async function _KlevuQuery_fetch() {
  var _a, _b, _c;
  const options = Object.assign({ limit: this.limit, sort: this.sort, id: "klevuquery", offset: this.offset }, this.options);
  const modifiers = [];
  if (this.filterGet) {
    modifiers.push(listFilters({
      filterManager: this.manager,
      limit: this.filterCount,
      rangeFilterSettings: this.filterWithPrices
        ? [
          {
            key: "klevu_price",
            minMax: true,
          },
        ]
        : undefined,
    }));
    modifiers.push(applyFilterWithManager(this.manager));
  }
  switch (this.type) {
    case "merchandising": {
      if (!this.category || !this.categoryTitle) {
        throw new Error("Missing category or category title");
      }
      if (this.sendSearchViewEvent) {
        modifiers.push(sendMerchandisingViewEvent(this.categoryTitle));
      }
      const usedModifiers = this.overrideModifiers || modifiers;
      const result = await KlevuFetch(categoryMerchandising(this.category, options, ...usedModifiers));
      const resultObject = result.queriesById("klevuquery");
      if (!resultObject) {
        console.error("KlevuQuery: Response meta", (_a = result.apiResponse) === null || _a === void 0 ? void 0 : _a.meta);
        throw new Error("KlevuQuery: Couldn't do fetch.");
      }
      __classPrivateFieldSet(this, _KlevuQuery_lastResult, resultObject, "f");
      this.klevuQueryResult.emit({
        result: resultObject,
        manager: this.manager,
      });
      break;
    }
    case "recommendation": {
      if (!this.recommendationId) {
        throw new Error("Recommendation requires KMC id");
      }
      const usedModifiers = this.overrideModifiers || modifiers;
      const result = await KlevuFetch(kmcRecommendation(this.recommendationId, {
        cartProductIds: this.recommendationCartProductIds,
        categoryPath: this.recommendationCategoryPath,
        currentProductId: this.recommendationCurrentProductId,
        itemGroupId: this.recommendationItemGroupId,
      }, ...usedModifiers));
      const resultObject = result.queriesById("klevuquery");
      if (!resultObject) {
        console.error("KlevuQuery: Response meta", (_b = result.apiResponse) === null || _b === void 0 ? void 0 : _b.meta);
        throw new Error("KlevuQuery: Couldn't do fetch.");
      }
      __classPrivateFieldSet(this, _KlevuQuery_lastResult, resultObject, "f");
      this.klevuQueryResult.emit({
        result: resultObject,
        manager: this.manager,
      });
      break;
    }
    case "search": {
      if (!this.searchTerm) {
        throw new Error("Search query requires search term");
      }
      if (this.sendSearchViewEvent) {
        modifiers.push(sendSearchEvent());
      }
      const usedModifiers = this.overrideModifiers || modifiers;
      const queries = [search(this.searchTerm, options, ...usedModifiers)];
      if (this.searchSuggestions) {
        queries.push(suggestions(this.searchTerm));
      }
      const result = await KlevuFetch(...queries);
      const resultObject = result.queriesById("klevuquery");
      const suggestionsResult = result.suggestionsById("suggestions");
      if (!resultObject) {
        console.error("KlevuQuery: Response meta", (_c = result.apiResponse) === null || _c === void 0 ? void 0 : _c.meta);
        throw new Error("KlevuQuery: Couldn't do fetch.");
      }
      __classPrivateFieldSet(this, _KlevuQuery_lastResult, resultObject, "f");
      this.klevuQueryResult.emit({
        result: resultObject,
        manager: this.manager,
        suggestions: suggestionsResult,
      });
      break;
    }
    default:
      const e = this.type;
      throw new Error(e);
  }
};
//# sourceMappingURL=klevu-query.js.map
