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

1 line
70 KiB
JavaScript

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