PlotDirector/PlotLine/wwwroot/js/word-companion-host.min.js

1 line
72 KiB
JavaScript

(()=>{const e="plotdirector.word.projectId",t="plotdirector.word.bookId",n="plotdirector.word.activeTab",r="plotdirector.word.documentGuid",a="plotdirector.word.boundBookId",o="plotdirector.word.boundProjectId",c="plotdirector.word.bindingVersion",i=new Set(["scene","links","structure","diagnostics"]),d=document.querySelector(".word-companion-shell"),s=document.querySelector(".word-companion-tabs"),l=[...document.querySelectorAll("[data-tab-button]")],u=[...document.querySelectorAll("[data-tab-panel]")],p=document.querySelector("[data-first-run-wizard]"),h=document.querySelector("[data-first-run-project-select]"),m=document.querySelector("[data-first-run-book-select]"),y=document.querySelector("[data-first-run-new-book-title]"),w=document.querySelector("[data-first-run-create-book]"),f=document.querySelector("[data-first-run-scan]"),g=document.querySelector("[data-first-run-cancel]"),S=document.querySelector("[data-first-run-status]"),C=document.querySelector("[data-first-run-summary]"),b=document.querySelector("[data-first-run-character-section]"),I=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]"),E=document.querySelector("[data-first-run-skip-characters]"),N=document.querySelector("[data-first-run-continue]"),L=document.querySelector("[data-first-run-import-actions]"),q=document.querySelector("[data-first-run-import]"),P=document.querySelector("[data-first-run-import-cancel]"),D=document.querySelector("[data-first-run-replace-dialog]"),A=document.querySelector("[data-first-run-replace-confirm]"),T=document.querySelector("[data-first-run-replace-cancel]"),$=document.querySelector("[data-office-status]"),W=document.querySelector("[data-connection-status]"),j=document.querySelector("[data-summary-connection]"),R=document.querySelector("[data-summary-project]"),U=document.querySelector("[data-summary-book]"),M=document.querySelector("[data-project-select]"),O=document.querySelector("[data-book-select]"),H=document.querySelector("[data-project-message]"),B=document.querySelector("[data-book-message]"),G=document.querySelector("[data-refresh-current-scene]"),F=document.querySelector("[data-refresh-document]"),V=document.querySelector("[data-current-chapter]"),J=document.querySelector("[data-current-scene]"),Y=document.querySelector("[data-current-word-count]"),z=document.querySelector("[data-scene-tracking-status]"),K=document.querySelector("[data-document-message]"),Q=document.querySelector("[data-sync-note]"),X=document.querySelector("[data-document-outline]"),Z=document.querySelector("[data-analyse-manuscript-structure]"),_=document.querySelector("[data-apply-structure-sync]"),ee=document.querySelector("[data-structure-preview-status]"),te=document.querySelector("[data-structure-preview-results]"),ne=document.querySelector("[data-refresh-plotdirector-scene]"),re=document.querySelector("[data-plotdirector-scene-status]"),ae=document.querySelector("[data-anchor-status]"),oe=document.querySelector("[data-anchor-book-id]"),ce=document.querySelector("[data-anchor-chapter-id]"),ie=document.querySelector("[data-anchor-scene-id]"),de=document.querySelector("[data-attach-plotdirector-ids]"),se=document.querySelector("[data-plotdirector-scene-details]"),le=document.querySelector("[data-plotdirector-scene-title]"),ue=document.querySelector("[data-plotdirector-revision-status]"),pe=document.querySelector("[data-plotdirector-estimated-words]"),he=document.querySelector("[data-plotdirector-actual-words]"),me=document.querySelector("[data-plotdirector-blocked-status]"),ye=document.querySelector("[data-plotdirector-blocked-reason-row]"),we=document.querySelector("[data-plotdirector-blocked-reason]"),fe=document.querySelector("[data-runtime-last-sync]"),ge=document.querySelector("[data-sync-scene-progress]"),Se=document.querySelector("[data-sync-word-count]"),Ce=document.querySelector("[data-sync-plotdirector-count]"),be=document.querySelector("[data-sync-last-synced]"),Ie=document.querySelector("[data-sync-status]"),ke=document.querySelector("[data-writing-brief-block]"),ve=document.querySelector("[data-writing-brief]"),xe=document.querySelector("[data-plotdirector-link-groups]"),Ee=document.querySelector("[data-character-chips]"),Ne=document.querySelector("[data-asset-chips]"),Le=(document.querySelector("[data-location-chips]"),document.querySelector("[data-primary-location-select]")),qe=document.querySelector("[data-save-scene-links]"),Pe=document.querySelector("[data-scene-links-status]"),De=document.querySelector("[data-links-editing-scene]"),Ae=document.querySelector("[data-chapter-create-link]"),Te=document.querySelector("[data-chapter-create-link-chapter]"),$e=document.querySelector("[data-create-plotdirector-chapter]"),We=document.querySelector("[data-link-existing-chapter]"),je=document.querySelector("[data-chapter-create-link-status]"),Re=document.querySelector("[data-scene-create-link]"),Ue=document.querySelector("[data-create-link-chapter]"),Me=document.querySelector("[data-create-link-scene]"),Oe=document.querySelector("[data-create-plotdirector-scene]"),He=document.querySelector("[data-link-existing-scene]"),Be=document.querySelector("[data-create-link-status]"),Ge=document.querySelector("[data-link-existing-dialog]"),Fe=document.querySelector("[data-link-scene-search]"),Ve=document.querySelector("[data-link-scene-options]"),Je=document.querySelector("[data-link-selected-scene]"),Ye=document.querySelector("[data-link-dialog-cancel]"),ze=document.querySelector("[data-link-dialog-status]"),Ke=document.querySelector("[data-create-scene-dialog]"),Qe=document.querySelector("[data-create-dialog-scene]"),Xe=document.querySelector("[data-create-dialog-chapter]"),Ze=document.querySelector("[data-create-dialog-confirm]"),_e=document.querySelector("[data-create-dialog-cancel]"),et=document.querySelector("[data-link-existing-chapter-dialog]"),tt=document.querySelector("[data-link-chapter-search]"),nt=document.querySelector("[data-link-chapter-options]"),rt=document.querySelector("[data-link-selected-chapter]"),at=document.querySelector("[data-link-chapter-dialog-cancel]"),ot=document.querySelector("[data-link-chapter-dialog-status]"),ct=document.querySelector("[data-create-chapter-dialog]"),it=document.querySelector("[data-create-chapter-dialog-chapter]"),dt=document.querySelector("[data-create-chapter-dialog-book]"),st=document.querySelector("[data-create-chapter-dialog-confirm]"),lt=document.querySelector("[data-create-chapter-dialog-cancel]"),ut=document.querySelector("[data-apply-structure-sync-dialog]"),pt=document.querySelector("[data-apply-structure-sync-summary]"),ht=document.querySelector("[data-apply-structure-sync-confirm]"),mt=document.querySelector("[data-apply-structure-sync-cancel]"),yt=document.querySelector("[data-resolve-project-id]"),wt=document.querySelector("[data-resolve-project-title]"),ft=document.querySelector("[data-resolve-book-id]"),gt=document.querySelector("[data-resolve-book-title]"),St=document.querySelector("[data-resolve-detected-chapter]"),Ct=document.querySelector("[data-resolve-detected-scene]"),bt=document.querySelector("[data-resolve-request-chapter]"),It=document.querySelector("[data-resolve-request-scene]"),kt=document.querySelector("[data-resolve-result]"),vt=document.querySelector("[data-resolve-chapter-id]"),xt=document.querySelector("[data-resolve-scene-id]"),Et=document.querySelector("[data-run-diagnostics]"),Nt=document.querySelector("[data-diagnostic-host]"),Lt=document.querySelector("[data-diagnostic-platform]"),qt=document.querySelector("[data-diagnostic-ready]"),Pt=document.querySelector("[data-diagnostic-word-api]"),Dt=document.querySelector("[data-diagnostic-last-scan]"),At=document.querySelector("[data-diagnostic-last-error]"),Tt=document.querySelector("[data-diagnostic-anchor-type]"),$t=document.querySelector("[data-diagnostic-stored-scene-id]"),Wt=document.querySelector("[data-diagnostic-stored-chapter-id]"),jt=document.querySelector("[data-diagnostic-resolution-method]"),Rt=document.querySelector("[data-diagnostic-paragraphs]"),Ut=document.querySelector("[data-diagnostic-heading1]"),Mt=document.querySelector("[data-diagnostic-heading2]"),Ot="true"===d?.dataset.authenticated;let Ht=[],Bt=[],Gt=!1,Ft=!1,Vt="Unknown",Jt="Unknown",Yt="",zt="",Kt=null,Qt=null,Xt=null,Zt=null,_t=null,en=null,tn="",nn="Title Match",rn=!1,an=[],on=null,cn=null,dn=[],sn=null,ln=null,un=null,pn=null,hn=null,mn=null,yn=null,wn=null,fn=null,gn=null,Sn=[],Cn=!1,bn=!1,In=0,kn=!1,vn=!1,xn=!1,En=null,Nn="Manual",Ln=!1,qn=null,Pn=!1,Dn=0,An=!1;const Tn=1200;let $n=!1,Wn=!1,jn=null,Rn=!1,Un=null,Mn=null,On="",Hn="",Bn=0,Gn={characters:[],assets:[],locations:[],primaryLocationId:null};const Fn=e=>{const t=Date.now();t-Bn<1e3||(Bn=t,console.debug(`[Word Companion Runtime] ${e}`))},Vn=e=>{$&&($.textContent=e)},Jn=(e,t=!0)=>{const r=i.has(e)&&l.some(t=>t.dataset.tabButton===e)?e:"scene";for(const e of l){const t=e.dataset.tabButton===r;e.classList.toggle("is-active",t),e.setAttribute("aria-selected",t?"true":"false")}for(const e of u){const t=e.dataset.tabPanel===r;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,r)},Yn=()=>{const e=(e=>{try{return window.localStorage.getItem(e)||""}catch{return""}})(n);Jn(i.has(e)?e:"scene",!1)},zn=e=>{W&&(W.textContent=e),j&&(j.textContent=e)},Kn=e=>{H&&(H.textContent=e)},Qn=e=>{B&&(B.textContent=e)},Xn=e=>{K&&(K.textContent=e)},Zn=e=>{re&&(re.textContent=e)},_n=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("anchorType")&&Br(Tt,wr(e.anchorType)),t("storedSceneId")&&Br($t,wr(e.storedSceneId)),t("storedChapterId")&&Br(Wt,wr(e.storedChapterId)),t("resolutionMethod")&&Br(jt,wr(e.resolutionMethod))},er=()=>{const e=Zr(),t=Number.isInteger(_t)&&_t>0&&Zt===_t,n=!Number.isInteger(en)||en<=0||Xt===en,r=t&&n;Br(ae,r?"Attached to PlotDirector":"Not attached"),Br(oe,e?.bookId?String(e.bookId):"-"),Br(ce,Number.isInteger(en)&&en>0?String(en):"-"),Br(ie,Number.isInteger(_t)&&_t>0?String(_t):"-"),de&&(de.disabled=!_t||r&&!rn,de.textContent=Zt&&!r?"Reattach PlotDirector IDs":"Attach PlotDirector IDs"),_n({anchorType:nn||"Title Match",storedSceneId:Zt,storedChapterId:Xt,resolutionMethod:tn})},tr=(e,t,n,r=null,a=null,o=null)=>{const c=e||"",i=t||"",d=Number.isInteger(n)?n:null,s=Number.isInteger(o)&&o>0?o:null,l=Number.isInteger(r)&&r>0?r:null,u=Number.isInteger(a)&&a>0?a:null,p=Yt===c&&zt===i&&Kt===d&&Qt===s&&Xt===l&&Zt===u;Yt=e||"",zt=t||"",Kt=Number.isInteger(n)?n:null,Qt=Number.isInteger(o)&&o>0?o:null,Xt=Number.isInteger(r)&&r>0?r:null,Zt=Number.isInteger(a)&&a>0?a:null,p||(V&&(V.textContent=e||"Not detected"),J&&(J.textContent=t||"Not detected"),Y&&(Y.textContent=Number.isInteger(n)?String(n):"-"),Br(Se,Number.isInteger(n)?String(n):"-"),er())},nr=()=>{jn&&(window.clearTimeout(jn),jn=null)},rr=(e,t)=>{e&&(e.hidden=t)},ar=e=>{Br(Ie,e)},or=e=>{Br(ee,e)},cr=(e="Select a project and book to analyse manuscript structure.")=>{if(un=null,te){te.innerHTML="";const e=document.createElement("p");e.textContent="No preview generated.",te.append(e)}or(e),dr()},ir=(e=un)=>((e=un)=>xa.flatMap(t=>Array.isArray(e?.[t.key])?e[t.key]:[]))(e).filter(e=>"couldLink"===e.category||"wouldCreateChapters"===e.category||"wouldCreateScenes"===e.category),dr=()=>{_&&(_.disabled=xn||0===ir().length)},sr=()=>{Z&&(Z.disabled=xn||!Xr()||!Zr()),dr()},lr=()=>{De&&(De.textContent=_t?`Editing links for: ${On||zt||"Current scene"}`:"Link a PlotDirector scene first.")},ur=()=>{const e=Ln||!_t,t=e||!en||Rn;ge&&(ge.disabled=t),qe&&(qe.disabled=e),Le&&(Le.disabled=e);for(const t of[Ee,Ne])for(const n of t?[...t.querySelectorAll("input[type='checkbox']")]:[])n.disabled=e},pr=e=>{"Live"!==e&&"Manual"!==e||(Nn=e),Br(z,e||Nn||"Manual")},hr=(e,t="")=>{Ln=!!e,Ln&&nr(),Br(z,Ln?"Stale":Nn),ur(),t&&(Xn(t),br(t))},mr=(e,t=null,n="")=>{_t=Number.isInteger(e)&&e>0?e:null,en=Number.isInteger(t)&&t>0?t:null,tn=n||"",_t!==Un&&(Mn=null),_t||nr(),ur(),ar(Ln?"Refresh Current Scene before syncing.":_t?"Ready to sync.":"No resolved PlotDirector scene."),br(Ln?"Refresh Current Scene before saving.":_t?"Ready to save.":"Link a PlotDirector scene first."),lr(),er()},yr=e=>{G&&(G.disabled=e,G.textContent=e?"Refreshing...":"Refresh Current Scene")},wr=e=>null==e||""===e?"-":String(e),fr=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"})}`},gr=e=>{hn=e||null;const t=hn?.lastSyncUtc||hn?.manuscriptDocument?.lastSyncUtc;Br(fe,fr(t)),Br(be,fr(t))},Sr=()=>{mn=null,yn=null,wn=null,gr(null)},Cr=()=>{yn=null,wn=null},br=e=>{Br(Pe,e)},Ir=e=>{Br(Be,e)},kr=e=>{Br(je,e)},vr=()=>!!Zr()&&!!Yt&&!en,xr=()=>!!Zr()&&!!zt&&Number.isInteger(en)&&en>0,Er=()=>{rr(Ae,!0),kr(""),$e&&($e.disabled=!0,$e.textContent="Create Chapter in PlotDirector"),We&&(We.disabled=!0,We.textContent="Link to Existing Chapter")},Nr=(e="")=>{Br(Te,wr(Yt)),rr(Ae,!1),kr(e);const t=vr();$e&&($e.disabled=!t,$e.textContent="Create Chapter in PlotDirector"),We&&(We.disabled=!t,We.textContent="Link to Existing Chapter")},Lr=()=>{rr(Re,!0),Ir(""),Oe&&(Oe.disabled=!0,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!0,He.textContent="Link to Existing Scene")},qr=(e="")=>{Br(Ue,wr(Yt)),Br(Me,wr(zt)),rr(Re,!1),Ir(e);const t=xr();Oe&&(Oe.disabled=!t,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!t,He.textContent="Link to Existing Scene")},Pr=e=>{Zn(e),rr(se,!0),rr(ke,!0),rr(xe,!1),Er(),Lr(),tn="",On="",Hn="",nn=Zt?"SceneID Anchor":Xt?"ChapterID Anchor":"Title Match",rn=!1,Gn={characters:[],assets:[],locations:[],primaryLocationId:null},Ar(Ee,[],"character"),Ar(Ne,[],"asset"),Tr([],null,!1),mr(null),Br(Ce,"-"),Br(le,"-"),Br(ue,"-"),Br(pe,"-"),Br(he,"-"),Br(me,"-"),Br(we,"-"),rr(ye,!0),er(),lr()},Dr=(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,Ar=(e,t,n,r=!1)=>{if(!e)return;e.innerHTML="";const a=Array.isArray(t)?t:[];if(0===a.length){const t=document.createElement("p");return t.className="word-companion-empty-list",t.textContent="None",void e.append(t)}for(const t of a){const a=Number.parseInt(Dr(t,n),10);if(!Number.isInteger(a)||a<=0)continue;const o=document.createElement("label");o.className="word-companion-check-item";const c=document.createElement("input");c.type="checkbox",c.value=String(a),c.checked=!!t.linked,c.disabled=!r;const i=document.createElement("span");i.textContent=t.name||"Unnamed",o.append(c,i),e.append(o)}},Tr=(e,t,n=!1)=>{if(!Le)return;Le.innerHTML="";const r=document.createElement("option");r.value="",r.textContent="None",Le.append(r);const a=Number.parseInt(t||"",10);for(const t of Array.isArray(e)?e:[]){const e=Number.parseInt(Dr(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===a,Le.append(n)}Le.disabled=!n},$r=e=>String(e||"").trim().replace(/\s+/g," "),Wr=(e,t)=>{const n=$r(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 $r(n.replace(r,""))||n},jr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("projectId")&&Br(yt,wr(e.projectId)),t("projectTitle")&&Br(wt,wr(e.projectTitle)),t("bookId")&&Br(ft,wr(e.bookId)),t("bookTitle")&&Br(gt,wr(e.bookTitle)),t("detectedChapter")&&Br(St,wr(e.detectedChapter)),t("detectedScene")&&Br(Ct,wr(e.detectedScene)),t("requestChapter")&&Br(bt,wr(e.requestChapter)),t("requestScene")&&Br(It,wr(e.requestScene)),t("result")&&Br(kt,wr(e.result)),t("chapterId")&&Br(vt,wr(e.chapterId)),t("sceneId")&&Br(xt,wr(e.sceneId))},Rr=async e=>{if(wn===e&&Array.isArray(yn?.chapters))return yn.chapters;const t=await za(`/api/word-companion/books/${e}/structure`);return wn=e,yn=t||null,Array.isArray(t?.chapters)?t.chapters:[]},Ur=async e=>{const t=await za(`/api/word-companion/books/${e}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},Mr=e=>{if(Number.isInteger(en)&&en>0){const t=e.find(e=>e.chapterId===en);if(t)return t}const t=Wr(Yt,"chapter").toLocaleLowerCase();return t&&e.find(e=>Wr(e.title,"chapter").toLocaleLowerCase()===t)||null},Or=async()=>{const e=Zr();return e?Mr(await Rr(e.bookId)):null},Hr=async(e,t,n,r,a)=>{const o=await za(`/api/word-companion/scenes/${t}/companion`);try{o.revisionStatus=await(async(e,t)=>{const n=await za(`/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{o.revisionStatus=""}var c;nn=a||"Title Match",rn=!1,hr(!1),Zn("Linked to PlotDirector"),Xn(""),Er(),Lr(),mr(t,n,r),c=o,On=c?.sceneTitle||zt||"",Hn=c?.chapterTitle||Yt||"",Br(le,wr(c?.sceneTitle)),Br(ue,wr(c?.revisionStatus||c?.revisionStatusName||"Not provided")),Br(pe,wr(c?.estimatedWords)),Br(he,wr(c?.actualWords)),Br(Ce,wr(c?.actualWords)),Br(me,c?.blocked?"Blocked":"Not blocked"),c?.blockedReason?(Br(we,c.blockedReason),rr(ye,!1)):(Br(we,"-"),rr(ye,!0)),ve&&(ve.textContent=c?.writingBrief||"No writing brief has been added for this scene."),Gn={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},Ar(Ee,Gn.characters,"character",!!_t&&!Ln),Ar(Ne,Gn.assets,"asset",!!_t&&!Ln),Tr(Gn.locations,Gn.primaryLocationId,!!_t&&!Ln),lr(),br(Ln?"Refresh Current Scene before saving.":_t?"Ready to save.":"No resolved PlotDirector scene."),rr(se,!1),rr(ke,!1),rr(xe,!1),ho()},Br=(e,t)=>{if(e){const n=null==t?"":String(t);e.textContent!==n&&(e.textContent=n)}},Gr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("host")&&Br(Nt,e.host),t("platform")&&Br(Lt,e.platform),t("ready")&&Br(qt,e.ready),t("wordApi")&&Br(Pt,e.wordApi),t("lastScan")&&Br(Dt,e.lastScan),t("lastError")&&Br(At,e.lastError),t("paragraphs")&&Br(Rt,e.paragraphs),t("heading1")&&Br(Ut,e.heading1),t("heading2")&&Br(Mt,e.heading2)},Fr=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)},Vr=async()=>{if(!window.Office||"function"!=typeof window.Office.onReady)return Gt=!1,Ft=!1,Vt="Unavailable",Jt="Unavailable",Gr({host:Vt,platform:Jt,ready:"No",wordApi:"No"}),null;const e=await window.Office.onReady();return Gt=!0,Vt=e?.host||"Unknown",Jt=e?.platform||"Unknown",Ft=!!window.Word&&!!window.Office.HostType&&e?.host===window.Office.HostType.Word,Gr({host:Vt,platform:Jt,ready:"Yes",wordApi:Ft?"Yes":"No"}),e},Jr=e=>{try{const t=window.localStorage.getItem(e),n=Number.parseInt(t||"",10);return Number.isInteger(n)&&n>0?n:null}catch{return null}},Yr=(e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}},zr=(e,t)=>{if(!e)return;e.innerHTML="";const n=document.createElement("option");n.value="",n.textContent=t,e.append(n),e.disabled=!0},Kr=(e,t,n,r,a)=>{if(!e)return;e.innerHTML="";const o=document.createElement("option");o.value="",o.textContent=t,e.append(o);for(const t of n){const n=document.createElement("option");n.value=String(t[r]),n.textContent=t[a],e.append(n)}e.disabled=0===n.length},Qr=e=>{const t=String(e?.title||"").trim(),n=String(e?.subtitle||"").trim();return n?`${t}: ${n}`:t},Xr=()=>{const e=Number.parseInt(M?.value||"",10);return Ht.find(t=>t.projectId===e)||null},Zr=()=>{const e=Number.parseInt(O?.value||"",10);return Bt.find(t=>t.bookId===e)||null},_r=()=>{const e=Number.parseInt(h?.value||"",10);return Ht.find(t=>t.projectId===e)||null},ea=()=>{const e=Number.parseInt(m?.value||"",10);return Bt.find(t=>t.bookId===e)||null},ta=e=>Br(S,e),na=()=>{const e=_r(),t=ea(),n=bn&&Date.now()-In>=750;f&&(f.disabled=!e||!t||kn),w&&(w.disabled=!e||!String(y?.value||"").trim()||kn),q&&(q.disabled=!fn?.canImport||!gn||kn),x&&(x.disabled=!n||vn||0===ca().length)},ra=e=>{rr(p,!e),rr(s,e);for(const t of u)rr(t,!!e||"scene"!==t.dataset.tabPanel&&!t.classList.contains("is-active"));e||Yn()},aa=()=>{if(!h)return;if(0===Ht.length)return void zr(h,"No projects available.");Kr(h,"Choose a project",Ht,"projectId","title");const e=Number.parseInt(M?.value||"",10);Number.isInteger(e)&&e>0&&(h.value=String(e))},oa=(e="Select a Project and Book to begin.")=>{fn=null,gn=null,Sn=[],Cn=!1,bn=!1,In=0,rr(C,!0),rr(L,!0),rr(b,!0),rr(v,!0),C&&(C.innerHTML=""),k&&(k.innerHTML=""),Br(I,""),ta(e),na()},ca=()=>k?[...k.querySelectorAll("input[type='checkbox']:checked")].map(e=>String(e.value||"").trim()).filter(Boolean):[],ia=e=>{if(Sn=Array.isArray(e)?e:[],b&&k){if(k.innerHTML="",rr(b,!1),rr(v,!Cn||0===Sn.length),rr(x,!1),rr(E,!1),rr(N,!0),0===Sn.length)return Br(I,"No likely major characters found."),void na();Br(I,`${Sn.length} likely major characters found.`);for(const e of Sn){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",na);const r=document.createElement("strong");r.textContent=e.text||"";const a=document.createElement("em"),o=String(e.reason||"").trim();a.textContent=o?`${Number(e.mentionCount||0).toLocaleString()} mentions · ${o}`:`${Number(e.mentionCount||0).toLocaleString()} mentions`;const c=document.createElement("span");c.className="word-companion-character-candidate-text",c.append(r,a),t.append(n,c),k.append(t)}na()}},da=()=>{const e=window.Office?.context?.document?.settings;if(!e)return null;const t=String(e.get(r)||"").trim(),n=Number.parseInt(e.get(a)||"",10),i=Number.parseInt(e.get(o)||"",10),d=Number.parseInt(e.get(c)||"",10);return!t||!Number.isInteger(n)||n<=0||!Number.isInteger(i)||i<=0?null:{documentGuid:t,bookId:n,projectId:i,bindingVersion:Number.isInteger(d)&&d>0?d:1}},sa=()=>pn?.documentGuid?pn.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)),la=()=>{const e=Xr(),t=Zr();R&&(R.textContent=e?.title||"(Not connected)"),U&&(U.textContent=t?Qr(t):"(Not connected)"),Q&&(Q.textContent=t?"":"Select a PlotDirector book before refreshing."),sr()},ua=e=>String(e?.styleBuiltIn||e?.style||"").replace(/\s+/g,"").toLowerCase(),pa=(e,t)=>{const n=ua(e);return n===`heading${t}`||n.endsWith(`.heading${t}`)||n.includes(`heading${t}`)},ha=e=>String(e||"").trim().split(/\s+/).filter(Boolean).length,ma=(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},ya=e=>{try{return Array.isArray(e?.contentControls?.items)?e.contentControls.items:[]}catch(e){return console.warn("Word paragraph content controls were not available.",e),[]}},wa=(e,t)=>{const n=ya(e);for(const e of n){const n=ma(e.tag,t);if(n)return n}return null},fa=(e,t)=>{const n=[];let r=0,a=0,o=null,c=null;e.forEach((e,t)=>{const i=String(e.text||"").trim();if(i){if(pa(e,1))return r+=1,o={index:n.length+1,paragraphIndex:t,title:i,anchorId:wa(e,"PD-CHAPTER"),scenes:[]},n.push(o),void(c=null);if(pa(e,2)){if(a+=1,!o)return;return c={index:o.scenes.length+1,paragraphIndex:t,title:i,anchorId:wa(e,"PD-SCENE"),wordCount:0},void o.scenes.push(c)}c&&(c.wordCount+=ha(i))}});const i=t.find(e=>String(e.text||"").trim()),d=i?e.findIndex(e=>{return t=e,n=i,String(t?.text||"").trim()===String(n?.text||"").trim()&&ua(t)===ua(n);var t,n}):-1,s=d>=0&&n.filter(e=>e.paragraphIndex<=d).at(-1)||null,l=s&&d>=0&&s.scenes.filter(e=>e.paragraphIndex<=d).at(-1)||null;return{chapters:n,currentChapter:s,currentScene:l,paragraphCount:e.length,heading1Count:r,heading2Count:a}},ga=new Set(["***","###"]),Sa=(e,t)=>{const n=String(e?.text||"").trim();return{index:t,text:n,styleBuiltIn:e?.styleBuiltIn||"",style:e?.style||"",wordCount:ha(n),chapterAnchorId:null,sceneAnchorId:null}},Ca=(e,t)=>{e&&(e.endParagraphIndex=t)},ba=(e,t)=>{e&&(e.endParagraphIndex=t,Ca(e.scenes.at(-1),t))},Ia=(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()&&ua(e)===ua(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]},ka=e=>{if(!mn)return!1;const t=((e,t)=>!e||!Number.isInteger(t)||t<0?null:e.chapters.filter(e=>e.startParagraphIndex<=t).at(-1)||null)(mn,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!==mn.currentChapter?.startParagraphIndex||n?.startParagraphIndex!==mn.currentScene?.startParagraphIndex||t?.anchorId!==mn.currentChapter?.anchorId||n?.anchorId!==mn.currentScene?.anchorId;return mn.currentParagraphIndex=e,mn.currentChapter=t,mn.currentScene=n,!!r&&(tr(t?.title,n?.title,n?.wordCount,t?.anchorId,n?.anchorId,t?.index),r)},va=e=>{if(!X)return;if(X.innerHTML="",0===e.chapters.length){const e=document.createElement("p");return e.textContent="No chapters detected. Use Heading 1 for chapter titles.",void X.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.",X.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)}X.append(e)}},xa=[{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"}],Ea={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},Na={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},La=(e,t)=>Wr(e,t).toLocaleLowerCase(),qa=({category:e,action:t,type:n,wordTitle:r,match:a="",anchorStatus:o="None",matches:c=[],pdChapter:i=null,pdScene:d=null,wordChapter:s=null,wordScene:l=null,parentItem:u=null})=>({id:`${n}-${s?.index||0}-${l?.index||0}-${s?.paragraphIndex??l?.paragraphIndex??0}`,category:e,action:t,type:n,wordTitle:r,match:a,anchorStatus:o,matches:c,pdChapter:i,pdScene:d,wordChapter:s,wordScene:l,parentItem:u,result:"Pending",error:""}),Pa=(e,t)=>{Array.isArray(e[t.category])&&e[t.category].push(t)},Da=e=>Array.isArray(e?.scenes)?e.scenes:[],Aa=(e,t,n)=>{const r=e.anchorId?`PD-CHAPTER-${e.anchorId}`:"None";if(e.anchorId){const a=t.find(t=>t.chapterId===e.anchorId);if(a){const t=qa({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:e.title,match:`Chapter ${a.chapterId}: ${a.title}`,anchorStatus:r,pdChapter:a,wordChapter:e});return Pa(n,t),t}const o=qa({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:`${r} not found`,matches:[],pdChapter:null,wordChapter:e});return Pa(n,o),o}const a=t.filter(t=>La(t.title,"chapter")===La(e.title,"chapter"));if(1===a.length){const t=qa({category:"couldLink",action:"couldLink",type:"Chapter",wordTitle:e.title,match:`Chapter ${a[0].chapterId}: ${a[0].title}`,anchorStatus:r,pdChapter:a[0],wordChapter:e});return Pa(n,t),t}if(a.length>1){const t=qa({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:r,matches:a.map(e=>`Chapter ${e.chapterId}: ${e.title}`),pdChapter:null,wordChapter:e});return Pa(n,t),t}const o=qa({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:e.title,anchorStatus:r,pdChapter:null,wordChapter:e});return Pa(n,o),o},Ta=(e,t,n,r)=>{const a=e.anchorId?`PD-SCENE-${e.anchorId}`:"None";if(e.anchorId){const o=((e,t)=>{for(const n of e){const e=Da(n).find(e=>e.sceneId===t);if(e)return{chapter:n,scene:e}}return null})(n,e.anchorId);return o?void Pa(r,qa({category:"alreadyLinked",action:"alreadyLinked",type:"Scene",wordTitle:e.title,match:`Scene ${o.scene.sceneId}: ${o.scene.title}`,anchorStatus:a,pdChapter:o.chapter,pdScene:o.scene,wordChapter:t?.wordChapter,wordScene:e,parentItem:t})):void Pa(r,qa({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:`${a} not found`,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}))}if(!t?.pdChapter&&"manualReview"===t?.category)return void Pa(r,qa({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:a,matches:["Parent chapter requires manual review."],wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));if(!t?.pdChapter)return void Pa(r,qa({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:a,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));const o=Da(t.pdChapter).filter(t=>La(t.title,"scene")===La(e.title,"scene"));1!==o.length?o.length>1?Pa(r,qa({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:a,matches:o.map(e=>`Scene ${e.sceneId}: ${e.title}`),wordChapter:t.wordChapter,wordScene:e,parentItem:t})):Pa(r,qa({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:a,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:e,parentItem:t})):Pa(r,qa({category:"couldLink",action:"couldLink",type:"Scene",wordTitle:e.title,match:`Scene ${o[0].sceneId}: ${o[0].title}`,anchorStatus:a,pdChapter:t.pdChapter,pdScene:o[0],wordChapter:t.wordChapter,wordScene:e,parentItem:t}))},$a=e=>{const t=document.createElement("article");t.className="word-companion-preview-item";const n=document.createElement("strong");n.textContent=`${Na[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 a=document.createElement("ul");for(const t of e.matches){const e=document.createElement("li");e.textContent=t,a.append(e)}n.append(a),t.append(n)}const a=document.createElement("span");if(a.textContent=`Action: ${Ea[e.action]||e.action}`,t.append(a),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},Wa=e=>{if(te){te.innerHTML="";for(const t of xa){const n=document.createElement("section");n.className="word-companion-preview-group";const r=document.createElement("strong");r.textContent=t.title,n.append(r);const a=Array.isArray(e?.[t.key])?e[t.key]:[];if(0===a.length){const e=document.createElement("p");e.className="word-companion-empty-list",e.textContent="None",n.append(e)}else for(const e of a)n.append($a(e));te.append(n)}dr()}},ja=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)(pa(e,1)||pa(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=fa(t.items,n.items);return r.bodyParagraphs=t.items,r},Ra=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 a=((e,t)=>{const n=e.map(Sa),r=[];let a=0,o=0,c=null,i=null,d=0;const s=(e,t=null,n=null)=>c?(Ca(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&&(pa(e,1)?(ba(c,e.index-1),a+=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,s(e,"Scene 1",e.sceneAnchorId),d+=e.wordCount):c&&(t&&ga.has(e.text)?(o+=1,s(e)):(c.wordCount+=e.wordCount,i&&(i.wordCount+=e.wordCount),d+=e.wordCount)));return ba(c,n.length-1),{paragraphs:n,chapters:r,usesExplicitScenes:!!t,paragraphCount:n.length,heading1Count:a,heading2Count:o,documentWordCount:d,currentParagraphIndex:null,currentChapter:null,currentScene:null}})(n.items,t),o=Ia(a,r.items);return mn=a,ka(o),Fn("Cache rebuilt."),a},Ua=async()=>{const e=mn?.currentScene;return e&&Number.isInteger(e.startParagraphIndex)&&Number.isInteger(e.endParagraphIndex)&&Gt&&Ft&&window.Word&&"function"==typeof window.Word.run?await window.Word.run(async t=>{const n=t.document.body.paragraphs;n.load("text"),await t.sync();let r=0;const a=Math.min(e.endParagraphIndex,n.items.length-1),o=mn.currentChapter?.startParagraphIndex;for(let t=e.startParagraphIndex;t<=a;t+=1){const e=String(n.items[t]?.text||"").trim();e&&!ga.has(e)&&t!==o&&(r+=ha(e))}return e.wordCount=r,tr(mn.currentChapter?.title,e.title,r,mn.currentChapter?.anchorId,e.anchorId,mn.currentChapter?.index),r}):Kt},Ma=async()=>{if(Xn(""),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return tr(null,null,null),Xn("Word document access is unavailable."),Gr({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;F&&(F.disabled=!0,F.textContent="Scanning..."),Xn("Scanning document structure...");try{const e=await window.Word.run(async e=>{const t=Zr();return t?await Ra(e,!!t.usesExplicitScenes):(mn=null,await ja(e))});return mn||tr(e.currentChapter?.title,e.currentScene?.title,e.currentScene?.wordCount,e.currentChapter?.anchorId,e.currentScene?.anchorId,e.currentChapter?.index),Pr("Not detected"),va(e),Xn(""),Gr({lastScan:"Success",lastError:"-",paragraphs:String(e.paragraphCount),heading1:String(e.heading1Count),heading2:String(e.heading2Count)}),!0}catch(e){const t=Fr(e);return console.error("Unable to scan the Word document.",e),tr(null,null,null),Xn(`Unable to scan the Word document: ${t}`),Gr({lastScan:"Failure",lastError:t}),!1}finally{F&&(F.disabled=!1,F.textContent="Refresh Document Structure")}},Oa=async()=>{const e=Zr();if(!Xr()||!e)return or("Select a project and book to analyse manuscript structure."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return or("Word document access is unavailable."),Gr({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;Z&&(Z.disabled=!0,Z.textContent="Analysing..."),or("Analysing manuscript structure...");try{const t=await window.Word.run(async e=>await ja(e)),n=await za(`/api/word-companion/books/${e.bookId}/structure`);return tr(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),va(t),un=((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=Aa(t,r,n);for(const a of Da(t))Ta(a,e,r,n)}return n})(t,n),Wa(un),or("Preview generated. No changes have been applied."),Gr({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),or("Unable to analyse manuscript structure."),Gr({lastScan:"Failure",lastError:Fr(e)}),!1}finally{Z&&(Z.textContent="Analyse Manuscript Structure",sr())}},Ha=e=>{En&&(En(e),En=null),ut?.close?ut.close():ut&&(ut.hidden=!0)},Ba=()=>{const e=((e=un)=>{const t=ir(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(!pt)return;pt.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)}pt.append(n)})(e),ut?new Promise(e=>{En=e,ut.showModal?ut.showModal():ut.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.`))},Ga=(e,t,n="")=>{e.result=t,e.error=n},Fa=e=>Number.isInteger(e?.wordChapter?.index)&&e.wordChapter.index>0?10*e.wordChapter.index:null,Va=e=>Number.isInteger(e?.wordScene?.index)&&e.wordScene.index>0?10*e.wordScene.index:null,Ja=async(e,t)=>{const n=await Ka(`/api/word-companion/books/${e}/chapters`,{title:$r(t.wordTitle),sortOrder:Fa(t)});if(!n?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");Cr(),t.pdChapter={chapterId:n.chapterId,title:n.title||t.wordTitle,sortOrder:n.sortOrder||Fa(t)||0,scenes:[]},t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},Ya=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 Ka(`/api/word-companion/books/${e}/chapters/${n.chapterId}/scenes`,{sceneTitle:$r(t.wordTitle),sortOrder:Va(t)});if(!r?.sceneId)throw new Error("Scene creation did not return a scene ID.");Cr(),t.pdChapter=n,t.pdScene={sceneId:r.sceneId,title:t.wordTitle,sortOrder:Va(t)||0},t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},za=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()},Ka=(e,t)=>za(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),Qa=async(e="")=>{bn=!1,In=0,Sn=[],k&&(k.innerHTML=""),rr(b,!0),ra(!1),ta(""),rr(v,!0),e&&Xn(e);const t=await Xa();e&&t&&Yt&&Xn(e)},Xa=async()=>{const e=Zr();if(!(e&&Gt&&Ft&&window.Word&&"function"==typeof window.Word.run))return!1;Xn("Reading manuscript position...");try{Cr(),await Rr(e.bookId);const t=await window.Word.run(async t=>await Ra(t,!!e.usesExplicitScenes));return va(t),Gr({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),Yt?(zt?await yo():await mo(),hr(!1),pr("Live"),Xn(""),!0):(Pr("Not detected"),hr(!1),pr("Live"),Xn("Manuscript linked. Click inside a chapter to show the current scene."),!0)}catch(e){return console.error("Unable to initialise bound manuscript runtime.",e),mn=null,pr("Manual"),Xn(`Unable to read manuscript position: ${Fr(e)}`),Gr({lastScan:"Failure",lastError:Fr(e)}),!1}},Za=e=>e?[...e.querySelectorAll("input[type='checkbox']:checked")].map(e=>Number.parseInt(e.value||"",10)).filter(e=>Number.isInteger(e)&&e>0):[],_a=()=>{const e=Number.parseInt(Le?.value||"",10);return Number.isInteger(e)&&e>0?e:null},eo=(e,t,n,r)=>{const a=((e,t)=>ya(e).find(e=>ma(e.tag,t))||null)(e,r),o=a||e.getRange().insertContentControl();return o.title=t,o.tag=n,o.appearance="Hidden",o},to=async(e="PlotDirector IDs attached successfully.")=>{if(!_t||!en)return Xn("No resolved PlotDirector scene."),!1;if((Zt&&Zt!==_t||Xt&&Xt!==en)&&!window.confirm("This scene is already linked. Replace the existing PlotDirector link?"))return!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Xn("Word document access is unavailable."),!1;de&&(de.disabled=!0,de.textContent="Attaching...");try{return await window.Word.run(async e=>{const t=await ja(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.");eo(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),eo(r,"PlotDirector Scene",`PD-SCENE-${_t}`,"PD-SCENE"),await e.sync()}),Xt=en,Zt=_t,rn=!1,nn="SceneID Anchor",tn="Anchor",Xn(e),Gr({lastError:"-"}),er(),!0}catch(e){return console.error("Unable to attach PlotDirector IDs.",e),Xn("Unable to attach PlotDirector IDs."),Gr({lastError:Fr(e)}),er(),!1}finally{de&&(de.textContent=Zt===_t?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",er())}},no=async e=>{if(!en)return kr("No resolved PlotDirector chapter."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return kr("Word document access is unavailable."),!1;try{return await window.Word.run(async e=>{const t=await ja(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.");eo(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),await e.sync()}),Xt=en,rn=!1,nn="ChapterID Anchor",tn="Chapter anchor",kr(e),Xn(e),Gr({lastError:"-"}),er(),!0}catch(e){return console.error("Unable to attach PlotDirector chapter ID.",e),kr("Unable to attach PlotDirector chapter ID."),Gr({lastError:Fr(e)}),er(),!1}},ro=async e=>{Er(),await yo(),Xn(e),kr(e)},ao=e=>{ln&&(ln(e),ln=null),ct?.close?ct.close():ct&&(ct.hidden=!0)},oo=()=>{if(!nt)return;const e=$r(tt?.value||"").toLocaleLowerCase(),t=dn.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(nt.innerHTML="",sn=null,rt&&(rt.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No chapters found.",void nt.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",()=>{sn=t,rt&&(rt.disabled=!1)});const a=document.createElement("span");a.textContent=e.title||"Untitled chapter",n.append(r,a),nt.append(n)}},co=()=>{et?.close?et.close():et&&(et.hidden=!0)},io=async(e,t,n)=>{const r=Zr();if(!r)return Ir("Select a PlotDirector book first."),!1;await Hr(r.bookId,e,t,"Manual link","Title Match");return!!await to(n)&&(Ir(n),Lr(),!0)},so=e=>{cn&&(cn(e),cn=null),Ke?.close?Ke.close():Ke&&(Ke.hidden=!0)},lo=()=>{if(!Ve)return;const e=$r(Fe?.value||"").toLocaleLowerCase(),t=an.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(Ve.innerHTML="",on=null,Je&&(Je.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No scenes found.",void Ve.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",()=>{on=t,Je&&(Je.disabled=!1)});const a=document.createElement("span");a.textContent=e.title||"Untitled scene",n.append(r,a),Ve.append(n)}},uo=()=>{Ge?.close?Ge.close():Ge&&(Ge.hidden=!0)},po=async()=>{if(!_t)return void ar("No resolved PlotDirector scene.");if(!en)return void ar("No resolved PlotDirector chapter.");if(Ln)return void ar("Refresh Current Scene before syncing.");const e=Zr(),t=pn?.documentGuid||da()?.documentGuid||"";if(!e||!t)return void ar("Bound manuscript metadata is unavailable.");if(Rn)return;nr(),Rn=!0;let n=Kt;try{n=await Ua()}catch(e){return ar("Sync failed"),Gr({lastError:Fr(e)}),Rn=!1,void ur()}if(!Number.isInteger(n)||n<0)return ar("Sync failed"),Rn=!1,void ur();if(Un===_t&&Mn===n)return ar("Synced"),Rn=!1,void ur();ge&&(ge.disabled=!0,ge.textContent="Syncing..."),ar("Syncing...");try{const r=await Ka("/api/word-companion/runtime/scene-word-count",{documentGuid:t,bookId:e.bookId,chapterId:en,sceneId:_t,wordCount:n}),a=r?.actualWords??n,o=new Date;Un=_t,Mn=a,Br(Ce,wr(a)),Br(he,wr(a)),Br(be,fr(o)),Br(fe,fr(o)),ar("Synced")}catch(e){ar("Sync failed"),Gr({lastError:Fr(e)})}finally{Rn=!1,ge&&(ge.textContent="Sync Current Scene"),ur()}},ho=(e=4e3)=>{nr(),_t&&en&&!Ln&&!Rn&&(jn=window.setTimeout(()=>{jn=null,po()},e))},mo=async()=>{const e=Xr(),t=Zr(),n=Wr(Yt,"chapter");if(jr({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Qr(t):void 0,detectedChapter:Yt,detectedScene:zt,requestChapter:n,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!t)return Pr("Not detected"),Xn("Select a PlotDirector book first."),!1;if(!Yt)return Pr("Not detected"),Xn("No chapter detected in Word. Use Heading 1 for chapters."),!1;Pr("Not detected");try{const e=await Ur(t.bookId),r=Xt?e.find(e=>e.chapterId===Xt):null,a=n.toLocaleLowerCase(),o=a?e.find(e=>Wr(e.title,"chapter").toLocaleLowerCase()===a):null,c=r||o;return c?(Er(),mr(null,c.chapterId,r?"Chapter anchor":"Chapter title"),nn=r?"ChapterID Anchor":"Title Match",Zn("Chapter linked to PlotDirector"),Xn("No scene detected in Word. Use Heading 2 for scenes."),jr({result:"Chapter matched",chapterId:c.chapterId,sceneId:null}),!0):(mr(null),Zn("Chapter not found in PlotDirector."),Xn("Chapter not found in PlotDirector."),jr({result:"Chapter not matched",chapterId:null,sceneId:null}),Nr("Chapter not found in PlotDirector."),!1)}catch(e){return Pr("Not found in PlotDirector"),Gr({lastError:Fr(e)}),Xn("Unable to load PlotDirector chapter data."),!1}},yo=async()=>{const e=Xr(),t=Zr(),n=Wr(Yt,"chapter"),r=Wr(zt,"scene");if(jr({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Qr(t):void 0,detectedChapter:Yt,detectedScene:zt,requestChapter:n,requestScene:r,result:"Not run",chapterId:null,sceneId:null}),_n({anchorType:Zt?"SceneID Anchor":Xt?"ChapterID Anchor":"Title Match",storedSceneId:Zt,storedChapterId:Xt,resolutionMethod:"-"}),!t)return Pr("Not detected"),Xn("Select a PlotDirector book first."),jr({result:"Error"}),!1;if(!Yt||!zt)return Pr("Not detected"),Xn("No scene detected in Word. Use Heading 2 for scenes."),jr({result:"Error"}),!1;ne&&(ne.disabled=!0,ne.textContent="Refreshing...");const a=()=>{ne&&(ne.disabled=!1,ne.textContent="Refresh PlotDirector Scene")};Pr("Not detected"),Xn("Resolving PlotDirector scene...");try{if(Zt){const e=await(async(e,t)=>{const n=await za(`/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===Zt);if(e)return jr({result:"Matched",chapterId:e.chapter.chapterId,sceneId:e.scene.sceneId}),await Hr(t.bookId,e.scene.sceneId,e.chapter.chapterId,"Anchor","SceneID Anchor"),!0;rn=!0,nn="SceneID Anchor",Zn("Not found in PlotDirector"),Xn("Stored PlotDirector ID is invalid."),jr({result:"Error",chapterId:Xt,sceneId:Zt}),_n({anchorType:"SceneID Anchor",storedSceneId:Zt,storedChapterId:Xt,resolutionMethod:"Anchor"})}if(Xt){const e=(await Rr(t.bookId)).find(e=>e.chapterId===Xt),n=e?(Array.isArray(e.scenes)?e.scenes:[]).find(e=>Wr(e.title,"scene").toLocaleLowerCase()===r.toLocaleLowerCase()):null;if(n)return jr({result:"Matched",chapterId:e.chapterId,sceneId:n.sceneId}),await Hr(t.bookId,n.sceneId,e.chapterId,"Anchor","ChapterID Anchor"),!0;e&&!Zt?(nn="ChapterID Anchor",mr(null,Xt,"Chapter anchor"),jr({result:"Chapter matched",chapterId:Xt,sceneId:null})):Zt||(nn="ChapterID Anchor",jr({result:"Chapter anchor not found",chapterId:Xt,sceneId:null}))}const e=await Ka(`/api/word-companion/books/${t.bookId}/resolve-scene`,{chapterTitle:n,sceneTitle:r});if(!e?.matched||!e.sceneId){const t=rn,n=Number.parseInt(e?.chapterId||"",10),r=Number.isInteger(en)&&en>0?en:null,o=Number.isInteger(n)&&n>0?n:r,c=!!e?.chapterMatched||!!o;return Pr("Not found in PlotDirector"),rn=t,c&&(mr(null,o,o===r?"Chapter anchor":"Chapter title"),Zn("Scene not found in PlotDirector.")),Xn(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."),jr({result:"Not matched",chapterId:c?o:e?.chapterId,sceneId:e?.sceneId}),t||(c?(Er(),qr("Scene not found in PlotDirector.")):(Lr(),Nr("Chapter not found in PlotDirector."))),a(),!1}const o=rn;return jr({result:o?"Matched by title fallback":"Matched",chapterId:e.chapterId,sceneId:e.sceneId}),await Hr(t.bookId,e.sceneId,e.chapterId,o?"Title fallback":"Title","Title Match"),o&&(rn=!0,Xn("Stored PlotDirector ID is invalid."),er()),!0}catch(e){const t=rn;return Gr({lastError:Fr(e)}),Pr("Not found in PlotDirector"),rn=t,Xn(t?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),jr({result:"Error"}),!1}finally{a()}},wo=async()=>{if(qn=null,Wn)return An=!0,void Fn("Runtime update deferred; update already running.");if(!Ot||!Zr())return Pn=!1,void Fn("Runtime update skipped.");if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Pn=!1,pr("Manual"),void Xn("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");if(!mn)return Pn=!1,pr("Manual"),void Xn("Document structure is not cached yet. Use Refresh Current Scene.");const e=Date.now()-Dn;if(Pn&&e<Tn)return Fn("Runtime update skipped (typing active)."),void fo(Tn-e);Wn=!0,Pn=!1,An=!1,pr("Updating..."),Fn("Runtime update executed.");try{const e=await window.Word.run(async e=>await(async e=>{const t=e.document.getSelection().paragraphs;return t.load("text,styleBuiltIn,style"),await e.sync(),t.items})(e)),t=Ia(mn,e),n=ka(t);if(await Ua(),!n)return hr(!1),pr("Current scene updated"),void ho();zt?await yo():await mo(),hr(!1),pr("Current scene updated"),Xn("Current scene updated."),ho()}catch(e){console.error("Unable to refresh current scene from Word selection.",e),Gr({lastError:Fr(e)}),hr(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving.")}finally{Wn=!1,(An||Pn)&&(An=!1,fo(Tn))}},fo=(e=1200)=>{qn&&window.clearTimeout(qn),qn=window.setTimeout(wo,Math.max(0,e)),pr("Waiting for typing to pause"),Fn("Runtime update scheduled.")},go=()=>{((e="selection",t=1200)=>{if(Pn=!0,Dn=Date.now(),nr(),Fn(`${e} changed.`),Wn)return An=!0,void pr("Waiting for typing to pause");fo(t)})("Selection")},So=()=>{if($n&&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:go}),$n=!1}catch(e){console.warn("Unable to remove Word selection tracking handler.",e)}},Co=async(e,n)=>{if(mn=null,Cr(),!e)return Bt=[],zr(O,"Select a project first"),zr(m,"Select a project first"),Qn(""),Yr(t,null),la(),Pr("Not detected"),void cr();zr(O,"Loading books..."),Qn(""),Pr("Not detected"),cr("Select a book to analyse manuscript structure.");try{const r=await za(`/api/word-companion/projects/${e}/books`);if(Bt=Array.isArray(r.books)?r.books:[],0===Bt.length)return zr(O,"No books available."),zr(m,"No books available."),Qn("No books available."),Yr(t,null),la(),void oa("No books available.");Kr(O,"Choose a book",Bt.map(e=>({...e,displayTitle:Qr(e)})),"bookId","displayTitle");const a=Bt.find(e=>e.bookId===n);a&&O?(O.value=String(a.bookId),Yr(t,a.bookId)):Yr(t,null),((e=null)=>{if(!m)return;if(0===Bt.length)return void zr(m,"No books available.");Kr(m,"Choose a book",Bt.map(e=>({...e,displayTitle:Qr(e)})),"bookId","displayTitle");const t=e||Number.parseInt(O?.value||"",10),n=Bt.find(e=>e.bookId===t);n&&(m.value=String(n.bookId)),na()})(a?.bookId||n),la(),Pr((Zr(),"Not detected")),cr(Zr()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),oa(ea()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{Bt=[],zr(O,"Unable to load books."),zr(m,"Unable to load books."),Qn("Unable to load books."),Yr(t,null),la(),Pr("Not detected"),cr("Unable to load books."),oa("Unable to load books.")}};for(const e of l)e.addEventListener("click",()=>Jn(e.dataset.tabButton));Yn(),M?.addEventListener("change",async()=>{const n=Number.parseInt(M.value||"",10);Sr(),h&&Number.isInteger(n)&&n>0&&(h.value=String(n)),Yr(e,Number.isInteger(n)&&n>0?n:null),Yr(t,null),Pr("Not detected"),cr(),oa("Select a Book to begin."),await Co(n,null)}),O?.addEventListener("change",()=>{const e=Number.parseInt(O.value||"",10);Sr(),Yr(t,Number.isInteger(e)&&e>0?e:null),m&&Number.isInteger(e)&&e>0&&(m.value=String(e)),la(),Pr("Not detected"),cr(Zr()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),oa(ea()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),h?.addEventListener("change",async()=>{const n=Number.parseInt(h.value||"",10);Sr(),M&&Number.isInteger(n)&&n>0&&(M.value=String(n)),Yr(e,Number.isInteger(n)&&n>0?n:null),Yr(t,null),oa("Select a Book to begin."),await Co(n,null)}),m?.addEventListener("change",()=>{const e=Number.parseInt(m.value||"",10);Sr(),O&&Number.isInteger(e)&&e>0&&(O.value=String(e)),Yr(t,Number.isInteger(e)&&e>0?e:null),la(),oa(ea()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),y?.addEventListener("input",na),w?.addEventListener("click",async()=>{const e=_r(),t=String(y?.value||"").trim();if(e&&t){w.disabled=!0,ta("Creating Book...");try{const n=await Ka(`/api/word-companion/projects/${e.projectId}/books`,{title:t});y&&(y.value=""),M&&(M.value=String(e.projectId)),await Co(e.projectId,n.bookId),m&&(m.value=String(n.bookId)),ta("Ready to scan manuscript structure.")}catch(e){console.error("Unable to create Book from Word Companion.",e),ta(`Unable to create Book: ${Fr(e)}`)}finally{na()}}else na()}),f?.addEventListener("click",async()=>{const e=_r(),t=ea();if(e&&t)if(Gt&&Ft&&window.Word&&"function"==typeof window.Word.run){f&&(f.disabled=!0,f.textContent="Scanning..."),ta("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,a=null,o=0;const c=[],i=new Set(["***","###"]),d=()=>{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 s=String(e.text||"").trim();if(!s)return;if(c.push(s),pa(e,1))return r={title:s,sortOrder:10*(n.length+1),wordCount:0,scenes:[]},n.push(r),a=d(),void(o+=ha(s));if(!r||!a)return;if(t&&i.has(s))return void(a=d());const l=ha(s);r.wordCount+=l,a.wordCount+=l,o+=l}),{chapters:n,chapterCount:n.length,sceneCount:n.reduce((e,t)=>e+t.scenes.length,0),wordCount:o,documentText:c.join("\n")}})(n.items,!!t.usesExplicitScenes)});gn=n,Cn=!1;const r=await Ka("/api/word-companion/manuscript/analyse",{projectId:e.projectId,bookId:t.bookId,documentGuid:sa(),chapterCount:n.chapterCount,sceneCount:n.sceneCount,wordCount:n.wordCount});fn=r,(e=>{if(!C)return;C.innerHTML="";const t=document.createElement("strong");t.textContent="Manuscript Analysis",C.append(t);const n=document.createElement("dl"),r=[["Project",e.projectTitle],["Book",Qr({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 a=document.createElement("dd");a.textContent=t||"-",n.append(r,a)}C.append(n),rr(C,!1),rr(L,!1),ta(e.message||"Preview generated."),na()})(r);try{const t=await Ka("/api/word-companion/manuscript/discover-characters",{projectId:e.projectId,documentText:n.documentText||""});Sn=Array.isArray(t?.candidates)?t.candidates:[],rr(b,!0),rr(v,!0)}catch(e){console.error("Unable to discover character candidates.",e),Sn=[],rr(b,!0),rr(v,!0)}Gr({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(n.chapterCount),heading2:"-"})}catch(e){console.error("Unable to scan manuscript for first-run import.",e),oa(`Unable to scan manuscript: ${Fr(e)}`),Gr({lastScan:"Failure",lastError:Fr(e)})}finally{f&&(f.textContent="Scan Manuscript"),na()}}else oa("Word document access is unavailable.");else oa("Select a Project and Book to begin.")}),q?.addEventListener("click",async()=>{const n=_r(),i=ea();if(!(n&&i&&gn&&fn?.canImport))return void na();let d=!1;if(!fn.requiresReplaceConfirmation||(d=await new Promise(e=>{if(!D||"function"!=typeof D.showModal)return void e(window.confirm("This Book already contains planned chapters and scenes.\n\nImporting this manuscript will replace the planned structure.\n\nContinue?"));const t=t=>{A?.removeEventListener("click",n),T?.removeEventListener("click",r),D?.removeEventListener("cancel",a),D?.close(),e(t)},n=()=>t(!0),r=()=>t(!1),a=e=>{e.preventDefault(),t(!1)};A?.addEventListener("click",n),T?.addEventListener("click",r),D?.addEventListener("cancel",a),D.showModal()}),d)){kn=!0,na(),ta("Importing manuscript structure...");try{const l=sa(),u=await Ka("/api/word-companion/manuscript/import",{projectId:n.projectId,bookId:i.bookId,documentGuid:l,bindingVersion:1,replacePlanned:d,chapters:gn.chapters});if(!u.imported)return fn={...fn,canImport:!u.requiresReplaceConfirmation,requiresReplaceConfirmation:!!u.requiresReplaceConfirmation,message:u.message||fn.message},ta(u.message||"Import was not completed."),void na();const p=u.manuscriptDocument;await(s={documentGuid:p?.documentGuid||l,bookId:u.bookId,projectId:u.projectId,bindingVersion:p?.bindingVersion||1},new Promise((e,t)=>{const n=window.Office?.context?.document?.settings;n?(n.set(r,s.documentGuid),n.set(a,String(s.bookId)),n.set(o,String(s.projectId)),n.set(c,String(s.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."))})),pn={documentGuid:p?.documentGuid||l,bookId:u.bookId,projectId:u.projectId,bindingVersion:p?.bindingVersion||1},Yr(e,u.projectId),Yr(t,u.bookId),M&&(M.value=String(u.projectId));const h=Sn;await Co(u.projectId,u.bookId),zn("Connected"),Cn=!0,bn=h.length>0,In=bn?Date.now():0,Sn=h,h.length>0?(ra(!0),ia(h),rr(L,!0),rr(v,!1),ta(u.message||"Manuscript structure imported."),Xn(u.message||"Manuscript structure imported."),window.setTimeout(na,750)):await Qa(u.message||"Manuscript structure imported.")}catch(e){console.error("Unable to import manuscript structure.",e),ta(`Unable to import manuscript: ${Fr(e)}`)}finally{kn=!1,na()}var s}else ta("Import cancelled.")}),x?.addEventListener("click",async()=>{const e=_r()||Xr(),t=ca();if(!bn||Date.now()-In<750||!e||0===t.length)na();else{vn=!0,na(),Br(I,"Creating selected characters...");try{const n=await Ka("/api/word-companion/manuscript/create-discovered-characters",{projectId:e.projectId,candidateNames:t});Xn(n.message||"Characters created."),Br(I,`${n.createdCount||0} created, ${n.skippedCount||0} already existed.`),await Qa(n.message||"Characters created.")}catch(e){console.error("Unable to create discovered characters.",e),Br(I,`Unable to create characters: ${Fr(e)}`)}finally{vn=!1,na()}}}),E?.addEventListener("click",()=>Qa("Character creation skipped.")),N?.addEventListener("click",()=>Qa()),g?.addEventListener("click",()=>ra(!1)),P?.addEventListener("click",()=>oa("Import cancelled.")),F?.addEventListener("click",Ma),Z?.addEventListener("click",Oa),_?.addEventListener("click",async()=>{const e=Zr();if(!e||0===ir().length||xn)return void dr();if(!await Ba())return;xn=!0,sr(),or("Applying structure sync...");const t={createdChapters:0,createdScenes:0,linkedChapters:0,linkedScenes:0,skipped:Array.isArray(un?.manualReview)?un.manualReview.length:0,failed:0},n=ir().filter(e=>"couldLink"===e.category&&"Chapter"===e.type),r=ir().filter(e=>"wouldCreateChapters"===e.category),a=ir().filter(e=>"couldLink"===e.category&&"Scene"===e.type),o=ir().filter(e=>"wouldCreateScenes"===e.category),c=[];let i="";const d=(e,t)=>{c.push({item:e,counterName:t})},s=async(e,n)=>{try{await(async e=>{if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)throw new Error("Word document access is unavailable.");await window.Word.run(async t=>{const n=await ja(t),r="Chapter"===e.type?e.wordChapter:e.wordScene,a=Number.isInteger(r?.paragraphIndex)?n.bodyParagraphs[r.paragraphIndex]:null;if(!a)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.");eo(a,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=e.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");eo(a,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()})})(e),Ga(e,"Success"),t[n]+=1}catch(n){Ga(e,"Failed",Fr(n)),t.failed+=1}};try{for(const e of n)d(e,"linkedChapters");for(const n of r)try{await Ja(e.bookId,n),d(n,"createdChapters")}catch(e){Ga(n,"Failed",Fr(e)),t.failed+=1}for(const e of a)d(e,"linkedScenes");for(const n of o)try{await Ya(e.bookId,n),d(n,"createdScenes")}catch(e){Ga(n,"Failed",Fr(e)),t.failed+=1}for(const e of c)await s(e.item,e.counterName);for(const e of un.manualReview||[])Ga(e,"Skipped");Wa(un),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),or(i)}finally{xn=!1,sr(),i&&(Cr(),await Oa(),or(`${i} Preview refreshed.`))}}),ht?.addEventListener("click",()=>Ha(!0)),mt?.addEventListener("click",()=>Ha(!1)),ut?.addEventListener("cancel",e=>{e.preventDefault(),Ha(!1)}),ne?.addEventListener("click",yo),G?.addEventListener("click",async()=>{if(!Zr())return Xn("Select a PlotDirector book first."),void Pr("Not detected");qn&&(window.clearTimeout(qn),qn=null),Pn=!1,An=!1,yr(!0),pr("Updating...");try{if(!await Ma())return;if(hr(!1),!zt)return await mo(),void pr("Current scene updated");await yo(),pr("Current scene updated")}finally{yr(!1)}}),ge?.addEventListener("click",po),qe?.addEventListener("click",async()=>{if(_t)if(!Ln&&await(async()=>{if(!_t)return!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return hr(!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 ja(e)),t=e.currentChapter?.title||"",n=e.currentScene?.title||"",r=e.currentScene?.anchorId||null,a=e.currentChapter?.anchorId||null,o=Number.isInteger(r)&&r===_t,c=Number.isInteger(a)&&a===en,i=Wr(n,"scene").toLocaleLowerCase()===Wr(On||zt,"scene").toLocaleLowerCase(),d=Wr(t,"chapter").toLocaleLowerCase()===Wr(Hn||Yt,"chapter").toLocaleLowerCase();return o||i&&(c||d)?(hr(!1),!0):(hr(!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),Gr({lastError:Fr(e)}),hr(!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/${_t}/links`,t={characterIds:Za(Ee),assetIds:Za(Ne),locationIds:[],primaryLocationId:_a()},za(e,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})),(()=>{const e=new Set(Za(Ee)),t=new Set(Za(Ne));Gn={characters:Gn.characters.map(t=>({...t,linked:e.has(Number.parseInt(Dr(t,"character"),10))})),assets:Gn.assets.map(e=>({...e,linked:t.has(Number.parseInt(Dr(e,"asset"),10))})),locations:Gn.locations,primaryLocationId:_a()}})(),br("Scene links saved successfully."),Gr({lastError:"-"})}catch(e){br("Unable to save scene links."),Gr({lastError:Fr(e)})}finally{qe&&(qe.disabled=!_t||Ln,qe.textContent="Save Scene Links")}var e,t}else br("The Word cursor is now in a different scene. Refresh Current Scene before saving.");else br("Link a PlotDirector scene first.")}),de?.addEventListener("click",async()=>{await to()}),$e?.addEventListener("click",async()=>{const e=Zr();if(!e||!Yt||en)return void Nr("Chapter not found in PlotDirector.");const t=$r(Yt),n=await((e,t)=>(Br(it,`"${e}"`),Br(dt,`"${t}"`),ct?new Promise(e=>{ln=e,ct.showModal?ct.showModal():ct.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector chapter:\n\n"${e}"\n\nin book:\n\n"${t}"\n\n?`))))(t,Qr(e)||"selected book");if(n){$e&&($e.disabled=!0,$e.textContent="Creating...");try{const n=Number.isInteger(Qt)&&Qt>0?10*Qt:null,r=await Ka(`/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.");Cr(),mr(null,r.chapterId,"Manual chapter link");if(!await no("Chapter created and linked successfully."))return;await ro("Chapter created and linked successfully.")}catch(e){kr("Unable to create chapter."),Gr({lastError:Fr(e)})}finally{$e&&($e.disabled=!vr(),$e.textContent="Create Chapter in PlotDirector")}}}),We?.addEventListener("click",async()=>{const e=Zr();if(e&&Yt&&!en){We&&(We.disabled=!0,We.textContent="Loading...");try{dn=await Ur(e.bookId),sn=null,tt&&(tt.value=""),Br(ot,""),oo(),et?.showModal?et.showModal():et&&(et.hidden=!1)}catch(e){kr("Unable to load chapters."),Gr({lastError:Fr(e)})}finally{We&&(We.disabled=!vr(),We.textContent="Link to Existing Chapter")}}else Nr("Chapter not found in PlotDirector.")}),tt?.addEventListener("input",oo),rt?.addEventListener("click",async()=>{const e=dn.find(e=>e.chapterId===sn);if(e){rt&&(rt.disabled=!0,rt.textContent="Linking...");try{mr(null,e.chapterId,"Manual chapter link");if(!await no("Chapter linked successfully."))return;co(),await ro("Chapter linked successfully.")}catch(e){Br(ot,"Unable to link chapter."),kr("Unable to link chapter."),Gr({lastError:Fr(e)})}finally{rt&&(rt.disabled=!sn,rt.textContent="Link Chapter")}}else Br(ot,"Select a chapter.")}),at?.addEventListener("click",co),st?.addEventListener("click",()=>ao(!0)),lt?.addEventListener("click",()=>ao(!1)),ct?.addEventListener("cancel",e=>{e.preventDefault(),ao(!1)}),Oe?.addEventListener("click",async()=>{const e=Zr();if(!e||!zt)return void qr("Scene not found in PlotDirector.");const t=Wr(zt,"scene"),n=Wr(Yt,"chapter"),r=await((e,t)=>(Br(Qe,`"${e}"`),Br(Xe,`"${t}"`),Ke?new Promise(e=>{cn=e,Ke.showModal?Ke.showModal():Ke.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector scene:\n\n"${e}"\n\nwithin chapter:\n\n"${t}"\n\n?`))))(t,n);if(r){Oe&&(Oe.disabled=!0,Oe.textContent="Creating...");try{const n=await Or();if(!n)return void qr("This chapter does not exist in PlotDirector. Create or link the chapter first.");const r=await Ka(`/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.");Cr(),await io(r.sceneId,r.chapterId,"Scene created and linked successfully.")}catch(e){Ir("Unable to create scene."),Gr({lastError:Fr(e)})}finally{Oe&&(Oe.disabled=!xr(),Oe.textContent="Create Scene in PlotDirector")}}}),He?.addEventListener("click",async()=>{const e=Zr();if(e&&zt){He&&(He.disabled=!0,He.textContent="Loading...");try{const t=await Rr(e.bookId),n=Mr(t);if(!n)return void qr("This chapter does not exist in PlotDirector. Create or link the chapter first.");an=Array.isArray(n.scenes)?n.scenes:[],on=null,Fe&&(Fe.value=""),Br(ze,""),lo(),Ge?.showModal?Ge.showModal():Ge&&(Ge.hidden=!1)}catch(e){Ir("Unable to load scenes."),Gr({lastError:Fr(e)})}finally{He&&(He.disabled=!xr(),He.textContent="Link to Existing Scene")}}else qr("Scene not found in PlotDirector.")}),Fe?.addEventListener("input",lo),Je?.addEventListener("click",async()=>{const e=Zr(),t=an.find(e=>e.sceneId===on);if(e&&t){Je&&(Je.disabled=!0,Je.textContent="Linking...");try{const e=await Or();if(!e)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");uo(),await io(t.sceneId,e.chapterId,"Scene linked successfully.")}catch(e){Br(ze,"Unable to link scene."),Ir("Unable to link scene."),Gr({lastError:Fr(e)})}finally{Je&&(Je.disabled=!on,Je.textContent="Link Scene")}}else Br(ze,"Select a scene.")}),Ye?.addEventListener("click",uo),Ze?.addEventListener("click",()=>so(!0)),_e?.addEventListener("click",()=>so(!1)),Ke?.addEventListener("cancel",e=>{e.preventDefault(),so(!1)}),Et?.addEventListener("click",async()=>{Et&&(Et.disabled=!0,Et.textContent="Running...");try{if(await Vr(),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return void Gr({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});Gr({lastScan:"Success",lastError:"-",paragraphs:String(e)})}catch(e){console.error("Word Companion diagnostics failed.",e);const t=Fr(e);Gr({lastScan:"Failure",lastError:t}),Xn(`Unable to scan the Word document: ${t}`)}finally{Et&&(Et.disabled=!1,Et.textContent="Run Diagnostics")}});const bo=Ot?(async()=>{zr(M,"Loading projects..."),zr(O,"Select a project first"),zr(h,"Loading projects..."),zr(m,"Select a project first"),Kn(""),Qn("");try{const n=await za("/api/word-companion/projects");if(Ht=Array.isArray(n.projects)?n.projects:[],0===Ht.length)return zr(M,"No projects available."),zr(h,"No projects available."),Kn("No projects available."),Yr(e,null),Yr(t,null),la(),void oa("No projects available.");Kr(M,"Choose a project",Ht,"projectId","title"),aa();const r=Jr(e),a=Ht.find(e=>e.projectId===r);a&&M?(M.value=String(a.projectId),h&&(h.value=String(a.projectId)),Yr(e,a.projectId),await Co(a.projectId,Jr(t))):(Yr(e,null),Yr(t,null),la(),oa("Select a Project and Book to begin."))}catch{Ht=[],Bt=[],zr(M,"Unable to connect to PlotDirector."),zr(O,"Select a project first"),zr(h,"Unable to connect to PlotDirector."),zr(m,"Select a project first"),zn("Unable to connect to PlotDirector."),Kn("Unable to connect to PlotDirector."),Yr(e,null),Yr(t,null),la(),oa("Unable to connect to PlotDirector.")}})():Promise.resolve();if(Ot||(zr(M,"Please sign in to PlotDirector."),zr(O,"Please sign in to PlotDirector."),zr(h,"Please sign in to PlotDirector."),zr(m,"Please sign in to PlotDirector."),la()),!window.Office||"function"!=typeof window.Office.onReady)return Vn("Word Companion ready"),Xn("Word document access is unavailable."),pr("Manual"),void Gr({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"});Vr().then(async()=>{Vn("Word Companion ready"),await bo,await(async()=>{if(!Ot||!Ft)return void ra(!1);const n=da();if(n)try{const r=await za(`/api/word-companion/runtime/book/${n.bookId}?documentGuid=${encodeURIComponent(n.documentGuid)}`),a=r?.manuscriptDocument;if(r?.bookId===n.bookId&&r?.projectId===n.projectId&&a&&String(a.documentGuid).toLowerCase()===n.documentGuid.toLowerCase())return pn=n,gr(r),Yr(e,r.projectId),Yr(t,r.bookId),M&&(M.value=String(r.projectId)),await Co(r.projectId,r.bookId),ra(!1),zn("Connected"),Qn("Bound manuscript detected."),void await Xa()}catch{}pn=null,Sr(),aa(),_r()?await Co(_r().projectId,null):zr(m,"Select a project first"),oa("Select a Project and Book to begin."),ra(!0)})(),Ft?(()=>{if(Ot){if(!window.Office?.context?.document||"function"!=typeof window.Office.context.document.addHandlerAsync||!window.Office?.EventType?.DocumentSelectionChanged)return pr("Manual"),void Xn("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");try{window.Office.context.document.addHandlerAsync(window.Office.EventType.DocumentSelectionChanged,go,e=>{e?.status===window.Office.AsyncResultStatus.Succeeded?($n=!0,pr("Live")):(pr("Manual"),Xn("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))}),window.addEventListener("beforeunload",So)}catch(e){console.warn("Unable to register Word selection tracking handler.",e),pr("Manual"),Xn("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}})():(Xn("Word document access is unavailable."),pr("Manual"))}).catch(e=>{console.error("Office readiness check failed.",e),zn("Unable to connect to PlotDirector."),Vn("Word Companion unavailable"),Xn("Word document access is unavailable."),Gr({ready:"No",wordApi:"No",lastScan:"Failure"})})})();