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