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 _EdenEditStructureEntry_instances, _EdenEditStructureEntry_checkLangFormExist, _EdenEditStructureEntry_formatMetadata, _EdenEditStructureEntry_initializeMetadata, _EdenEditStructureEntry_filterMetadataFieldsDisplay, _EdenEditStructureEntry_initializeForm, _EdenEditStructureEntry_saveFormContent, _EdenEditStructureEntry_showForm, _EdenEditStructureEntry_switchLang, _EdenEditStructureEntry_checkSEOQuality, _EdenEditStructureEntry_copyUrl, _EdenEditStructureEntry_onUrlInputChange, _EdenEditStructureEntry_startLoading, _EdenEditStructureEntry_stopLoading, _EdenEditStructureEntry_setUnsavedChanges, _EdenEditStructureEntry_removeUnsavedChanges, _EdenEditStructureEntry_detectChanges, _EdenEditStructureEntry_getPaths;
import { copyToClipboard } from "../../services/clipboard.js";
import { noTrailingSlash } from "../../services/check.js";
import { snackbar } from "../common/eden-snackbar.js";
import { saveNode } from "../../services/action.js";
import template from "./eden-edit-structure-entry.template.js";
import styles from "./eden-edit-structure-entry.styles.js";
import html from "../../services/html.js";
import t from "../../i18n/index.js";
import { ensureStructureLangEntry, formatStructureMetadata, initializeStructureMetadata, filterMetadataByPath, isExternalUrl, normalizePathBeforeSave, normalizeStructurePathInput, } from "./eden-edit-structure-entry-state.js";
import { collectChangedPaths, collectEntryPaths, } from "./structure-paths.js";
const SEO_PILL_STATUSES = {
    ALERT: "alert",
    WARNING: "warning",
    OK: "ok",
};
const SEO_DESCRIPTION_LENGTH_INTERVAL = [50, 200];
class EdenEditStructureEntry extends HTMLElement {
    constructor(templates) {
        const { langs = [], lang, pagesMetadata } = window.EdenConfig;
        super();
        _EdenEditStructureEntry_instances.add(this);
        _EdenEditStructureEntry_checkLangFormExist.set(this, () => {
            this.entryData = ensureStructureLangEntry(this.entryData, this.currentLang);
        });
        _EdenEditStructureEntry_formatMetadata.set(this, () => {
            const pagesMetadata = window.EdenConfig.pagesMetadata;
            const filteredMetadata = filterMetadataByPath(pagesMetadata, this.pageTemplate);
            return formatStructureMetadata(this.metadataFields, filteredMetadata);
        });
        _EdenEditStructureEntry_initializeMetadata.set(this, (metadata) => {
            const pagesMetadata = window.EdenConfig.pagesMetadata;
            initializeStructureMetadata(this.metadataFields, pagesMetadata, metadata);
            const filteredMetadata = filterMetadataByPath(pagesMetadata, this.pageTemplate);
            __classPrivateFieldGet(this, _EdenEditStructureEntry_filterMetadataFieldsDisplay, "f").call(this, filteredMetadata);
        });
        _EdenEditStructureEntry_filterMetadataFieldsDisplay.set(this, (filteredMetadata) => {
            const allowedCodes = new Set(filteredMetadata?.map((m) => m.code) ?? []);
            this.metadataFields.forEach((field) => {
                const isAllowed = field.name && allowedCodes.has(field.name);
                field.style.display = isAllowed ? "" : "none";
            });
        });
        _EdenEditStructureEntry_initializeForm.set(this, (preserveChange) => {
            this.observer.disconnect();
            const { active, highlight, virtualPage, metadata } = this.entryData;
            const pageTemplate = virtualPage === "/index" ? "/" : virtualPage;
            this.pageTemplate = pageTemplate;
            __classPrivateFieldGet(this, _EdenEditStructureEntry_checkLangFormExist, "f").call(this);
            const { label, shortLabel, subTitle, disabled, path, seo = {}, } = this.entryData[this.currentLang];
            const isHome = path === "/";
            const disabledField = this.querySelector('[name="disabled"]');
            if (isHome) {
                disabledField.setAttribute("disabled", "");
                disabledField.setAttribute("checked", "false");
            }
            else {
                disabledField.removeAttribute("disabled");
                disabledField.setAttribute("checked", Boolean(disabled).toString());
            }
            const visibleField = this.querySelector('[name="visible"]');
            const highlightField = this.querySelector('[name="highlight"]');
            const labelField = this.querySelector('[name="label"]');
            const subTitleField = this.querySelector('[name="subTitle"]');
            const shortLabelField = this.querySelector('[name="shortLabel"]');
            visibleField.setAttribute("checked", Boolean(active).toString());
            highlightField.setAttribute("checked", Boolean(highlight).toString());
            labelField.setAttribute("value", label || "");
            subTitleField.setAttribute("value", subTitle || "");
            shortLabelField.setAttribute("value", shortLabel || "");
            if (isHome) {
                this.urlInput.setAttribute("disabled", "");
            }
            else {
                this.urlInput.removeAttribute("disabled");
            }
            this.urlInput.setAttribute("value", path || "");
            this.SEOTitle.setAttribute("value", seo.title || "");
            const keywordsField = this.querySelector('[name="keywords"]');
            keywordsField.setAttribute("value", seo.keywords || "");
            this.SEODescription.setAttribute("value", seo.description || "");
            const robotsField = this.querySelector('[name="robots"]');
            robotsField.setAttribute("value", seo.robots || "");
            const canonicalField = this.querySelector('[name="canonical"]');
            canonicalField.setAttribute("value", seo.canonical || "");
            const includedField = this.querySelector('[name="included"]');
            includedField.setAttribute("checked", Boolean(seo.inSitemap).toString());
            const frequencyField = this.querySelector('[name="frequency"]');
            frequencyField.setAttribute("value", seo.frequency || "");
            const priorityField = this.querySelector('[name="priority"]');
            priorityField.setAttribute("value", seo.priority ? String(seo.priority) : "");
            const pageTemplateField = this.querySelector('[name="page-template"]');
            pageTemplateField.setAttribute("value", pageTemplate);
            __classPrivateFieldGet(this, _EdenEditStructureEntry_checkSEOQuality, "f").call(this);
            __classPrivateFieldGet(this, _EdenEditStructureEntry_initializeMetadata, "f").call(this, metadata);
            if (!preserveChange) {
                this.oldPaths = __classPrivateFieldGet(this, _EdenEditStructureEntry_getPaths, "f").call(this);
                __classPrivateFieldGet(this, _EdenEditStructureEntry_removeUnsavedChanges, "f").call(this);
            }
            this.inputs.forEach((input) => this.observer.observe(input, {
                attributes: true,
                attributeOldValue: true,
                attributeFilter: ["value", "checked"],
            }));
        });
        _EdenEditStructureEntry_saveFormContent.set(this, () => {
            const pathWithoutTralingSlash = normalizePathBeforeSave(this.urlInput.value);
            this.urlInput.setAttribute("value", pathWithoutTralingSlash);
            const hasExternalUrl = isExternalUrl(this.urlInput.value);
            if (hasExternalUrl) {
                const pageTemplateField = this.querySelector('[name="page-template"]');
                pageTemplateField.setAttribute("value", "");
            }
            else {
                const isEmpty = this.urlInput.value?.trim().length === 0;
                const isStartingWithSlash = this.urlInput.value.startsWith("/");
                if (!isEmpty && !isStartingWithSlash) {
                    this.urlInput.setAttribute("value", `/${this.urlInput.value}`);
                }
            }
            const disabledField = this.querySelector('[name="disabled"]');
            const visibleField = this.querySelector('[name="visible"]');
            const highlightField = this.querySelector('[name="highlight"]');
            const labelField = this.querySelector('[name="label"]');
            const subTitleField = this.querySelector('[name="subTitle"]');
            const shortLabelField = this.querySelector('[name="shortLabel"]');
            const titleField = this.querySelector('[name="title"]');
            const keywordsField = this.querySelector('[name="keywords"]');
            const descriptionField = this.querySelector('[name="description"]');
            const robotsField = this.querySelector('[name="robots"]');
            const canonicalField = this.querySelector('[name="canonical"]');
            const includedField = this.querySelector('[name="included"]');
            const frequencyField = this.querySelector('[name="frequency"]');
            const priorityField = this.querySelector('[name="priority"]');
            const pageTemplateField = this.querySelector('[name="page-template"]');
            const metadata = __classPrivateFieldGet(this, _EdenEditStructureEntry_formatMetadata, "f").call(this);
            this.entryData = {
                ...this.entryData,
                virtualPage: pageTemplateField.value,
                active: visibleField.checked,
                highlight: highlightField.checked,
                metadata,
                [this.currentLang]: {
                    disabled: disabledField.checked,
                    label: labelField.value,
                    shortLabel: shortLabelField.value,
                    subTitle: subTitleField.value,
                    path: this.urlInput.value !== "" ? this.urlInput.value : undefined,
                    seo: {
                        title: titleField.value,
                        keywords: keywordsField.value,
                        description: descriptionField.value,
                        robots: robotsField.value,
                        canonical: canonicalField.value,
                        inSitemap: includedField.checked,
                        frequency: frequencyField.value,
                        priority: Number(priorityField.value),
                    },
                },
            };
        });
        _EdenEditStructureEntry_showForm.set(this, (e) => {
            const target = e.target;
            if (!target)
                return;
            const tab = target.closest(".edit-structure-entry__tab");
            if (tab === null)
                return;
            const which = whichTab(tab);
            if (which) {
                const tabs = Array.from(this.tabs.querySelectorAll(".edit-structure-entry__tab"));
                const forms = Array.from(this.forms.querySelectorAll(".edit-structure-entry__form"));
                tabs.forEach((t) => {
                    if (t === tab) {
                        t.classList.add("edit-structure-entry__tab--active");
                    }
                    else {
                        t.classList.remove("edit-structure-entry__tab--active");
                    }
                });
                forms.forEach((form) => {
                    if (form.classList.contains(`edit-structure-entry__form--${which}`)) {
                        form.classList.add("edit-structure-entry__form--visible");
                    }
                    else {
                        form.classList.remove("edit-structure-entry__form--visible");
                    }
                });
            }
            which === "page" || which === "metadata"
                ? this.langSwitch.classList.add("edit-structure-entry__lang-switch--hidden")
                : this.langSwitch.classList.remove("edit-structure-entry__lang-switch--hidden");
        });
        _EdenEditStructureEntry_switchLang.set(this, (e) => {
            const target = e.target;
            if (!target)
                return;
            const lang = target.closest(".edit-structure-entry__lang");
            if (lang === null ||
                lang.classList.contains("edit-structure-entry__lang--active"))
                return;
            const clickedLang = lang.innerText.toLowerCase();
            const langs = Array.from(this.langSwitch.querySelectorAll(".edit-structure-entry__lang"));
            langs.forEach((lang) => {
                if (lang === lang) {
                    lang.classList.add("edit-structure-entry__lang--active");
                }
                else {
                    lang.classList.remove("edit-structure-entry__lang--active");
                }
            });
            __classPrivateFieldGet(this, _EdenEditStructureEntry_saveFormContent, "f").call(this);
            this.currentLang = clickedLang;
            __classPrivateFieldGet(this, _EdenEditStructureEntry_initializeForm, "f").call(this, true);
        });
        _EdenEditStructureEntry_checkSEOQuality.set(this, () => {
            const { ALERT, WARNING, OK } = SEO_PILL_STATUSES;
            const [DESCRIPTION_MIN_LENGTH, DESCRIPTION_MAX_LENGTH] = SEO_DESCRIPTION_LENGTH_INTERVAL;
            const { value: titleValue } = this.SEOTitle;
            const { value: descriptionValue } = this.SEODescription;
            const titleAlert = titleValue === "";
            const descriptionAlert = descriptionValue === "";
            const descriptionWarning = descriptionValue.length < DESCRIPTION_MIN_LENGTH ||
                descriptionValue.length > DESCRIPTION_MAX_LENGTH;
            Object.keys(SEO_PILL_STATUSES).forEach((key) => {
                [this.SEOTabPill, this.SEOTitlePill, this.SEODescriptionPill].forEach((pill) => pill.classList.remove(`edit-structure-entry__pill--${SEO_PILL_STATUSES[key]}`));
            });
            this.SEOTitlePill.classList.add(`edit-structure-entry__pill--${titleAlert ? ALERT : OK}`);
            if (descriptionAlert) {
                this.SEODescriptionPill.classList.add(`edit-structure-entry__pill--${ALERT}`);
            }
            else if (descriptionWarning) {
                this.SEODescriptionPill.classList.add(`edit-structure-entry__pill--${WARNING}`);
            }
            else {
                this.SEODescriptionPill.classList.add(`edit-structure-entry__pill--${OK}`);
            }
            if (titleAlert && descriptionAlert) {
                this.SEOTabPill.classList.add(`edit-structure-entry__pill--${ALERT}`);
            }
            else if (titleAlert || descriptionAlert || descriptionWarning) {
                this.SEOTabPill.classList.add(`edit-structure-entry__pill--${WARNING}`);
            }
            else {
                this.SEOTabPill.classList.add(`edit-structure-entry__pill--${OK}`);
            }
            this.SEODescriptionCount.innerText = String(descriptionValue.length);
        });
        _EdenEditStructureEntry_copyUrl.set(this, () => {
            const value = this.urlInput.value;
            copyToClipboard(noTrailingSlash(value) ? value : value.concat("/"));
            snackbar(t("snackbars.url-copied-in-clipboard"), "success");
        });
        _EdenEditStructureEntry_onUrlInputChange.set(this, () => {
            const value = this.urlInput.value;
            if (isExternalUrl(value)) {
                const pageTemplateField = this.querySelector('[name="page-template"]');
                pageTemplateField.setAttribute("value", "");
                return;
            }
            const validPath = normalizeStructurePathInput(value);
            this.urlInput.setAttribute("value", validPath);
        });
        this.saveNode = async (e) => {
            e?.preventDefault();
            __classPrivateFieldGet(this, _EdenEditStructureEntry_instances, "m", _EdenEditStructureEntry_startLoading).call(this);
            __classPrivateFieldGet(this, _EdenEditStructureEntry_saveFormContent, "f").call(this);
            const node = this.entryData;
            let pathsToRevalidate = [];
            if (this.oldPaths.length > 0) {
                const newPaths = __classPrivateFieldGet(this, _EdenEditStructureEntry_getPaths, "f").call(this);
                pathsToRevalidate = collectChangedPaths(this.oldPaths, newPaths);
            }
            await saveNode(node, pathsToRevalidate);
            this.oldPaths = __classPrivateFieldGet(this, _EdenEditStructureEntry_getPaths, "f").call(this);
            __classPrivateFieldGet(this, _EdenEditStructureEntry_removeUnsavedChanges, "f").call(this);
            __classPrivateFieldGet(this, _EdenEditStructureEntry_instances, "m", _EdenEditStructureEntry_stopLoading).call(this);
        };
        _EdenEditStructureEntry_setUnsavedChanges.set(this, () => {
            this.unsavedChanges = true;
            this.saveButton.removeAttribute("disabled");
        });
        _EdenEditStructureEntry_removeUnsavedChanges.set(this, () => {
            this.unsavedChanges = false;
            this.saveButton.setAttribute("disabled", "");
        });
        _EdenEditStructureEntry_detectChanges.set(this, (mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.oldValue !== null && !this.unsavedChanges) {
                    __classPrivateFieldGet(this, _EdenEditStructureEntry_setUnsavedChanges, "f").call(this);
                }
            });
        });
        _EdenEditStructureEntry_getPaths.set(this, () => {
            const { langs = [] } = window.EdenConfig;
            return collectEntryPaths(this.entryData, langs);
        });
        this.isSuperAdmin = window.Eden.pageUi.isSuperAdmin;
        this.unsavedChanges = false;
        this.oldPaths = [];
        this.currentLang = lang;
        this.innerHTML = html `<style>
        ${styles}
      </style>
      ${template({
            langs,
            lang: this.currentLang,
            templates,
            metadata: pagesMetadata,
            isSuperAdmin: this.isSuperAdmin,
        })}`;
    }
    connectedCallback() {
        this.urlInput = this.querySelector('[name="url"]');
        this.tabs = this.querySelector(".edit-structure-entry__tabs");
        this.forms = this.querySelector(".edit-structure-entry__forms");
        this.langSwitch = this.querySelector(".edit-structure-entry__lang-switch");
        this.SEOTabPill = this.querySelector(".edit-structure-entry__pill--tab");
        this.SEOTitle = this.querySelector('[name="title"]');
        this.SEODescription = this.querySelector('[name="description"]');
        this.SEOTitlePill = this.SEOTitle.querySelector(".edit-structure-entry__pill--title");
        this.SEODescriptionPill = this.SEODescription.querySelector(".edit-structure-entry__pill--description");
        this.SEODescriptionCount = this.querySelector(".edit-structure-entry__description-count");
        this.SEODescriptionCountMax = this.querySelector(".edit-structure-entry__description-count-max");
        this.SEODescriptionCountMax.innerText =
            SEO_DESCRIPTION_LENGTH_INTERVAL[1].toString();
        this.metadataFields = this.querySelectorAll(".edit-structure-entry__form--metadata :is(eden-input, eden-checkbox, eden-tag-manager)");
        this.copyUrlButton = this.querySelector(".edit-structure-entry__action--copy-url");
        this.saveButton = this.querySelector(".edit-structure-entry__button--confirm");
        this.inputs = Array.from(this.querySelectorAll("eden-input, eden-checkbox, eden-tag-manager"));
        this.observer = new MutationObserver(__classPrivateFieldGet(this, _EdenEditStructureEntry_detectChanges, "f"));
        __classPrivateFieldGet(this, _EdenEditStructureEntry_removeUnsavedChanges, "f").call(this);
        this.langSwitch.addEventListener("click", __classPrivateFieldGet(this, _EdenEditStructureEntry_switchLang, "f"));
        this.tabs.addEventListener("click", __classPrivateFieldGet(this, _EdenEditStructureEntry_showForm, "f"));
        this.SEOTitle.addEventListener("input", __classPrivateFieldGet(this, _EdenEditStructureEntry_checkSEOQuality, "f"));
        this.SEODescription.addEventListener("input", __classPrivateFieldGet(this, _EdenEditStructureEntry_checkSEOQuality, "f"));
        this.urlInput.addEventListener("input", __classPrivateFieldGet(this, _EdenEditStructureEntry_onUrlInputChange, "f"));
        this.copyUrlButton.addEventListener("click", __classPrivateFieldGet(this, _EdenEditStructureEntry_copyUrl, "f"));
        this.addEventListener("submit", this.saveNode);
    }
    disconnectedCallback() {
        this.removeEventListener("submit", this.saveNode);
        this.copyUrlButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenEditStructureEntry_copyUrl, "f"));
        this.urlInput.removeEventListener("input", __classPrivateFieldGet(this, _EdenEditStructureEntry_onUrlInputChange, "f"));
        this.SEODescription.removeEventListener("input", __classPrivateFieldGet(this, _EdenEditStructureEntry_checkSEOQuality, "f"));
        this.SEOTitle.removeEventListener("input", __classPrivateFieldGet(this, _EdenEditStructureEntry_checkSEOQuality, "f"));
        this.tabs.removeEventListener("click", __classPrivateFieldGet(this, _EdenEditStructureEntry_showForm, "f"));
        this.langSwitch.removeEventListener("click", __classPrivateFieldGet(this, _EdenEditStructureEntry_switchLang, "f"));
        this.observer.disconnect();
    }
    static get observedAttributes() {
        return ["entryselected"];
    }
    attributeChangedCallback(name) {
        if (name === "entryselected") {
            __classPrivateFieldGet(this, _EdenEditStructureEntry_initializeForm, "f").call(this);
        }
    }
}
_EdenEditStructureEntry_checkLangFormExist = new WeakMap(), _EdenEditStructureEntry_formatMetadata = new WeakMap(), _EdenEditStructureEntry_initializeMetadata = new WeakMap(), _EdenEditStructureEntry_filterMetadataFieldsDisplay = new WeakMap(), _EdenEditStructureEntry_initializeForm = new WeakMap(), _EdenEditStructureEntry_saveFormContent = new WeakMap(), _EdenEditStructureEntry_showForm = new WeakMap(), _EdenEditStructureEntry_switchLang = new WeakMap(), _EdenEditStructureEntry_checkSEOQuality = new WeakMap(), _EdenEditStructureEntry_copyUrl = new WeakMap(), _EdenEditStructureEntry_onUrlInputChange = new WeakMap(), _EdenEditStructureEntry_setUnsavedChanges = new WeakMap(), _EdenEditStructureEntry_removeUnsavedChanges = new WeakMap(), _EdenEditStructureEntry_detectChanges = new WeakMap(), _EdenEditStructureEntry_getPaths = new WeakMap(), _EdenEditStructureEntry_instances = new WeakSet(), _EdenEditStructureEntry_startLoading = function _EdenEditStructureEntry_startLoading() {
    this.saveButtonHtml = this.saveButton.innerHTML;
    this.saveButton.style.width = `${this.saveButton.offsetWidth}px`;
    this.saveButton.style.height = `${this.saveButton.offsetHeight}px`;
    this.saveButton.classList.add("spin");
    this.saveButton.innerHTML = html `<eden-icon
      code="loader"
      class="spinner"
    ></eden-icon>`;
}, _EdenEditStructureEntry_stopLoading = function _EdenEditStructureEntry_stopLoading() {
    this.saveButton.innerHTML = this.saveButtonHtml;
    this.saveButton.removeAttribute("style");
    this.saveButton.classList.remove("spin");
};
export default EdenEditStructureEntry;
if (!customElements.get("eden-edit-structure-entry")) {
    customElements.define("eden-edit-structure-entry", EdenEditStructureEntry);
}
function whichTab(tab) {
    if (tab.classList.contains("edit-structure-entry__tab--menu"))
        return "menu";
    if (tab.classList.contains("edit-structure-entry__tab--page"))
        return "page";
    if (tab.classList.contains("edit-structure-entry__tab--seo"))
        return "seo";
    if (tab.classList.contains("edit-structure-entry__tab--metadata"))
        return "metadata";
    return false;
}
