(()=>{"use strict";const t=StimulusModule;var e;!function(t){t.INITIAL="initial",t.LOADING="loading",t.ERROR="error",t.SUGGESTED="suggested",t.NO_MORE="no_more"}(e||(e={}));class n extends t.Controller{static targets=["suggestButton"];static values={relationName:String,url:{default:window.wagtailAI.config.urls.SUGGESTED_CONTENT,type:String},state:{default:e.INITIAL,type:String},seenPks:{default:[],type:Array},vectorIndex:String,instancePk:String,limit:Number,chunkSize:Number};abortController=null;#t=null;connect(){this.stateValue=e.INITIAL}get panelComponent(){return this.#t||(this.#t=window.wagtail.editHandler.getPanelByName(this.relationNameValue)),this.#t}addItem(t){const e=this.panelComponent;e.addForm();const n=e.formCount-1,o=`${e.opts.formsetPrefix}-${n}-${e.opts.chooserFieldName}`,a=document.querySelector(`[data-inline-panel-child]:has(#${o})`);a&&(a.setAttribute(`data-${this.identifier}-suggested`,"true"),e.chooserWidgetFactory.getById(o).setState({id:t.id,adminTitle:t.title,editUrl:t.editUrl}))}async getSuggestions(){const t=await async function(){const t=window.wagtail.app.queryController("w-preview");return t?(t.ready||(await t.checkAndUpdatePreview(),await new Promise((t=>{document.addEventListener("w-preview:loaded",t,{once:!0})}))),t.extractContent()):null}();if(!t)throw new Error("Unable to get page content for analysis.");let e=this.limitValue;const n=this.panelComponent.opts.maxForms;n&&(e=Math.min(n-this.panelComponent.getChildCount(),this.limitValue));const{innerText:o}=t;try{const t=await fetch(this.urlValue,{method:"POST",headers:{[wagtailConfig.CSRF_HEADER_NAME]:wagtailConfig.CSRF_TOKEN},body:JSON.stringify({arguments:{vector_index:this.vectorIndexValue,exclude_pks:[this.instancePkValue,...this.seenPksValue,...this.getFormsetChildIds()],content:o,limit:e,chunk_size:this.hasChunkSizeValue?this.chunkSizeValue:void 0}}),signal:this.abortController?.signal});if(!t.ok)throw new Error(`Error fetching AI response: ${t.status} ${t.statusText}`);return await t.json().then((({data:t})=>t))}catch(t){throw console.error("Error fetching AI response:",t),t}}clearSuggestions(){const t=this.element.querySelectorAll(`[data-${this.identifier}-suggested="true"]`);t.forEach((t=>t.remove())),this.panelComponent.totalFormsInput.val(this.panelComponent.formCount-t.length)}getFormsetChildIds(){return Array.from(this.panelComponent.formsElt[0].querySelectorAll(":scope > [data-inline-panel-child]:not(.deleted)")).map(((t,e)=>t.querySelector(`#${this.panelComponent.opts.formsetPrefix}-${e}-related_page`)?.value))}updateControlStates(){const t=this.panelComponent.opts.maxForms,n=t&&this.panelComponent.getChildCount()>=t,o=this.stateValue===e.NO_MORE;this.suggestButtonTarget.disabled=!(!n&&!o),this.panelComponent.updateControlStates()}async suggest(){this.abortController=new AbortController,this.stateValue=e.LOADING;try{const t=await this.getSuggestions();this.clearSuggestions(),t&&t.length>0?(t.forEach((t=>{this.seenPksValue.push(t.id),this.addItem(t)})),this.stateValue=e.SUGGESTED):this.stateValue=e.NO_MORE,this.updateControlStates()}catch(t){return this.abortController?.signal.aborted?(this.stateValue=e.INITIAL,void(this.abortController=null)):(console.error("Error parsing AI response:",t),void(this.stateValue=e.ERROR))}}async cancel(){this.abortController?.abort("Cancelled by user")}async clear(){this.stateValue=e.INITIAL,this.seenPksValue.length=0,this.clearSuggestions(),this.updateControlStates()}}window.wagtail.app.register("wai-chooser-panel",n)})();