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 _EdenStructureSearch_updateSearch, _EdenStructureSearch_closeSearch, _EdenStructureSearch_renderResults, _EdenStructureSearch_flattenStructure, _EdenStructureSearch_handleResultClick, _EdenStructureSearch_updateCurrent, _EdenStructureSearch_getCurrentId;
import { normalize } from "../../services/text.js";
import template from "./eden-structure-search.template.js";
import styles from "./eden-structure-search.styles.js";
import html from "../../services/html.js";
class EdenStructureSearch extends HTMLElement {
    constructor({ editStructure: structureTree, structure, label = "name", templateToMatch, }) {
        super();
        _EdenStructureSearch_updateSearch.set(this, () => {
            this.search = this.input.value;
            this.opened = this.search.trim().length > 0;
            __classPrivateFieldGet(this, _EdenStructureSearch_renderResults, "f").call(this);
        });
        _EdenStructureSearch_closeSearch.set(this, () => {
            this.search = "";
            this.opened = false;
            this.input.setAttribute("value", "");
            this.results.innerHTML = "";
        });
        _EdenStructureSearch_renderResults.set(this, () => {
            const currentId = __classPrivateFieldGet(this, _EdenStructureSearch_getCurrentId, "f").call(this);
            if (this.search.trim().length < 2) {
                return "";
            }
            const filteredResults = this.flattenedStructure.reduce((acc, { id, name, path, template }) => {
                const normalizedName = normalize(name.toLowerCase());
                const normalizedSearch = normalize(this.search.toLowerCase());
                const isInName = normalizedName.includes(normalizedSearch);
                const isInPath = path.includes(normalizedSearch);
                if (!isInName && !isInPath)
                    return acc;
                const base = this.label === "name" ? name : path;
                const comparution = this.label === "name" ? normalizedName : path;
                let formattedLabel = base;
                if ((this.label === "name" && isInName) ||
                    (this.label === "path" && isInPath)) {
                    const startPos = comparution.indexOf(normalizedSearch);
                    const endPos = startPos + this.search.length;
                    const start = base.slice(0, startPos);
                    const matching = base.slice(startPos, endPos);
                    const end = base.slice(endPos, base.length);
                    formattedLabel = html `${start}<b>${matching}</b>${end}`;
                }
                const isCurrent = id === currentId;
                const currentAttribute = isCurrent ? "data-current" : "";
                const isDisabled = this.templateToMatch && template !== this.templateToMatch;
                const disabledAttribute = isDisabled ? "disabled" : "";
                const button = html ` <button
          data-id="${id}"
          ${currentAttribute}
          ${disabledAttribute}
          class="edit-structure-search-result"
        >
          <span>${formattedLabel}</span>
        </button>`;
                return [...acc, button];
            }, []);
            this.results.innerHTML = filteredResults.join("");
        });
        _EdenStructureSearch_flattenStructure.set(this, (structure) => {
            return structure.reduce((acc, item) => {
                if (!item || !item?.subs)
                    return acc;
                if (item.subs?.length > 0) {
                    return [...acc, item, ...__classPrivateFieldGet(this, _EdenStructureSearch_flattenStructure, "f").call(this, item.subs)];
                }
                return [...acc, item];
            }, []);
        });
        _EdenStructureSearch_handleResultClick.set(this, (e) => {
            const target = e.target;
            if (!target)
                return;
            const result = target?.closest(".edit-structure-search-result");
            const id = Number(result?.dataset?.id);
            if (!id)
                return;
            const node = this.editStructure.querySelector(`eden-structure-tree [data-id="${id}"] .structure-tree__node-leaf`);
            if (node) {
                node.click();
            }
            __classPrivateFieldGet(this, _EdenStructureSearch_updateCurrent, "f").call(this, result);
        });
        _EdenStructureSearch_updateCurrent.set(this, (element) => {
            const results = Array.from(this.results.querySelectorAll(".edit-structure-search-result"));
            results.forEach((result) => {
                result.removeAttribute("data-current");
            });
            element.setAttribute("data-current", "");
        });
        _EdenStructureSearch_getCurrentId.set(this, () => {
            const entry = this.editStructure.querySelector("eden-edit-structure-entry");
            return entry?.entryData?.id || null;
        });
        this.label = label;
        this.editStructure = structureTree;
        this.structure = window.structuredClone(structure);
        this.flattenedStructure = __classPrivateFieldGet(this, _EdenStructureSearch_flattenStructure, "f").call(this, this.structure);
        this.templateToMatch = templateToMatch;
        this.search = "";
        this.innerHTML = html `<style>
        ${styles}
      </style>
      ${template()}`;
    }
    connectedCallback() {
        this.input = this.querySelector("eden-input");
        this.close = this.querySelector(".edit-structure-search-close");
        this.results = this.querySelector(".edit-structure-search-results");
        __classPrivateFieldGet(this, _EdenStructureSearch_renderResults, "f").call(this);
        this.input.addEventListener("input", __classPrivateFieldGet(this, _EdenStructureSearch_updateSearch, "f"));
        this.close.addEventListener("click", __classPrivateFieldGet(this, _EdenStructureSearch_closeSearch, "f"));
        this.results.addEventListener("click", __classPrivateFieldGet(this, _EdenStructureSearch_handleResultClick, "f"));
    }
    disconnectedCallback() {
        this.results.removeEventListener("click", __classPrivateFieldGet(this, _EdenStructureSearch_handleResultClick, "f"));
        this.close.removeEventListener("click", __classPrivateFieldGet(this, _EdenStructureSearch_closeSearch, "f"));
        this.input.removeEventListener("input", __classPrivateFieldGet(this, _EdenStructureSearch_updateSearch, "f"));
    }
    get opened() {
        return this.hasAttribute("opened");
    }
    set opened(value) {
        if (value) {
            this.setAttribute("opened", "");
        }
        else {
            this.removeAttribute("opened");
        }
    }
}
_EdenStructureSearch_updateSearch = new WeakMap(), _EdenStructureSearch_closeSearch = new WeakMap(), _EdenStructureSearch_renderResults = new WeakMap(), _EdenStructureSearch_flattenStructure = new WeakMap(), _EdenStructureSearch_handleResultClick = new WeakMap(), _EdenStructureSearch_updateCurrent = new WeakMap(), _EdenStructureSearch_getCurrentId = new WeakMap();
export default EdenStructureSearch;
if (!customElements.get("eden-structure-search")) {
    customElements.define("eden-structure-search", EdenStructureSearch);
}
