import { getNode } from "../../services/action.js";
import { fetchStructure } from "../../services/fetcher.js";
import { EdenEvents } from "../../services/event.js";
import html from "../../services/html.js";
import structureTreeStyles from "../styles/eden-structure-tree-styles.js";
import { buildConfirmCancelButtons, openPluginModal, } from "./modal-controller.js";
import t from "../../i18n/index.js";
const SLASH = "/";
export default class LinkFromStructureModal {
    constructor({ onChange, templateToMatch, returnAllBarePaths }) {
        this.init = async () => {
            const path = document.location.pathname;
            const { lang, langPrefix } = window.EdenConfig;
            const { structure } = await fetchStructure(path, lang, langPrefix);
            const { default: EdenStructureTree } = await import("../structure/eden-structure-tree.js");
            const navTree = new EdenStructureTree({
                tree: structure,
                linking: true,
                templateToMatch: this.templateToMatch,
                depth: 0,
            });
            this.modal = openPluginModal({
                icon: "tree",
                title: t("modals.select-page.title"),
                content: template(this.templateToMatch),
                onClose: this.closeModal,
                buttons: buildConfirmCancelButtons({
                    confirmLabel: t("common.validate"),
                    onConfirm: this.confirm,
                    autofocus: true,
                }),
                noPadding: true,
            });
            const root = this.modal.shadowRoot;
            const navContainer = root.querySelector(".modal__structure-container");
            const { default: EdenStructureSearch } = await import("../structure/eden-structure-search.js");
            navContainer.appendChild(new EdenStructureSearch({
                editStructure: navTree,
                structure,
                label: "path",
                templateToMatch: this.templateToMatch,
            }));
            navContainer.appendChild(navTree);
            root.addEventListener(EdenEvents.structureNodeClicked, this.nodeClicked);
            const nodesToOpen = Array.from(root.querySelectorAll(".modal__structure-container > eden-structure-tree > eden-structure-tree-node, .modal__structure-container > eden-structure-tree > eden-structure-tree-node > .structure-tree__node > eden-structure-tree > eden-structure-tree-node"));
            nodesToOpen.forEach((node) => node.openNode());
        };
        this.nodeClicked = async (e) => {
            const root = this.modal.shadowRoot;
            const customEvent = e;
            const node = customEvent.detail;
            if (node === this.selectedEntry)
                return;
            this.selectedEntry = node;
            if (!this.selectedEntry.nodeId)
                return;
            const content = await getNode(this.selectedEntry.nodeId);
            const { lang, langs, langPrefix } = window.EdenConfig;
            const prefix = typeof langPrefix === "object" && langPrefix.links === true
                ? `/${lang}`
                : "";
            const path = content[lang]?.path || content[langs[0]].path;
            const prefixedPath = prefix.concat(path);
            const patchedPath = isLocalUrl(path)
                ? prefixedPath.concat("/")
                : path;
            this.url = this.returnAllBarePaths
                ? langs.reduce((acc, l) => {
                    const patchedContent = content[l] || content[langs[0]];
                    return { ...acc, [l]: patchedContent.path };
                }, {})
                : patchedPath;
            this.selectedEntry.setAttribute("selected", "");
            this.selectedEntry.setAttribute("entryselected", "");
            Array.from(root.querySelectorAll("eden-structure-tree-node")).forEach((el) => {
                if (el !== this.selectedEntry && el.hasAttribute("selected"))
                    el.removeAttribute("selected");
            });
        };
        this.confirm = () => {
            this.onChange(this.url);
        };
        this.closeModal = () => {
            const root = this.modal.shadowRoot;
            root.removeEventListener(EdenEvents.structureNodeClicked, this.nodeClicked);
        };
        this.onChange = onChange;
        this.templateToMatch = templateToMatch;
        this.returnAllBarePaths = returnAllBarePaths;
        this.url = returnAllBarePaths ? {} : "";
    }
}
function template(templateToMatch) {
    const helper = templateToMatch
        ? html ` <div class="modal__structure-container-helper">
        ${t("modals.link-from-structure.helper")}
      </div>`
        : "";
    return html `
    <style>
      .modal__structure-container {
        position: relative;
        width: 680px;
        max-width: 100%;
        height: 520px;
        max-height: 90vh;
        background-color: var(--eden-grey-100);
        border-radius: var(--eden-radius-200);
      }

      .modal__structure-container .edit-structure-search-header eden-input input,
      .modal__structure-container .edit-structure-search-header eden-input input:focus {
        border: 0;
        border-radius: 0;
      }

      .modal__structure-container > eden-structure-search > .edit-structure-search-header {
        width: 100%;
        display: flex;
        box-sizing: border-box;
        background-color: var(--eden-grey-000);
        border-bottom: 1px solid var(--eden-grey-100);
        border-radius: var(--eden-radius-200) var(--eden-radius-200) 0 0;
      }

      .modal__structure-container > eden-structure-tree {
        position: absolute;
        top: 34px;
        left: 0;
        width: 100%;
        height: calc(100% - 34px);
        border-radius: 0 0  var(--eden-radius-200) var(--eden-radius-200);
      }

      .modal__structure-container-helper {
        padding: 4px;
        text-align: center;
        font-size: 13px;
        color: var(--eden-grey-500);
        border-top: 1px solid var(--eden-grey-100);
      }
      ${structureTreeStyles(".modal__structure-container")}
    </style>
    <div class="modal__structure-container"></div>
    ${helper}
  `;
}
function isLocalUrl(href) {
    return (href !== null &&
        href !== undefined &&
        href.length > 2 &&
        href[0] === SLASH &&
        href[1] !== SLASH);
}
