PlotDirector/PlotLine/wwwroot/js/word-companion-host.min.js
2026-07-03 14:18:38 +01:00

1 line
85 KiB
JavaScript

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