import{LitElement as e,html as t,css as i}from"../../../../lit/index.js";import{encapScript as a,findTagsInHTML as s,wipeSlot as o,varExists as n,localStorageSet as l,validURL as d}from"../../../utils/utils.js";import{autorun as r,toJS as m}from"../../../../mobx/dist/mobx.esm.js";import{store as h,HAXcmsStore as c}from"./haxcms-site-store.js";import"./haxcms-site-router.js";import"../../../simple-progress/simple-progress.js";import{I18NMixin as p}from"../../../i18n-manager/lib/I18NMixin.js";import{SuperDaemonInstance as u}from"../../../super-daemon/super-daemon.js";import{UserScaffoldInstance as g}from"../../../user-scaffold/user-scaffold.js";import"../../../replace-tag/replace-tag.js";function darkToggle(e){e.matches?h.darkMode=!0:h.darkMode=!1}class HAXCMSSiteBuilder extends(p(e)){static get styles(){return[i`
        :host {
          display: block;
          position: relative;
        }
        :host([is-logged-in]) {
          max-height: calc(100vh - 48px);
        }
        :host #slot {
          opacity: 0.2;
          visibility: hidden;
        }
        :host([theme-loaded]) #slot {
          opacity: 1;
          visibility: visible;
        }
        simple-progress {
          display: block;
          width: 100%;
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          background-color: transparent;
          z-index: 1000;
          --simple-progress-active-color: var(
            --haxcms-color,
            rgba(255, 255, 255, 0.5)
          );
        }
        simple-progress[disabled] {
          display: none;
        }
      `]}static get tag(){return"haxcms-site-builder"}render(){return t`
      <site-ai-chat></site-ai-chat>
      <haxcms-site-router base-uri="${this.baseURI}"></haxcms-site-router>
      <simple-progress .disabled="${!this.loading}"></simple-progress>
      <div id="slot"><slot></slot></div>
      <slot name="haxcms-site-editor-ui-prefix-avatar"></slot>
      <slot name="haxcms-site-editor-ui-prefix-buttons"></slot>
      <slot name="haxcms-site-editor-ui-suffix-buttons"></slot>
      <slot name="haxcms-site-editor-ui-main-menu"></slot>
      <slot name="haxcms-site-editor-ui-topbar-character-button"></slot>
      <simple-colors-polymer></simple-colors-polymer>
    `}_updateManifest(e){this.manifest={...e}}_updateLoading(e){this.loading=e.detail.value}hashCode(e){return e.split("").reduce(((e,t)=>0|(e=(e<<5)-e+t.charCodeAt(0))),0)}nodeNormalizeIDs(e){if(e.tagName&&null==e.getAttribute("id")&&["H1","H2","H3","H4","H5","H6"].includes(e.tagName))if(e.getAttribute("resource"))e.setAttribute("id",e.getAttribute("resource"));else{let t=e.tagName.toLowerCase()+"-"+this.hashCode(e.innerText);e.setAttribute("id",t)}}_updateActiveItemContent(e){if(e){let t=globalThis.document.createElement("div");t.innerHTML=e;for(const e of t.childNodes)this.nodeNormalizeIDs(e);e=t.innerHTML,this.activeItemContent="",setTimeout((()=>{this.activeItemContent=e}),0)}else h.cmsSiteEditorBackend.instance&&h.cmsSiteEditorBackend.instance.updateActiveItemContent?h.cmsSiteEditorBackend.instance.updateActiveItemContent():this.activeItemContent=""}display404Error(){if(h.themeElement){let e=globalThis.document.createDocumentFragment(),t=globalThis.document.createElement("p");t.innerHTML=`<strong>${h.getInternalRoute()}</strong> ${this.t.couldNotBeLocated}. ${this.t.hereAreSomePossibleRemedies}\n      <ul>\n        <li><a href="x/search?search=${h.getInternalRoute()}">${this.t.useSearchToLocateTheContentYouAreLookingFor}</a></li>\n        <li><a href="./">${this.t.goToTheHomePage}</a></li>\n        <li>${this.t.navigateToAnotherPageInTheMenu}</li>\n      </ul>`,e.appendChild(t),o(h.themeElement,"*"),h.themeElement.appendChild(e),setTimeout((()=>{h.toast(this.t.pageNotFound,4e3,{fire:!0,walking:!0})}),1e3)}}renderInternalRoute(){if(h.themeElement){let e=globalThis.document.createDocumentFragment();h.activeItem.component&&import(`../ui-components/routes/${h.activeItem.component}.js`).then((()=>{let t=globalThis.document.createElement(h.activeItem.component);e.appendChild(t),o(h.themeElement,"*"),h.themeElement.appendChild(e)}))}}async loadPageData(){if(this.activeItemLocation&&!this.loading){this.loading=!0;let e=`${this.outlineLocation}${this.activeItemLocation}`;this._timeStamp&&(-1!=e.indexOf("?")?e+=`&${this._timeStamp}`:e+=`?${this._timeStamp}`),"hax-internal-route.html"===this.activeItemLocation?(this.renderInternalRoute(),this.loading=!1):await fetch(e).then((e=>{if(e.ok)return e.text();this.display404Error()})).then((e=>{this._updateActiveItemContent(e),this.loading=!1})).catch((e=>{this.lastErrorChanged(e)}))}}async loadJOSData(){if(this.file){this.loading=!0;let e=`${this.outlineLocation}${this.file}`;try{let e=JSON.parse(this.file);this._updateManifest(e),this.loading=!1}catch(t){this._timeStamp&&""!=this._timeStamp&&(-1!=e.indexOf("?")?e+=`&${this._timeStamp}`:e+=`?${this._timeStamp}`);await fetch(e,{cache:"no-cache"}).then((e=>{if(e.ok)return e.json()})).then((e=>{this._updateManifest(e),this.loading=!1})).catch((e=>{this.lastErrorChanged(e)}))}}}updated(e){super.updated&&super.updated(e);let t=!1,i=!1;e.forEach(((e,a)=>{["outlineLocation","activeItemLocation"].includes(a)&&""!=this[a]&&(i=!0),["outlineLocation","file"].includes(a)&&""!=this[a]&&(t=!0),"_timeStamp"==a&&this[a]&&(t=!0,i=!0),"themeData"==a?this._themeChanged(this[a],e):"themeName"==a?this._themeNameChanged(this[a],e):"outlineLocation"==a?this.dispatchEvent(new CustomEvent("outline-location-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:this[a]})):"manifest"==a?(this.dispatchEvent(new CustomEvent("manifest-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:this[a]})),this._manifestChanged(this[a],e)):"activeItem"==a?(this.dispatchEvent(new CustomEvent("active-item-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:this[a]})),this._activeItemChanged(this[a],e)):"activeItemContent"==a&&(this.dispatchEvent(new CustomEvent("active-item-content-changed",{bubbles:!0,detail:this[a]})),this._activeItemContentChanged(this[a],e))})),t&&this.__ready&&this.loadJOSData(),i&&this.__ready&&this.loadPageData()}static get properties(){return{...super.properties,activeItemLocation:{type:String,attribute:"active-item-location"},disableFeatures:{type:String,reflect:!0,attribute:"disable-features"},_timeStamp:{type:String},isLoggedIn:{type:Boolean,reflect:!0,attribute:"is-logged-in"},queryParams:{type:Object},loading:{type:Boolean,reflect:!0},outlineLocation:{type:String,attribute:"outline-location"},manifest:{type:Object},themeData:{type:Object},themeName:{type:String},__imported:{type:Object},themeLoaded:{type:Boolean,reflect:!0,attribute:"theme-loaded"},activeItemContent:{type:String},file:{type:String},baseURI:{type:String,attribute:"base-uri"}}}_themeNameChanged(e){e&&(h.themeElement&&h.themeElement.remove(),o(this,"*"),h.themeElement=globalThis.document.createElement(e),h.themeElement.classList.add("haxcms-theme-element"),this.appendChild(h.themeElement))}lastErrorChanged(e){e&&(console.error(e),e.detail&&e.detail.value?(window&&globalThis.location&&globalThis.appSettings&&globalThis.appSettings.reloadOnError&&globalThis.location.reload(),h.toast(e.detail.value.status+" "+e.detail.value.statusText,5e3,{fire:!0})):window&&globalThis.location&&globalThis.appSettings&&globalThis.appSettings.reloadOnError&&globalThis.location.reload())}constructor(){for(var e in super(),this.windowControllers=new AbortController,this.t={...super.t,pageNotFound:"Page not found",navigateToAnotherPageInTheMenu:"Navigate to another page in the menu",couldNotBeLocated:"could not be located",hereAreSomePossibleRemedies:"Here are some possible remedies:",useSearchToLocateTheContentYouAreLookingFor:"Use Search to locate the content you are looking for",goToTheHomePage:"Go to the home page"},this.registerLocalization({context:this,namespace:"haxcms",localesPath:new URL("../../locales/haxcms.es.json",import.meta.url).href.replace("/haxcms.es.json","/"),locales:["es"]}),this._timeStamp=Math.floor(Date.now()/1e3),this.disableFeatures="",this.isLoggedIn=!1,this.__disposer=[],this.queryParams={},this.loading=!1,this.__imported={},this.themeLoaded=!1,this.outlineLocation="",this.activeItemLocation="",c.storePieces.siteBuilder=this,this.children)if(this.children[e].tagName&&this.children[e].getAttribute("slot")){const t=this.children[e].cloneNode(!0);let i=t.getAttribute("slot");switch(i){case"haxcms-site-editor-ui-prefix-avatar":case"haxcms-site-editor-ui-prefix-buttons":case"haxcms-site-editor-ui-suffix-buttons":case"haxcms-site-editor-ui-main-menu":case"haxcms-site-editor-ui-topbar-character-button":h.setupSlots[i].push(t)}}globalThis.addEventListener("hax-store-ready",this.storeReady.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("haxcms-trigger-update",this._triggerUpdatedData.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("haxcms-trigger-update-node",this._triggerUpdatedNode.bind(this),{signal:this.windowControllers.signal}),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",darkToggle,{signal:this.windowControllers.signal}),r((()=>{l("app-hax-darkMode",m(h.darkMode)),m(h.darkMode)?globalThis.document.body.classList.add("dark-mode"):globalThis.document.body.classList.remove("dark-mode")})),r((()=>{this.isLoggedIn=m(h.isLoggedIn),g.writeMemory("isLoggedIn",this.isLoggedIn);const e=Math.floor(Date.now()/1e3);if(this.isLoggedIn&&!this.loggedInTime){this.loggedInTime=e,this._timeStamp=this.loggedInTime;var t=g.readMemory("recentLogins");t?t&&(t.length<5&&t.shift(),t.push(e),g.writeMemory("recentLogins",t,"long")):g.writeMemory("recentLogins",[e],"long")}})),r((()=>{const e=m(g.memory),t=m(g.action);!1===e.editMode&&e.interactionDelay>=3600&&null===t.type&&h.cmsSiteEditor.haxCmsSiteEditorUIElement&&h.cmsSiteEditor.haxCmsSiteEditorUIElement.shadowRoot&&setTimeout((()=>{h.cmsSiteEditor.haxCmsSiteEditorUIElement.shadowRoot.querySelector("#editbutton").dataPulse="1"}),300),g.active&&g.memory.isLoggedIn&&g.memory.recentTarget===u&&null===u.programName&&g.memory.interactionDelay>600&&["paste","key"].includes(t.type)?d(u.value)&&u.waveWand([u.value,"/",{},"hax-agent","Agent"],null,"coin2"):g.active&&g.memory.isLoggedIn&&null===u.programName&&["paste"].includes(t.type)&&"url"==g.data.architype&&u.waveWand([m(g.data.value),"/",{},"hax-agent","Agent"],null,"coin2")}))}firstUpdated(e){super.firstUpdated&&super.firstUpdated(e),this.__ready=!0,h.appReady=!0,globalThis.dispatchEvent(new CustomEvent("haxcms-ready",{bubbles:!0,composed:!0,cancelable:!1,detail:this})),import("./haxcms-editor-builder.js").then((e=>{import("./haxcms-toast.js"),this.editorBuilder=globalThis.document.createElement("haxcms-editor-builder"),this.parentNode?this.parentNode.insertBefore(this.editorBuilder,this):globalThis.document.body.appendChild(this.editorBuilder),"published"!==c.getApplicationContext()?this._timeStamp=Math.floor(Date.now()/1e3):this._timeStamp=""})).catch((e=>{console.warn(e)})),globalThis.dispatchEvent(new Event("resize")),setTimeout((()=>{r((e=>{if(this.themeData=m(h.themeData),this.themeData){const e=new URLSearchParams(globalThis.location.search),t=e.get("format");if(null!=t&&"print-page"===t)this.themeData.element="haxcms-print-theme";const i=e.get("disable-features");null!=i&&(this.disableFeatures=i)}this.themeData&&this.themeData.element!==this.themeName&&(this.themeName=this.themeData.element),this.__disposer.push(e)})),r((e=>{const t=m(h.activeItem);t&&t.location&&(this.activeItemLocation=t.location),this.__disposer.push(e)}))}),0)}disconnectedCallback(){for(var e in this.__disposer)this.__disposer[e].dispose();this.windowControllers.abort(),super.disconnectedCallback()}storeReady(e){h.cmsSiteEditor&&h.cmsSiteEditor.instance&&globalThis.HaxStore.requestAvailability().activeHaxBody&&h.activeItemContent&&globalThis.HaxStore.requestAvailability().activeHaxBody.importContent(h.activeItemContent)}replaceTagReplacement(e){for(var t=/\<(\w+?\-\w*.*)\s*?\>/gim,i=t.exec(e);null!=i;){let a=i[1].replace("<","").replace(">","");a.indexOf(" ")&&(a=a.split(" ")[0]),-1!=a.indexOf("-")&&(e=(e=e.replace("<"+a,'<replace-tag with="'+a+'" ')).replace("</"+a+">","</replace-tag>")),i=t.exec(e)}return e}_activeItemContentChanged(e,t){if(e){var i=e;null!==i&&h.activeItem&&h.activeItem.metadata&&(o(h.themeElement,"*"),e=`<page-break\n        break-type="site"\n        title="${h.activeItem.title}"\n        parent="${h.activeItem.parent}"\n        item-id="${h.activeItem.id}"\n        slug="${h.activeItem.slug}"\n        description="${h.activeItem.description}"\n        order="${h.activeItem.order}"\n        ${h.activeItem.metadata.pageType?`page-type="${h.activeItem.metadata.pageType}"`:""}\n        ${h.activeItem.metadata.tags?`tags="${h.activeItem.metadata.tags}"`:""}\n        ${h.activeItem.metadata.hideInMenu?'hide-in-menu="hide-in-menu"':""}\n        ${h.activeItem.metadata.relatedItems?`related-items="${h.activeItem.metadata.relatedItems}"`:""}\n        ${h.activeItem.metadata.image?`image="${h.activeItem.metadata.image}"`:""}\n        ${h.activeItem.metadata.icon?`icon="${h.activeItem.metadata.icon}"`:""}\n        ${h.activeItem.metadata.accentColor?`accent-color="${h.activeItem.metadata.accentColor}"`:""}\n        ${h.activeItem.metadata.theme&&h.activeItem.metadata.theme.key?`developer-theme="${h.activeItem.metadata.theme.key}"`:""}\n        ${h.activeItem.metadata.locked?'locked="locked"':""}\n        ${!1===h.activeItem.metadata.published?"":'published="published"'} ></page-break>${e}`,i=a(e),h.activeItemContent=i,setTimeout((()=>{if(0===h.themeElement.childNodes.length){let e=document.createRange().createContextualFragment(this.replaceTagReplacement(i));h.themeElement.appendChild(e),this.dispatchEvent(new CustomEvent("json-outline-schema-active-body-changed",{bubbles:!0,composed:!0,cancelable:!1,detail:i}))}if(!globalThis.WCAutoload&&n(this.manifest,"metadata.node.dynamicElementLoader")){let t=s(i);const a=new URL("./locales/haxcms.es.json",import.meta.url).href+"/../";for(var e in t){const i=t[e];this.manifest.metadata.node.dynamicElementLoader[i]&&!globalThis.customElements.get(i)&&import(`${a}../../../../${this.manifest.metadata.node.dynamicElementLoader[i]}`).then((e=>{})).catch((e=>{console.warn(e)}))}}else globalThis.WCAutoload&&setTimeout((()=>{globalThis.WCAutoload.process()}),0)}),5))}}_activeItemChanged(e,t){this.shadowRoot&&e&&void 0!==e.id?this.queryParams.nodeId=e.id:t&&!e&&this.dispatchEvent(new CustomEvent("json-outline-schema-active-body-changed",{bubbles:!0,composed:!0,cancelable:!1,detail:null}))}_triggerUpdatedData(e){this.isLoggedIn?this._timeStamp=Math.floor(Date.now()/1e3):this._timeStamp=""}_triggerUpdatedNode(e){this.loadPageData()}_manifestChanged(e,t){e&&e.metadata&&e.items&&h.loadManifest(e,this)}_themeChanged(e,t){if(e){this.themeLoaded=!1;let t=e;if(void 0!==this.__imported[t.element])this.themeLoaded=!0;else if(globalThis.WCAutoload)this.__imported[t.element]=t.element,this.themeLoaded=!0,setTimeout((()=>{globalThis.WCAutoload.process(),globalThis.dispatchEvent(new CustomEvent("haxcms-theme-ready",{bubbles:!0,composed:!0,cancelable:!1,detail:this}))}),5);else try{import(new URL("./../../../../../"+e.path,import.meta.url).href).then((e=>{this.__imported[t.element]=t.element,this.themeLoaded=!0}))}catch(e){this.themeLoaded=!0}}}}globalThis.HAXme=function(e=null){null==e&&(e="demo",globalThis.appSettings={login:"dist/dev/login.json",logout:"dist/dev/logout.json",saveNodePath:"dist/dev/saveNode.json",saveManifestPath:"dist/dev/saveManifestPath.json",createNodePath:"dist/dev/saveNode.json",deleteNodePath:"dist/dev/saveNode.json",saveOutlinePath:"dist/dev/saveNode.json",publishSitePath:"dist/dev/saveNode.json",syncSitePath:"dist/dev/saveNode.json",getSiteFieldsPath:"dist/dev/getSiteFieldsPath.json",revertSitePath:"dist/dev/saveNode.json",getFormToken:"adskjadshjudfu823u823u8fu8fij",appStore:{url:"dist/dev/appstore.json"},jwt:"made-up-thing",themes:{"haxcms-dev-theme":{element:"haxcms-dev-theme",path:"@haxtheweb/haxcms-elements/lib/haxcms-dev-theme.js",name:"Developer theme"}}}),"demo"==e&&(globalThis.HAXCMSContext="demo"),globalThis.document.body&&(globalThis.document.body.querySelector("haxcms-editor-builder").__appliedContext=!1,globalThis.document.body.querySelector("haxcms-editor-builder").applyContext(e))},customElements.define(HAXCMSSiteBuilder.tag,HAXCMSSiteBuilder);export{HAXCMSSiteBuilder};