/*!
 * Custom elements for Nanopore-Digital Web applications
 */
import { proxyCustomElement, HTMLElement, createEvent, Build, Host } from '@stencil/core/internal/client';
import { h } from './renderer.js';
import { W as Wormhole, S as SearchChangeEvent } from './algolia-data.js';

const AlgoliaResults = /*@__PURE__*/ proxyCustomElement(class AlgoliaResults extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        this.__attachShadow();
        this.nanoPageChanged = createEvent(this, "nanoPageChanged", 7);
        this.nanoTplUpdated = createEvent(this, "nanoTplUpdated", 7);
    }
    get el() { return this; }
    resultTpl;
    resultTplSlot;
    startTpl;
    startTplSlot;
    endTpl;
    endTplSlot;
    outputSlot;
    outputEle;
    outputTo;
    startOutputSlot;
    endOutputSlot;
    io;
    infiniteScrollBar;
    append = false;
    shouldClear = true;
    currHitNum = 0;
    showResults = false;
    tplRenderFn;
    results = null;
    indexResults = null;
    resultsPage = 0;
    changeEvent = SearchChangeEvent.Init;
    facets;
    isLoading = true;
    /**
     * Load and append pages automatically on scroll
     */
    infiniteScroll = false;
    /**
     * Whether new pages loaded by pagination will replace or be appended to the results block
     * (this will be ignored if 'infiniteScroll' is set to true)
     */
    appendPages = false;
    /**
     * Emitted when the page number changes
     */
    nanoPageChanged;
    /**
     * Emitted when templates are updated
     */
    nanoTplUpdated;
    // For append / infinite-scroll it's useful to have a universal index on render
    addContentIndex() {
        this.shouldPageClear();
        if (this.shouldClear || this.resultsPage === 0)
            this.currHitNum = 0;
        if (this.indexResults && this.indexResults.results) {
            this.indexResults.results.map((res) => {
                res._uIndex = this.currHitNum++;
            });
        }
    }
    // Update content template and perhaps add IO for infinite scrolling
    resultsChange() {
        this.shouldPageClear();
        // console.log('going to do update', this.resultsPage, this.results.length);
        this.updateResultContent();
        this.infiniteScrollChange();
    }
    // We have a foot / head slot template.
    // Can be useful to display current filter / search meta
    headerFooterChange() {
        this.updateStartEndContent();
    }
    appendChange() {
        this.append = this.infiniteScroll ? true : this.appendPages;
    }
    infiniteScrollChange() {
        this.append = this.infiniteScroll ? true : this.appendPages;
        if (this.infiniteScroll)
            this.attachIO();
        else
            this.detachIO();
    }
    handlePageChage() {
        if (this.infiniteScroll)
            this.attachIO();
        else
            this.detachIO();
    }
    handleLoading() {
        if (!this.isLoading)
            this.infiniteScrollChange();
    }
    // Decide whether incoming content should clear or not.
    // if incoming change event is from a pagechange AND the current page is 0 OR appendPages option set...
    // Then leave up to the current, set append behaviour. Other clear it all out.
    shouldPageClear() {
        this.shouldClear =
            this.changeEvent === SearchChangeEvent.Page ? !this.append : true;
    }
    // Called by IO. Emits page change event to parent which then iterated the global page count.
    nextPage() {
        this.shouldClear = !this.append;
        this.nanoPageChanged.emit({ page: this.resultsPage + 1 });
    }
    attachIO() {
        if (!this.infiniteScrollBar ||
            !this.infiniteScroll ||
            this.io ||
            !Build.isBrowser ||
            typeof window === 'undefined' ||
            !window.IntersectionObserver)
            return;
        this.io = new window.IntersectionObserver(async (data) => {
            if (data[0].isIntersecting || (data[1] && data[1].isIntersecting)) {
                this.nextPage();
                this.detachIO();
            }
        }, { document, rootMargin: '100px', threshold: 1 });
        this.io.observe(this.infiniteScrollBar);
    }
    detachIO() {
        if (this.io) {
            this.io.disconnect();
            this.io = null;
        }
    }
    updateStartEndContent() {
        // clear start slot if present
        if (this.startTpl && this.startOutputSlot) {
            this.startOutputSlot.innerHTML = this.tplRenderFn(this.startTpl, this.indexResults);
        }
        // clear end slot if present
        if (this.endOutputSlot && this.endTpl) {
            this.endOutputSlot.innerHTML = this.tplRenderFn(this.endTpl, this.indexResults);
        }
        this.nanoTplUpdated.emit(this.el);
    }
    updateResultContent() {
        this.outputTo = this.outputSlot || this.outputEle;
        if (!this.resultTpl || !this.indexResults)
            return;
        // after filtering or new index - clear all content.
        // after pagination when the 'appendPages' set to true - don't clear results content
        if (this.shouldClear)
            this.outputTo.innerHTML = '';
        if (!this.tplRenderFn)
            return;
        const div = document.createElement('div');
        div.innerHTML = this.tplRenderFn(this.resultTpl, this.indexResults);
        Array.from(div.children).forEach((child) => {
            this.outputTo.appendChild(child);
        });
        this.shouldClear = true;
        this.nanoTplUpdated.emit(this.el);
    }
    connectedCallback() {
        this.startTplSlot = this.el.querySelector('[slot="start-template"]');
        this.startOutputSlot = this.el.querySelector('[slot="start-output"]');
        if (this.startTplSlot) {
            this.startTpl = this.startTplSlot.innerHTML;
            this.startTpl = this.startTpl.replace(/=&gt;/gm, '=>');
        }
        this.resultTplSlot = this.el.querySelector('[slot="result-template"]');
        this.outputSlot = this.el.querySelector('[slot="result-output"]');
        if (this.resultTplSlot) {
            this.resultTpl = this.resultTplSlot.innerHTML;
            this.resultTpl = this.resultTpl.replace(/=&gt;/gm, '=>');
        }
        this.endTplSlot = this.el.querySelector('[slot="end-template"]');
        this.endOutputSlot = this.el.querySelector('[slot="end-output"]');
        if (this.endTplSlot) {
            this.endTpl = this.endTplSlot.innerHTML;
            this.endTpl = this.endTpl.replace(/=&gt;/gm, '=>');
        }
        if (this.indexResults) {
            this.addContentIndex();
            this.updateResultContent();
        }
    }
    componentDidLoad() {
        this.updateStartEndContent();
    }
    disconnectedCallback() {
        if (this.io) {
            this.io.disconnect();
            this.io = undefined;
        }
    }
    render() {
        return (h(Host, { key: '857784ead2b9536559ef2220bff26d508061781c', class: {
                'show-results': this.showResults,
                'nano-results': true,
            } }, h("div", { key: 'be165b02c4ec5d2358e15dadfd4695fd5901f0b0', class: "default" }, h("slot", { key: '1ab64bb71c75531e8f6b0c65833de7d2dc1ee0ca' })), h("div", { key: 'cee981cead8b921e29fd4223e4985c3615e0e063', ref: (div) => (this.outputEle = div) }, h("slot", { key: 'cff96070ca2acf18f7b8165444b28f433ca3601d', name: "start-output" }), h("slot", { key: '76833dd55d415baf083527ed5580049f90c36b40', name: "result-output" }), h("div", { key: 'dac7a9081d1a65b4e17dec60044467e17575568e', ref: (div) => (this.infiniteScrollBar = div) }), h("slot", { key: '07c82d60a58c11bcc50807ab95d63cf3fd59d768', name: "end-output" }))));
    }
    static get watchers() { return {
        "results": ["addContentIndex", "resultsChange"],
        "tplRenderFn": ["resultsChange"],
        "facets": ["headerFooterChange"],
        "appendPages": ["appendChange"],
        "infiniteScroll": ["infiniteScrollChange"],
        "resultsPage": ["handlePageChage"],
        "isLoading": ["handleLoading"]
    }; }
}, [257, "nano-algolia-results", {
        "infiniteScroll": [4, "infinite-scroll"],
        "appendPages": [4, "append-pages"],
        "showResults": [32],
        "tplRenderFn": [32],
        "results": [32],
        "indexResults": [32],
        "resultsPage": [32],
        "changeEvent": [32],
        "facets": [32],
        "isLoading": [32]
    }, undefined, {
        "results": ["addContentIndex", "resultsChange"],
        "tplRenderFn": ["resultsChange"],
        "facets": ["headerFooterChange"],
        "appendPages": ["appendChange"],
        "infiniteScroll": ["infiniteScrollChange"],
        "resultsPage": ["handlePageChage"],
        "isLoading": ["handleLoading"]
    }]);
Wormhole(AlgoliaResults, [
    'indexResults',
    'results',
    'tplRenderFn',
    'resultsPage',
    'changeEvent',
    'facets',
    'isLoading',
]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["nano-algolia-results"];
    components.forEach(tagName => { switch (tagName) {
        case "nano-algolia-results":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, AlgoliaResults);
            }
            break;
    } });
}

const NanoAlgoliaResults = AlgoliaResults;
const defineCustomElement = defineCustomElement$1;

export { NanoAlgoliaResults, defineCustomElement };
