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 _EdenAddBlock_openCategory, _EdenAddBlock_goBack, _EdenAddBlock_showDescription, _EdenAddBlock_hideDescription, _EdenAddBlock_toggleVariants, _EdenAddBlock_selectTemplate, _EdenAddBlock_paste, _EdenAddBlock_close, _EdenAddBlock_computeStyles, _EdenAddBlock_handleBackdropClick, _EdenAddBlock_refreshSearchResults, _EdenAddBlock_closeSearch;
import { normalize } from "../../services/text.js";
import { createBlockPreview } from "../../services/block-preview.js";
import EdenAddBlockPreview from "./eden-add-block-preview.js";
import template, { CATEGORY_ICONS } from "./eden-add-block.template.js";
import styles from "./eden-add-block.styles.js";
import html from "../../services/html.js";
import t from "../../i18n/index.js";
const ACTIVE = "category--active";
class EdenAddBlock extends HTMLElement {
    constructor(event, callbacks, authorizedTemplates, hidePaste) {
        super();
        this.elementWidth = 0;
        this.elementHeight = 0;
        this.leftPosition = 0;
        this.currentCategory = null;
        this.closing = false;
        _EdenAddBlock_openCategory.set(this, (e) => {
            const target = e.target;
            const category = target.closest(".category");
            if (category === null || category.classList.contains(ACTIVE))
                return;
            const key = category.innerText;
            this.currentCategory = key;
            this.categories.forEach((el) => el.classList.remove(ACTIVE));
            category.classList.add(ACTIVE);
            this.templatesList.innerHTML = renderTemplates(this.templates[key], true, key);
            this.columns.forEach((column) => (column.style.transform = "translateX(-100%)"));
        });
        _EdenAddBlock_goBack.set(this, () => {
            this.categories.forEach((el) => el.classList.remove(ACTIVE));
            this.columns.forEach((column) => column.removeAttribute("style"));
            this.templatesList.innerHTML = "";
        });
        _EdenAddBlock_showDescription.set(this, async (e) => {
            const target = e.target;
            const template = target.closest(".template, .template-variants__variant");
            const parent = target.closest(".column--templates, .search__results");
            __classPrivateFieldGet(this, _EdenAddBlock_hideDescription, "f").call(this);
            if (!template || !parent || this.closing || window.innerWidth < 1000) {
                return;
            }
            const code = template.dataset.code;
            if (!code) {
                return;
            }
            const matchingTemplate = window.Eden.templates[code];
            const { description = "", preview } = matchingTemplate || {};
            if (!description && !preview) {
                return;
            }
            let fullDescription = description
                ? html `<div class="eden-description-inner">${description}</div>`
                : "";
            if (preview) {
                const variant = template.getAttribute("data-variant") || undefined;
                const preview = createBlockPreview(code, variant);
                fullDescription = fullDescription.concat(html `<div class="eden-description-preview">${preview}</div>`);
            }
            const bounds = this.dropdown.getBoundingClientRect();
            const descriptionContainer = new EdenAddBlockPreview(bounds, fullDescription);
            this.descriptionContainer = descriptionContainer;
            document.body.appendChild(this.descriptionContainer);
        });
        _EdenAddBlock_hideDescription.set(this, () => {
            if (this.descriptionContainer) {
                this.descriptionContainer.remove();
                this.descriptionContainer = undefined;
            }
        });
        _EdenAddBlock_toggleVariants.set(this, (toggle, template) => {
            const variants = template.nextElementSibling;
            if (!variants)
                return;
            if (variants.classList.contains("template-variants--opened")) {
                toggle.classList.remove("template__button--open");
                variants.classList.remove("template-variants--opened");
            }
            else {
                toggle.classList.add("template__button--open");
                variants.classList.add("template-variants--opened");
            }
        });
        _EdenAddBlock_selectTemplate.set(this, (e) => {
            const target = e.target;
            const goBack = target.closest(".category-title");
            if (goBack) {
                __classPrivateFieldGet(this, _EdenAddBlock_goBack, "f").call(this);
                return;
            }
            const template = target.closest(".template");
            if (target.classList.contains("template__button--variants")) {
                __classPrivateFieldGet(this, _EdenAddBlock_toggleVariants, "f").call(this, target, template);
            }
            else if (target.classList.contains("template-variants__variant")) {
                const code = target.getAttribute("data-code");
                const variant = target.getAttribute("data-variant");
                this.callbacks.addBlock(code, variant);
                __classPrivateFieldGet(this, _EdenAddBlock_close, "f").call(this);
            }
            else {
                if (template === null)
                    return;
                const code = template.getAttribute("data-code");
                this.callbacks.addBlock(code);
                __classPrivateFieldGet(this, _EdenAddBlock_close, "f").call(this);
            }
        });
        _EdenAddBlock_paste.set(this, () => {
            this.callbacks.paste();
            __classPrivateFieldGet(this, _EdenAddBlock_close, "f").call(this);
        });
        _EdenAddBlock_close.set(this, () => {
            this.closing = true;
            this.setAttribute("closing", "");
            __classPrivateFieldGet(this, _EdenAddBlock_hideDescription, "f").call(this);
            setTimeout(() => {
                this.remove();
            }, 300);
        });
        _EdenAddBlock_computeStyles.set(this, () => {
            this.elementWidth = this.dropdown.clientWidth;
            this.elementHeight = this.dropdown.clientHeight;
            const { clientX: x, clientY: y } = this.event;
            const { innerWidth, innerHeight } = window;
            const hasEnoughSpaceOnBottom = y + this.elementHeight < innerHeight;
            const hasEnoughSpaceOnLeft = x + this.elementWidth > 0;
            const hasEnoughSpaceOnRight = x + this.elementWidth < innerWidth;
            if (!hasEnoughSpaceOnBottom && hasEnoughSpaceOnRight) {
                return {
                    top: y - this.elementHeight,
                    left: x,
                    transformOrigin: "left bottom",
                };
            }
            if (!hasEnoughSpaceOnBottom && hasEnoughSpaceOnLeft) {
                return {
                    top: y - this.elementHeight,
                    left: x - this.elementWidth,
                    transformOrigin: "bottom right",
                };
            }
            if (hasEnoughSpaceOnBottom && !hasEnoughSpaceOnRight) {
                return {
                    left: x - this.elementWidth,
                    top: y,
                    transformOrigin: "top right",
                };
            }
            return { top: y, left: x, transformOrigin: "top left" };
        });
        _EdenAddBlock_handleBackdropClick.set(this, (e) => {
            e.stopPropagation();
            __classPrivateFieldGet(this, _EdenAddBlock_close, "f").call(this);
        });
        _EdenAddBlock_refreshSearchResults.set(this, () => {
            const value = this.searchInput.value;
            const templates = window.Eden.templates;
            const results = Object.keys(templates).reduce((acc, key) => {
                const template = templates[key];
                const { name } = template;
                const normalizedName = normalize(name.toLowerCase());
                const normalizedValue = normalize(value.toLowerCase());
                const isInName = normalizedName.includes(normalizedValue);
                if (isInName) {
                    const startPos = normalizedName.indexOf(normalizedValue);
                    const endPos = startPos + value.length;
                    const start = name.slice(0, startPos);
                    const matching = name.slice(startPos, endPos);
                    const end = name.slice(endPos, name.length);
                    return [
                        ...acc,
                        { ...template, code: key, name: `${start}<b>${matching}</b>${end}` },
                    ];
                }
                return acc;
            }, []);
            this.searchResults.scrollTop = 0;
            if (!results.length) {
                this.searchResults.innerHTML = html `<div class="search__no-results">
        Aucun template trouvé...
      </div>`;
            }
            else {
                this.searchResults.innerHTML = renderTemplates(results);
            }
            if (value === "") {
                this.searchResults.innerHTML = "";
                this.search.classList.remove("search--opened");
            }
            else {
                this.search.classList.add("search--opened");
            }
        });
        _EdenAddBlock_closeSearch.set(this, () => {
            this.search.classList.remove("search--opened");
            this.searchInput.setAttribute("value", "");
        });
        this.event = event;
        this.authorizedTemplates = authorizedTemplates;
        this.descriptionContainer = undefined;
        this.templates =
            authorizedTemplates !== undefined
                ? Object.entries(window.Eden.groupedTemplates).reduce((acc, [group, templates]) => {
                    const filteredTemplates = templates.filter((template) => authorizedTemplates.includes(template.code));
                    return filteredTemplates.length > 0
                        ? { ...acc, [group]: filteredTemplates }
                        : acc;
                }, {})
                : window.Eden.groupedTemplates;
        this.attachShadow({ mode: "open" });
        this.shadowRoot.innerHTML = template(this.templates, hidePaste, authorizedTemplates);
        const sheet = new CSSStyleSheet();
        sheet.replaceSync(styles);
        this.shadowRoot.adoptedStyleSheets = [sheet];
        this.callbacks = callbacks;
    }
    connectedCallback() {
        this.dropdown = this.shadowRoot.querySelector(".dropdown");
        this.backdrop = this.shadowRoot.querySelector(".backdrop");
        this.search = this.shadowRoot.querySelector(".search");
        this.searchButton = this.search?.querySelector(".search__button");
        this.searchInput = this.search?.querySelector(".search__input");
        this.searchResults = this.search?.querySelector(".search__results-inner");
        this.templatesList = this.shadowRoot.querySelector(".column--templates");
        this.categoriesList = this.shadowRoot.querySelector(".column--categories");
        this.categories = Array.from(this.shadowRoot.querySelectorAll(".category"));
        this.columns = Array.from(this.shadowRoot.querySelectorAll(".column"));
        this.clipboardButton = this.shadowRoot.querySelector(".clipboard-item");
        const { top, left, transformOrigin } = __classPrivateFieldGet(this, _EdenAddBlock_computeStyles, "f").call(this);
        this.leftPosition = left;
        this.dropdown.style = `
      top: ${top}px;
      left: ${left}px;
      transform-origin: ${transformOrigin};
    `;
        if (this.clipboardButton) {
            this.clipboardButton.addEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_paste, "f"));
        }
        if (!this.authorizedTemplates) {
            this.searchInput.focus();
            this.searchButton.addEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_closeSearch, "f"));
            this.searchInput.addEventListener("input", __classPrivateFieldGet(this, _EdenAddBlock_refreshSearchResults, "f"));
            this.searchResults.addEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_selectTemplate, "f"));
        }
        this.categoriesList.addEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_openCategory, "f"));
        this.dropdown.addEventListener("mouseover", __classPrivateFieldGet(this, _EdenAddBlock_showDescription, "f"));
        this.dropdown.addEventListener("mouseleave", __classPrivateFieldGet(this, _EdenAddBlock_hideDescription, "f"));
        this.templatesList.addEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_selectTemplate, "f"));
        window.addEventListener("resize", __classPrivateFieldGet(this, _EdenAddBlock_close, "f"));
        this.backdrop.addEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_handleBackdropClick, "f"));
    }
    disconnectedCallback() {
        this.backdrop.removeEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_handleBackdropClick, "f"));
        window.removeEventListener("resize", __classPrivateFieldGet(this, _EdenAddBlock_close, "f"));
        this.templatesList.removeEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_selectTemplate, "f"));
        this.dropdown.removeEventListener("mouseleave", __classPrivateFieldGet(this, _EdenAddBlock_hideDescription, "f"));
        this.dropdown.removeEventListener("mouseover", __classPrivateFieldGet(this, _EdenAddBlock_showDescription, "f"));
        this.categoriesList.removeEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_openCategory, "f"));
        if (!this.authorizedTemplates) {
            this.searchResults.removeEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_selectTemplate, "f"));
            this.searchInput.removeEventListener("input", __classPrivateFieldGet(this, _EdenAddBlock_refreshSearchResults, "f"));
            this.searchButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_closeSearch, "f"));
        }
        if (this.clipboardButton) {
            this.clipboardButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenAddBlock_paste, "f"));
        }
    }
}
_EdenAddBlock_openCategory = new WeakMap(), _EdenAddBlock_goBack = new WeakMap(), _EdenAddBlock_showDescription = new WeakMap(), _EdenAddBlock_hideDescription = new WeakMap(), _EdenAddBlock_toggleVariants = new WeakMap(), _EdenAddBlock_selectTemplate = new WeakMap(), _EdenAddBlock_paste = new WeakMap(), _EdenAddBlock_close = new WeakMap(), _EdenAddBlock_computeStyles = new WeakMap(), _EdenAddBlock_handleBackdropClick = new WeakMap(), _EdenAddBlock_refreshSearchResults = new WeakMap(), _EdenAddBlock_closeSearch = new WeakMap();
export default EdenAddBlock;
if (!customElements.get("eden-add-block")) {
    customElements.define("eden-add-block", EdenAddBlock);
}
function renderVariants(variants, code) {
    if (!variants)
        return "";
    return html `
    <div class="template-variants">
      ${variants
        .map((variant) => {
        const { name, cssClass } = variant;
        return html `
            <button
              class="template-variants__variant"
              data-code="${code}"
              data-variant="${cssClass}"
            >
              <eden-icon
                code="tune"
                class="template-variants__variant-icon"
              ></eden-icon>
              ${name}
            </button>
          `;
    })
        .join("")}
    </div>
  `;
}
function renderVariantsButton(variants) {
    if (!variants)
        return "";
    return html `
    <button
      is="eden-button"
      tooltip="${t("ui.add-block.hide-show-variants")}"
      direction="left"
      class="template__button template__button--variants"
    >
      <eden-icon code="chevron_down" class="template__button-icon"></eden-icon>
    </button>
  `;
}
function renderTemplates(templates, withGoBack, key) {
    const title = withGoBack
        ? html ` <button class="category-title">
        <eden-icon
          code="chevron_left"
          class="category-title__go-back"
        ></eden-icon>
        ${key}
      </button>`
        : key
            ? html ` <div class="category-title">${key}</div>`
            : "";
    const list = templates
        .map((template) => {
        const { code, name, group, variants, unique } = template;
        const iconCode = CATEGORY_ICONS[group] ||
            CATEGORY_ICONS.SectionDefault;
        const category = !key
            ? `<span class="template__category">${group}</span>`
            : "";
        const uniqueLabel = unique
            ? html `<span class="template__warning"
            >${t("ui.add-block.maximum-1-per-page")}</span
          >`
            : "";
        return html `
        <div class="template" data-code="${code}" tabindex="0">
          <span class="template__inner">
            <span class="template__name">
              <span class="template__icon"
                ><eden-icon code="${iconCode}"></eden-icon
              ></span>
              <span class="template__name-inner">
                ${category}
                <span>${name}</span>
              </span>
            </span>
            ${uniqueLabel}
          </span>
          ${renderVariantsButton(variants)}
        </div>
        ${renderVariants(variants, code)}
      `;
    })
        .join("");
    if (!withGoBack)
        return title.concat(list);
    return title.concat(list);
}
