/*!
 * Custom elements for Nanopore-Digital Web applications
 */
import { Host, getAssetPath, Build, } from "@stencil/core";
import algoliaSearch from "algoliasearch/dist/algoliasearch-lite.esm.browser";
import { h } from "../../utils/renderer";
import { debounce } from "../../utils/throttle";
import { addGlobalStylesheetToShadow } from "../../utils/style";
import searchInsight from "../../utils/search-insights";
const MIN_SEARCH_LENGTH = 3;
/**
 * The Global nav component standardises navigation within and across web applications.
 *
 * @version 8.0.0
 * @status new
 *
 * @slot menu - Main menu items. Can be used with `<nano-nav-item>` or `<a>` elements.
 * @slot - Main site content.
 *
 * @part main-menu - The main menu bar nav element.
 * @part search-form - The search form element.
 * @part search-input - The search input element.
 * @part search-select - The search select element.
 * @part wrapper - The main wrapper for the component.
 * @part drawer - The drawer element which controls the overflow menu.
 * @part overflow-header - The header for the overflow menu.
 * @part overflow-menu - The overflow menu items.
 * @part menu-bar - The main menu bar.
 * @part site-wrapper - The main site content area.
 * @part logo-link - The logo link element.
 * @part logo - The logo element.
 * @part user-panel - The user panel element.
 * @part site-search-results - The nano-global-search-results element
 */
