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