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