(()=>{const e="plotdirector.word.projectId",t="plotdirector.word.bookId",n="plotdirector.word.activeTab",r={documentGuid:"plotdirector.word.documentGuid",bookId:"plotdirector.word.boundBookId",projectId:"plotdirector.word.boundProjectId",bindingVersion:"plotdirector.word.bindingVersion"},o=new Set(["scene","review","maintenance","diagnostics"]),a=document.querySelector(".word-companion-shell"),c=document.querySelector(".word-companion-tabs"),i=[...document.querySelectorAll("[data-tab-button]")],s=[...document.querySelectorAll("[data-tab-panel]")],d=document.querySelector("[data-linked-manuscript-card]"),l=document.querySelector("[data-linked-project-title]"),u=document.querySelector("[data-linked-book-title]"),p=document.querySelector("[data-first-run-wizard]"),h=document.querySelector("[data-first-run-project-select]"),m=document.querySelector("[data-first-run-book-select]"),g=document.querySelector("[data-first-run-new-book-title]"),y=document.querySelector("[data-first-run-create-book]"),w=document.querySelector("[data-first-run-scan]"),f=document.querySelector("[data-first-run-cancel]"),b=document.querySelector("[data-first-run-status]"),I=document.querySelector("[data-first-run-summary]"),C=document.querySelector("[data-first-run-character-section]"),S=document.querySelector("[data-first-run-character-status]"),k=document.querySelector("[data-first-run-character-candidates]"),v=document.querySelector("[data-first-run-character-actions]"),x=document.querySelector("[data-first-run-create-characters]"),P=document.querySelector("[data-first-run-skip-characters]"),D=document.querySelector("[data-first-run-continue]"),E=document.querySelector("[data-first-run-import-actions]"),N=document.querySelector("[data-first-run-import]"),L=document.querySelector("[data-first-run-import-cancel]"),q=document.querySelector("[data-first-run-replace-dialog]"),A=document.querySelector("[data-first-run-replace-confirm]"),$=document.querySelector("[data-first-run-replace-cancel]"),T=document.querySelector("[data-unlink-word-document-dialog]"),W=document.querySelector("[data-unlink-word-document-confirm]"),j=document.querySelector("[data-unlink-word-document-cancel]"),R=document.querySelector("[data-clean-unlink-word-document-dialog]"),U=document.querySelector("[data-clean-unlink-word-document-confirm]"),M=document.querySelector("[data-clean-unlink-word-document-cancel]"),O=document.querySelector("[data-office-status]"),B=document.querySelector("[data-connection-status]"),H=document.querySelector("[data-summary-connection]"),G=document.querySelector("[data-summary-project]"),F=document.querySelector("[data-summary-book]"),V=document.querySelector("[data-project-select]"),K=document.querySelector("[data-book-select]"),Y=document.querySelector("[data-runtime-book-selectors]"),J=document.querySelector("[data-project-message]"),_=document.querySelector("[data-book-message]"),z=document.querySelector("[data-refresh-current-scene]"),Q=document.querySelector("[data-refresh-document]"),X=document.querySelector("[data-current-chapter]"),Z=document.querySelector("[data-current-scene]"),ee=document.querySelector("[data-current-word-count]"),te=document.querySelector("[data-scene-tracking-status]"),ne=document.querySelector("[data-document-message]"),re=document.querySelector("[data-sync-note]"),oe=document.querySelector("[data-document-outline]"),ae=document.querySelector("[data-analyse-manuscript-structure]"),ce=document.querySelector("[data-apply-structure-sync]"),ie=document.querySelector("[data-structure-preview-status]"),se=document.querySelector("[data-structure-preview-results]"),de=document.querySelector("[data-refresh-plotdirector-scene]"),le=document.querySelector("[data-plotdirector-scene-status]"),ue=document.querySelector("[data-anchor-status]"),pe=document.querySelector("[data-anchor-book-id]"),he=document.querySelector("[data-anchor-chapter-id]"),me=document.querySelector("[data-anchor-scene-id]"),ge=document.querySelector("[data-attach-plotdirector-ids]"),ye=document.querySelector("[data-unlink-word-document]"),we=document.querySelector("[data-clean-unlink-word-document]"),fe=document.querySelector("[data-marker-binding-status]"),be=document.querySelector("[data-marker-chapter-count]"),Ie=document.querySelector("[data-marker-scene-count]"),Ce=document.querySelector("[data-unlink-dialog-chapter-count]"),Se=document.querySelector("[data-unlink-dialog-scene-count]"),ke=document.querySelector("[data-clean-dialog-chapter-count]"),ve=document.querySelector("[data-clean-dialog-scene-count]"),xe=document.querySelector("[data-plotdirector-scene-details]"),Pe=document.querySelector("[data-plotdirector-scene-title]"),De=document.querySelector("[data-plotdirector-revision-status]"),Ee=document.querySelector("[data-plotdirector-estimated-words]"),Ne=document.querySelector("[data-plotdirector-actual-words]"),Le=document.querySelector("[data-plotdirector-blocked-status]"),qe=document.querySelector("[data-plotdirector-blocked-reason-row]"),Ae=document.querySelector("[data-plotdirector-blocked-reason]"),$e=document.querySelector("[data-runtime-last-sync]"),Te=document.querySelector("[data-sync-scene-progress]"),We=document.querySelector("[data-sync-word-count]"),je=document.querySelector("[data-sync-plotdirector-count]"),Re=document.querySelector("[data-sync-last-synced]"),Ue=document.querySelector("[data-sync-status]"),Me=document.querySelector("[data-writing-brief-block]"),Oe=document.querySelector("[data-writing-brief]"),Be=document.querySelector("[data-plotdirector-link-groups]"),He=document.querySelector("[data-character-review-summary]"),Ge=document.querySelector("[data-asset-review-summary]"),Fe=document.querySelector("[data-location-review-summary]"),Ve=document.querySelector("[data-character-chips]"),Ke=document.querySelector("[data-asset-chips]"),Ye=(document.querySelector("[data-location-chips]"),document.querySelector("[data-primary-location-select]")),Je=document.querySelector("[data-save-scene-links]"),_e=document.querySelector("[data-scene-links-status]"),ze=document.querySelector("[data-links-editing-scene]"),Qe=document.querySelector("[data-chapter-create-link]"),Xe=document.querySelector("[data-chapter-create-link-chapter]"),Ze=document.querySelector("[data-create-plotdirector-chapter]"),et=document.querySelector("[data-link-existing-chapter]"),tt=document.querySelector("[data-chapter-create-link-status]"),nt=document.querySelector("[data-scene-create-link]"),rt=document.querySelector("[data-create-link-chapter]"),ot=document.querySelector("[data-create-link-scene]"),at=document.querySelector("[data-create-plotdirector-scene]"),ct=document.querySelector("[data-link-existing-scene]"),it=document.querySelector("[data-create-link-status]"),st=document.querySelector("[data-link-existing-dialog]"),dt=document.querySelector("[data-link-scene-search]"),lt=document.querySelector("[data-link-scene-options]"),ut=document.querySelector("[data-link-selected-scene]"),pt=document.querySelector("[data-link-dialog-cancel]"),ht=document.querySelector("[data-link-dialog-status]"),mt=document.querySelector("[data-create-scene-dialog]"),gt=document.querySelector("[data-create-dialog-scene]"),yt=document.querySelector("[data-create-dialog-chapter]"),wt=document.querySelector("[data-create-dialog-confirm]"),ft=document.querySelector("[data-create-dialog-cancel]"),bt=document.querySelector("[data-link-existing-chapter-dialog]"),It=document.querySelector("[data-link-chapter-search]"),Ct=document.querySelector("[data-link-chapter-options]"),St=document.querySelector("[data-link-selected-chapter]"),kt=document.querySelector("[data-link-chapter-dialog-cancel]"),vt=document.querySelector("[data-link-chapter-dialog-status]"),xt=document.querySelector("[data-create-chapter-dialog]"),Pt=document.querySelector("[data-create-chapter-dialog-chapter]"),Dt=document.querySelector("[data-create-chapter-dialog-book]"),Et=document.querySelector("[data-create-chapter-dialog-confirm]"),Nt=document.querySelector("[data-create-chapter-dialog-cancel]"),Lt=document.querySelector("[data-apply-structure-sync-dialog]"),qt=document.querySelector("[data-apply-structure-sync-summary]"),At=document.querySelector("[data-apply-structure-sync-confirm]"),$t=document.querySelector("[data-apply-structure-sync-cancel]"),Tt=document.querySelector("[data-resolve-project-id]"),Wt=document.querySelector("[data-resolve-project-title]"),jt=document.querySelector("[data-resolve-book-id]"),Rt=document.querySelector("[data-resolve-book-title]"),Ut=document.querySelector("[data-resolve-detected-chapter]"),Mt=document.querySelector("[data-resolve-detected-scene]"),Ot=document.querySelector("[data-resolve-request-chapter]"),Bt=document.querySelector("[data-resolve-request-scene]"),Ht=document.querySelector("[data-resolve-result]"),Gt=document.querySelector("[data-resolve-chapter-id]"),Ft=document.querySelector("[data-resolve-scene-id]"),Vt=document.querySelector("[data-run-diagnostics]"),Kt=document.querySelector("[data-diagnostic-host]"),Yt=document.querySelector("[data-diagnostic-platform]"),Jt=document.querySelector("[data-diagnostic-ready]"),_t=document.querySelector("[data-diagnostic-word-api]"),zt=document.querySelector("[data-diagnostic-last-scan]"),Qt=document.querySelector("[data-diagnostic-last-error]"),Xt=document.querySelector("[data-diagnostic-anchor-type]"),Zt=document.querySelector("[data-diagnostic-stored-scene-id]"),en=document.querySelector("[data-diagnostic-stored-chapter-id]"),tn=document.querySelector("[data-diagnostic-resolution-method]"),nn=document.querySelector("[data-diagnostic-paragraphs]"),rn=document.querySelector("[data-diagnostic-heading1]"),on=document.querySelector("[data-diagnostic-heading2]"),an="true"===a?.dataset.authenticated,cn=Number.parseInt(a?.dataset.userId||"",10),sn=String(a?.dataset.companionVersion||"20C").trim();let dn=[],ln=[],un=!1,pn=!1,hn="Unknown",mn="Unknown",gn="",yn="",wn=null,fn=null,bn=null,In=null,Cn=null,Sn=null,kn="",vn="Title Match",xn=!1,Pn=[],Dn=null,En=null,Nn=[],Ln=null,qn=null,An=null,$n=null,Tn=null,Wn=null,jn=null,Rn=null,Un=null,Mn=null,On=[],Bn=null,Hn=!1,Gn=!1,Fn=0,Vn=!1,Kn=!1,Yn=!1,Jn=null,_n="Manual",zn=!1,Qn=null,Xn=!1,Zn=0,er=!1,tr=0,nr=null;const rr=1200;let or=!1,ar=!1,cr=null,ir=!1,sr=!1,dr=null,lr=null,ur=null,pr=!1,hr=!1,mr=null,gr="",yr=[],wr=null,fr="",br=null,Ir="",Cr=[],Sr=null,kr="",vr=null,xr="",Pr=[],Dr=null,Er="",Nr="",Lr="",qr="",Ar=0,$r=null,Tr=null,Wr={characters:[],assets:[],locations:[],primaryLocationId:null},jr={chapterCount:0,sceneCount:0,totalCount:0,available:!1,message:"Not inspected"};const Rr="PD-CHAPTER-",Ur="PD-SCENE-",Mr=e=>{const t=String(e?.tag||"").trim().toUpperCase();return t.startsWith(Rr)?"chapter":t.startsWith(Ur)?"scene":""};window.PlotDirectorWordMarkers={classify:Mr};const Or=e=>{const t=Date.now();t-Ar<1e3||(Ar=t,console.debug(`[Word Companion Runtime] ${e}`))},Br=e=>{console.debug(`[Word Companion Timing] ${e}`)},Hr=e=>{O&&(O.textContent=e)},Gr=e=>"links"===e?"review":"structure"===e?"maintenance":e,Fr=(e,t=!0)=>{const r=Gr(e),a=o.has(r)&&i.some(e=>e.dataset.tabButton===r)?r:"scene";for(const e of i){const t=e.dataset.tabButton===a;e.classList.toggle("is-active",t),e.setAttribute("aria-selected",t?"true":"false")}for(const e of s){const t=e.dataset.tabPanel===a;e.classList.toggle("is-active",t),e.hidden=!t}t&&((e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}})(n,a)},Vr=()=>{const e=Gr((e=>{try{return window.localStorage.getItem(e)||""}catch{return""}})(n));Fr(o.has(e)?e:"scene",!1)},Kr=e=>{B&&(B.textContent=e),H&&(H.textContent=e)},Yr=e=>{J&&(J.textContent=e)},Jr=e=>{_&&(_.textContent=e)},_r=e=>{ne&&(ne.textContent=e)},zr=e=>{le&&(le.textContent=e)},Qr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("anchorType")&&Fo(Xt,fo(e.anchorType)),t("storedSceneId")&&Fo(Zt,fo(e.storedSceneId)),t("storedChapterId")&&Fo(en,fo(e.storedChapterId)),t("resolutionMethod")&&Fo(tn,fo(e.resolutionMethod))},Xr=()=>{const e=ta(),t=Number.isInteger(Cn)&&Cn>0&&In===Cn,n=!Number.isInteger(Sn)||Sn<=0||bn===Sn,r=t&&n;Fo(ue,r?"Attached to PlotDirector":"Not attached"),Fo(pe,e?.bookId?String(e.bookId):"-"),Fo(he,Number.isInteger(Sn)&&Sn>0?String(Sn):"-"),Fo(me,Number.isInteger(Cn)&&Cn>0?String(Cn):"-"),ge&&(to(ge,r&&!xn),ge.disabled=!Cn||r&&!xn,ge.textContent=In&&!r?"Reattach PlotDirector IDs":"Attach PlotDirector IDs"),Qr({anchorType:vn||"Title Match",storedSceneId:In,storedChapterId:bn,resolutionMethod:kn})},Zr=(e,t,n,r=null,o=null,a=null)=>{const c=e||"",i=t||"",s=Number.isInteger(n)?n:null,d=Number.isInteger(a)&&a>0?a:null,l=Number.isInteger(r)&&r>0?r:null,u=Number.isInteger(o)&&o>0?o:null,p=gn===c&&yn===i&&wn===s&&fn===d&&bn===l&&In===u;gn=e||"",yn=t||"",wn=Number.isInteger(n)?n:null,fn=Number.isInteger(a)&&a>0?a:null,bn=Number.isInteger(r)&&r>0?r:null,In=Number.isInteger(o)&&o>0?o:null,p||(X&&(X.textContent=e||"Not detected"),Z&&(Z.textContent=t||"Not detected"),ee&&(ee.textContent=Number.isInteger(n)?String(n):"-"),Fo(We,Number.isInteger(n)?String(n):"-"),Xr())},eo=()=>{cr&&(window.clearTimeout(cr),cr=null)},to=(e,t)=>{e&&(e.hidden=t)},no=()=>{to(ye,!$n)},ro=(e=jr)=>{const t=fa();Fo(fe,t?"Linked":"Not linked"),Fo(be,e.available?String(e.chapterCount):"-"),Fo(Ie,e.available?String(e.sceneCount):"-"),Fo(Ce,e.available?String(e.chapterCount):"-"),Fo(Se,e.available?String(e.sceneCount):"-"),Fo(ke,e.available?String(e.chapterCount):"-"),Fo(ve,e.available?String(e.sceneCount):"-"),we&&(we.disabled=!pn||!un)},oo=async()=>{if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)return jr={chapterCount:0,sceneCount:0,totalCount:0,available:!1,message:"Word document access is unavailable."},ro(),jr;try{return jr=await window.Word.run(async e=>{const t=e.document.contentControls;t.load("items/tag,title"),await e.sync();let n=0,r=0;for(const e of t.items||[]){const t=Mr(e);"chapter"===t?n+=1:"scene"===t&&(r+=1)}return{chapterCount:n,sceneCount:r,totalCount:n+r,available:!0,message:"Marker inspection complete."}}),ro(jr),jr}catch(e){throw console.error("Unable to inspect PlotDirector markers.",e),jr={chapterCount:0,sceneCount:0,totalCount:0,available:!1,message:`Unable to inspect markers: ${Ko(e)}`},ro(),e}},ao=e=>{Fo(Ue,e)},co=e=>{Fo(ie,e)},io=(e="Select a project and book to analyse manuscript structure.")=>{if(An=null,se){se.innerHTML="";const e=document.createElement("p");e.textContent="No preview generated.",se.append(e)}co(e),lo()},so=(e=An)=>((e=An)=>Ka.flatMap(t=>Array.isArray(e?.[t.key])?e[t.key]:[]))(e).filter(e=>"couldLink"===e.category||"wouldCreateChapters"===e.category||"wouldCreateScenes"===e.category),lo=()=>{ce&&(ce.disabled=Yn||0===so().length)},uo=()=>{ae&&(ae.disabled=Yn||!ea()||!ta()),lo()},po=()=>{ze&&(ze.textContent=Cn?`Editing links for: ${Lr||yn||"Current scene"}`:"Link a PlotDirector scene first.")},ho=()=>{const e=zn||!Cn,t=e||!Sn||ir;Te&&(Te.disabled=t),Je&&(Je.disabled=e),Ye&&(Ye.disabled=e);for(const t of[Ve,Ke])for(const n of t?[...t.querySelectorAll("input[type='checkbox']")]:[])n.disabled=e},mo=e=>{"Live"!==e&&"Manual"!==e||(_n=e),Fo(te,e||_n||"Manual")},go=(e,t="")=>{zn=!!e,zn&&(eo(),Oc()),Fo(te,zn?"Stale":_n),ho(),t&&(_r(t),ko(t))},yo=(e,t=null,n="")=>{Cn=Number.isInteger(e)&&e>0?e:null,Sn=Number.isInteger(t)&&t>0?t:null,kn=n||"",Cn!==dr&&(lr=null),Cn||(eo(),Oc()),ho(),ao(zn?"Refresh Current Scene before syncing.":Cn?"Ready to sync.":"No resolved PlotDirector scene."),ko(zn?"Refresh Current Scene before saving.":Cn?"Ready to save.":"Link a PlotDirector scene first."),po(),Xr()},wo=e=>{z&&(z.disabled=e,z.textContent=e?"Refreshing...":"Refresh Current Scene")},fo=e=>null==e||""===e?"-":String(e),bo=e=>{if(!e)return"-";const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))return"-";const n=new Date;return`Last synced: ${t.toDateString()===n.toDateString()?"Today":t.toLocaleDateString()} ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`},Io=e=>{Tn=e||null;const t=Tn?.lastSyncUtc||Tn?.manuscriptDocument?.lastSyncUtc;Fo($e,bo(t)),Fo(Re,bo(t)),Zo()},Co=()=>{Wn=null,jn=null,Rn=null,tr+=1,nr=null,Bc(),Hc(),Gc(),Io(null)},So=()=>{jn=null,Rn=null},ko=e=>{Fo(_e,e)},vo=e=>{Fo(it,e)},xo=e=>{Fo(tt,e)},Po=()=>!!ta()&&!!gn&&!Sn,Do=()=>!!ta()&&!!yn&&Number.isInteger(Sn)&&Sn>0,Eo=()=>{to(Qe,!0),xo(""),Ze&&(Ze.disabled=!0,Ze.textContent="Create Chapter in PlotDirector"),et&&(et.disabled=!0,et.textContent="Link to Existing Chapter")},No=(e="")=>{Fo(Xe,fo(gn)),to(Qe,!1),xo(e);const t=Po();Ze&&(Ze.disabled=!t,Ze.textContent="Create Chapter in PlotDirector"),et&&(et.disabled=!t,et.textContent="Link to Existing Chapter")},Lo=()=>{to(nt,!0),vo(""),at&&(at.disabled=!0,at.textContent="Create Scene in PlotDirector"),ct&&(ct.disabled=!0,ct.textContent="Link to Existing Scene")},qo=(e="")=>{Fo(rt,fo(gn)),Fo(ot,fo(yn)),to(nt,!1),vo(e);const t=Do();at&&(at.disabled=!t,at.textContent="Create Scene in PlotDirector"),ct&&(ct.disabled=!t,ct.textContent="Link to Existing Scene")},Ao=e=>{zr(e),to(xe,!0),to(Me,!0),to(Be,!1),Eo(),Lo(),kn="",Lr="",qr="",vn=In?"SceneID Anchor":bn?"ChapterID Anchor":"Title Match",xn=!1,Wr={characters:[],assets:[],locations:[],primaryLocationId:null},To(Ve,[],"character"),To(Ke,[],"asset"),Wo([],null,!1),ka(),yo(null),Fo(je,"-"),Fo(Pe,"-"),Fo(De,"-"),Fo(Ee,"-"),Fo(Ne,"-"),Fo(Le,"-"),Fo(Ae,"-"),to(qe,!0),Xr(),po()},$o=(e,t)=>"asset"===t?e?.assetId||e?.AssetId||e?.storyAssetId||e?.StoryAssetId||0:"location"===t?e?.locationId||e?.LocationId||0:e?.characterId||e?.CharacterId||0,To=(e,t,n,r=!1)=>{if(!e)return;e.innerHTML="";const o=Array.isArray(t)?t:[];if(0===o.length){const t=document.createElement("p");return t.className="word-companion-empty-list",t.textContent="None",void e.append(t)}for(const t of o){const o=Number.parseInt($o(t,n),10);if(!Number.isInteger(o)||o<=0)continue;const a=document.createElement("label");a.className="word-companion-check-item";const c=document.createElement("input");c.type="checkbox",c.value=String(o),c.checked=!!t.linked,c.disabled=!r;const i=document.createElement("span");i.textContent=t.name||"Unnamed",a.append(c,i),e.append(a)}},Wo=(e,t,n=!1)=>{if(!Ye)return;Ye.innerHTML="";const r=document.createElement("option");r.value="",r.textContent="None",Ye.append(r);const o=Number.parseInt(t||"",10);for(const t of Array.isArray(e)?e:[]){const e=Number.parseInt($o(t,"location"),10);if(!Number.isInteger(e)||e<=0)continue;const n=document.createElement("option");n.value=String(e),n.textContent=t.name||"Unnamed",n.selected=e===o,Ye.append(n)}Ye.disabled=!n},jo=e=>String(e||"").trim().replace(/\s+/g," "),Ro=(e,t)=>{const n=jo(e);if(!n)return"";const r=new RegExp(`^${"scene"===t?"scene":"chapter"}\\s+(?:\\d+|[ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)\\s*(?::|-|\\u2013|\\u2014)\\s*`,"i");return jo(n.replace(r,""))||n},Uo=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("projectId")&&Fo(Tt,fo(e.projectId)),t("projectTitle")&&Fo(Wt,fo(e.projectTitle)),t("bookId")&&Fo(jt,fo(e.bookId)),t("bookTitle")&&Fo(Rt,fo(e.bookTitle)),t("detectedChapter")&&Fo(Ut,fo(e.detectedChapter)),t("detectedScene")&&Fo(Mt,fo(e.detectedScene)),t("requestChapter")&&Fo(Ot,fo(e.requestChapter)),t("requestScene")&&Fo(Bt,fo(e.requestScene)),t("result")&&Fo(Ht,fo(e.result)),t("chapterId")&&Fo(Gt,fo(e.chapterId)),t("sceneId")&&Fo(Ft,fo(e.sceneId))},Mo=async e=>{if(Rn===e&&Array.isArray(jn?.chapters))return jn.chapters;const t=await fc(`/api/word-companion/books/${e}/structure`);return Rn=e,jn=t||null,Array.isArray(t?.chapters)?t.chapters:[]},Oo=async e=>{const t=await fc(`/api/word-companion/books/${e}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},Bo=e=>{if(Number.isInteger(Sn)&&Sn>0){const t=e.find(e=>e.chapterId===Sn);if(t)return t}const t=Ro(gn,"chapter").toLocaleLowerCase();return t&&e.find(e=>Ro(e.title,"chapter").toLocaleLowerCase()===t)||null},Ho=async()=>{const e=ta();return e?Bo(await Mo(e.bookId)):null},Go=async(e,t,n,r,o)=>{const a=await fc(`/api/word-companion/scenes/${t}/companion`);try{a.revisionStatus=await(async(e,t)=>{const n=await fc(`/api/word-companion/books/${e}/structure`),r=Array.isArray(n?.chapters)?n.chapters:[];for(const e of r){const n=(Array.isArray(e.scenes)?e.scenes:[]).find(e=>e.sceneId===t);if(n)return n.revisionStatus||""}return""})(e,t)}catch{a.revisionStatus=""}var c;vn=o||"Title Match",xn=!1,go(!1),zr("Linked to PlotDirector"),_r(""),Eo(),Lo(),yo(t,n,r),c=a,Lr=c?.sceneTitle||yn||"",qr=c?.chapterTitle||gn||"",Fo(Pe,fo(c?.sceneTitle)),Fo(De,fo(c?.revisionStatus||c?.revisionStatusName||"Not provided")),Fo(Ee,fo(c?.estimatedWords)),Fo(Ne,fo(c?.actualWords)),Fo(je,fo(c?.actualWords)),Fo(Le,c?.blocked?"Blocked":"Not blocked"),c?.blockedReason?(Fo(Ae,c.blockedReason),to(qe,!1)):(Fo(Ae,"-"),to(qe,!0)),Oe&&(Oe.textContent=c?.writingBrief||"No writing brief has been added for this scene."),Wr={characters:Array.isArray(c?.characters)?c.characters:[],assets:Array.isArray(c?.assets)?c.assets:[],locations:Array.isArray(c?.locations)?c.locations:[],primaryLocationId:c?.primaryLocationId??null},To(Ve,Wr.characters,"character",!!Cn&&!zn),To(Ke,Wr.assets,"asset",!!Cn&&!zn),Wo(Wr.locations,Wr.primaryLocationId,!!Cn&&!zn),ka(),po(),ko(zn?"Refresh Current Scene before saving.":Cn?"Ready to save.":"No resolved PlotDirector scene."),to(xe,!1),to(Me,!1),to(Be,!1),Cc(t,n),Mc(),zc()},Fo=(e,t)=>{if(e){const n=null==t?"":String(t);e.textContent!==n&&(e.textContent=n)}},Vo=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("host")&&Fo(Kt,e.host),t("platform")&&Fo(Yt,e.platform),t("ready")&&Fo(Jt,e.ready),t("wordApi")&&Fo(_t,e.wordApi),t("lastScan")&&Fo(zt,e.lastScan),t("lastError")&&Fo(Qt,e.lastError),t("paragraphs")&&Fo(nn,e.paragraphs),t("heading1")&&Fo(rn,e.heading1),t("heading2")&&Fo(on,e.heading2)},Ko=e=>{const t=[];return e?.name&&t.push(e.name),e?.code&&e.code!==e.name&&t.push(e.code),e?.message&&t.push(e.message),e?.debugInfo?.errorLocation&&t.push(`Location: ${e.debugInfo.errorLocation}`),t.length>0?t.join(": "):String(e)},Yo=async()=>{if(!window.Office||"function"!=typeof window.Office.onReady)return un=!1,pn=!1,hn="Unavailable",mn="Unavailable",Vo({host:hn,platform:mn,ready:"No",wordApi:"No"}),null;const e=await window.Office.onReady();return un=!0,hn=e?.host||"Unknown",mn=e?.platform||"Unknown",pn=!!window.Word&&!!window.Office.HostType&&e?.host===window.Office.HostType.Word,Vo({host:hn,platform:mn,ready:"Yes",wordApi:pn?"Yes":"No"}),e},Jo=e=>{try{const t=window.localStorage.getItem(e),n=Number.parseInt(t||"",10);return Number.isInteger(n)&&n>0?n:null}catch{return null}},_o=(e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}},zo=(e,t)=>{if(!e)return;e.innerHTML="";const n=document.createElement("option");n.value="",n.textContent=t,e.append(n),e.disabled=!0},Qo=(e,t,n,r,o)=>{if(!e)return;e.innerHTML="";const a=document.createElement("option");a.value="",a.textContent=t,e.append(a);for(const t of n){const n=document.createElement("option");n.value=String(t[r]),n.textContent=t[o],e.append(n)}e.disabled=0===n.length},Xo=e=>{const t=String(e?.displayTitle||"").trim();if(t)return t;const n=String(e?.title||"").trim(),r=String(e?.subtitle||"").trim();return r?`${n}: ${r}`:n},Zo=()=>{const e=!!$n;to(d,!e),to(Y,e),e&&(Fo(l,Tn?.projectTitle||ea()?.title||"Project"),Fo(u,Tn?.bookTitle||Xo(ta())||"Book")),ro()},ea=()=>{const e=Number.parseInt(V?.value||"",10);return dn.find(t=>t.projectId===e)||null},ta=()=>{const e=Number.parseInt(K?.value||"",10);return ln.find(t=>t.bookId===e)||null},na=()=>{const e=Number.parseInt(h?.value||"",10);return dn.find(t=>t.projectId===e)||null},ra=()=>{const e=Number.parseInt(m?.value||"",10);return ln.find(t=>t.bookId===e)||null},oa=()=>{const t=$n?.projectId||na()?.projectId||ea()?.projectId||Jo(e);return Number.isInteger(t)&&t>0?t:null},aa=()=>{const e=$n?.bookId||ra()?.bookId||ta()?.bookId||Jo(t);return Number.isInteger(e)&&e>0?e:null},ca=()=>{const e=String(window.Office?.context?.document?.url||"").trim();if(!e)return"";const t=e.split(/[\\/]/).filter(Boolean).pop()||"";try{return decodeURIComponent(t)}catch{return t}},ia=()=>({userID:Number.isInteger(cn)&&cn>0?cn:null,companionVersion:sn,machineName:"",documentOpen:!!pn,currentDocumentName:ca(),linkedProjectID:oa(),linkedBookID:aa()}),sa=()=>{(async()=>{$r&&$r.state===signalR.HubConnectionState.Connected&&await $r.invoke("CompanionHeartbeat",ia())})().catch(e=>{console.debug("Word Companion heartbeat unavailable.",e)})},da=async()=>{an&&window.signalR&&!$r&&($r=(new signalR.HubConnectionBuilder).withUrl("/hubs/word-companion-follow").withAutomaticReconnect().build(),$r.onreconnected(sa),$r.on("ScanCurrentDocument",e=>{Oa(e)}),$r.on("UpdateOnboardingBuildMarkers",e=>{Ba(e)}),$r.onclose(()=>{Tr&&(window.clearInterval(Tr),Tr=null)}),await $r.start(),await $r.invoke("RegisterCompanion",ia()),Tr=window.setInterval(sa,25e3))};window.addEventListener("beforeunload",()=>{Tr&&(window.clearInterval(Tr),Tr=null),$r&&$r.stop().catch(()=>{})});const la=e=>Fo(b,e),ua=()=>{const e=na(),t=ra(),n=Gn&&Date.now()-Fn>=750;w&&(w.disabled=!e||!t||Vn),y&&(y.disabled=!e||!String(g?.value||"").trim()||Vn),N&&(N.disabled=!Un?.canImport||!Mn||Vn),x&&(x.disabled=!n||Kn||0===ga().length)},pa=e=>{to(p,!e),to(c,e),no(),Zo();for(const t of s)to(t,!!e||"scene"!==t.dataset.tabPanel&&!t.classList.contains("is-active"));e||Vr()},ha=()=>{if(!h)return;if(0===dn.length)return void zo(h,"No projects available.");Qo(h,"Choose a project",dn,"projectId","title");const e=Number.parseInt(V?.value||"",10);Number.isInteger(e)&&e>0&&(h.value=String(e))},ma=(e="Select a Project and Book to begin.")=>{Un=null,Mn=null,On=[],Hn=!1,Gn=!1,Fn=0,to(I,!0),to(E,!0),to(C,!0),to(v,!0),I&&(I.innerHTML=""),k&&(k.innerHTML=""),Fo(S,""),la(e),ua()},ga=()=>k?[...k.querySelectorAll("input[type='checkbox']:checked")].map(e=>String(e.value||"").trim()).filter(Boolean):[],ya=e=>{if(On=Array.isArray(e)?e:[],C&&k){if(k.innerHTML="",to(C,!1),to(v,!Hn||0===On.length),to(x,!1),to(P,!1),to(D,!0),0===On.length)return Fo(S,"No likely major characters found."),void ua();Fo(S,`${On.length} likely major characters found.`);for(const e of On){const t=document.createElement("label");t.className="word-companion-character-candidate";const n=document.createElement("input");n.type="checkbox",n.value=e.text||"",n.checked="high"===String(e.confidence||"").trim().toLowerCase(),n.addEventListener("change",ua);const r=document.createElement("strong");r.textContent=e.text||"";const o=document.createElement("em"),a=String(e.reason||"").trim();o.textContent=a?`${Number(e.mentionCount||0).toLocaleString()} mentions · ${a}`:`${Number(e.mentionCount||0).toLocaleString()} mentions`;const c=document.createElement("span");c.className="word-companion-character-candidate-text",c.append(r,o),t.append(n,c),k.append(t)}ua()}},wa=()=>{const e=window.Office?.context?.document?.settings;if(!e)return null;const t=String(e.get(r.documentGuid)||"").trim(),n=Number.parseInt(e.get(r.bookId)||"",10),o=Number.parseInt(e.get(r.projectId)||"",10),a=Number.parseInt(e.get(r.bindingVersion)||"",10);return!t||!Number.isInteger(n)||n<=0||!Number.isInteger(o)||o<=0?null:{documentGuid:t,bookId:n,projectId:o,bindingVersion:Number.isInteger(a)&&a>0?a:1}},fa=()=>{const e=$n||wa();if(e)return e;const t=Tn?.manuscriptDocument?.documentGuid||"",n=Number.parseInt(Tn?.bookId||"",10),r=Number.parseInt(Tn?.projectId||"",10);return t&&Number.isInteger(n)&&n>0&&Number.isInteger(r)&&r>0?{documentGuid:t,bookId:n,projectId:r,bindingVersion:Number.parseInt(Tn?.manuscriptDocument?.bindingVersion||"",10)||1}:null},ba=()=>new Promise((e,t)=>{const n=window.Office?.context?.document?.settings;if(n){for(const e of Object.values(r))"function"==typeof n.remove?n.remove(e):n.set(e,"");n.saveAsync(n=>{n.status===window.Office.AsyncResultStatus.Succeeded?e():t(n.error||new Error("Unable to remove Word document metadata."))})}else t(new Error("Word document settings are unavailable."))}),Ia=()=>$n?.documentGuid?$n.documentGuid:window.crypto?.randomUUID?window.crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(Number(e)^16*Math.random()>>Number(e)/4).toString(16)),Ca=()=>$n?.documentGuid||wa()?.documentGuid||"",Sa=()=>{const e=ea(),t=ta();G&&(G.textContent=e?.title||"(Not connected)"),F&&(F.textContent=t?Xo(t):"(Not connected)"),re&&(re.textContent=t?"":"Select a PlotDirector book before refreshing."),uo(),Zo()},ka=()=>{const e=Array.isArray(Wr.characters)?Wr.characters.length:0,t=Array.isArray(Wr.assets)?Wr.assets.length:0,n=Array.isArray(Wr.locations)?Wr.locations.length:0;Fo(He,`Characters (${e})`),Fo(Ge,`Assets (${t})`),Fo(Fe,`Locations (${n})`)},va=e=>String(e?.styleBuiltIn||e?.style||"").replace(/\s+/g,"").toLowerCase(),xa=(e,t)=>{const n=va(e);return n===`heading${t}`||n.endsWith(`.heading${t}`)||n.includes(`heading${t}`)},Pa=e=>String(e||"").trim().split(/\s+/).filter(Boolean).length,Da=(e,t)=>{const n=String(e||"").match(new RegExp(`^${t}-(\\d+)$`,"i"));if(!n)return null;const r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null},Ea=e=>{try{return Array.isArray(e?.contentControls?.items)?e.contentControls.items:[]}catch(e){return console.warn("Word paragraph content controls were not available.",e),[]}},Na=(e,t)=>{const n=Ea(e);for(const e of n){const n=Da(e.tag,t);if(n)return n}return null},La=(e,t)=>{const n=[];let r=0,o=0,a=null,c=null;e.forEach((e,t)=>{const i=String(e.text||"").trim();if(i){if(xa(e,1))return r+=1,a={index:n.length+1,paragraphIndex:t,title:i,anchorId:Na(e,"PD-CHAPTER"),scenes:[]},n.push(a),void(c=null);if(xa(e,2)){if(o+=1,!a)return;return c={index:a.scenes.length+1,paragraphIndex:t,title:i,anchorId:Na(e,"PD-SCENE"),wordCount:0},void a.scenes.push(c)}c&&(c.wordCount+=Pa(i))}});const i=t.find(e=>String(e.text||"").trim()),s=i?e.findIndex(e=>{return t=e,n=i,String(t?.text||"").trim()===String(n?.text||"").trim()&&va(t)===va(n);var t,n}):-1,d=s>=0&&n.filter(e=>e.paragraphIndex<=s).at(-1)||null,l=d&&s>=0&&d.scenes.filter(e=>e.paragraphIndex<=s).at(-1)||null;return{chapters:n,currentChapter:d,currentScene:l,paragraphCount:e.length,heading1Count:r,heading2Count:o}},qa=new Set(["***","###"]),Aa=(e,t)=>{const n=String(e?.text||"").trim();return{index:t,text:n,styleBuiltIn:e?.styleBuiltIn||"",style:e?.style||"",wordCount:Pa(n),chapterAnchorId:null,sceneAnchorId:null}},$a=(e,t)=>{e&&(e.endParagraphIndex=t)},Ta=(e,t)=>{e&&(e.endParagraphIndex=t,$a(e.scenes.at(-1),t))},Wa=(e,t,n)=>e?.[t]??e?.[n]??null,ja=(e,t)=>{const n=[],r=[],o=[];let a=null,c=null,i=0,s=0,d=!1;const l=()=>{c=null},u=(e,t,r=!1)=>(l(),a={temporaryChapterKey:`chapter-${n.length+1}`,chapterNumber:n.length+1,title:t,wordCount:0,chapterTextParagraphs:[],chapterText:"",startPosition:e?.index??null,existingChapterID:r?null:Na(e,"PD-CHAPTER")},n.push(a),p(e,null),a),p=(e,t=null)=>a?(l(),c={temporarySceneKey:`scene-${r.length+1}`,temporaryChapterKey:a.temporaryChapterKey,sceneNumberWithinChapter:r.filter(e=>e.temporaryChapterKey===a.temporaryChapterKey).length+1,title:t,wordCount:0,openingTextPreview:"",startPosition:e?.index??null,existingSceneID:e?Na(e,"PD-SCENE"):null},r.push(c),c):null,h=(e,t)=>{!a||!c||t<=0||(a.wordCount+=t,a.chapterTextParagraphs.push(e),c.wordCount+=t,c.openingTextPreview||!e||qa.has(e)||(c.openingTextPreview=e.length>180?`${e.slice(0,177)}...`:e))};if(e.forEach((e,t)=>{e.index=t;const n=String(e.text||"").trim();if(!n)return;const r=Pa(n);if(xa(e,1)){if(!d&&(e=>{const t=Ro(e||"","").toLocaleLowerCase();return["title page","copyright","dedication","contents","table of contents","acknowledgements","acknowledgments","about the author"].includes(t)})(n))return;return d=!0,o.push(n),s+=1,u(e,n),i+=r,a.wordCount+=r,void a.chapterTextParagraphs.push(n)}if(!a){if(!d)return;u(e,"Opening pages",!0)}if(o.push(n),xa(e,2))return p(e,n),i+=r,void h(n,r);qa.has(n)?p(e,null):(i+=r,h(n,r))}),0===i)throw new Error("The document appears to be empty. Add manuscript text, then try again.");if(0===s)throw new Error("No chapters were detected. Make sure your chapter headings use Heading 1, or add clear chapter headings.");n.forEach(e=>{e.chapterText=Array.isArray(e.chapterTextParagraphs)?e.chapterTextParagraphs.join("\n\n"):"",delete e.chapterTextParagraphs});const m=o.join("\n");return{previewID:"00000000-0000-0000-0000-000000000000",userID:Ra(t,"userID","UserID","userId"),onboardingID:Ra(t,"onboardingID","OnboardingID","onboardingId"),projectID:Ra(t,"projectID","ProjectID","projectId"),bookID:Ra(t,"bookID","BookID","bookId"),source:"WordCompanion",documentTitle:ca()||"Word manuscript",companionDocumentIdentifier:Ca(),totalWordCount:i,chapterCount:n.length,sceneCount:r.length,characterCandidateCount:0,createdUtc:(new Date).toISOString(),chapters:n,scenes:r,characterCandidates:[],documentTextForDiscovery:m}},Ra=(e,...t)=>{for(const n of t)if(null!=e?.[n])return e[n];return null},Ua=async(e,t,n,r={})=>{$r&&$r.state===signalR.HubConnectionState.Connected&&await $r.invoke("ReportOnboardingScanProgress",{userID:Ra(e,"userID","UserID","userId"),onboardingID:Ra(e,"onboardingID","OnboardingID","onboardingId"),message:t,percentComplete:n,chapterCount:r.chapterCount||0,sceneCount:r.sceneCount||0,characterCandidateCount:r.characterCandidateCount||0,totalWordCount:r.totalWordCount||0})},Ma=async(e,t)=>{$r&&$r.state===signalR.HubConnectionState.Connected&&await $r.invoke("FailOnboardingScan",{userID:Ra(e,"userID","UserID","userId"),onboardingID:Ra(e,"onboardingID","OnboardingID","onboardingId"),message:t})},Oa=async e=>{var t;if(pn&&window.Word)try{await Ua(e,"Preparing document scan",5);const n=await window.Word.run(async t=>{const n=t.document.body.paragraphs;n.load("items/text,items/style,items/styleBuiltIn"),await t.sync(),await Ua(e,"Detecting chapters",20);for(const e of n.items)(xa(e,1)||xa(e,2))&&e.contentControls.load("items/tag,title");return await t.sync(),n.items}),r=ja(n,e);await Ua(e,"Detecting scene breaks",50,r),await Ua(e,`Scene ${r.sceneCount} of ${r.sceneCount} scanned`,70,r),await Ua(e,"Finding character candidates",85,r);const o=r.documentTextForDiscovery||"";delete r.documentTextForDiscovery;try{const e=await bc("/api/word-companion/manuscript/discover-characters",{projectId:r.projectID,documentText:o,includeExcluded:!0});r.characterCandidates=(t=e?.candidates,(Array.isArray(t)?t:[]).map((e,t)=>({temporaryCharacterKey:`character-${t+1}`,name:Wa(e,"text","Text")||Wa(e,"name","Name")||"",mentionCount:Number.parseInt(Wa(e,"mentionCount","MentionCount")||"0",10)||0,qualityScore:Number.parseInt(Wa(e,"qualityScore","QualityScore")||"0",10)||0,category:Wa(e,"category","Category")||"PossibleCharacter",reason:Wa(e,"reason","Reason")||"",isExistingCharacterMatch:!!Wa(e,"isExistingCharacterMatch","IsExistingCharacterMatch"),suggestedImportance:null})).filter(e=>e.name)),r.characterCandidateCount=r.characterCandidates.filter(e=>"excluded"!==String(e.category||"").toLowerCase()).length}catch(e){console.warn("Unable to refine onboarding character candidates.",e),r.characterCandidates=[],r.characterCandidateCount=0}await Ua(e,"Preparing preview",95,r),Bn=r,await $r.invoke("CompleteOnboardingScan",r)}catch(t){console.error("Unable to complete onboarding scan.",t),await Ma(e,Ha(t))}else await Ma(e,"Open your manuscript in Microsoft Word, then try the scan again.")},Ba=async e=>{if(!Bn||!pn||!window.Word||"function"!=typeof window.Word.run)throw new Error("Word document access is unavailable.");const t=new Map((e?.chapterMappings||e?.ChapterMappings||[]).map(e=>[e.temporaryChapterKey||e.TemporaryChapterKey,e.chapterID||e.ChapterID])),n=new Map((e?.sceneMappings||e?.SceneMappings||[]).map(e=>[e.temporarySceneKey||e.TemporarySceneKey,e.sceneID||e.SceneID]));await window.Word.run(async e=>{const r=e.document.body.paragraphs;r.load("items/text,items/style,items/styleBuiltIn"),await e.sync();for(const e of Bn.chapters||[]){const n=t.get(e.temporaryChapterKey),o=Number.parseInt(e.startPosition,10);n&&Number.isInteger(o)&&r.items[o]&&Pc(r.items[o],"PlotDirector Chapter",`PD-CHAPTER-${n}`,"PD-CHAPTER")}for(const e of Bn.scenes||[]){const t=n.get(e.temporarySceneKey),o=Number.parseInt(e.startPosition,10);t&&Number.isInteger(o)&&r.items[o]&&Pc(r.items[o],"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await e.sync()}),await oo().catch(()=>null)},Ha=e=>{const t=Ko(e);return/No chapters were detected/i.test(t)?"No chapters were detected. Make sure your chapter headings use Heading 1, or add clear chapter headings.":/empty/i.test(t)?"The document appears to be empty. Add manuscript text, then try again.":/network|disconnect|connection/i.test(t)?"The Word Companion disconnected before the scan finished. Reopen Word and try again.":`The scan could not finish: ${t}`},Ga=(e,t)=>{const n=(t||[]).find(e=>String(e.text||"").trim());if(!e||!n)return e?.currentParagraphIndex??-1;const r=e.paragraphs.filter(e=>((e,t)=>String(e?.text||"").trim()===String(t?.text||"").trim()&&va(e)===va(t))(e,n)).map(e=>e.index);return 0===r.length?e.currentParagraphIndex??-1:Number.isInteger(e.currentParagraphIndex)?r.reduce((t,n)=>Math.abs(n-e.currentParagraphIndex){if(!Wn)return!1;const t=((e,t)=>!e||!Number.isInteger(t)||t<0?null:e.chapters.filter(e=>e.startParagraphIndex<=t).at(-1)||null)(Wn,e),n=((e,t)=>!e||!Number.isInteger(t)||t<0?null:e.scenes.filter(e=>e.startParagraphIndex<=t).at(-1)||null)(t,e),r=t?.startParagraphIndex!==Wn.currentChapter?.startParagraphIndex||n?.startParagraphIndex!==Wn.currentScene?.startParagraphIndex||t?.anchorId!==Wn.currentChapter?.anchorId||n?.anchorId!==Wn.currentScene?.anchorId;return Wn.currentParagraphIndex=e,Wn.currentChapter=t,Wn.currentScene=n,!!r&&(Zr(t?.title,n?.title,n?.wordCount,t?.anchorId,n?.anchorId,t?.index),r)},Va=e=>{if(!oe)return;if(oe.innerHTML="",0===e.chapters.length){const e=document.createElement("p");return e.textContent="No chapters detected. Use Heading 1 for chapter titles.",void oe.append(e)}if(!e.chapters.some(e=>e.scenes.length>0)){const e=document.createElement("p");e.textContent="No scenes detected. Use Heading 2 for scene titles.",oe.append(e)}for(const t of e.chapters){const e=document.createElement("div");e.className="word-companion-outline-chapter";const n=document.createElement("strong");if(n.textContent=t.title,e.append(n),t.scenes.length>0){const n=document.createElement("ul");for(const e of t.scenes){const t=document.createElement("li");t.textContent=e.title,n.append(t)}e.append(n)}oe.append(e)}},Ka=[{key:"alreadyLinked",title:"Already Linked"},{key:"couldLink",title:"Could Link"},{key:"wouldCreateChapters",title:"Would Create Chapters"},{key:"wouldCreateScenes",title:"Would Create Scenes"},{key:"manualReview",title:"Manual Review Required"}],Ya={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},Ja={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},_a=(e,t)=>Ro(e,t).toLocaleLowerCase(),za=({category:e,action:t,type:n,wordTitle:r,match:o="",anchorStatus:a="None",matches:c=[],pdChapter:i=null,pdScene:s=null,wordChapter:d=null,wordScene:l=null,parentItem:u=null})=>({id:`${n}-${d?.index||0}-${l?.index||0}-${d?.paragraphIndex??l?.paragraphIndex??0}`,category:e,action:t,type:n,wordTitle:r,match:o,anchorStatus:a,matches:c,pdChapter:i,pdScene:s,wordChapter:d,wordScene:l,parentItem:u,result:"Pending",error:""}),Qa=(e,t)=>{Array.isArray(e[t.category])&&e[t.category].push(t)},Xa=e=>Array.isArray(e?.scenes)?e.scenes:[],Za=(e,t,n)=>{const r=e.anchorId?`PD-CHAPTER-${e.anchorId}`:"None";if(e.anchorId){const o=t.find(t=>t.chapterId===e.anchorId);if(o){const t=za({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:e.title,match:`Chapter ${o.chapterId}: ${o.title}`,anchorStatus:r,pdChapter:o,wordChapter:e});return Qa(n,t),t}const a=za({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:`${r} not found`,matches:[],pdChapter:null,wordChapter:e});return Qa(n,a),a}const o=t.filter(t=>_a(t.title,"chapter")===_a(e.title,"chapter"));if(1===o.length){const t=za({category:"couldLink",action:"couldLink",type:"Chapter",wordTitle:e.title,match:`Chapter ${o[0].chapterId}: ${o[0].title}`,anchorStatus:r,pdChapter:o[0],wordChapter:e});return Qa(n,t),t}if(o.length>1){const t=za({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:r,matches:o.map(e=>`Chapter ${e.chapterId}: ${e.title}`),pdChapter:null,wordChapter:e});return Qa(n,t),t}const a=za({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:e.title,anchorStatus:r,pdChapter:null,wordChapter:e});return Qa(n,a),a},ec=(e,t,n,r)=>{const o=e.anchorId?`PD-SCENE-${e.anchorId}`:"None";if(e.anchorId){const a=((e,t)=>{for(const n of e){const e=Xa(n).find(e=>e.sceneId===t);if(e)return{chapter:n,scene:e}}return null})(n,e.anchorId);return a?void Qa(r,za({category:"alreadyLinked",action:"alreadyLinked",type:"Scene",wordTitle:e.title,match:`Scene ${a.scene.sceneId}: ${a.scene.title}`,anchorStatus:o,pdChapter:a.chapter,pdScene:a.scene,wordChapter:t?.wordChapter,wordScene:e,parentItem:t})):void Qa(r,za({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:`${o} not found`,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}))}if(!t?.pdChapter&&"manualReview"===t?.category)return void Qa(r,za({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:o,matches:["Parent chapter requires manual review."],wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));if(!t?.pdChapter)return void Qa(r,za({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:o,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));const a=Xa(t.pdChapter).filter(t=>_a(t.title,"scene")===_a(e.title,"scene"));1!==a.length?a.length>1?Qa(r,za({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:o,matches:a.map(e=>`Scene ${e.sceneId}: ${e.title}`),wordChapter:t.wordChapter,wordScene:e,parentItem:t})):Qa(r,za({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:o,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:e,parentItem:t})):Qa(r,za({category:"couldLink",action:"couldLink",type:"Scene",wordTitle:e.title,match:`Scene ${a[0].sceneId}: ${a[0].title}`,anchorStatus:o,pdChapter:t.pdChapter,pdScene:a[0],wordChapter:t.wordChapter,wordScene:e,parentItem:t}))},tc=e=>{const t=document.createElement("article");t.className="word-companion-preview-item";const n=document.createElement("strong");n.textContent=`${Ja[e.action]||""} ${e.type}: ${e.wordTitle}`,t.append(n);const r=document.createElement("span");if(r.textContent=`Anchor: ${e.anchorStatus||"None"}`,t.append(r),e.match){const n=document.createElement("span");n.textContent=`Match: ${e.match}`,t.append(n)}if(Array.isArray(e.matches)&&e.matches.length>0){const n=document.createElement("div");n.className="word-companion-preview-matches";const r=document.createElement("span");r.textContent="Matches:",n.append(r);const o=document.createElement("ul");for(const t of e.matches){const e=document.createElement("li");e.textContent=t,o.append(e)}n.append(o),t.append(n)}const o=document.createElement("span");if(o.textContent=`Action: ${Ya[e.action]||e.action}`,t.append(o),e.result&&"Pending"!==e.result){const n=document.createElement("span");n.textContent=e.error?`Result: ${e.result} - ${e.error}`:`Result: ${e.result}`,t.append(n)}return t},nc=e=>{if(se){se.innerHTML="";for(const t of Ka){const n=document.createElement("section");n.className="word-companion-preview-group";const r=document.createElement("strong");r.textContent=t.title,n.append(r);const o=Array.isArray(e?.[t.key])?e[t.key]:[];if(0===o.length){const e=document.createElement("p");e.className="word-companion-empty-list",e.textContent="None",n.append(e)}else for(const e of o)n.append(tc(e));se.append(n)}lo()}},rc=async e=>{const t=e.document.body.paragraphs,n=e.document.getSelection().paragraphs;t.load("text,styleBuiltIn,style"),n.load("text,styleBuiltIn,style"),await e.sync();try{for(const e of t.items)(xa(e,1)||xa(e,2))&&e.contentControls.load("items/tag,title");await e.sync()}catch(e){console.warn("Unable to load Word heading content controls. Continuing without PlotDirector anchors.",e)}const r=La(t.items,n.items);return r.bodyParagraphs=t.items,r},oc=async(e,t)=>{const n=e.document.body.paragraphs,r=e.document.getSelection().paragraphs;n.load("text,styleBuiltIn,style"),r.load("text,styleBuiltIn,style"),await e.sync();const o=((e,t)=>{const n=e.map(Aa),r=[];let o=0,a=0,c=null,i=null,s=0;const d=(e,t=null,n=null)=>c?($a(i,e.index-1),i={index:c.scenes.length+1,paragraphIndex:e.index,startParagraphIndex:e.index,endParagraphIndex:e.index,title:t||`Scene ${c.scenes.length+1}`,anchorId:n,wordCount:0},c.scenes.push(i),i):null;for(const e of n)e.text&&(xa(e,1)?(Ta(c,e.index-1),o+=1,c={index:r.length+1,paragraphIndex:e.index,startParagraphIndex:e.index,endParagraphIndex:e.index,title:e.text,anchorId:e.chapterAnchorId,wordCount:0,scenes:[]},r.push(c),i=null,d(e,"Scene 1",e.sceneAnchorId),s+=e.wordCount):c&&(t&&qa.has(e.text)?(a+=1,d(e)):(c.wordCount+=e.wordCount,i&&(i.wordCount+=e.wordCount),s+=e.wordCount)));return Ta(c,n.length-1),{paragraphs:n,chapters:r,usesExplicitScenes:!!t,paragraphCount:n.length,heading1Count:o,heading2Count:a,documentWordCount:s,currentParagraphIndex:null,currentChapter:null,currentScene:null}})(n.items,t),a=Ga(o,r.items);return Wn=o,Fa(a),Or("Cache rebuilt."),o},ac=()=>window.performance&&"function"==typeof window.performance.now?window.performance.now():Date.now(),cc=e=>!!e&&!e.stale&&e.generation===tr&&e.documentGuid===Ca()&&e.sceneId===Cn,ic=async(e={})=>{const t=!!e.includeSelection,n=!1!==e.updateDisplay,r=tr,o=ac(),a=ea(),c=ta(),i=Wn?.currentScene;if(!i||!Number.isInteger(i.startParagraphIndex)||!Number.isInteger(i.endParagraphIndex))return null;if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)return null;const s=ac(),d=await window.Word.run(async e=>{const n=e.document.body.paragraphs;n.load("text");let r=null;return t&&(r=e.document.getSelection().paragraphs,r.load("text,styleBuiltIn,style")),await e.sync(),{bodyTexts:n.items.map(e=>String(e.text||"")),selectionParagraphs:t&&r?r.items.map(e=>({text:String(e.text||""),styleBuiltIn:e.styleBuiltIn,style:e.style})):[]}}),l=Math.round(ac()-s);if(r!==tr)return Br(`Office snapshot: ${l}ms stale`),{stale:!0,generation:r};let u=!1;if(t){const e=Ga(Wn,d.selectionParagraphs);u=Fa(e)}const p=Wn?.currentScene;if(!p||!Number.isInteger(p.startParagraphIndex)||!Number.isInteger(p.endParagraphIndex))return null;const h=[];let m=0;const g=Math.min(p.endParagraphIndex,d.bodyTexts.length-1),y=Wn.currentChapter?.startParagraphIndex;for(let e=p.startParagraphIndex;e<=g;e+=1){const t=String(d.bodyTexts[e]||"").trim();t&&!qa.has(t)&&e!==y&&(h.push(t),m+=Pa(t))}p.wordCount=m,n&&Zr(Wn.currentChapter?.title,p.title,m,Wn.currentChapter?.anchorId,p.anchorId,Wn.currentChapter?.index);const w={documentGuid:Ca(),projectId:a?.projectId||null,bookId:c?.bookId||null,chapterId:Sn,sceneId:Cn,chapterTitle:Wn.currentChapter?.title||"",sceneTitle:p.title||"",sceneText:h.join("\n"),wordCount:m,selectionSignature:`${Wn.currentParagraphIndex??-1}:${p.startParagraphIndex}:${p.endParagraphIndex}`,selectionChanged:u,generation:r};return nr=w,Br(`Office snapshot: ${l}ms; scene words: ${m}; total snapshot: ${Math.round(ac()-o)}ms`),w},sc=async()=>cc(nr)?nr:await ic(),dc=async()=>{if(_r(""),!un||!pn||!window.Word||"function"!=typeof window.Word.run)return Zr(null,null,null),_r("Word document access is unavailable."),Vo({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;Q&&(Q.disabled=!0,Q.textContent="Scanning..."),_r("Scanning document structure...");try{const e=await window.Word.run(async e=>{const t=ta();return t?await oc(e,!!t.usesExplicitScenes):(Wn=null,await rc(e))});return Wn||Zr(e.currentChapter?.title,e.currentScene?.title,e.currentScene?.wordCount,e.currentChapter?.anchorId,e.currentScene?.anchorId,e.currentChapter?.index),Ao("Not detected"),Va(e),_r(""),Vo({lastScan:"Success",lastError:"-",paragraphs:String(e.paragraphCount),heading1:String(e.heading1Count),heading2:String(e.heading2Count)}),!0}catch(e){const t=Ko(e);return console.error("Unable to scan the Word document.",e),Zr(null,null,null),_r(`Unable to scan the Word document: ${t}`),Vo({lastScan:"Failure",lastError:t}),!1}finally{Q&&(Q.disabled=!1,Q.textContent="Refresh Document Structure"),await oo().catch(()=>null)}},lc=async()=>{const e=ta();if(!ea()||!e)return co("Select a project and book to analyse manuscript structure."),!1;if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)return co("Word document access is unavailable."),Vo({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;ae&&(ae.disabled=!0,ae.textContent="Analysing..."),co("Analysing manuscript structure...");try{const t=await window.Word.run(async e=>await rc(e)),n=await fc(`/api/word-companion/books/${e.bookId}/structure`);return Zr(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),Va(t),An=((e,t)=>{const n={alreadyLinked:[],couldLink:[],wouldCreateChapters:[],wouldCreateScenes:[],manualReview:[]},r=Array.isArray(t?.chapters)?t.chapters:[];for(const t of Array.isArray(e?.chapters)?e.chapters:[]){const e=Za(t,r,n);for(const o of Xa(t))ec(o,e,r,n)}return n})(t,n),nc(An),co("Preview generated. No changes have been applied."),Vo({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),!0}catch(e){return console.error("Unable to analyse manuscript structure.",e),co("Unable to analyse manuscript structure."),Vo({lastScan:"Failure",lastError:Ko(e)}),!1}finally{ae&&(ae.textContent="Analyse Manuscript Structure",uo())}},uc=e=>{Jn&&(Jn(e),Jn=null),Lt?.close?Lt.close():Lt&&(Lt.hidden=!0)},pc=()=>{const e=((e=An)=>{const t=so(e);return{linkChapters:t.filter(e=>"couldLink"===e.category&&"Chapter"===e.type).length,linkScenes:t.filter(e=>"couldLink"===e.category&&"Scene"===e.type).length,createChapters:t.filter(e=>"wouldCreateChapters"===e.category).length,createScenes:t.filter(e=>"wouldCreateScenes"===e.category).length,manualReview:Array.isArray(e?.manualReview)?e.manualReview.length:0}})();return(e=>{if(!qt)return;qt.innerHTML="";const t=[`Link ${e.linkChapters+e.linkScenes} chapters/scenes`,`Create ${e.createChapters} chapters`,`Create ${e.createScenes} scenes`],n=document.createElement("ul");for(const e of t){const t=document.createElement("li");t.textContent=e,n.append(t)}qt.append(n)})(e),Lt?new Promise(e=>{Jn=e,Lt.showModal?Lt.showModal():Lt.hidden=!1}):Promise.resolve(window.confirm(`Apply Structure Sync?\n\nThis will:\n\n- Link ${e.linkChapters+e.linkScenes} chapters/scenes\n- Create ${e.createChapters} chapters\n- Create ${e.createScenes} scenes\n\nManual review items will be skipped.`))},hc=(e,t,n="")=>{e.result=t,e.error=n},mc=e=>Number.isInteger(e?.wordChapter?.index)&&e.wordChapter.index>0?10*e.wordChapter.index:null,gc=e=>Number.isInteger(e?.wordScene?.index)&&e.wordScene.index>0?10*e.wordScene.index:null,yc=async(e,t)=>{const n=await bc(`/api/word-companion/books/${e}/chapters`,{title:jo(t.wordTitle),sortOrder:mc(t)});if(!n?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");So(),t.pdChapter={chapterId:n.chapterId,title:n.title||t.wordTitle,sortOrder:n.sortOrder||mc(t)||0,scenes:[]},t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},wc=async(e,t)=>{const n=t.pdChapter||t.parentItem?.pdChapter;if(!n?.chapterId)throw new Error("Scene parent chapter is not available.");const r=await bc(`/api/word-companion/books/${e}/chapters/${n.chapterId}/scenes`,{sceneTitle:jo(t.wordTitle),sortOrder:gc(t)});if(!r?.sceneId)throw new Error("Scene creation did not return a scene ID.");So(),t.pdChapter=n,t.pdScene={sceneId:r.sceneId,title:t.wordTitle,sortOrder:gc(t)||0},t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},fc=async(e,t={})=>{const n=await window.fetch(e,{credentials:"same-origin",...t,headers:{Accept:"application/json",...t.headers||{}}});if(!n.ok)throw new Error(`Request failed: ${n.status}`);return await n.json()},bc=(e,t)=>fc(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),Ic=async(e="")=>{Gn=!1,Fn=0,On=[],k&&(k.innerHTML=""),to(C,!0),pa(!1),la(""),to(v,!0),e&&_r(e);const t=await Sc();e&&t&&gn&&_r(e)},Cc=async(e=Cn,t=Sn)=>{const n=ea(),r=ta(),o=Ca(),a=Number.parseInt(e||"",10),c=Number.parseInt(t||"",10);if(!n||!r||!o||!Number.isInteger(a)||a<=0||!Number.isInteger(c)||c<=0)return;const i=`${n.projectId}:${r.bookId}:${a}`;if(Nr!==i){Nr=i;try{await bc("/api/word-companion/runtime/current-scene",{documentGuid:o,projectId:n.projectId,bookId:r.bookId,chapterId:c,sceneId:a}),Or("Current scene follow event sent.")}catch(e){Nr="",console.debug("Unable to notify PlotDirector of current scene.",e)}}},Sc=async()=>{const e=ta();if(!(e&&un&&pn&&window.Word&&"function"==typeof window.Word.run))return!1;_r("Reading manuscript position...");try{So(),await Promise.all([Fc(!0),Vc(!0),Kc(!0)]),await Mo(e.bookId);const t=await window.Word.run(async t=>await oc(t,!!e.usesExplicitScenes));return Va(t),Vo({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),gn?(yn?await Xc():await Qc(),go(!1),mo("Live"),_r(""),!0):(Ao("Not detected"),go(!1),mo("Live"),_r("Manuscript linked. Click inside a chapter to show the current scene."),!0)}catch(e){return console.error("Unable to initialise bound manuscript runtime.",e),Wn=null,mo("Manual"),_r(`Unable to read manuscript position: ${Ko(e)}`),Vo({lastScan:"Failure",lastError:Ko(e)}),!1}},kc=async n=>{$n=null,ti(),eo(),Co(),Ao("Not detected"),mo("Manual"),Kr("Connected"),_o(e,null),_o(t,null),V&&(V.value=""),zo(K,"Select a project first"),ha(),h&&(h.value=""),zo(m,"Select a project first"),ma(n||"Select a Project and Book to begin."),_r(n||"Manuscript unlinked."),ao("No resolved PlotDirector scene."),pa(!0),no()},vc=e=>e?[...e.querySelectorAll("input[type='checkbox']:checked")].map(e=>Number.parseInt(e.value||"",10)).filter(e=>Number.isInteger(e)&&e>0):[],xc=()=>{const e=Number.parseInt(Ye?.value||"",10);return Number.isInteger(e)&&e>0?e:null},Pc=(e,t,n,r)=>{const o=((e,t)=>Ea(e).find(e=>Da(e.tag,t))||null)(e,r),a=o||e.getRange().insertContentControl();return a.title=t,a.tag=n,a.appearance="Hidden",a},Dc=async(e="PlotDirector IDs attached successfully.")=>{if(!Cn||!Sn)return _r("No resolved PlotDirector scene."),!1;if((In&&In!==Cn||bn&&bn!==Sn)&&!window.confirm("This scene is already linked. Replace the existing PlotDirector link?"))return!1;if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)return _r("Word document access is unavailable."),!1;ge&&(ge.disabled=!0,ge.textContent="Attaching...");try{return await window.Word.run(async e=>{const t=await rc(e);if(!t.currentChapter||!t.currentScene)throw new Error("No scene detected in Word. Use Heading 2 for scenes.");const n=t.bodyParagraphs[t.currentChapter.paragraphIndex],r=t.bodyParagraphs[t.currentScene.paragraphIndex];if(!n||!r)throw new Error("Unable to locate the current Word headings.");Pc(n,"PlotDirector Chapter",`PD-CHAPTER-${Sn}`,"PD-CHAPTER"),Pc(r,"PlotDirector Scene",`PD-SCENE-${Cn}`,"PD-SCENE"),await e.sync()}),await oo().catch(()=>null),bn=Sn,In=Cn,xn=!1,vn="SceneID Anchor",kn="Anchor",_r(e),Vo({lastError:"-"}),Xr(),!0}catch(e){return console.error("Unable to attach PlotDirector IDs.",e),_r("Unable to attach PlotDirector IDs."),Vo({lastError:Ko(e)}),Xr(),!1}finally{ge&&(ge.textContent=In===Cn?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",Xr())}},Ec=async e=>{if(!Sn)return xo("No resolved PlotDirector chapter."),!1;if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)return xo("Word document access is unavailable."),!1;try{return await window.Word.run(async e=>{const t=await rc(e);if(!t.currentChapter)throw new Error("No chapter detected in Word. Use Heading 1 for chapters.");const n=t.bodyParagraphs[t.currentChapter.paragraphIndex];if(!n)throw new Error("Unable to locate the current Word chapter heading.");Pc(n,"PlotDirector Chapter",`PD-CHAPTER-${Sn}`,"PD-CHAPTER"),await e.sync()}),await oo().catch(()=>null),bn=Sn,xn=!1,vn="ChapterID Anchor",kn="Chapter anchor",xo(e),_r(e),Vo({lastError:"-"}),Xr(),!0}catch(e){return console.error("Unable to attach PlotDirector chapter ID.",e),xo("Unable to attach PlotDirector chapter ID."),Vo({lastError:Ko(e)}),Xr(),!1}},Nc=async e=>{Eo(),await Xc(),_r(e),xo(e)},Lc=e=>{qn&&(qn(e),qn=null),xt?.close?xt.close():xt&&(xt.hidden=!0)},qc=()=>{if(!Ct)return;const e=jo(It?.value||"").toLocaleLowerCase(),t=Nn.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(Ct.innerHTML="",Ln=null,St&&(St.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No chapters found.",void Ct.append(e)}for(const e of t){const t=Number.parseInt(e.chapterId||"",10);if(!Number.isInteger(t)||t<=0)continue;const n=document.createElement("label");n.className="word-companion-scene-option";const r=document.createElement("input");r.type="radio",r.name="word-companion-link-chapter",r.value=String(t),r.addEventListener("change",()=>{Ln=t,St&&(St.disabled=!1)});const o=document.createElement("span");o.textContent=e.title||"Untitled chapter",n.append(r,o),Ct.append(n)}},Ac=()=>{bt?.close?bt.close():bt&&(bt.hidden=!0)},$c=async(e,t,n)=>{const r=ta();if(!r)return vo("Select a PlotDirector book first."),!1;await Go(r.bookId,e,t,"Manual link","Title Match");return!!await Dc(n)&&(vo(n),Lo(),!0)},Tc=e=>{En&&(En(e),En=null),mt?.close?mt.close():mt&&(mt.hidden=!0)},Wc=()=>{if(!lt)return;const e=jo(dt?.value||"").toLocaleLowerCase(),t=Pn.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(lt.innerHTML="",Dn=null,ut&&(ut.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No scenes found.",void lt.append(e)}for(const e of t){const t=Number.parseInt(e.sceneId||"",10);if(!Number.isInteger(t)||t<=0)continue;const n=document.createElement("label");n.className="word-companion-scene-option";const r=document.createElement("input");r.type="radio",r.name="word-companion-link-scene",r.value=String(t),r.addEventListener("change",()=>{Dn=t,ut&&(ut.disabled=!1)});const o=document.createElement("span");o.textContent=e.title||"Untitled scene",n.append(r,o),lt.append(n)}},jc=()=>{st?.close?st.close():st&&(st.hidden=!0)},Rc=()=>{ir=!1,ho(),sr&&(sr=!1,Mc(1e3))},Uc=async(e={})=>{const t=e.source||"manual",n=ac();if(!Cn)return void ao("No resolved PlotDirector scene.");if(!Sn)return void ao("No resolved PlotDirector chapter.");if(zn)return void ao("Refresh Current Scene before syncing.");const r=ta(),o=Ca();if(!r||!o)return void ao("Bound manuscript metadata is unavailable.");if(ir)return sr=!0,void Or("Scene sync deferred; sync already running.");eo(),ir=!0,sr=!1;let a=e.snapshot||null;try{a=cc(a)?a:await sc()}catch(e){return ao("Sync failed"),Vo({lastError:Ko(e)}),Or("Scene sync failed."),void Rc()}if(!cc(a))return ao("Waiting for typing to pause"),Or("Scene sync skipped (stale snapshot)."),void Rc();const c=a.wordCount;if(!Number.isInteger(c)||c<0)return ao("Sync failed"),Or("Scene sync failed."),void Rc();if(dr===a.sceneId&&lr===c)return ao("Synced"),Or("Sync skipped (count unchanged)."),void Rc();Or("Scene word count changed."),Te&&(Te.disabled=!0,Te.textContent="Syncing..."),ao("Syncing..."),Or(`Scene sync started (${t}).`);try{const e=ac(),t=await bc("/api/word-companion/runtime/scene-word-count",{documentGuid:a.documentGuid||o,bookId:a.bookId||r.bookId,chapterId:a.chapterId,sceneId:a.sceneId,wordCount:c});if(Br(`Word count sync API: ${Math.round(ac()-e)}ms`),!cc(a))return void Or("Scene sync result ignored (stale snapshot).");const i=t?.actualWords??c,s=new Date;dr=a.sceneId,lr=i,Fo(je,fo(i)),Fo(Ne,fo(i)),Fo(Re,bo(s)),Fo($e,bo(s)),ao("Synced"),Or("Scene sync succeeded."),Br(`Total word count sync: ${Math.round(ac()-n)}ms`)}catch(e){ao("Sync failed"),Vo({lastError:Ko(e)}),Or("Scene sync failed.")}finally{Te&&(Te.textContent="Sync Current Scene"),Rc()}},Mc=(e=4e3)=>{eo(),Cn&&Sn&&!zn&&!ir&&(cr=window.setTimeout(()=>{cr=null,Uc({source:"automatic"})},e))},Oc=()=>{ur&&(window.clearTimeout(ur),ur=null)},Bc=()=>{mr=null,gr="",yr=[],wr=null,fr="",Oc()},Hc=()=>{br=null,Ir="",Cr=[],Sr=null,kr=""},Gc=()=>{vr=null,xr="",Pr=[],Dr=null,Er=""},Fc=async(e=!1)=>{const t=ea(),n=Ca();if(!t||!n)return yr=[],[];if(!e&&mr===t.projectId&&gr===n&&yr.length>0)return yr;const r=await fc(`/api/word-companion/runtime/characters?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(n)}`);return mr=t.projectId,gr=n,yr=Array.isArray(r?.characters)?r.characters:[],Or("Character alias cache refreshed."),yr},Vc=async(e=!1)=>{const t=ea(),n=Ca();if(!t||!n)return Cr=[],[];if(!e&&br===t.projectId&&Ir===n&&Cr.length>0)return Cr;const r=await fc(`/api/word-companion/runtime/assets?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(n)}`);return br=t.projectId,Ir=n,Cr=Array.isArray(r?.assets)?r.assets:[],Or(`Asset cache loaded: ${Cr.length} aliases.`),Cr},Kc=async(e=!1)=>{const t=ea(),n=Ca();if(!t||!n)return Pr=[],[];if(!e&&vr===t.projectId&&xr===n&&Pr.length>0)return Pr;const r=await fc(`/api/word-companion/runtime/locations?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(n)}`);return vr=t.projectId,xr=n,Pr=Array.isArray(r?.locations)?r.locations:[],Or(`Location cache loaded: ${Pr.length} aliases.`),Pr},Yc=(e,t)=>{const n=String(t||"").trim();if(!n)return!1;const r=(o=n,String(o||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).replace(/\s+/g,"\\s+");var o;return new RegExp(`(^|[^\\p{L}\\p{N}_])${r}(?=$|[^\\p{L}\\p{N}_])`,"iu").test(e)},Jc=e=>{if(e?.excludeFromCompanionDetection)return!1;const t=Number.parseInt(e?.detectionPriority||"0",10);return n=e?.matchText,String(n||"").trim().split(/\s+/).filter(Boolean).length>=2||Number.isInteger(t)&&t>=75;var n},_c=async()=>{if(ur=null,!Cn||zn||!Ca())return;if(pr)return hr=!0,void Or("Character suggestion detection deferred; detection already running.");pr=!0,hr=!1;const e=ac();try{const t=await sc();if(!cc(t))return void Or("Runtime suggestions skipped (stale snapshot).");const[n,r,o]=await Promise.all([Fc(),Vc(),Kc()]);if(!cc(t))return void Or("Runtime suggestions skipped after cache load (stale snapshot).");const a=t.sceneText||"",c=ac(),i=((e,t)=>{if(!e||!Array.isArray(t)||0===t.length)return[];const n=new Map;for(const r of t){const t=Number.parseInt(r.characterId||"",10);!Number.isInteger(t)||t<=0||n.has(t)||Yc(e,r.matchText)&&n.set(t,r.name||r.matchText||"Character")}return[...n.entries()].map(([e,t])=>({characterId:e,name:t}))})(a,n);Br(`Character detection: ${Math.round(ac()-c)}ms`);const s=i.map(e=>e.characterId),d=s.slice().sort((e,t)=>e-t).join(","),l=ac(),u=((e,t)=>{if(!e||!Array.isArray(t)||0===t.length)return[];const n=new Map;for(const r of t){const t=Number.parseInt(r.assetId||"",10);!Number.isInteger(t)||t<=0||n.has(t)||Yc(e,r.matchText)&&n.set(t,r.name||r.matchText||"Asset")}return[...n.entries()].map(([e,t])=>({assetId:e,name:t}))})(a,r);Br(`Asset detection: ${Math.round(ac()-l)}ms`);const p=u.map(e=>e.assetId),h=p.slice().sort((e,t)=>e-t).join(","),m=ac(),g=((e,t)=>{if(!e||!Array.isArray(t)||0===t.length)return[];const n=new Map;for(const r of t){const t=Number.parseInt(r.locationId||"",10);!Number.isInteger(t)||t<=0||n.has(t)||!Jc(r)||Yc(e,r.matchText)&&n.set(t,r.name||r.matchText||"Location")}return[...n.entries()].map(([e,t])=>({locationId:e,name:t}))})(a,o);Br(`Location detection: ${Math.round(ac()-m)}ms`);const y=g.map(e=>e.locationId),w=y.slice().sort((e,t)=>e-t).join(",");if(!d||wr===Cn&&fr===d)Or("Character suggestions skipped.");else{if(!cc(t))return void Or("Character suggestions skipped before submit (stale snapshot).");const e=ac(),n=await bc("/api/word-companion/runtime/character-suggestions",{documentGuid:t.documentGuid,sceneId:t.sceneId,characterIds:s});if(Br(`Character suggestion API: ${Math.round(ac()-e)}ms`),!cc(t))return void Or("Character suggestion result ignored (stale snapshot).");if(wr=t.sceneId,fr=d,(n?.createdCount||0)>0){const e=i.slice(0,3).map(e=>e.name).join(", "),t=i.length>3?" +"+(i.length-3):"";_r(e?`Characters detected: ${e}${t}`:n.message)}Or(n?.message||"Character suggestions submitted.")}if(!h||Sr===Cn&&kr===h)Or("Asset suggestions skipped.");else{if(!cc(t))return void Or("Asset suggestions skipped before submit (stale snapshot).");Or(`Asset matches found: ${u.map(e=>e.name).join(", ")}`);const e=ac(),n=await bc("/api/word-companion/runtime/asset-suggestions",{documentGuid:t.documentGuid,sceneId:t.sceneId,assetIds:p});if(Br(`Asset suggestion API: ${Math.round(ac()-e)}ms`),!cc(t))return void Or("Asset suggestion result ignored (stale snapshot).");if(Sr=t.sceneId,kr=h,(n?.createdCount||0)>0){const e=u.slice(0,3).map(e=>e.name).join(", "),t=u.length>3?" +"+(u.length-3):"";_r(e?`Assets detected: ${e}${t}`:n.message)}Or(n?.message||"Asset suggestions submitted.")}if(!w||Dr===Cn&&Er===w)Or("Location suggestions skipped.");else{if(!cc(t))return void Or("Location suggestions skipped before submit (stale snapshot).");Or(`Location matches found: ${g.map(e=>e.name).join(", ")}`);const e=ac(),n=await bc("/api/word-companion/runtime/location-suggestions",{documentGuid:t.documentGuid,sceneId:t.sceneId,locationIds:y});if(Br(`Location suggestion API: ${Math.round(ac()-e)}ms`),!cc(t))return void Or("Location suggestion result ignored (stale snapshot).");if(Dr=t.sceneId,Er=w,(n?.createdCount||0)>0){const e=g.slice(0,3).map(e=>e.name).join(", "),t=g.length>3?" +"+(g.length-3):"";_r(e?`Locations detected: ${e}${t}`:n.message)}Or(n?.message||"Location suggestions submitted.")}Br(`Total suggestion pass: ${Math.round(ac()-e)}ms`)}catch(e){console.error("Unable to detect runtime suggestions.",e),Vo({lastError:Ko(e)})}finally{pr=!1,hr&&(hr=!1,zc(1500))}},zc=(e=2500)=>{Oc(),!Cn||zn||pr?pr&&(hr=!0):ur=window.setTimeout(()=>{_c()},e)},Qc=async()=>{const e=ea(),t=ta(),n=Ro(gn,"chapter");if(Uo({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Xo(t):void 0,detectedChapter:gn,detectedScene:yn,requestChapter:n,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!t)return Ao("Not detected"),_r("Select a PlotDirector book first."),!1;if(!gn)return Ao("Not detected"),_r("No chapter detected in Word. Use Heading 1 for chapters."),!1;Ao("Not detected");try{const e=await Oo(t.bookId),r=bn?e.find(e=>e.chapterId===bn):null,o=n.toLocaleLowerCase(),a=o?e.find(e=>Ro(e.title,"chapter").toLocaleLowerCase()===o):null,c=r||a;return c?(Eo(),yo(null,c.chapterId,r?"Chapter anchor":"Chapter title"),vn=r?"ChapterID Anchor":"Title Match",zr("Chapter linked to PlotDirector"),_r("No scene detected in Word. Use Heading 2 for scenes."),Uo({result:"Chapter matched",chapterId:c.chapterId,sceneId:null}),!0):(yo(null),zr("Chapter not found in PlotDirector."),_r("Chapter not found in PlotDirector."),Uo({result:"Chapter not matched",chapterId:null,sceneId:null}),No("Chapter not found in PlotDirector."),!1)}catch(e){return Ao("Not found in PlotDirector"),Vo({lastError:Ko(e)}),_r("Unable to load PlotDirector chapter data."),!1}},Xc=async()=>{const e=ea(),t=ta(),n=Ro(gn,"chapter"),r=Ro(yn,"scene");if(Uo({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Xo(t):void 0,detectedChapter:gn,detectedScene:yn,requestChapter:n,requestScene:r,result:"Not run",chapterId:null,sceneId:null}),Qr({anchorType:In?"SceneID Anchor":bn?"ChapterID Anchor":"Title Match",storedSceneId:In,storedChapterId:bn,resolutionMethod:"-"}),!t)return Ao("Not detected"),_r("Select a PlotDirector book first."),Uo({result:"Error"}),!1;if(!gn||!yn)return Ao("Not detected"),_r("No scene detected in Word. Use Heading 2 for scenes."),Uo({result:"Error"}),!1;de&&(de.disabled=!0,de.textContent="Refreshing...");const o=()=>{de&&(de.disabled=!1,de.textContent="Refresh PlotDirector Scene")};Ao("Not detected"),_r("Resolving PlotDirector scene...");try{if(In){const e=await(async(e,t)=>{const n=await fc(`/api/word-companion/books/${e}/structure`),r=Array.isArray(n?.chapters)?n.chapters:[];for(const e of r){const n=Array.isArray(e.scenes)?e.scenes:[];for(const r of n)if(t(e,r))return{chapter:e,scene:r}}return null})(t.bookId,(e,t)=>t.sceneId===In);if(e)return Uo({result:"Matched",chapterId:e.chapter.chapterId,sceneId:e.scene.sceneId}),await Go(t.bookId,e.scene.sceneId,e.chapter.chapterId,"Anchor","SceneID Anchor"),!0;xn=!0,vn="SceneID Anchor",zr("Not found in PlotDirector"),_r("Stored PlotDirector ID is invalid."),Uo({result:"Error",chapterId:bn,sceneId:In}),Qr({anchorType:"SceneID Anchor",storedSceneId:In,storedChapterId:bn,resolutionMethod:"Anchor"})}if(bn){const e=(await Mo(t.bookId)).find(e=>e.chapterId===bn),n=e?(Array.isArray(e.scenes)?e.scenes:[]).find(e=>Ro(e.title,"scene").toLocaleLowerCase()===r.toLocaleLowerCase()):null;if(n)return Uo({result:"Matched",chapterId:e.chapterId,sceneId:n.sceneId}),await Go(t.bookId,n.sceneId,e.chapterId,"Anchor","ChapterID Anchor"),!0;e&&!In?(vn="ChapterID Anchor",yo(null,bn,"Chapter anchor"),Uo({result:"Chapter matched",chapterId:bn,sceneId:null})):In||(vn="ChapterID Anchor",Uo({result:"Chapter anchor not found",chapterId:bn,sceneId:null}))}const e=await bc(`/api/word-companion/books/${t.bookId}/resolve-scene`,{chapterTitle:n,sceneTitle:r});if(!e?.matched||!e.sceneId){const t=xn,n=Number.parseInt(e?.chapterId||"",10),r=Number.isInteger(Sn)&&Sn>0?Sn:null,a=Number.isInteger(n)&&n>0?n:r,c=!!e?.chapterMatched||!!a;return Ao("Not found in PlotDirector"),xn=t,c&&(yo(null,a,a===r?"Chapter anchor":"Chapter title"),zr("Scene not found in PlotDirector.")),_r(t?"Stored PlotDirector ID is invalid.":c?"Scene not found in PlotDirector.":"This chapter does not exist in PlotDirector. Create or link the chapter first."),Uo({result:"Not matched",chapterId:c?a:e?.chapterId,sceneId:e?.sceneId}),t||(c?(Eo(),qo("Scene not found in PlotDirector.")):(Lo(),No("Chapter not found in PlotDirector."))),o(),!1}const a=xn;return Uo({result:a?"Matched by title fallback":"Matched",chapterId:e.chapterId,sceneId:e.sceneId}),await Go(t.bookId,e.sceneId,e.chapterId,a?"Title fallback":"Title","Title Match"),a&&(xn=!0,_r("Stored PlotDirector ID is invalid."),Xr()),!0}catch(e){const t=xn;return Vo({lastError:Ko(e)}),Ao("Not found in PlotDirector"),xn=t,_r(t?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),Uo({result:"Error"}),!1}finally{o()}},Zc=async()=>{if(Qn=null,ar)return er=!0,void Or("Runtime update deferred; update already running.");if(!an||!ta())return Xn=!1,void Or("Runtime update skipped.");if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)return Xn=!1,mo("Manual"),void _r("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");if(!Wn)return Xn=!1,mo("Manual"),void _r("Document structure is not cached yet. Use Refresh Current Scene.");const e=Date.now()-Zn;if(Xn&&e{Qn&&window.clearTimeout(Qn),Qn=window.setTimeout(Zc,Math.max(0,e)),mo("Waiting for typing to pause"),Or("Runtime update scheduled.")},ti=()=>{Qn&&(window.clearTimeout(Qn),Qn=null),Xn=!1,er=!1},ni=()=>{((e="selection",t=1200)=>{if(Xn=!0,Zn=Date.now(),tr+=1,nr=null,eo(),Oc(),ir&&(sr=!0),pr&&(hr=!0),Or(`${e} changed.`),ar)return er=!0,void mo("Waiting for typing to pause");ei(t)})("Selection")},ri=()=>{if(or&&window.Office?.context?.document&&"function"==typeof window.Office.context.document.removeHandlerAsync&&window.Office?.EventType?.DocumentSelectionChanged)try{window.Office.context.document.removeHandlerAsync(window.Office.EventType.DocumentSelectionChanged,{handler:ni}),or=!1}catch(e){console.warn("Unable to remove Word selection tracking handler.",e)}},oi=async(e,n)=>{if(Wn=null,So(),!e)return ln=[],zo(K,"Select a project first"),zo(m,"Select a project first"),Jr(""),_o(t,null),Sa(),Ao("Not detected"),void io();zo(K,"Loading books..."),Jr(""),Ao("Not detected"),io("Select a book to analyse manuscript structure.");try{const r=await fc(`/api/word-companion/projects/${e}/books`);if(ln=Array.isArray(r.books)?r.books:[],0===ln.length)return zo(K,"No books available."),zo(m,"No books available."),Jr("No books available."),_o(t,null),Sa(),void ma("No books available.");Qo(K,"Choose a book",ln.map(e=>({...e,displayTitle:Xo(e)})),"bookId","displayTitle");const o=ln.find(e=>e.bookId===n);o&&K?(K.value=String(o.bookId),_o(t,o.bookId)):_o(t,null),((e=null)=>{if(!m)return;if(0===ln.length)return void zo(m,"No books available.");Qo(m,"Choose a book",ln.map(e=>({...e,displayTitle:Xo(e)})),"bookId","displayTitle");const t=e||Number.parseInt(K?.value||"",10),n=ln.find(e=>e.bookId===t);n&&(m.value=String(n.bookId)),ua()})(o?.bookId||n),Sa(),Ao((ta(),"Not detected")),io(ta()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),ma(ra()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{ln=[],zo(K,"Unable to load books."),zo(m,"Unable to load books."),Jr("Unable to load books."),_o(t,null),Sa(),Ao("Not detected"),io("Unable to load books."),ma("Unable to load books.")}};for(const e of i)e.addEventListener("click",()=>Fr(e.dataset.tabButton));Vr(),V?.addEventListener("change",async()=>{const n=Number.parseInt(V.value||"",10);Co(),h&&Number.isInteger(n)&&n>0&&(h.value=String(n)),_o(e,Number.isInteger(n)&&n>0?n:null),_o(t,null),Ao("Not detected"),io(),ma("Select a Book to begin."),await oi(n,null),sa()}),K?.addEventListener("change",()=>{const e=Number.parseInt(K.value||"",10);Co(),_o(t,Number.isInteger(e)&&e>0?e:null),m&&Number.isInteger(e)&&e>0&&(m.value=String(e)),Sa(),Ao("Not detected"),io(ta()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),ma(ra()?"Ready to scan manuscript structure.":"Select a Book to begin."),sa()}),h?.addEventListener("change",async()=>{const n=Number.parseInt(h.value||"",10);Co(),V&&Number.isInteger(n)&&n>0&&(V.value=String(n)),_o(e,Number.isInteger(n)&&n>0?n:null),_o(t,null),ma("Select a Book to begin."),await oi(n,null),sa()}),m?.addEventListener("change",()=>{const e=Number.parseInt(m.value||"",10);Co(),K&&Number.isInteger(e)&&e>0&&(K.value=String(e)),_o(t,Number.isInteger(e)&&e>0?e:null),Sa(),ma(ra()?"Ready to scan manuscript structure.":"Select a Book to begin."),sa()}),g?.addEventListener("input",ua),y?.addEventListener("click",async()=>{const e=na(),t=String(g?.value||"").trim();if(e&&t){y.disabled=!0,la("Creating Book...");try{const n=await bc(`/api/word-companion/projects/${e.projectId}/books`,{title:t});g&&(g.value=""),V&&(V.value=String(e.projectId)),await oi(e.projectId,n.bookId),m&&(m.value=String(n.bookId)),la("Ready to scan manuscript structure.")}catch(e){console.error("Unable to create Book from Word Companion.",e),la(`Unable to create Book: ${Ko(e)}`)}finally{ua()}}else ua()}),w?.addEventListener("click",async()=>{const e=na(),t=ra();if(e&&t)if(un&&pn&&window.Word&&"function"==typeof window.Word.run){w&&(w.disabled=!0,w.textContent="Scanning..."),la("Scanning manuscript structure...");try{const n=await window.Word.run(async e=>{const n=e.document.body.paragraphs;return n.load("text,styleBuiltIn,style"),await e.sync(),((e,t)=>{const n=[];let r=null,o=null,a=0;const c=[],i=new Set(["***","###"]),s=()=>{if(!r)return null;const e={title:`Scene ${r.scenes.length+1}`,sortOrder:10*(r.scenes.length+1),wordCount:0};return r.scenes.push(e),e};return e.forEach(e=>{const d=String(e.text||"").trim();if(!d)return;if(c.push(d),xa(e,1))return r={title:d,sortOrder:10*(n.length+1),wordCount:0,scenes:[]},n.push(r),o=s(),void(a+=Pa(d));if(!r||!o)return;if(t&&i.has(d))return void(o=s());const l=Pa(d);r.wordCount+=l,o.wordCount+=l,a+=l}),{chapters:n,chapterCount:n.length,sceneCount:n.reduce((e,t)=>e+t.scenes.length,0),wordCount:a,documentText:c.join("\n")}})(n.items,!!t.usesExplicitScenes)});Mn=n,Hn=!1;const r=await bc("/api/word-companion/manuscript/analyse",{projectId:e.projectId,bookId:t.bookId,documentGuid:Ia(),chapterCount:n.chapterCount,sceneCount:n.sceneCount,wordCount:n.wordCount});Un=r,(e=>{if(!I)return;I.innerHTML="";const t=document.createElement("strong");t.textContent="Manuscript Analysis",I.append(t);const n=document.createElement("dl"),r=[["Project",e.projectTitle],["Book",Xo({title:e.bookTitle,subtitle:e.bookSubtitle})],["Chapters",Number(e.chapterCount||0).toLocaleString()],["Scenes",Number(e.sceneCount||0).toLocaleString()],["Words",Number(e.wordCount||0).toLocaleString()]];for(const[e,t]of r){const r=document.createElement("dt");r.textContent=e;const o=document.createElement("dd");o.textContent=t||"-",n.append(r,o)}I.append(n),to(I,!1),to(E,!1),la(e.message||"Preview generated."),ua()})(r);try{const t=await bc("/api/word-companion/manuscript/discover-characters",{projectId:e.projectId,documentText:n.documentText||""});On=Array.isArray(t?.candidates)?t.candidates:[],to(C,!0),to(v,!0)}catch(e){console.error("Unable to discover character candidates.",e),On=[],to(C,!0),to(v,!0)}Vo({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(n.chapterCount),heading2:"-"})}catch(e){console.error("Unable to scan manuscript for first-run import.",e),ma(`Unable to scan manuscript: ${Ko(e)}`),Vo({lastScan:"Failure",lastError:Ko(e)})}finally{w&&(w.textContent="Scan Manuscript"),ua()}}else ma("Word document access is unavailable.");else ma("Select a Project and Book to begin.")}),N?.addEventListener("click",async()=>{const n=na(),o=ra();if(!(n&&o&&Mn&&Un?.canImport))return void ua();let a=!1;if(!Un.requiresReplaceConfirmation||(a=await new Promise(e=>{if(!q||"function"!=typeof q.showModal)return void e(window.confirm("This Book already contains planned chapters and scenes.\n\nImporting this manuscript will replace the planned structure.\n\nContinue?"));const t=t=>{A?.removeEventListener("click",n),$?.removeEventListener("click",r),q?.removeEventListener("cancel",o),q?.close(),e(t)},n=()=>t(!0),r=()=>t(!1),o=e=>{e.preventDefault(),t(!1)};A?.addEventListener("click",n),$?.addEventListener("click",r),q?.addEventListener("cancel",o),q.showModal()}),a)){Vn=!0,ua(),la("Importing manuscript structure...");try{const i=Ia(),s=await bc("/api/word-companion/manuscript/import",{projectId:n.projectId,bookId:o.bookId,documentGuid:i,bindingVersion:1,replacePlanned:a,chapters:Mn.chapters});if(!s.imported)return Un={...Un,canImport:!s.requiresReplaceConfirmation,requiresReplaceConfirmation:!!s.requiresReplaceConfirmation,message:s.message||Un.message},la(s.message||"Import was not completed."),void ua();const d=s.manuscriptDocument;await(c={documentGuid:d?.documentGuid||i,bookId:s.bookId,projectId:s.projectId,bindingVersion:d?.bindingVersion||1},new Promise((e,t)=>{const n=window.Office?.context?.document?.settings;n?(n.set(r.documentGuid,c.documentGuid),n.set(r.bookId,String(c.bookId)),n.set(r.projectId,String(c.projectId)),n.set(r.bindingVersion,String(c.bindingVersion||1)),n.saveAsync(n=>{n.status===window.Office.AsyncResultStatus.Succeeded?e():t(n.error||new Error("Unable to save Word document metadata."))})):t(new Error("Word document settings are unavailable."))})),$n={documentGuid:d?.documentGuid||i,bookId:s.bookId,projectId:s.projectId,bindingVersion:d?.bindingVersion||1},_o(e,s.projectId),_o(t,s.bookId),V&&(V.value=String(s.projectId));const l=On;await oi(s.projectId,s.bookId),Kr("Connected"),Hn=!0,Gn=l.length>0,Fn=Gn?Date.now():0,On=l,l.length>0?(pa(!0),ya(l),to(E,!0),to(v,!1),la(s.message||"Manuscript structure imported."),_r(s.message||"Manuscript structure imported."),window.setTimeout(ua,750)):await Ic(s.message||"Manuscript structure imported.")}catch(e){console.error("Unable to import manuscript structure.",e),la(`Unable to import manuscript: ${Ko(e)}`)}finally{Vn=!1,ua()}var c}else la("Import cancelled.")}),x?.addEventListener("click",async()=>{const e=na()||ea(),t=ga();if(!Gn||Date.now()-Fn<750||!e||0===t.length)ua();else{Kn=!0,ua(),Fo(S,"Creating selected characters...");try{const n=await bc("/api/word-companion/manuscript/create-discovered-characters",{projectId:e.projectId,candidateNames:t});_r(n.message||"Characters created."),Fo(S,`${n.createdCount||0} created, ${n.skippedCount||0} already existed.`),await Ic(n.message||"Characters created.")}catch(e){console.error("Unable to create discovered characters.",e),Fo(S,`Unable to create characters: ${Ko(e)}`)}finally{Kn=!1,ua()}}}),P?.addEventListener("click",()=>Ic("Character creation skipped.")),D?.addEventListener("click",()=>Ic()),f?.addEventListener("click",()=>pa(!1)),L?.addEventListener("click",()=>ma("Import cancelled.")),Q?.addEventListener("click",dc),ae?.addEventListener("click",lc),ce?.addEventListener("click",async()=>{const e=ta();if(!e||0===so().length||Yn)return void lo();if(!await pc())return;Yn=!0,uo(),co("Applying structure sync...");const t={createdChapters:0,createdScenes:0,linkedChapters:0,linkedScenes:0,skipped:Array.isArray(An?.manualReview)?An.manualReview.length:0,failed:0},n=so().filter(e=>"couldLink"===e.category&&"Chapter"===e.type),r=so().filter(e=>"wouldCreateChapters"===e.category),o=so().filter(e=>"couldLink"===e.category&&"Scene"===e.type),a=so().filter(e=>"wouldCreateScenes"===e.category),c=[];let i="";const s=(e,t)=>{c.push({item:e,counterName:t})},d=async(e,n)=>{try{await(async e=>{if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)throw new Error("Word document access is unavailable.");await window.Word.run(async t=>{const n=await rc(t),r="Chapter"===e.type?e.wordChapter:e.wordScene,o=Number.isInteger(r?.paragraphIndex)?n.bodyParagraphs[r.paragraphIndex]:null;if(!o)throw new Error("Unable to locate the Word heading.");if("Chapter"===e.type){const t=e.pdChapter?.chapterId;if(!t)throw new Error("Chapter ID is not available.");Pc(o,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=e.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");Pc(o,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()}),await oo().catch(()=>null)})(e),hc(e,"Success"),t[n]+=1}catch(n){hc(e,"Failed",Ko(n)),t.failed+=1}};try{for(const e of n)s(e,"linkedChapters");for(const n of r)try{await yc(e.bookId,n),s(n,"createdChapters")}catch(e){hc(n,"Failed",Ko(e)),t.failed+=1}for(const e of o)s(e,"linkedScenes");for(const n of a)try{await wc(e.bookId,n),s(n,"createdScenes")}catch(e){hc(n,"Failed",Ko(e)),t.failed+=1}for(const e of c)await d(e.item,e.counterName);for(const e of An.manualReview||[])hc(e,"Skipped");nc(An),i=(e=>`Structure Sync Complete. Created: ${e.createdChapters} Chapters, ${e.createdScenes} Scenes. Linked: ${e.linkedChapters} Chapters, ${e.linkedScenes} Scenes. Skipped: ${e.skipped} Manual Review items. Failed: ${e.failed} Items.`)(t),co(i)}finally{Yn=!1,uo(),i&&(So(),await lc(),co(`${i} Preview refreshed.`))}}),At?.addEventListener("click",()=>uc(!0)),$t?.addEventListener("click",()=>uc(!1)),Lt?.addEventListener("cancel",e=>{e.preventDefault(),uc(!1)}),de?.addEventListener("click",Xc),z?.addEventListener("click",async()=>{if(!ta())return _r("Select a PlotDirector book first."),void Ao("Not detected");ti(),wo(!0),mo("Updating...");try{await Promise.all([Fc(!0),Vc(!0),Kc(!0)]);if(!await dc())return;if(go(!1),!yn)return await Qc(),void mo("Current scene updated");await Xc(),mo("Current scene updated")}finally{wo(!1)}}),Te?.addEventListener("click",()=>Uc({source:"manual"})),Je?.addEventListener("click",async()=>{if(Cn)if(!zn&&await(async()=>{if(!Cn)return!1;if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)return go(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1;try{const e=await window.Word.run(async e=>await rc(e)),t=e.currentChapter?.title||"",n=e.currentScene?.title||"",r=e.currentScene?.anchorId||null,o=e.currentChapter?.anchorId||null,a=Number.isInteger(r)&&r===Cn,c=Number.isInteger(o)&&o===Sn,i=Ro(n,"scene").toLocaleLowerCase()===Ro(Lr||yn,"scene").toLocaleLowerCase(),s=Ro(t,"chapter").toLocaleLowerCase()===Ro(qr||gn,"chapter").toLocaleLowerCase();return a||i&&(c||s)?(go(!1),!0):(go(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1)}catch(e){return console.error("Unable to verify current Word scene before saving.",e),Vo({lastError:Ko(e)}),go(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1}})()){Je&&(Je.disabled=!0,Je.textContent="Saving...");try{await(e=`/api/word-companion/scenes/${Cn}/links`,t={characterIds:vc(Ve),assetIds:vc(Ke),locationIds:[],primaryLocationId:xc()},fc(e,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})),(()=>{const e=new Set(vc(Ve)),t=new Set(vc(Ke));Wr={characters:Wr.characters.map(t=>({...t,linked:e.has(Number.parseInt($o(t,"character"),10))})),assets:Wr.assets.map(e=>({...e,linked:t.has(Number.parseInt($o(e,"asset"),10))})),locations:Wr.locations,primaryLocationId:xc()}})(),ko("Scene links saved successfully."),Vo({lastError:"-"})}catch(e){ko("Unable to save scene links."),Vo({lastError:Ko(e)})}finally{Je&&(Je.disabled=!Cn||zn,Je.textContent="Save Scene Links")}var e,t}else ko("The Word cursor is now in a different scene. Refresh Current Scene before saving.");else ko("Link a PlotDirector scene first.")}),ge?.addEventListener("click",async()=>{await Dc()}),ye?.addEventListener("click",async()=>{console.debug("Word Companion unlink clicked"),_r("Preparing to unlink manuscript...");const e=fa();if(!e)return void _r("This Word document is not linked.");if(!e.documentGuid||!Number.isInteger(e.bookId)||e.bookId<=0)return void _r("Unable to unlink: bound document metadata is incomplete.");try{await oo()}catch{_r("Marker counts are unavailable. You can still unlink without removing hidden anchors.")}if(await new Promise(e=>{if(!T||"function"!=typeof T.showModal)return void e(window.confirm(`This will remove PlotDirector binding metadata from this Word document and unlink this Book in PlotDirector.\n\nHidden PlotDirector anchors will be left in place for possible reuse.\n\nCurrent marker count:\n${jr.chapterCount} chapter markers\n${jr.sceneCount} scene markers\n\nYour manuscript text will not be changed.\n\nContinue?`));const t=t=>{W?.removeEventListener("click",n),j?.removeEventListener("click",r),T?.removeEventListener("cancel",o),T?.close(),e(t)},n=()=>t(!0),r=()=>t(!1),o=e=>{e.preventDefault(),t(!1)};W?.addEventListener("click",n),j?.addEventListener("click",r),T?.addEventListener("cancel",o),T.showModal()})){_r("Unlinking manuscript..."),ye&&(ye.disabled=!0,ye.textContent="Unlinking...");try{await bc("/api/word-companion/manuscript/unlink",{documentGuid:e.documentGuid,bookId:e.bookId}),await ba(),await oo().catch(()=>null),await kc("Manuscript unlinked.")}catch(e){console.error("Unable to unlink manuscript binding.",e),_r("Unable to unlink from PlotDirector.");if(window.confirm("PlotDirector could not be updated, but you can still remove the binding from this Word document.\n\nYou may need to unlink the Book manually in PlotDirector later.\n\nRemove binding from this Word document only?"))try{await ba(),await oo().catch(()=>null),await kc("Word metadata removed. Unlink the Book manually in PlotDirector if it still shows as linked.")}catch(e){console.error("Unable to remove Word document metadata.",e),_r(`Unable to remove Word metadata: ${Ko(e)}`)}else _r(`Unable to unlink manuscript: ${Ko(e)}`)}finally{ye&&(ye.disabled=!1,ye.textContent="Unlink from PlotDirector"),no()}}else _r("Unlink cancelled.")}),we?.addEventListener("click",async()=>{console.debug("Word Companion clean and unlink clicked");const e=fa();if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)return void _r("Word document access is unavailable.");_r("Inspecting PlotDirector markers...");try{await oo()}catch(e){return void _r(`Unable to inspect markers: ${Ko(e)}`)}if(await new Promise(e=>{const t=`This will remove PlotDirector hidden anchors from this Word document while preserving manuscript text.\n\nThis will remove:\n${jr.chapterCount} PlotDirector chapter markers\n${jr.sceneCount} PlotDirector scene markers\nthe document's PlotDirector binding\n\nThe document can be linked again later if desired.\n\nContinue?`;if(!R||"function"!=typeof R.showModal)return void e(window.confirm(t));const n=t=>{U?.removeEventListener("click",r),M?.removeEventListener("click",o),R?.removeEventListener("cancel",a),R?.close(),e(t)},r=()=>n(!0),o=()=>n(!1),a=e=>{e.preventDefault(),n(!1)};U?.addEventListener("click",r),M?.addEventListener("click",o),R?.addEventListener("cancel",a),R.showModal()})){we&&(we.disabled=!0,we.textContent="Cleaning..."),ye&&(ye.disabled=!0);try{_r("Removing PlotDirector hidden anchors..."),await(async()=>{if(!un||!pn||!window.Word||"function"!=typeof window.Word.run)throw new Error("Word document access is unavailable.");return await window.Word.run(async e=>{const t=e.document.contentControls;t.load("items/tag,title"),await e.sync();let n=0,r=0;for(const e of t.items||[]){const t=Mr(e);t&&("chapter"===t?n+=1:"scene"===t&&(r+=1),e.delete(!0))}return await e.sync(),{chapterCount:n,sceneCount:r,totalCount:n+r,available:!0,message:"PlotDirector markers removed."}})})(),await new Promise(e=>{const t=window.Office?.context?.document;t&&"function"==typeof t.saveAsync?t.saveAsync(t=>{e(t.status===window.Office.AsyncResultStatus.Succeeded)}):e(!1)});try{await oo()}catch(e){return console.error("Unable to verify PlotDirector marker cleanup.",e),void _r(`PlotDirector markers were removed, but cleanup verification failed: ${Ko(e)}`)}if(jr.available&&jr.totalCount>0)return void _r(`Cleanup stopped: ${jr.totalCount} PlotDirector marker${1===jr.totalCount?"":"s"} remain.`);_r("Removing PlotDirector binding metadata...");try{await ba()}catch(e){return console.error("Unable to remove Word document metadata after marker cleanup.",e),void _r(`PlotDirector markers were removed, but Word binding metadata remains: ${Ko(e)}`)}let t="";if(e?.documentGuid&&Number.isInteger(e.bookId)&&e.bookId>0)try{await bc("/api/word-companion/manuscript/unlink",{documentGuid:e.documentGuid,bookId:e.bookId})}catch(e){console.error("Word document cleaned, but PlotDirector server unlink failed.",e),t=" Word document is clean, but unlink the Book manually in PlotDirector if it still shows as linked."}await oo().catch(()=>null),await kc(`Word document cleaned and unlinked.${t}`)}catch(e){console.error("Unable to clean PlotDirector markers.",e),_r(`Cleanup failed before unlinking: ${Ko(e)}`)}finally{we&&(we.disabled=!1,we.textContent="Clean and unlink"),ye&&(ye.disabled=!1),no(),ro()}}else _r("Clean and unlink cancelled.")}),Ze?.addEventListener("click",async()=>{const e=ta();if(!e||!gn||Sn)return void No("Chapter not found in PlotDirector.");const t=jo(gn),n=await((e,t)=>(Fo(Pt,`"${e}"`),Fo(Dt,`"${t}"`),xt?new Promise(e=>{qn=e,xt.showModal?xt.showModal():xt.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector chapter:\n\n"${e}"\n\nin book:\n\n"${t}"\n\n?`))))(t,Xo(e)||"selected book");if(n){Ze&&(Ze.disabled=!0,Ze.textContent="Creating...");try{const n=Number.isInteger(fn)&&fn>0?10*fn:null,r=await bc(`/api/word-companion/books/${e.bookId}/chapters`,{title:t,sortOrder:n});if(!r?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");So(),yo(null,r.chapterId,"Manual chapter link");if(!await Ec("Chapter created and linked successfully."))return;await Nc("Chapter created and linked successfully.")}catch(e){xo("Unable to create chapter."),Vo({lastError:Ko(e)})}finally{Ze&&(Ze.disabled=!Po(),Ze.textContent="Create Chapter in PlotDirector")}}}),et?.addEventListener("click",async()=>{const e=ta();if(e&&gn&&!Sn){et&&(et.disabled=!0,et.textContent="Loading...");try{Nn=await Oo(e.bookId),Ln=null,It&&(It.value=""),Fo(vt,""),qc(),bt?.showModal?bt.showModal():bt&&(bt.hidden=!1)}catch(e){xo("Unable to load chapters."),Vo({lastError:Ko(e)})}finally{et&&(et.disabled=!Po(),et.textContent="Link to Existing Chapter")}}else No("Chapter not found in PlotDirector.")}),It?.addEventListener("input",qc),St?.addEventListener("click",async()=>{const e=Nn.find(e=>e.chapterId===Ln);if(e){St&&(St.disabled=!0,St.textContent="Linking...");try{yo(null,e.chapterId,"Manual chapter link");if(!await Ec("Chapter linked successfully."))return;Ac(),await Nc("Chapter linked successfully.")}catch(e){Fo(vt,"Unable to link chapter."),xo("Unable to link chapter."),Vo({lastError:Ko(e)})}finally{St&&(St.disabled=!Ln,St.textContent="Link Chapter")}}else Fo(vt,"Select a chapter.")}),kt?.addEventListener("click",Ac),Et?.addEventListener("click",()=>Lc(!0)),Nt?.addEventListener("click",()=>Lc(!1)),xt?.addEventListener("cancel",e=>{e.preventDefault(),Lc(!1)}),at?.addEventListener("click",async()=>{const e=ta();if(!e||!yn)return void qo("Scene not found in PlotDirector.");const t=Ro(yn,"scene"),n=Ro(gn,"chapter"),r=await((e,t)=>(Fo(gt,`"${e}"`),Fo(yt,`"${t}"`),mt?new Promise(e=>{En=e,mt.showModal?mt.showModal():mt.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector scene:\n\n"${e}"\n\nwithin chapter:\n\n"${t}"\n\n?`))))(t,n);if(r){at&&(at.disabled=!0,at.textContent="Creating...");try{const n=await Ho();if(!n)return void qo("This chapter does not exist in PlotDirector. Create or link the chapter first.");const r=await bc(`/api/word-companion/books/${e.bookId}/chapters/${n.chapterId}/scenes`,{sceneTitle:t});if(!r?.sceneId||!r?.chapterId)throw new Error("Scene creation did not return a scene ID.");So(),await $c(r.sceneId,r.chapterId,"Scene created and linked successfully.")}catch(e){vo("Unable to create scene."),Vo({lastError:Ko(e)})}finally{at&&(at.disabled=!Do(),at.textContent="Create Scene in PlotDirector")}}}),ct?.addEventListener("click",async()=>{const e=ta();if(e&&yn){ct&&(ct.disabled=!0,ct.textContent="Loading...");try{const t=await Mo(e.bookId),n=Bo(t);if(!n)return void qo("This chapter does not exist in PlotDirector. Create or link the chapter first.");Pn=Array.isArray(n.scenes)?n.scenes:[],Dn=null,dt&&(dt.value=""),Fo(ht,""),Wc(),st?.showModal?st.showModal():st&&(st.hidden=!1)}catch(e){vo("Unable to load scenes."),Vo({lastError:Ko(e)})}finally{ct&&(ct.disabled=!Do(),ct.textContent="Link to Existing Scene")}}else qo("Scene not found in PlotDirector.")}),dt?.addEventListener("input",Wc),ut?.addEventListener("click",async()=>{const e=ta(),t=Pn.find(e=>e.sceneId===Dn);if(e&&t){ut&&(ut.disabled=!0,ut.textContent="Linking...");try{const e=await Ho();if(!e)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");jc(),await $c(t.sceneId,e.chapterId,"Scene linked successfully.")}catch(e){Fo(ht,"Unable to link scene."),vo("Unable to link scene."),Vo({lastError:Ko(e)})}finally{ut&&(ut.disabled=!Dn,ut.textContent="Link Scene")}}else Fo(ht,"Select a scene.")}),pt?.addEventListener("click",jc),wt?.addEventListener("click",()=>Tc(!0)),ft?.addEventListener("click",()=>Tc(!1)),mt?.addEventListener("cancel",e=>{e.preventDefault(),Tc(!1)}),Vt?.addEventListener("click",async()=>{Vt&&(Vt.disabled=!0,Vt.textContent="Running...");try{if(await Yo(),!un||!pn||!window.Word||"function"!=typeof window.Word.run)return void Vo({lastScan:"Failure",lastError:"Word document access is unavailable.",paragraphs:"-",heading1:"-",heading2:"-"});const e=await window.Word.run(async e=>{const t=e.document.body.paragraphs;return t.load("items"),await e.sync(),t.items.length});Vo({lastScan:"Success",lastError:"-",paragraphs:String(e)})}catch(e){console.error("Word Companion diagnostics failed.",e);const t=Ko(e);Vo({lastScan:"Failure",lastError:t}),_r(`Unable to scan the Word document: ${t}`)}finally{Vt&&(Vt.disabled=!1,Vt.textContent="Run Diagnostics")}});const ai=an?(async()=>{zo(V,"Loading projects..."),zo(K,"Select a project first"),zo(h,"Loading projects..."),zo(m,"Select a project first"),Yr(""),Jr("");try{const n=await fc("/api/word-companion/projects");if(dn=Array.isArray(n.projects)?n.projects:[],0===dn.length)return zo(V,"No projects available."),zo(h,"No projects available."),Yr("No projects available."),_o(e,null),_o(t,null),Sa(),void ma("No projects available.");Qo(V,"Choose a project",dn,"projectId","title"),ha();const r=Jo(e),o=dn.find(e=>e.projectId===r);o&&V?(V.value=String(o.projectId),h&&(h.value=String(o.projectId)),_o(e,o.projectId),await oi(o.projectId,Jo(t))):(_o(e,null),_o(t,null),Sa(),ma("Select a Project and Book to begin."))}catch{dn=[],ln=[],zo(V,"Unable to connect to PlotDirector."),zo(K,"Select a project first"),zo(h,"Unable to connect to PlotDirector."),zo(m,"Select a project first"),Kr("Unable to connect to PlotDirector."),Yr("Unable to connect to PlotDirector."),_o(e,null),_o(t,null),Sa(),ma("Unable to connect to PlotDirector.")}})():Promise.resolve();if(an||(zo(V,"Please sign in to PlotDirector."),zo(K,"Please sign in to PlotDirector."),zo(h,"Please sign in to PlotDirector."),zo(m,"Please sign in to PlotDirector."),Sa()),!window.Office||"function"!=typeof window.Office.onReady)return Hr("Word Companion ready"),_r("Word document access is unavailable."),mo("Manual"),Vo({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"}),void da().catch(e=>{console.debug("Word Companion presence unavailable.",e)});Yo().then(async()=>{Hr("Word Companion ready"),await ai,await(async()=>{if(!an||!pn)return void pa(!1);const n=wa();if(n)try{const r=await fc(`/api/word-companion/runtime/book/${n.bookId}?documentGuid=${encodeURIComponent(n.documentGuid)}`),o=r?.manuscriptDocument;if(r?.bookId===n.bookId&&r?.projectId===n.projectId&&o&&String(o.documentGuid).toLowerCase()===n.documentGuid.toLowerCase())return $n=n,Io(r),_o(e,r.projectId),_o(t,r.bookId),V&&(V.value=String(r.projectId)),await oi(r.projectId,r.bookId),pa(!1),Kr("Connected"),Jr("Bound manuscript detected."),void await Sc()}catch{}$n=null,Co(),ha(),na()?await oi(na().projectId,null):zo(m,"Select a project first"),ma("Select a Project and Book to begin."),pa(!0)})(),await da(),pn?(await oo().catch(()=>null),(()=>{if(an){if(!window.Office?.context?.document||"function"!=typeof window.Office.context.document.addHandlerAsync||!window.Office?.EventType?.DocumentSelectionChanged)return mo("Manual"),void _r("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");try{window.Office.context.document.addHandlerAsync(window.Office.EventType.DocumentSelectionChanged,ni,e=>{e?.status===window.Office.AsyncResultStatus.Succeeded?(or=!0,mo("Live")):(mo("Manual"),_r("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))}),window.addEventListener("beforeunload",ri)}catch(e){console.warn("Unable to register Word selection tracking handler.",e),mo("Manual"),_r("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}})()):(_r("Word document access is unavailable."),mo("Manual"))}).catch(e=>{console.error("Office readiness check failed.",e),Kr("Unable to connect to PlotDirector."),Hr("Word Companion unavailable"),_r("Word document access is unavailable."),Vo({ready:"No",wordApi:"No",lastScan:"Failure"})})})();