export class GlobalNav {
    /// COMMON ///
    host;
    overflowMenu;
    overflowOpen = false;
    /** The link to put on the logo */
    logoUrl = location.protocol + '//' + location.host;
    /** Url to the Nanopore store cart. Will default to the url supplied by MyAccount */
    cartUrl = '';
    /** Url to the Nanopore message center. Will default to the url supplied by MyAccount  */
    msgUrl = '';
    /** Url to the Nanopore login page. Will default to the url supplied by MyAccount */
    loginUrl = '';
    /** Url to the Nanopore login page. Will default to the url supplied by MyAccount */
    logoutUrl = '';
    /** Url to the Nanopore contact page */
    contactUrl = 'https://nanoporetech.com/contact';
    _sessionRedirect = window.location.href;
    /** A url to take the user after login or logout. Defaults to current URL. Is automatically URI encoded */
    get sessionRedirect() {
        return encodeURIComponent(this._sessionRedirect);
    }
    set sessionRedirect(val) {
        this._sessionRedirect = val;
    }
    /** MyAccount store cart count.*/
    cartCount = 0;
    /** MyAccount un-read message count. */
    msgCount = 0;
    /** Manually open the overflow menu */
    async openOverflowMenu() {
        this.overflowOpen = true;
    }
    /** Manually close the overflow menu */
    async closeOverflowMenu() {
        this.overflowOpen = false;
    }
    /// MY-ACCOUNT - start ///
    /** A base url to retrieve global nav / sso data. `nav_bar_data.json` will be appended to this url */
    myAccountUrl;
    async handleMyAccountUrl() {
        if (!this.myAccountUrl)
            return;
        if (this.myAccountUrl === 'local-logged-in') {
            this.myAccountData = (await import(`./assets/local-logged-in.json`));
            return;
        }
        else if (this.myAccountUrl === 'local-logged-out') {
            this.myAccountData = (await import(`./assets/local-logged-out.json`));
            return;
        }
        fetch(this.myAccountUrl + '/nav_bar_data.json')
            .then((res) => res.json())
            .then((data) => {
            this.myAccountData = data;
        })
            .catch((err) => {
            console.error('Error fetching MyAccount data', err);
        });
    }
    /**
     * MyAccount data is automatically set via `myAccountUrl`.
     * Alternatively you can directly provide a JSON object which is useful for SSR
     * (ref https://myaccount.nanoporetech.com/nav_bar_data.json)
     */
    myAccountData;
    /** Emitted when myaccount data has loaded */
    nanoUserData;
    /// MY-ACCOUNT - end ///
    /// USER LOGIN ///
    userLinks = [];
    isLoggedIn = false;
    /** Logged in user details automatically populated from MyAccount */
    get myAccountUser() {
        return this.myAccountData?.user?.uuid ? this.myAccountData.user : null;
    }
    processUserData() {
        if (!this.myAccountUser) {
            this.isLoggedIn = false;
            this.userLinks = [];
            this.msgUrl = '';
            this.msgCount = 0;
            this.nanoUserData.emit(null);
            return;
        }
        this.userLinks =
            this.myAccountData?.links?.filter((link) => link.area === 'profile-panel-list') || [];
        this.loginUrl = this.loginUrl || this.myAccountData.urls?.login;
        this.logoutUrl = this.logoutUrl || this.myAccountData.urls?.logout;
        this.msgUrl = this.msgUrl || this.myAccountData.urls?.messages;
        this.msgCount = this.msgCount || this.myAccountData.notifications?.count;
        this.cartUrl = this.cartUrl || this.myAccountData.urls?.cart;
        this.cartCount = this.cartCount || this.myAccountData.cart?.count;
        this.isLoggedIn = true;
        this.nanoUserData.emit(this.myAccountUser);
    }
    formatLoginLink(link) {
        if (!link)
            return '';
        if (!this.sessionRedirect)
            return link;
        if (link.endsWith('='))
            return link + this.sessionRedirect;
        if (link.includes('?'))
            return link + '&ReplayState=' + this.sessionRedirect;
        return link + '?ReplayState=' + this.sessionRedirect;
    }
    /// USER LOGIN - end ///
    /// RESIZING - start ///
    resizeObserver;
    cachedWidth;
    mainMenu;
    _mainMenuBar;
    get mainMenuBar() {
        return this._mainMenuBar;
    }
    set mainMenuBar(el) {
        if (this._mainMenuBar === el)
            return;
        this._mainMenuBar = el;
        this.addMainmenuRo();
    }
    /**
     * Manually triggers the main menu bar resize behaviour.
     * This can be useful if you append new children to the global-nav
     */
    async triggerResize() {
        this.shouldResize = true;
        this.breakpoint = 0;
    }
    shouldResize = true;
    breakpoint = 0;
    breakpointChanged() {
        if (this.breakpoint < this.bpPartials.mainMenu.breakpoint &&
            this.shouldResize === false) {
            this.overflowOpen = false;
        }
    }
    debounceResetResize = debounce(() => {
        this.shouldResize = false;
    }, 300);
    addMainmenuRo() {
        this.removeMainmenuRo();
        const ro = (this.resizeObserver = new ResizeObserver(() => {
            if (this.shouldResize ||
                (this.mainMenuBar.clientWidth >= this.cachedWidth &&
                    this.breakpoint === 0) ||
                (this.mainMenuBar.clientWidth <= this.cachedWidth &&
                    this.mainMenuBar.clientWidth >= this.mainMenu.scrollWidth)) {
                // if we're already resizing,
                // OR we're already at the biggest breakpoint and the bar's size is now bigger than what it was,
                // OR the bar's size is less than it was but is still bigger than the menu's size
                // we don't need to do anything
                return;
            }
            // reset breakpoint and start resizing
            this.shouldResize = true;
            this.breakpoint = 0;
        }));
        ro.observe(this.mainMenuBar);
    }
    removeMainmenuRo() {
        if (!this.resizeObserver)
            return;
        if (this.mainMenuBar)
            this.resizeObserver.unobserve(this.mainMenuBar);
        else
            this.resizeObserver.disconnect();
    }
    handleResize = () => {
        if (!this.shouldResize)
            return;
        if (this.breakpoint < 4 &&
            this.mainMenu.scrollWidth > this.mainMenuBar.clientWidth) {
            // changing 'breakpoint' will keep triggering a re-render until the content fits
            this.breakpoint++;
        }
        else {
            // content now fits
            this.cachedWidth = this.mainMenuBar.clientWidth;
            this.debounceResetResize();
        }
    };
    /// RESIZING - end ///
    /// SEARCH - start ///
    algoliaClient;
    searchResults;
    searchInput;
    activeIndex;
    autocompleteResults;
    searchForm;
    searchIndices = [];
    searchBarShown = false;
    searchLoading = false;
    _searchValue = '';
    /** Emitted when search results are successfully returned from Algolia. */
    nanoSearchResult;
    /** Emitted when algolia returns an error. */
    nanoSearchError;
    /** Emitted when search field is cleared. */
    nanoSearchReset;
    /** Algolia search index to search within */
    searchIndex = 'All';
    /** A search string used to load and show autocomplete results */
    get searchValue() {
        return this._searchValue;
    }
    set searchValue(val) {
        if (val) {
            this.host.componentOnReady().then(() => {
                this.searchBarShown = true;
                this.handleSearchTermChangeEvent(val);
            });
        }
    }
    /** Send the current search term and selected index to a nested `nano-global-search-results` */
    async submitSearch() {
        this.onSearchSubmit();
        return;
    }
    handleSearchIndex() {
        if (!this.searchIndices?.length)
            return;
        if (!this.searchIndex) {
            this.activeIndex = this.searchIndices[0];
            return;
        }
        this.activeIndex =
            this.searchIndices.find((index) => index.name === this.searchIndex) ||
                this.searchIndices[0];
        return this.activeIndex;
    }
    initSearch() {
        if (!this.myAccountData)
            return;
        const { search } = this.myAccountData;
        if (!search?.app_id || !search?.api_key)
            return;
        // initialise algolia
        this.algoliaClient = algoliaSearch(search.app_id, search.api_key);
        // setup algolia analytics
        searchInsight.init(search.app_id, search.api_key).then(() => {
            if (this.myAccountUser)
                searchInsight.setUser(this.myAccountUser.uuid);
        });
        // initialise all search indices
        this.searchIndices = this.myAccountData.search.indeces;
        this.searchIndices.forEach((searchIndex) => {
            searchIndex.algoliaIndex = this.algoliaClient.initIndex(searchIndex.index);
        });
        // set the initial search index if it's not manually set
        if (!this.searchIndex) {
            this.searchIndex = this.searchIndices[0].name;
        }
    }
    /**
     * Called whenever the search form is submitted (but can also be called manually).
     * Fires event which will activate / display `nano-global-search-results`
     */
    onSearchSubmit = async (ev) => {
        if (ev)
            ev.preventDefault();
        if (!this.activeIndex ||
            !this.myAccountData ||
            this._searchValue?.length < MIN_SEARCH_LENGTH)
            return;
        if (!this.searchResults)
            await this.doAlgoliaSearch();
        const { search } = this.myAccountData;
        const activeIndex = this.searchResults?.results.find((res) => this.activeIndex.index === res.index);
        const { index, domain, filters, query, replicas } = activeIndex;
        this.searchBarShown = false;
        this.nanoSearchResult.emit({
            meta: {
                indexTitle: activeIndex.indexName,
                index,
                domain,
                filters,
                query,
                replicas,
            },
            client: { apiKey: search.api_key, appId: search.app_id },
        });
    };
    async doAlgoliaSearch() {
        this.searchResults = null;
        if (!this.algoliaClient)
            return;
        const queries = this.searchIndices.map((index) => {
            const toReturn = {
                clickAnalytics: true,
                attributesToSnippet: ['body:5', 'title:8'],
                indexName: index.index,
                query: this._searchValue,
                facets: index.filters,
                hitsPerPage: 5,
                filters: '',
            };
            if (index.name === 'Community') {
                toReturn.filters =
                    'created > ' + Math.floor((Date.now() - 63115200000) / 1000); // only get last 2 years
            }
            return toReturn;
        });
        try {
            this.searchLoading = true;
            // process results, adding correct domains to url fields.
            this.searchResults = this.processSearchResults((await this.algoliaClient.search(queries)));
        }
        catch (e) {
            console.error(e);
            this.nanoSearchError.emit(e);
        }
        this.searchLoading = false;
        return this.searchResults;
    }
    /**
     * Process a set (or multiple sets) of algolia results
     * and applies correct domain names / http protocol to each result's url
     * @returns algolia results with correct domains applied
     */
    processSearchResults(results) {
        const multiResults = results;
        const singleResult = results;
        if (multiResults?.results) {
            multiResults.results.forEach((result, i) => {
                result = {
                    ...result,
                    indexName: this.searchIndices[i].name,
                    selected: this.activeIndex.name === this.searchIndices[i].name,
                    domain: this.activeIndex.domain || null,
                    domains: this.myAccountData.domains || null,
                    allGroup: !!this.searchIndices[i].allGroup,
                    filters: this.searchIndices[i].filters,
                    replicas: this.activeIndex.replicas,
                };
                multiResults.results[i] = this.processSearchResults(result);
            });
            return multiResults;
        }
        singleResult.hits.map((hit) => {
            if (hit.url && !hit.url.match(/^http/))
                hit.url =
                    location.protocol + '//' + this.domainFor(hit.origin) + hit.url;
        });
        return singleResult;
    }
    // Finds a correct domain (as defined by myAccount data) for a given origin
    domainFor(origin) {
        if (!this.myAccountData)
            return '';
        const domain = this.myAccountData.domains.find((dm) => dm.origin === origin);
        return domain ? domain.domain : '';
    }
    async setAutocompleteResults() {
        this.autocompleteResults = null;
        if (this._searchValue.length < MIN_SEARCH_LENGTH) {
            if (!this._searchValue.length)
                this.nanoSearchReset.emit();
            return;
        }
        this.autocompleteResults = (await this.doAlgoliaSearch())?.results.find((res) => res.selected);
    }
    autocompleteSnippet(hit) {
        return hit._snippetResult?.title?.value || hit.title;
    }
    // Search event handlers
    handleSearchOpenEvent = (e) => {
        if (!e.target.classList.contains('gn__search-dropdown') ||
            !this.searchInput) {
            return;
        }
        this.searchInput.setFocus();
        this.searchBarShown = true;
    };
    handleSearchCloseEvent = (e) => {
        if (e.target.classList.contains('gn__search-dropdown')) {
            requestAnimationFrame(() => (this.searchBarShown = false));
        }
    };
    handleSearchTermInputEvent = (e) => {
        if (e.detail.type === 'input' &&
            this.searchInput.value.length >= MIN_SEARCH_LENGTH) {
            this.autocompleteResults = null;
            this.searchLoading = true;
        }
    };
    handleSearchTermChangeEvent = (searchStr) => {
        if (this._searchValue === searchStr)
            return;
        this._searchValue = searchStr;
        this.setAutocompleteResults();
    };
    handleSearchIndexChangeEvent = (e) => {
        if (!e.detail?.value?.length)
            return;
        const index = e.detail.value;
        if (this.activeIndex.index === index)
            return;
        const selectedIndex = this.searchIndices.find((searchIndex) => searchIndex.index === index);
        if (!selectedIndex || !selectedIndex.algoliaIndex)
            return;
        this.searchIndex = selectedIndex.name;
        if (this._searchValue.length >= MIN_SEARCH_LENGTH) {
            this.searchInput.setFocus();
            this.searchBarShown = true;
            this.setAutocompleteResults();
        }
    };
    /// SEARCH - end ///
    /// LIFECYCLE ///
    constructor() {
        this.handleResize = debounce(this.handleResize, 75);
    }
    componentWillLoad() {
        this.handleMyAccountUrl();
        this.initSearch();
        this.processUserData();
        if (Build.isBrowser)
            addGlobalStylesheetToShadow(this.host.shadowRoot);
    }
    componentDidRender() {
        this.handleResize();
    }
    /// RENDER ///
    loggedInPanel() {
        if (!this.isLoggedIn || !this.myAccountUser)
            return;
        return (h("div", { part: "user-panel", class: `gn__user-panel nano-theme-dark` }, h("div", { class: "gn__user-panel-head", slot: "label" }, h("nano-avatar", { initials: this.myAccountUser.first_name?.charAt(0) +
                this.myAccountUser.last_name?.charAt(0) }, this.myAccountUser.small_avatar_url &&
            !this.myAccountUser.small_avatar_url.includes('generic') && (h("img", { src: this.myAccountUser.small_avatar_url, alt: "User Avatar", height: 40, width: 40 }))), h("div", null, this.myAccountUser.name, h("br", null), this.myAccountUser.job_title && this.myAccountUser?.company
            ? `${this.myAccountUser.job_title}, ${this.myAccountUser.company}`
            : this.myAccountUser.job_title ||
                this.myAccountUser.company ||
                '')), h("div", { class: "gn__user-panel-body" }, this.userLinks.map((link) => (h("a", { href: link.address, target: link.target || undefined }, link.title, (link.title === 'Messages' ||
            link.address.includes(this.msgUrl) ||
            this.msgUrl.includes(link.address)) &&
            this.msgCount > 0 && (h("nano-badge", { theme: "danger", strength: "2" }, this.msgCount)))))), h("div", { class: "gn__user-panel-foot" }, h("nano-cta", { secondary: true, size: "small", icon: "false", class: "gn__login-cta" }, typeof this.logoutUrl === 'string' ? (h("a", { href: this.formatLoginLink(this.logoutUrl) }, "Logout")) : (h("button", { onClick: this.logoutUrl }, "Logout"))))));
    }
    bpPartials = {
        contact: {
            tpl: () => this.contactUrl && h("a", { href: this.contactUrl }, "Contact"),
            breakpoint: 0,
        },
        mainMenu: {
            tpl: () => h("slot", { name: "menu" }),
            breakpoint: 1,
        },
        logo: {
            tpl: () => { },
            breakpoint: 2,
        },
    };
    noResultPartial() {
        if (this.searchLoading ||
            this.autocompleteResults?.hits.length ||
            this._searchValue.length < MIN_SEARCH_LENGTH) {
            // it's loading or there are results or there's no search term
            return;
        }
        const toReturn = [];
        if (this.searchIndex === 'All') {
            toReturn.push(h("div", { slot: "no-result", class: "gn__search-no-results" }, "No results matching for \"", h("strong", null, this._searchValue), "\" Try another phrase"));
            return toReturn;
        }
        this.searchResults?.results.forEach((result) => {
            if (result.hits.length) {
                toReturn.push(h("nano-option", { class: "gn__search-result", onNanoSelect: (e) => {
                        e.preventDefault();
                        this.searchIndex = result.indexName;
                        this.onSearchSubmit(e);
                    } }, "Show results for \"", h("strong", null, this._searchValue), "\" in\u00A0", h("strong", null, result.indexName)));
            }
        });
        toReturn.unshift(h("div", { slot: toReturn.length ? 'list-top' : 'no-result', class: "gn__search-no-results" }, "No results matching for \"", h("strong", null, this._searchValue), "\" in", ' ', h("strong", null, this.searchIndex), ". Try another phrase"));
        return toReturn;
    }
    render() {
        const bpps = this.bpPartials;
        return (h(Host, { key: '6f3ecd6fac6825f4b137592e1becb86046278542', class: {
                'overflow-menu': this.breakpoint > bpps.mainMenu.breakpoint,
                'bar-menu': this.breakpoint <= bpps.mainMenu.breakpoint,
                'nano-global-nav': true,
            } }, h("div", { key: '8ecbd0ecc9ac93f1a1dd5defa8f119874f623daf', class: {
                gn: true,
                'gn__search-open': this.searchBarShown,
            } }, h("nano-drawer", { key: '728b760496d041fc5f1d78905081e7fe59b7047c', ref: (el) => (this.overflowMenu = el), label: "Main menu", part: "drawer", class: "gn__drawer nano-theme-dark", placement: "start", open: this.overflowOpen, onNanoAfterHide: () => (this.overflowOpen = false), onNanoAfterShow: () => (this.overflowOpen = true) }, h("div", { key: 'd1b99ae15e00511594abf476a06f8374d4fad508', class: "gn__drawer-header", part: "overflow-header", slot: "label" }, "Main menu"), h("nav", { key: '97debdda75a0d7d9f2a6e23306fa93bd2d73de06', class: "gn__drawer-menu", part: "overflow-menu" }, this.breakpoint > bpps.mainMenu.breakpoint
            ? bpps.mainMenu.tpl()
            : '', h("slot", { key: 'd500a55cb220088df7af00b356f902a3d80fb47d', name: "overflow" }))), h("div", { key: 'c1454d4666561a77a850d9328d13795d5f989d89', class: "gn__menu-bar-wrapper" }, h("div", { key: 'f32f9a8302ad3501ae3d9e8afdf2ed7d59297335', class: "gn__menu-bar", part: "menu-bar", ref: (el) => (this.mainMenuBar = el) }, h("nav", { key: '8605e4bf473e4b34e3890ddaf69c555abc397716', "aria-label": "Global navigation", class: `gn__main-menu ${this.shouldResize ? 'resizing' : ''}`, part: "main-menu", ref: (el) => (this.mainMenu = el) }, this.breakpoint > bpps.mainMenu.breakpoint && (h("nano-icon-button", { key: '04aaa626447c7377fadcd8d374fa9120ef5fea62', class: "gn__overflow-button", iconName: "light/bars", label: "Open Menu", onClick: () => this.overflowMenu.show() })), h("slot", { key: '3f858438db16a112c2dee67ee8b865afba9180fe', name: "logo" }, h("a", { key: 'ddc758422fb964b2644e825c98ec0aec832895db', href: this.logoUrl, class: "gn__logo-link", part: "logo-link" }, this.breakpoint <= bpps.logo.breakpoint ? (h("img", { src: getAssetPath('../nano-assets/ont-logo.svg'), alt: `Oxford Nanopore Technologies logo. Features a stylised representation of a nanopore,
                            (a tiny protein channel embedded in a membrane) through which DNA or RNA molecules are passed in for sequencing.`, class: "gn__logo gn__logo--large", width: "152", height: "36", part: "logo logo--large" })) : (h("img", { src: getAssetPath('../nano-assets/ont-wheel.svg'), alt: `Oxford Nanopore Technologies logo. A stylised representation of a nanopore,
                            (a tiny protein channel embedded in a membrane) through which DNA or RNA molecules are passed in for sequencing.`, class: "gn__logo gn__logo--small", width: "36", height: "36", part: "logo logo--small" })))), this.breakpoint <= bpps.mainMenu.breakpoint && (h("div", { key: 'c48d4d74b18f876cffee723a8da0bd4d82300b7b', class: "gn__main-menu-links" }, bpps.mainMenu.tpl())), h("div", { key: 'e433743c122dc9e4427de3f0fdd7067bcd52f558', class: "gn__main-menu-actions" }, !this.myAccountData ||
            (!!this.searchIndices.length && (h("nano-dropdown", { key: 'e6c5655701e5a91409f5fad4f45efd868cbd1a50', dialogTitle: "Search Oxford Nanopore Technologies", placement: "bottom", class: "gn__search-dropdown", skidding: -30, distance: 25, open: this.searchBarShown, onNanoAfterShow: this.handleSearchOpenEvent, onNanoAfterHide: this.handleSearchCloseEvent, autoOpen: !!this.searchIndices.length }, h("nano-icon-button", { key: '8de3fb7f465103bda3063e96876345701d942a01', class: "gn__search-button", slot: "trigger", iconName: "light/magnifying-glass", label: "Search" }), h("form", { key: '18fca7445c9471089e013cea8d83aa749e655aab', ref: (form) => (this.searchForm = form), class: "gn__search-form", part: "search-form", onSubmit: this.onSearchSubmit }, this.searchIndices.length > 1 && (h("nano-select", { key: '7b37f759f2a24d8686d46a3ebbcb3afaa54cbbee', part: "search-select", label: "Which site do you wish to search in?", mask: true, hideLabel: true, value: this.activeIndex?.index, onNanoChange: this.handleSearchIndexChangeEvent }, this.searchIndices.map((index) => (h("nano-option", { selected: index.name === this.searchIndex, value: index.index }, index.name || index.index))))), h("nano-input", { key: '93838bee803808b06f56c14886975cd3fc8ab827', ref: (ele) => (this.searchInput = ele), part: "search-input", label: "Search Oxford Nanopore Technologies", placeholder: "Search Oxford Nanopore...", hideLabel: true, clearable: true, showInlineError: false, onNanoChange: (e) => {
                    this.handleSearchTermChangeEvent(e.detail.value);
                }, onNanoInput: this.handleSearchTermInputEvent, debounce: 500, value: this._searchValue }, h("nano-icon", { key: 'd39203dd3727a34b60c5c71fc6b9a14c23ef2465', slot: "end", name: "light/magnifying-glass" }), h("nano-datalist", { key: '9826082e21b53f54254c8f2490b3b42c215edacb', class: "gn__search-results", onNanoSelect: (e) => e.preventDefault(), dropDownConfig: { tetherTo: this.searchForm }, disableFilter: true }, this.searchLoading && (h("div", { key: '65f17640b43bce0f44e59f092b7c8ef562f02e19', slot: "no-result", class: "gn__search-loading" }, h("nano-spinner", { key: 'f0162dd8c60aae95e35d9e02770a9398bede0828' }, "Searching..."))), this.noResultPartial(), !!this.autocompleteResults?.hits.length && [
                this.autocompleteResults.hits.map((hit, i) => (h("nano-option", { href: hit.url, class: "gn__search-result", onClick: () => {
                        searchInsight.sendClick({
                            index: this.activeIndex.index,
                            eventName: 'Global nav quick search - search result clicked',
                            queryID: this.autocompleteResults.queryID,
                            objectIDs: [hit.objectID],
                            positions: [i + 1],
                        });
                    } }, h("span", { innerHTML: this.autocompleteSnippet(hit) })))),
                h("nano-option", { key: 'ddf176669705bb04a45575ee1bf8897d46ae9704', class: "gn__search-viewall", onNanoSelect: this.onSearchSubmit }, "View all results"),
            ])))))), h("div", { key: 'f84317012affbf6aa952810f627ca318f042dd0b', class: "gn__cart" }, this.cartUrl && [
            h("nano-icon-button", { key: 'c656b17e3ee2462900fc855c8128b2e92e3ad4cb', iconName: "light/cart-shopping", label: "View your cart", href: this.cartUrl }),
            !!this.cartCount && (h("nano-badge", { key: 'f6dbaa60f1960c3674c446fec760b27e9655d537', theme: "danger", strength: "2" }, this.cartCount > 9 ? '9+' : this.cartCount)),
        ]), this.breakpoint <= bpps.contact.breakpoint
            ? bpps.contact.tpl()
            : '', this.isLoggedIn ? (h("nano-dropdown", { dialogTitle: "User menu", class: "gn__user-dropdown", distance: 10, placement: "bottom-end" }, h("button", { slot: "trigger", class: "gn__user-dropdown-trigger" }, h("nano-icon", { name: "light/user" }), h("nano-icon", { name: "light/chevron-down", class: "gn__user-dropdown-chevron" }), !!this.msgCount && (h("nano-badge", { theme: "danger", strength: "2" }, this.msgCount > 9 ? '9+' : this.msgCount))), this.loggedInPanel())) : (h("nano-cta", { secondary: true, size: "small", icon: "false", class: "gn__login-cta" }, typeof this.loginUrl === 'string' ? (h("a", { href: this.formatLoginLink(this.loginUrl) }, "Login")) : (h("button", { onClick: this.loginUrl }, "Login")))))))), h("nano-global-search-results", { key: '673b8dc2257fce9a5bb0766768cfcb7750e890f5', part: "site-search-results" }, h("div", { key: '73d76e83b1e397ed135bc102f45c37f41ca6759c', class: "gn__site", part: "site-wrapper" }, h("slot", { key: '940796917153c26f98dfb7359465989274673770' }))))));
    }
    static get is() { return "nano-global-nav"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["global-nav.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["global-nav.css"]
        };
    }
    static get assetsDirs() { return ["assets"]; }
    static get properties() {
        return {
            "logoUrl": {
                "type": "string",
                "attribute": "logo-url",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The link to put on the logo"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "location.protocol + '//' + location.host"
            },
            "cartUrl": {
                "type": "string",
                "attribute": "cart-url",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Url to the Nanopore store cart. Will default to the url supplied by MyAccount"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "msgUrl": {
                "type": "string",
                "attribute": "msg-url",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Url to the Nanopore message center. Will default to the url supplied by MyAccount"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "loginUrl": {
                "type": "string",
                "attribute": "login-url",
                "mutable": true,
                "complexType": {
                    "original": "string | (() => void)",
                    "resolved": "(() => void) | string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Url to the Nanopore login page. Will default to the url supplied by MyAccount"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "logoutUrl": {
                "type": "string",
                "attribute": "logout-url",
                "mutable": true,
                "complexType": {
                    "original": "string | (() => void)",
                    "resolved": "(() => void) | string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Url to the Nanopore login page. Will default to the url supplied by MyAccount"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "contactUrl": {
                "type": "string",
                "attribute": "contact-url",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Url to the Nanopore contact page"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'https://nanoporetech.com/contact'"
            },
            "sessionRedirect": {
                "type": "string",
                "attribute": "session-redirect",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "A url to take the user after login or logout. Defaults to current URL. Is automatically URI encoded"
                },
                "getter": true,
                "setter": true,
                "reflect": false
            },
            "cartCount": {
                "type": "number",
                "attribute": "cart-count",
                "mutable": true,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "MyAccount store cart count."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "0"
            },
            "msgCount": {
                "type": "number",
                "attribute": "msg-count",
                "mutable": true,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "MyAccount un-read message count."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "0"
            },
            "myAccountUrl": {
                "type": "string",
                "attribute": "my-account-url",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "A base url to retrieve global nav / sso data. `nav_bar_data.json` will be appended to this url"
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "myAccountData": {
                "type": "unknown",
                "attribute": "my-account-data",
                "mutable": true,
                "complexType": {
                    "original": "MyAccountData | null",
                    "resolved": "MyAccountData",
                    "references": {
                        "MyAccountData": {
                            "location": "import",
                            "path": "./global-nav-interface",
                            "id": "src/components/global-nav/global-nav-interface.d.ts::MyAccountData"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "MyAccount data is automatically set via `myAccountUrl`.\nAlternatively you can directly provide a JSON object which is useful for SSR\n(ref https://myaccount.nanoporetech.com/nav_bar_data.json)"
                },
                "getter": false,
                "setter": false
            },
            "myAccountUser": {
                "type": "unknown",
                "attribute": "my-account-user",
                "mutable": false,
                "complexType": {
                    "original": "MyAccountData['user']",
                    "resolved": "MyAccountUser",
                    "references": {
                        "MyAccountData": {
                            "location": "import",
                            "path": "./global-nav-interface",
                            "id": "src/components/global-nav/global-nav-interface.d.ts::MyAccountData"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Logged in user details automatically populated from MyAccount"
                },
                "getter": true,
                "setter": false
            },
            "searchIndex": {
                "type": "string",
                "attribute": "search-index",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Algolia search index to search within"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'All'"
            },
            "searchValue": {
                "type": "string",
                "attribute": "search-value",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "A search string used to load and show autocomplete results"
                },
                "getter": true,
                "setter": true,
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "overflowOpen": {},
            "isLoggedIn": {},
            "shouldResize": {},
            "breakpoint": {},
            "searchIndices": {},
            "searchBarShown": {},
            "searchLoading": {},
            "_searchValue": {}
        };
    }
    static get events() {
        return [{
                "method": "nanoUserData",
                "name": "nanoUserData",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when myaccount data has loaded"
                },
                "complexType": {
                    "original": "MyAccountData['user']",
                    "resolved": "MyAccountUser",
                    "references": {
                        "MyAccountData": {
                            "location": "import",
                            "path": "./global-nav-interface",
                            "id": "src/components/global-nav/global-nav-interface.d.ts::MyAccountData"
                        }
                    }
                }
            }, {
                "method": "nanoSearchResult",
                "name": "nanoSearchResult",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when search results are successfully returned from Algolia."
                },
                "complexType": {
                    "original": "AlgoliaSearchResultDetail",
                    "resolved": "AlgoliaSearchResultDetail",
                    "references": {
                        "AlgoliaSearchResultDetail": {
                            "location": "import",
                            "path": "../algolia/algolia-interface",
                            "id": "src/components/algolia/algolia-interface.ts::AlgoliaSearchResultDetail"
                        }
                    }
                }
            }, {
                "method": "nanoSearchError",
                "name": "nanoSearchError",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when algolia returns an error."
                },
                "complexType": {
                    "original": "AlgoliaNetworkError",
                    "resolved": "AlgoliaNetworkError",
                    "references": {
                        "AlgoliaNetworkError": {
                            "location": "import",
                            "path": "./global-nav-interface",
                            "id": "src/components/global-nav/global-nav-interface.d.ts::AlgoliaNetworkError"
                        }
                    }
                }
            }, {
                "method": "nanoSearchReset",
                "name": "nanoSearchReset",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when search field is cleared."
                },
                "complexType": {
                    "original": "AlgoliaSearchResultDetail",
                    "resolved": "AlgoliaSearchResultDetail",
                    "references": {
                        "AlgoliaSearchResultDetail": {
                            "location": "import",
                            "path": "../algolia/algolia-interface",
                            "id": "src/components/algolia/algolia-interface.ts::AlgoliaSearchResultDetail"
                        }
                    }
                }
            }];
    }
    static get methods() {
        return {
            "openOverflowMenu": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Manually open the overflow menu",
                    "tags": []
                }
            },
            "closeOverflowMenu": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Manually close the overflow menu",
                    "tags": []
                }
            },
            "triggerResize": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Manually triggers the main menu bar resize behaviour.\nThis can be useful if you append new children to the global-nav",
                    "tags": []
                }
            },
            "submitSearch": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Send the current search term and selected index to a nested `nano-global-search-results`",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "host"; }
    static get watchers() {
        return [{
                "propName": "myAccountUrl",
                "methodName": "handleMyAccountUrl"
            }, {
                "propName": "myAccountData",
                "methodName": "processUserData"
            }, {
                "propName": "shouldResize",
                "methodName": "breakpointChanged"
            }, {
                "propName": "breakpoint",
                "methodName": "breakpointChanged"
            }, {
                "propName": "searchIndices",
                "methodName": "handleSearchIndex"
            }, {
                "propName": "searchIndex",
                "methodName": "handleSearchIndex"
            }, {
                "propName": "myAccountData",
                "methodName": "initSearch"
            }];
    }
}
