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 __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 _KlevuSearchField_lastQueryResult, _KlevuSearchField_doSearch, _KlevuSearchField_handleChange, _KlevuSearchField_handleSearchClick;
import { fallback, klaviyo, KlevuFetch, KlevuTypeOfRecord, personalisation, search, sendSearchEvent, suggestions, } from "@klevu/core";
import { h, Host } from "@stencil/core";
import { debounce } from "../../utils/utils";
import { KlevuInit } from "../klevu-init/klevu-init";
import { getTranslation } from "../../utils/getTranslation";
import { getKMCSettings } from "../../utils/getKMCSettings";
/**
 * Plain textfield that does the searching. It queries Klevu and returns the results
 * in a custom event. Then you can decide what to do with the results.
 */
export class KlevuSearchField {
  constructor() {
    _KlevuSearchField_lastQueryResult.set(this, void 0);
    _KlevuSearchField_doSearch.set(this, debounce(async (term) => {
      if (term.length < 3) {
        return;
      }
      const searchModifiers = [];
      // if fallback term is defined use it to search
      if (this.fallbackTerm && this.searchProducts) {
        searchModifiers.push(fallback(search(this.fallbackTerm, {
          limit: this.limit,
        })));
      }
      if (this.sendAnalytics) {
        searchModifiers.push(sendSearchEvent());
      }
      if (this.usePersonalisation) {
        searchModifiers.push(personalisation());
      }
      if (this.useKlaviyo) {
        console.log("pushing klaviyo");
        searchModifiers.push(klaviyo());
      }
      const allSearchQueries = [];
      if (this.searchProducts) {
        allSearchQueries.push(search(term, { limit: this.limit, typeOfRecords: [KlevuTypeOfRecord.Product], sort: this.sort }, ...searchModifiers));
      }
      if (this.searchCmsPages) {
        allSearchQueries.push(search(term, { id: "cmsSearch", limit: this.limit, typeOfRecords: [KlevuTypeOfRecord.Cms], sort: this.sort }));
      }
      if (this.searchCategories) {
        allSearchQueries.push(search(term, {
          id: "categorySearch",
          limit: this.limit,
          typeOfRecords: [KlevuTypeOfRecord.Category],
          sort: this.sort,
        }));
      }
      if (this.searchSuggestions) {
        allSearchQueries.push(suggestions(term));
      }
      if (allSearchQueries.length === 0) {
        throw new Error("You need specify at least one thing to search");
      }
      const result = await KlevuFetch(...allSearchQueries);
      __classPrivateFieldSet(this, _KlevuSearchField_lastQueryResult, {
        fallback: result.queryExists("search-fallback") ? result.queriesById("search-fallback") : undefined,
        search: result.queryExists("search") ? result.queriesById("search") : undefined,
        category: result.queryExists("categorySearch") ? result.queriesById("categorySearch") : undefined,
        cms: result.queryExists("cmsSearch") ? result.queriesById("cmsSearch") : undefined,
      }, "f");
      this.klevuSearchResults.emit(__classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f"));
      const suggestionsResult = result.suggestionsById("suggestions");
      if (suggestionsResult) {
        this.klevuSearchSuggestions.emit(suggestionsResult.suggestions.map((s) => s.suggest));
      }
    }, 500)
    /**
     * Fetch next page of results from previous query
     *
     * @param type what type of content to get page from
     * @param pageIndex from what page. If empty next page is fetched
     */
    );
    _KlevuSearchField_handleChange.set(this, (event) => {
      this.term = event.detail;
      __classPrivateFieldGet(this, _KlevuSearchField_doSearch, "f").call(this, event.detail);
    });
    _KlevuSearchField_handleSearchClick.set(this, () => {
      this.klevuSearchClick.emit(this.term);
    });
    this.term = "";
    this.tPlaceholder = getTranslation("searchField.tPlaceholder");
    this.tSearchText = getTranslation("searchField.tSearchText");
    this.limit = 10;
    this.fallbackTerm = undefined;
    this.searchProducts = undefined;
    this.searchSuggestions = undefined;
    this.searchCategories = undefined;
    this.searchCmsPages = undefined;
    this.sendAnalytics = undefined;
    this.sort = undefined;
    this.variant = "default";
    this.usePersonalisation = undefined;
    this.useKlaviyo = undefined;
  }
  async connectedCallback() {
    await KlevuInit.ready();
    const settings = getKMCSettings();
    if (this.usePersonalisation === undefined && (settings === null || settings === void 0 ? void 0 : settings.klevu_uc_userOptions.enablePersonalisationInSearch)) {
      this.usePersonalisation = true;
    }
  }
  /**
   * Programmatically trigger search
   *
   * @param term What to search
   */
  async makeSearch(term) {
    this.term = term;
    await __classPrivateFieldGet(this, _KlevuSearchField_doSearch, "f").call(this, term);
  }
  /**
   * Fetch next page of results from previous query
   *
   * @param type what type of content to get page from
   * @param pageIndex from what page. If empty next page is fetched
   */
  async getPage(type, pageIndex) {
    if (!__classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f")) {
      throw new Error("No search results to get page from");
    }
    switch (type) {
      case "search": {
        const res = __classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f").search;
        if (res && res.getPage) {
          const result = await res.getPage({ pageIndex });
          __classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f").search = result === null || result === void 0 ? void 0 : result.queriesById("search");
          this.klevuSearchResults.emit({
            search: result === null || result === void 0 ? void 0 : result.queriesById("search"),
          });
        }
      }
      case "category": {
        const res = __classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f").category;
        if (res && res.getPage) {
          const result = await res.getPage({ pageIndex });
          __classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f").category = result === null || result === void 0 ? void 0 : result.queriesById("categorySearch");
          this.klevuSearchResults.emit({
            category: result === null || result === void 0 ? void 0 : result.queriesById("categorySearch"),
          });
        }
      }
      case "cms": {
        const res = __classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f").cms;
        if (res && res.getPage) {
          const result = await res.getPage({ pageIndex });
          __classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f").cms = result === null || result === void 0 ? void 0 : result.queriesById("cmsSearch");
          this.klevuSearchResults.emit({
            cms: result === null || result === void 0 ? void 0 : result.queriesById("cmsSearch"),
          });
        }
      }
    }
  }
  /**
   * Fetches query result from last request
   *
   * @param type type of query result
   * @returns
   */
  async getQueryResult(type) {
    if (!__classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f")) {
      throw new Error("No search results to get query results");
    }
    return __classPrivateFieldGet(this, _KlevuSearchField_lastQueryResult, "f")[type];
  }
  async propsChanged() {
    __classPrivateFieldGet(this, _KlevuSearchField_doSearch, "f").call(this, this.term);
  }
  render() {
    return (h(Host, null, h("klevu-textfield", { value: this.term, placeholder: this.tPlaceholder, onKlevuTextChanged: __classPrivateFieldGet(this, _KlevuSearchField_handleChange, "f").bind(this), onKlevuTextEnterPressed: __classPrivateFieldGet(this, _KlevuSearchField_handleSearchClick, "f").bind(this), "aria-role": "search", variant: this.variant, icon: "search" }, h("slot", { name: "end-of-input", slot: "end" })), this.variant !== "pill" && (h("klevu-button", { onClick: __classPrivateFieldGet(this, _KlevuSearchField_handleSearchClick, "f").bind(this) }, this.tSearchText))));
  }
  static get is() { return "klevu-search-field"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["klevu-search-field.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["klevu-search-field.css"]
    };
  }
  static get properties() {
    return {
      "tPlaceholder": {
        "type": "any",
        "mutable": false,
        "complexType": {
          "original": "any",
          "resolved": "any",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "The placeholder text to display in the search field."
        },
        "attribute": "t-placeholder",
        "reflect": false,
        "defaultValue": "getTranslation(\"searchField.tPlaceholder\")"
      },
      "tSearchText": {
        "type": "any",
        "mutable": false,
        "complexType": {
          "original": "any",
          "resolved": "any",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Button text"
        },
        "attribute": "t-search-text",
        "reflect": false,
        "defaultValue": "getTranslation(\"searchField.tSearchText\")"
      },
      "limit": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Maximum amount of results"
        },
        "attribute": "limit",
        "reflect": false,
        "defaultValue": "10"
      },
      "fallbackTerm": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Fallback term to use if there are no results"
        },
        "attribute": "fallback-term",
        "reflect": false
      },
      "searchProducts": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Should search products"
        },
        "attribute": "search-products",
        "reflect": false
      },
      "searchSuggestions": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Should search suggestions"
        },
        "attribute": "search-suggestions",
        "reflect": false
      },
      "searchCategories": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Should try to find categories as well"
        },
        "attribute": "search-categories",
        "reflect": false
      },
      "searchCmsPages": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Should try to find cms pages as well"
        },
        "attribute": "search-cms-pages",
        "reflect": false
      },
      "sendAnalytics": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Sends analytics when making query"
        },
        "attribute": "send-analytics",
        "reflect": false
      },
      "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": "In case you want to sort the results"
        },
        "attribute": "sort",
        "reflect": false
      },
      "variant": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "SearchFieldVariant",
          "resolved": "\"default\" | \"pill\"",
          "references": {
            "SearchFieldVariant": {
              "location": "local",
              "path": "/home/runner/work/frontend-sdk/frontend-sdk/packages/klevu-ui/src/components/klevu-search-field/klevu-search-field.tsx",
              "id": "src/components/klevu-search-field/klevu-search-field.tsx::SearchFieldVariant"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Variant of the search field"
        },
        "attribute": "variant",
        "reflect": false,
        "defaultValue": "\"default\""
      },
      "usePersonalisation": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Enable personalisation on the query"
        },
        "attribute": "use-personalisation",
        "reflect": false
      },
      "useKlaviyo": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Enable Klaviyo integration for search terms and clicks"
        },
        "attribute": "use-klaviyo",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "term": {}
    };
  }
  static get events() {
    return [{
        "method": "klevuSearchResults",
        "name": "klevuSearchResults",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "When results come from after typing in the search field. This is debounced to avoid excessive requests."
        },
        "complexType": {
          "original": "SearchResultsEventData",
          "resolved": "{ fallback?: KlevuResponseQueryObject | undefined; search?: KlevuResponseQueryObject | undefined; category?: KlevuResponseQueryObject | undefined; cms?: KlevuResponseQueryObject | undefined; }",
          "references": {
            "SearchResultsEventData": {
              "location": "local",
              "path": "/home/runner/work/frontend-sdk/frontend-sdk/packages/klevu-ui/src/components/klevu-search-field/klevu-search-field.tsx",
              "id": "src/components/klevu-search-field/klevu-search-field.tsx::SearchResultsEventData"
            }
          }
        }
      }, {
        "method": "klevuSearchSuggestions",
        "name": "klevuSearchSuggestions",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "When searchfield gives some suggestions"
        },
        "complexType": {
          "original": "SuggestionsEventData",
          "resolved": "string[]",
          "references": {
            "SuggestionsEventData": {
              "location": "local",
              "path": "/home/runner/work/frontend-sdk/frontend-sdk/packages/klevu-ui/src/components/klevu-search-field/klevu-search-field.tsx",
              "id": "src/components/klevu-search-field/klevu-search-field.tsx::SuggestionsEventData"
            }
          }
        }
      }, {
        "method": "klevuSearchClick",
        "name": "klevuSearchClick",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "When user clicks search button. Returns the search term."
        },
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "makeSearch": {
        "complexType": {
          "signature": "(term: string) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "term What to search"
                }],
              "text": "What to search"
            }],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Programmatically trigger search",
          "tags": [{
              "name": "param",
              "text": "term What to search"
            }]
        }
      },
      "getPage": {
        "complexType": {
          "signature": "(type: \"search\" | \"category\" | \"cms\", pageIndex?: number) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "type what type of content to get page from"
                }],
              "text": "what type of content to get page from"
            }, {
              "tags": [{
                  "name": "param",
                  "text": "pageIndex from what page. If empty next page is fetched"
                }],
              "text": "from what page. If empty next page is fetched"
            }],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Fetch next page of results from previous query",
          "tags": [{
              "name": "param",
              "text": "type what type of content to get page from"
            }, {
              "name": "param",
              "text": "pageIndex from what page. If empty next page is fetched"
            }]
        }
      },
      "getQueryResult": {
        "complexType": {
          "signature": "(type: \"search\" | \"category\" | \"cms\") => Promise<KlevuResponseQueryObject | undefined>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "type type of query result"
                }],
              "text": "type of query result"
            }],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            },
            "KlevuResponseQueryObject": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::KlevuResponseQueryObject"
            }
          },
          "return": "Promise<KlevuResponseQueryObject | undefined>"
        },
        "docs": {
          "text": "Fetches query result from last request",
          "tags": [{
              "name": "param",
              "text": "type type of query result"
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      }
    };
  }
  static get watchers() {
    return [{
        "propName": "sort",
        "methodName": "propsChanged"
      }];
  }
}
_KlevuSearchField_lastQueryResult = new WeakMap(), _KlevuSearchField_doSearch = new WeakMap(), _KlevuSearchField_handleChange = new WeakMap(), _KlevuSearchField_handleSearchClick = new WeakMap();
//# sourceMappingURL=klevu-search-field.js.map
