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

25 lines
93 KiB
JavaScript

(()=>{const s={projectId:"plotdirector.word.projectId",bookId:"plotdirector.word.bookId",activeTab:"plotdirector.word.activeTab"},bi={documentGuid:"plotdirector.word.documentGuid",bookId:"plotdirector.word.boundBookId",projectId:"plotdirector.word.boundProjectId",bindingVersion:"plotdirector.word.bindingVersion"},pl=new Set(["scene","review","maintenance","diagnostics"]),th=document.querySelector(".word-companion-shell"),wp=document.querySelector(".word-companion-tabs"),ih=[...document.querySelectorAll("[data-tab-button]")],wl=[...document.querySelectorAll("[data-tab-panel]")],bp=document.querySelector("[data-linked-manuscript-card]"),kp=document.querySelector("[data-linked-project-title]"),dp=document.querySelector("[data-linked-book-title]"),gp=document.querySelector("[data-first-run-wizard]"),et=document.querySelector("[data-first-run-project-select]"),g=document.querySelector("[data-first-run-book-select]"),te=document.querySelector("[data-first-run-new-book-title]"),oo=document.querySelector("[data-first-run-create-book]"),sr=document.querySelector("[data-first-run-scan]"),nw=document.querySelector("[data-first-run-cancel]"),tw=document.querySelector("[data-first-run-status]"),hr=document.querySelector("[data-first-run-summary]"),ku=document.querySelector("[data-first-run-character-section]"),du=document.querySelector("[data-first-run-character-status]"),ki=document.querySelector("[data-first-run-character-candidates]"),gu=document.querySelector("[data-first-run-character-actions]"),so=document.querySelector("[data-first-run-create-characters]"),bl=document.querySelector("[data-first-run-skip-characters]"),kl=document.querySelector("[data-first-run-continue]"),rh=document.querySelector("[data-first-run-import-actions]"),uh=document.querySelector("[data-first-run-import]"),iw=document.querySelector("[data-first-run-import-cancel]"),nf=document.querySelector("[data-first-run-replace-dialog]"),dl=document.querySelector("[data-first-run-replace-confirm]"),gl=document.querySelector("[data-first-run-replace-cancel]"),tf=document.querySelector("[data-unlink-word-document-dialog]"),na=document.querySelector("[data-unlink-word-document-confirm]"),ta=document.querySelector("[data-unlink-word-document-cancel]"),ia=document.querySelector("[data-office-status]"),ra=document.querySelector("[data-connection-status]"),ua=document.querySelector("[data-summary-connection]"),fa=document.querySelector("[data-summary-project]"),ea=document.querySelector("[data-summary-book]"),p=document.querySelector("[data-project-select]"),ot=document.querySelector("[data-book-select]"),rw=document.querySelector("[data-runtime-book-selectors]"),oa=document.querySelector("[data-project-message]"),sa=document.querySelector("[data-book-message]"),ho=document.querySelector("[data-refresh-current-scene]"),tu=document.querySelector("[data-refresh-document]"),ha=document.querySelector("[data-current-chapter]"),ca=document.querySelector("[data-current-scene]"),la=document.querySelector("[data-current-word-count]"),aa=document.querySelector("[data-scene-tracking-status]"),va=document.querySelector("[data-document-message]"),ya=document.querySelector("[data-sync-note]"),ie=document.querySelector("[data-document-outline]"),cr=document.querySelector("[data-analyse-manuscript-structure]"),fh=document.querySelector("[data-apply-structure-sync]"),uw=document.querySelector("[data-structure-preview-status]"),rf=document.querySelector("[data-structure-preview-results]"),iu=document.querySelector("[data-refresh-plotdirector-scene]"),pa=document.querySelector("[data-plotdirector-scene-status]"),fw=document.querySelector("[data-anchor-status]"),ew=document.querySelector("[data-anchor-book-id]"),ow=document.querySelector("[data-anchor-chapter-id]"),sw=document.querySelector("[data-anchor-scene-id]"),ai=document.querySelector("[data-attach-plotdirector-ids]"),lr=document.querySelector("[data-unlink-word-document]"),wa=document.querySelector("[data-plotdirector-scene-details]"),ba=document.querySelector("[data-plotdirector-scene-title]"),ka=document.querySelector("[data-plotdirector-revision-status]"),da=document.querySelector("[data-plotdirector-estimated-words]"),eh=document.querySelector("[data-plotdirector-actual-words]"),ga=document.querySelector("[data-plotdirector-blocked-status]"),oh=document.querySelector("[data-plotdirector-blocked-reason-row]"),sh=document.querySelector("[data-plotdirector-blocked-reason]"),nv=document.querySelector("[data-runtime-last-sync]"),ar=document.querySelector("[data-sync-scene-progress]"),hw=document.querySelector("[data-sync-word-count]"),hh=document.querySelector("[data-sync-plotdirector-count]"),tv=document.querySelector("[data-sync-last-synced]"),cw=document.querySelector("[data-sync-status]"),iv=document.querySelector("[data-writing-brief-block]"),rv=document.querySelector("[data-writing-brief]"),uv=document.querySelector("[data-plotdirector-link-groups]"),lw=document.querySelector("[data-character-review-summary]"),aw=document.querySelector("[data-asset-review-summary]"),vw=document.querySelector("[data-location-review-summary]"),re=document.querySelector("[data-character-chips]"),ue=document.querySelector("[data-asset-chips]"),btt=document.querySelector("[data-location-chips]"),vr=document.querySelector("[data-primary-location-select]"),di=document.querySelector("[data-save-scene-links]"),yw=document.querySelector("[data-scene-links-status]"),fv=document.querySelector("[data-links-editing-scene]"),ev=document.querySelector("[data-chapter-create-link]"),pw=document.querySelector("[data-chapter-create-link-chapter]"),yt=document.querySelector("[data-create-plotdirector-chapter]"),pt=document.querySelector("[data-link-existing-chapter]"),ww=document.querySelector("[data-chapter-create-link-status]"),ov=document.querySelector("[data-scene-create-link]"),bw=document.querySelector("[data-create-link-chapter]"),kw=document.querySelector("[data-create-link-scene]"),wt=document.querySelector("[data-create-plotdirector-scene]"),bt=document.querySelector("[data-link-existing-scene]"),dw=document.querySelector("[data-create-link-status]"),yr=document.querySelector("[data-link-existing-dialog]"),co=document.querySelector("[data-link-scene-search]"),lo=document.querySelector("[data-link-scene-options]"),oi=document.querySelector("[data-link-selected-scene]"),gw=document.querySelector("[data-link-dialog-cancel]"),ch=document.querySelector("[data-link-dialog-status]"),gi=document.querySelector("[data-create-scene-dialog]"),nb=document.querySelector("[data-create-dialog-scene]"),tb=document.querySelector("[data-create-dialog-chapter]"),ib=document.querySelector("[data-create-dialog-confirm]"),rb=document.querySelector("[data-create-dialog-cancel]"),pr=document.querySelector("[data-link-existing-chapter-dialog]"),ao=document.querySelector("[data-link-chapter-search]"),vo=document.querySelector("[data-link-chapter-options]"),si=document.querySelector("[data-link-selected-chapter]"),ub=document.querySelector("[data-link-chapter-dialog-cancel]"),lh=document.querySelector("[data-link-chapter-dialog-status]"),nr=document.querySelector("[data-create-chapter-dialog]"),fb=document.querySelector("[data-create-chapter-dialog-chapter]"),eb=document.querySelector("[data-create-chapter-dialog-book]"),ob=document.querySelector("[data-create-chapter-dialog-confirm]"),sb=document.querySelector("[data-create-chapter-dialog-cancel]"),tr=document.querySelector("[data-apply-structure-sync-dialog]"),ah=document.querySelector("[data-apply-structure-sync-summary]"),hb=document.querySelector("[data-apply-structure-sync-confirm]"),cb=document.querySelector("[data-apply-structure-sync-cancel]"),lb=document.querySelector("[data-resolve-project-id]"),ab=document.querySelector("[data-resolve-project-title]"),vb=document.querySelector("[data-resolve-book-id]"),yb=document.querySelector("[data-resolve-book-title]"),pb=document.querySelector("[data-resolve-detected-chapter]"),wb=document.querySelector("[data-resolve-detected-scene]"),bb=document.querySelector("[data-resolve-request-chapter]"),kb=document.querySelector("[data-resolve-request-scene]"),db=document.querySelector("[data-resolve-result]"),gb=document.querySelector("[data-resolve-chapter-id]"),nk=document.querySelector("[data-resolve-scene-id]"),ru=document.querySelector("[data-run-diagnostics]"),tk=document.querySelector("[data-diagnostic-host]"),ik=document.querySelector("[data-diagnostic-platform]"),rk=document.querySelector("[data-diagnostic-ready]"),uk=document.querySelector("[data-diagnostic-word-api]"),fk=document.querySelector("[data-diagnostic-last-scan]"),ek=document.querySelector("[data-diagnostic-last-error]"),ok=document.querySelector("[data-diagnostic-anchor-type]"),sk=document.querySelector("[data-diagnostic-stored-scene-id]"),hk=document.querySelector("[data-diagnostic-stored-chapter-id]"),ck=document.querySelector("[data-diagnostic-resolution-method]"),lk=document.querySelector("[data-diagnostic-paragraphs]"),ak=document.querySelector("[data-diagnostic-heading1]"),vk=document.querySelector("[data-diagnostic-heading2]"),uf=th?.dataset.authenticated==="true",vh=Number.parseInt(th?.dataset.userId||"",10),yk=String(th?.dataset.companionVersion||"20C").trim();let ir=[],ii=[],kt=!1,nt=!1,yo="Unknown",po="Unknown",w="",rt="",sv=null,fe=null,b=null,tt=null,u=null,o=null,ee="",rr="Title Match",dt=!1,yh=[],oe=null,wo=null,ph=[],se=null,bo=null,vi=null,ri=null,ur=null,l=null,he=null,ko=null,wr=null,ce=null,hi=[],go=null,ns=!1,ff=!1,le=0,ae=!1,wh=!1,ve=!1,ts=null,bh="Manual",ht=!1,uu=null,br=!1,hv=0,ef=!1,ye=0,pe=null;const we=1200;let kh=!1,is=!1,be=null,sf=!1,ke=!1,dh=null,gh=null,de=null,hf=!1,cf=!1,nc=null,tc="",lf=[],ic=null,rc="",uc=null,fc="",fu=[],ec=null,oc="",sc=null,hc="",eu=[],cc=null,lc="",ac="",rs="",vc="",cv=0,d=null,ou=null,ct={characters:[],assets:[],locations:[],primaryLocationId:null};const i=n=>{const t=Date.now();t-cv<1e3||(cv=t,console.debug(`[Word Companion Runtime] ${n}`))},ci=n=>{console.debug(`[Word Companion Timing] ${n}`)},yc=n=>{ia&&(ia.textContent=n)},pk=n=>{try{return window.localStorage.getItem(n)||""}catch{return""}},wk=(n,t)=>{try{t?window.localStorage.setItem(n,String(t)):window.localStorage.removeItem(n)}catch{}},lv=n=>n==="links"?"review":n==="structure"?"maintenance":n,av=(n,t=true)=>{const i=lv(n),r=pl.has(i)&&ih.some(n=>n.dataset.tabButton===i)?i:"scene";for(const n of ih){const t=n.dataset.tabButton===r;n.classList.toggle("is-active",t);n.setAttribute("aria-selected",t?"true":"false")}for(const n of wl){const t=n.dataset.tabPanel===r;n.classList.toggle("is-active",t);n.hidden=!t}t&&wk(s.activeTab,r)},vv=()=>{const n=lv(pk(s.activeTab));av(pl.has(n)?n:"scene",!1)},ge=n=>{ra&&(ra.textContent=n),ua&&(ua.textContent=n)},pc=n=>{oa&&(oa.textContent=n)},af=n=>{sa&&(sa.textContent=n)},t=n=>{va&&(va.textContent=n)},vf=n=>{pa&&(pa.textContent=n)},wc=t=>{const i=n=>Object.prototype.hasOwnProperty.call(t,n);i("anchorType")&&n(ok,a(t.anchorType));i("storedSceneId")&&n(sk,a(t.storedSceneId));i("storedChapterId")&&n(hk,a(t.storedChapterId));i("resolutionMethod")&&n(ck,a(t.resolutionMethod))},fr=()=>{const i=h(),f=Number.isInteger(u)&&u>0&&tt===u,e=!Number.isInteger(o)||o<=0||b===o,t=f&&e;n(fw,t?"Attached to PlotDirector":"Not attached");n(ew,i?.bookId?String(i.bookId):"-");n(ow,Number.isInteger(o)&&o>0?String(o):"-");n(sw,Number.isInteger(u)&&u>0?String(u):"-");ai&&(r(ai,t&&!dt),ai.disabled=!u||t&&!dt,ai.textContent=tt&&!t?"Reattach PlotDirector IDs":"Attach PlotDirector IDs");wc({anchorType:rr||"Title Match",storedSceneId:tt,storedChapterId:b,resolutionMethod:ee})},yf=(t,i,r,u=null,f=null,e=null)=>{const o=t||"",s=i||"",h=Number.isInteger(r)?r:null,c=Number.isInteger(e)&&e>0?e:null,l=Number.isInteger(u)&&u>0?u:null,a=Number.isInteger(f)&&f>0?f:null,v=w===o&&rt===s&&sv===h&&fe===c&&b===l&&tt===a;(w=t||"",rt=i||"",sv=Number.isInteger(r)?r:null,fe=Number.isInteger(e)&&e>0?e:null,b=Number.isInteger(u)&&u>0?u:null,tt=Number.isInteger(f)&&f>0?f:null,v)||(ha&&(ha.textContent=t||"Not detected"),ca&&(ca.textContent=i||"Not detected"),la&&(la.textContent=Number.isInteger(r)?String(r):"-"),n(hw,Number.isInteger(r)?String(r):"-"),fr())},pf=()=>{be&&(window.clearTimeout(be),be=null)},r=(n,t)=>{n&&(n.hidden=t)},bc=()=>{r(lr,!ri)},gt=t=>{n(cw,t)},er=t=>{n(uw,t)},wf=(n="Select a project and book to analyse manuscript structure.")=>{if(vi=null,rf){rf.innerHTML="";const n=document.createElement("p");n.textContent="No preview generated.";rf.append(n)}er(n);us()},bk=(n=vi)=>yy.flatMap(t=>Array.isArray(n?.[t.key])?n[t.key]:[]),su=(n=vi)=>bk(n).filter(n=>n.category==="couldLink"||n.category==="wouldCreateChapters"||n.category==="wouldCreateScenes"),us=()=>{fh&&(fh.disabled=ve||su().length===0)},fs=()=>{cr&&(cr.disabled=ve||!ni()||!h()),us()},kc=()=>{fv&&(fv.textContent=u?`Editing links for: ${rs||rt||"Current scene"}`:"Link a PlotDirector scene first.")},dc=()=>{const n=ht||!u,t=n||!o||sf;ar&&(ar.disabled=t);di&&(di.disabled=n);vr&&(vr.disabled=n);for(const t of[re,ue])for(const i of t?[...t.querySelectorAll("input[type='checkbox']")]:[])i.disabled=n},k=t=>{(t==="Live"||t==="Manual")&&(bh=t),n(aa,t||bh||"Manual")},li=(i,r="")=>{ht=!!i,ht&&(pf(),fo()),n(aa,ht?"Stale":bh),dc(),r&&(t(r),cu(r))},kr=(n,t=null,i="")=>{u=Number.isInteger(n)&&n>0?n:null,o=Number.isInteger(t)&&t>0?t:null,ee=i||"",u!==dh&&(gh=null),u||(pf(),fo()),dc(),gt(ht?"Refresh Current Scene before syncing.":u?"Ready to sync.":"No resolved PlotDirector scene."),cu(ht?"Refresh Current Scene before saving.":u?"Ready to save.":"Link a PlotDirector scene first."),kc(),fr()},yv=n=>{ho&&(ho.disabled=n,ho.textContent=n?"Refreshing...":"Refresh Current Scene")},a=n=>n===null||n===undefined||n===""?"-":String(n),ktt=n=>{if(!n)return"-";const t=new Date(n);return Number.isNaN(t.getTime())?"-":t.toLocaleString()},es=n=>{if(!n)return"-";const t=n instanceof Date?n:new Date(n);if(Number.isNaN(t.getTime()))return"-";const i=new Date,r=t.toDateString()===i.toDateString()?"Today":t.toLocaleDateString();return`Last synced: ${r} ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`},pv=t=>{ur=t||null;const i=ur?.lastSyncUtc||ur?.manuscriptDocument?.lastSyncUtc;n(nv,es(i));n(tv,es(i));tl()},bf=()=>{l=null,he=null,ko=null,ye+=1,pe=null,gn(),ntt(),ttt(),pv(null)},hu=()=>{he=null,ko=null},cu=t=>{n(yw,t)},lu=t=>{n(dw,t)},yi=t=>{n(ww,t)},gc=()=>!!h()&&!!w&&!o,nl=()=>!!h()&&!!rt&&Number.isInteger(o)&&o>0,no=()=>{r(ev,!0),yi(""),yt&&(yt.disabled=!0,yt.textContent="Create Chapter in PlotDirector"),pt&&(pt.disabled=!0,pt.textContent="Link to Existing Chapter")},os=(t="")=>{n(pw,a(w));r(ev,!1);yi(t);const i=gc();yt&&(yt.disabled=!i,yt.textContent="Create Chapter in PlotDirector");pt&&(pt.disabled=!i,pt.textContent="Link to Existing Chapter")},ss=()=>{r(ov,!0),lu(""),wt&&(wt.disabled=!0,wt.textContent="Create Scene in PlotDirector"),bt&&(bt.disabled=!0,bt.textContent="Link to Existing Scene")},to=(t="")=>{n(bw,a(w));n(kw,a(rt));r(ov,!1);lu(t);const i=nl();wt&&(wt.disabled=!i,wt.textContent="Create Scene in PlotDirector");bt&&(bt.disabled=!i,bt.textContent="Link to Existing Scene")},it=t=>{vf(t),r(wa,!0),r(iv,!0),r(uv,!1),no(),ss(),ee="",rs="",vc="",rr=tt?"SceneID Anchor":b?"ChapterID Anchor":"Title Match",dt=!1,ct={characters:[],assets:[],locations:[],primaryLocationId:null},cs(re,[],"character"),cs(ue,[],"asset"),wv([],null,!1),ey(),kr(null),n(hh,"-"),n(ba,"-"),n(ka,"-"),n(da,"-"),n(eh,"-"),n(ga,"-"),n(sh,"-"),r(oh,!0),fr(),kc()},hs=(n,t)=>t==="asset"?n?.assetId||n?.AssetId||n?.storyAssetId||n?.StoryAssetId||0:t==="location"?n?.locationId||n?.LocationId||0:n?.characterId||n?.CharacterId||0,cs=(n,t,i,r=false)=>{if(n){n.innerHTML="";const u=Array.isArray(t)?t:[];if(u.length===0){const t=document.createElement("p");t.className="word-companion-empty-list";t.textContent="None";n.append(t);return}for(const t of u){const f=Number.parseInt(hs(t,i),10);if(Number.isInteger(f)&&!(f<=0)){const e=document.createElement("label");e.className="word-companion-check-item";const u=document.createElement("input");u.type="checkbox";u.value=String(f);u.checked=!!t.linked;u.disabled=!r;const o=document.createElement("span");o.textContent=t.name||"Unnamed";e.append(u,o);n.append(e)}}}},wv=(n,t,i=false)=>{if(vr){vr.innerHTML="";const r=document.createElement("option");r.value="";r.textContent="None";vr.append(r);const u=Number.parseInt(t||"",10);for(const t of Array.isArray(n)?n:[]){const n=Number.parseInt(hs(t,"location"),10);if(Number.isInteger(n)&&!(n<=0)){const i=document.createElement("option");i.value=String(n);i.textContent=t.name||"Unnamed";i.selected=n===u;vr.append(i)}}vr.disabled=!i}},kk=t=>{rs=t?.sceneTitle||rt||"",vc=t?.chapterTitle||w||"",n(ba,a(t?.sceneTitle)),n(ka,a(t?.revisionStatus||t?.revisionStatusName||"Not provided")),n(da,a(t?.estimatedWords)),n(eh,a(t?.actualWords)),n(hh,a(t?.actualWords)),n(ga,t?.blocked?"Blocked":"Not blocked"),t?.blockedReason?(n(sh,t.blockedReason),r(oh,!1)):(n(sh,"-"),r(oh,!0)),rv&&(rv.textContent=t?.writingBrief||"No writing brief has been added for this scene."),ct={characters:Array.isArray(t?.characters)?t.characters:[],assets:Array.isArray(t?.assets)?t.assets:[],locations:Array.isArray(t?.locations)?t.locations:[],primaryLocationId:t?.primaryLocationId??null},cs(re,ct.characters,"character",!!u&&!ht),cs(ue,ct.assets,"asset",!!u&&!ht),wv(ct.locations,ct.primaryLocationId,!!u&&!ht),ey(),kc(),cu(ht?"Refresh Current Scene before saving.":u?"Ready to save.":"No resolved PlotDirector scene."),r(wa,!1),r(iv,!1),r(uv,!1)},au=n=>String(n||"").trim().replace(/\s+/g," "),ut=(n,t)=>{const i=au(n);if(!i)return"";const r=t==="scene"?"scene":"chapter",u=new RegExp(`^${r}\\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"),f=au(i.replace(u,""));return f||i},vt=t=>{const i=n=>Object.prototype.hasOwnProperty.call(t,n);i("projectId")&&n(lb,a(t.projectId));i("projectTitle")&&n(ab,a(t.projectTitle));i("bookId")&&n(vb,a(t.bookId));i("bookTitle")&&n(yb,a(t.bookTitle));i("detectedChapter")&&n(pb,a(t.detectedChapter));i("detectedScene")&&n(wb,a(t.detectedScene));i("requestChapter")&&n(bb,a(t.requestChapter));i("requestScene")&&n(kb,a(t.requestScene));i("result")&&n(db,a(t.result));i("chapterId")&&n(gb,a(t.chapterId));i("sceneId")&&n(nk,a(t.sceneId))},dk=async(n,t)=>{const i=await at(`/api/word-companion/books/${n}/structure`),r=Array.isArray(i?.chapters)?i.chapters:[];for(const n of r){const r=Array.isArray(n.scenes)?n.scenes:[],i=r.find(n=>n.sceneId===t);if(i)return i.revisionStatus||""}return""},gk=async(n,t)=>{const i=await at(`/api/word-companion/books/${n}/structure`),r=Array.isArray(i?.chapters)?i.chapters:[];for(const n of r){const i=Array.isArray(n.scenes)?n.scenes:[];for(const r of i)if(t(n,r))return{chapter:n,scene:r}}return null},ls=async n=>{if(ko===n&&Array.isArray(he?.chapters))return he.chapters;const t=await at(`/api/word-companion/books/${n}/structure`);return ko=n,he=t||null,Array.isArray(t?.chapters)?t.chapters:[]},bv=async n=>{const t=await at(`/api/word-companion/books/${n}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},kv=n=>{if(Number.isInteger(o)&&o>0){const t=n.find(n=>n.chapterId===o);if(t)return t}const t=ut(w,"chapter").toLocaleLowerCase();return t?n.find(n=>ut(n.title,"chapter").toLocaleLowerCase()===t)||null:null},dv=async()=>{const n=h();return n?kv(await ls(n.bookId)):null},as=async(n,i,r,u,f)=>{const e=await at(`/api/word-companion/scenes/${i}/companion`);try{e.revisionStatus=await dk(n,i)}catch{e.revisionStatus=""}rr=f||"Title Match";dt=!1;li(!1);vf("Linked to PlotDirector");t("");no();ss();kr(i,r,u);kk(e);rn(i,r);gs();nh()},n=(n,t)=>{if(n){const i=t===null||t===undefined?"":String(t);n.textContent!==i&&(n.textContent=i)}},f=t=>{const i=n=>Object.prototype.hasOwnProperty.call(t,n);i("host")&&n(tk,t.host);i("platform")&&n(ik,t.platform);i("ready")&&n(rk,t.ready);i("wordApi")&&n(uk,t.wordApi);i("lastScan")&&n(fk,t.lastScan);i("lastError")&&n(ek,t.lastError);i("paragraphs")&&n(lk,t.paragraphs);i("heading1")&&n(ak,t.heading1);i("heading2")&&n(vk,t.heading2)},e=n=>{const t=[];return n?.name&&t.push(n.name),n?.code&&n.code!==n.name&&t.push(n.code),n?.message&&t.push(n.message),n?.debugInfo?.errorLocation&&t.push(`Location: ${n.debugInfo.errorLocation}`),t.length>0?t.join(": "):String(n)},gv=async()=>{if(!window.Office||typeof window.Office.onReady!="function")return kt=!1,nt=!1,yo="Unavailable",po="Unavailable",f({host:yo,platform:po,ready:"No",wordApi:"No"}),null;const n=await window.Office.onReady();return kt=!0,yo=n?.host||"Unknown",po=n?.platform||"Unknown",nt=!!window.Word&&!!window.Office.HostType&&n?.host===window.Office.HostType.Word,f({host:yo,platform:po,ready:"Yes",wordApi:nt?"Yes":"No"}),n},vs=n=>{try{const i=window.localStorage.getItem(n),t=Number.parseInt(i||"",10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},v=(n,t)=>{try{t?window.localStorage.setItem(n,String(t)):window.localStorage.removeItem(n)}catch{}},c=(n,t)=>{if(n){n.innerHTML="";const i=document.createElement("option");i.value="";i.textContent=t;n.append(i);n.disabled=!0}},ys=(n,t,i,r,u)=>{if(n){n.innerHTML="";const f=document.createElement("option");f.value="";f.textContent=t;n.append(f);for(const t of i){const i=document.createElement("option");i.value=String(t[r]);i.textContent=t[u];n.append(i)}n.disabled=i.length===0}},dr=n=>{const t=String(n?.displayTitle||"").trim();if(t)return t;const i=String(n?.title||"").trim(),r=String(n?.subtitle||"").trim();return r?`${i}: ${r}`:i},nd=()=>ur?.projectTitle||ni()?.title||"Project",td=()=>ur?.bookTitle||dr(h())||"Book",tl=()=>{const t=!!ri;r(bp,!t);r(rw,t);t&&(n(kp,nd()),n(dp,td()))},ni=()=>{const n=Number.parseInt(p?.value||"",10);return ir.find(t=>t.projectId===n)||null},h=()=>{const n=Number.parseInt(ot?.value||"",10);return ii.find(t=>t.bookId===n)||null},gr=()=>{const n=Number.parseInt(et?.value||"",10);return ir.find(t=>t.projectId===n)||null},vu=()=>{const n=Number.parseInt(g?.value||"",10);return ii.find(t=>t.bookId===n)||null},id=()=>{const n=ri?.projectId||gr()?.projectId||ni()?.projectId||vs(s.projectId);return Number.isInteger(n)&&n>0?n:null},rd=()=>{const n=ri?.bookId||vu()?.bookId||h()?.bookId||vs(s.bookId);return Number.isInteger(n)&&n>0?n:null},ny=()=>{const n=String(window.Office?.context?.document?.url||"").trim();if(!n)return"";const t=n.split(/[\\/]/).filter(Boolean).pop()||"";try{return decodeURIComponent(t)}catch{return t}},ty=()=>({userID:Number.isInteger(vh)&&vh>0?vh:null,companionVersion:yk,machineName:"",documentOpen:!!nt,currentDocumentName:ny(),linkedProjectID:id(),linkedBookID:rd()}),ud=async()=>{d&&d.state===signalR.HubConnectionState.Connected&&await d.invoke("CompanionHeartbeat",ty())},kf=()=>{ud().catch(n=>{console.debug("Word Companion heartbeat unavailable.",n)})},iy=async()=>{if(uf&&window.signalR&&!d){d=(new signalR.HubConnectionBuilder).withUrl("/hubs/word-companion-follow").withAutomaticReconnect().build();d.onreconnected(kf);d.on("ScanCurrentDocument",n=>{void bd(n)});d.on("UpdateOnboardingBuildMarkers",n=>{void kd(n)});d.onclose(()=>{ou&&(window.clearInterval(ou),ou=null)});await d.start();await d.invoke("RegisterCompanion",ty());ou=window.setInterval(kf,25e3)}};window.addEventListener("beforeunload",()=>{ou&&(window.clearInterval(ou),ou=null),d&&d.stop().catch(()=>{})});const ui=t=>n(tw,t),ft=()=>{const n=gr(),t=vu(),i=ff&&Date.now()-le>=750;sr&&(sr.disabled=!n||!t||ae);oo&&(oo.disabled=!n||!String(te?.value||"").trim()||ae);uh&&(uh.disabled=!wr?.canImport||!ce||ae);so&&(so.disabled=!i||wh||ry().length===0)},yu=n=>{r(gp,!n);r(wp,n);bc();tl();for(const t of wl)r(t,n?!0:t.dataset.tabPanel!=="scene"&&!t.classList.contains("is-active"));n||vv()},il=()=>{if(et){if(ir.length===0){c(et,"No projects available.");return}ys(et,"Choose a project",ir,"projectId","title");const n=Number.parseInt(p?.value||"",10);Number.isInteger(n)&&n>0&&(et.value=String(n))}},fd=(n=null)=>{if(g){if(ii.length===0){c(g,"No books available.");return}ys(g,"Choose a book",ii.map(n=>({...n,displayTitle:dr(n)})),"bookId","displayTitle");const i=n||Number.parseInt(ot?.value||"",10),t=ii.find(n=>n.bookId===i);t&&(g.value=String(t.bookId));ft()}},lt=(t="Select a Project and Book to begin.")=>{wr=null,ce=null,hi=[],ns=!1,ff=!1,le=0,r(hr,!0),r(rh,!0),r(ku,!0),r(gu,!0),hr&&(hr.innerHTML=""),ki&&(ki.innerHTML=""),n(du,""),ui(t),ft()},ry=()=>ki?[...ki.querySelectorAll("input[type='checkbox']:checked")].map(n=>String(n.value||"").trim()).filter(Boolean):[],ed=t=>{if(hi=Array.isArray(t)?t:[],ku&&ki){if(ki.innerHTML="",r(ku,!1),r(gu,!ns||hi.length===0),r(so,!1),r(bl,!1),r(kl,!0),hi.length===0){n(du,"No likely major characters found.");ft();return}n(du,`${hi.length} likely major characters found.`);for(const n of hi){const i=document.createElement("label");i.className="word-companion-character-candidate";const t=document.createElement("input");t.type="checkbox";t.value=n.text||"";t.checked=String(n.confidence||"").trim().toLowerCase()==="high";t.addEventListener("change",ft);const u=document.createElement("strong");u.textContent=n.text||"";const f=document.createElement("em"),e=String(n.reason||"").trim();f.textContent=e?`${Number(n.mentionCount||0).toLocaleString()} mentions · ${e}`:`${Number(n.mentionCount||0).toLocaleString()} mentions`;const r=document.createElement("span");r.className="word-companion-character-candidate-text";r.append(u,f);i.append(t,r);ki.append(i)}ft()}},od=n=>{if(hr){hr.innerHTML="";const t=document.createElement("strong");t.textContent="Manuscript Analysis";hr.append(t);const i=document.createElement("dl"),u=[["Project",n.projectTitle],["Book",dr({title:n.bookTitle,subtitle:n.bookSubtitle})],["Chapters",Number(n.chapterCount||0).toLocaleString()],["Scenes",Number(n.sceneCount||0).toLocaleString()],["Words",Number(n.wordCount||0).toLocaleString()]];for(const[n,t]of u){const r=document.createElement("dt");r.textContent=n;const u=document.createElement("dd");u.textContent=t||"-";i.append(r,u)}hr.append(i);r(hr,!1);r(rh,!1);ui(n.message||"Preview generated.");ft()}},rl=()=>{const n=window.Office?.context?.document?.settings;if(!n)return null;const u=String(n.get(bi.documentGuid)||"").trim(),t=Number.parseInt(n.get(bi.bookId)||"",10),i=Number.parseInt(n.get(bi.projectId)||"",10),r=Number.parseInt(n.get(bi.bindingVersion)||"",10);return!u||!Number.isInteger(t)||t<=0||!Number.isInteger(i)||i<=0?null:{documentGuid:u,bookId:t,projectId:i,bindingVersion:Number.isInteger(r)&&r>0?r:1}},sd=()=>{const i=ri||rl();if(i)return i;const r=ur?.manuscriptDocument?.documentGuid||"",n=Number.parseInt(ur?.bookId||"",10),t=Number.parseInt(ur?.projectId||"",10);return r&&Number.isInteger(n)&&n>0&&Number.isInteger(t)&&t>0?{documentGuid:r,bookId:n,projectId:t,bindingVersion:Number.parseInt(ur?.manuscriptDocument?.bindingVersion||"",10)||1}:null},hd=n=>new Promise((t,i)=>{const r=window.Office?.context?.document?.settings;if(!r){i(new Error("Word document settings are unavailable."));return}r.set(bi.documentGuid,n.documentGuid);r.set(bi.bookId,String(n.bookId));r.set(bi.projectId,String(n.projectId));r.set(bi.bindingVersion,String(n.bindingVersion||1));r.saveAsync(n=>{n.status===window.Office.AsyncResultStatus.Succeeded?t():i(n.error||new Error("Unable to save Word document metadata."))})}),uy=()=>new Promise((n,t)=>{const i=window.Office?.context?.document?.settings;if(!i){t(new Error("Word document settings are unavailable."));return}for(const n of Object.values(bi))typeof i.remove=="function"?i.remove(n):i.set(n,"");i.saveAsync(i=>{i.status===window.Office.AsyncResultStatus.Succeeded?n():t(i.error||new Error("Unable to remove Word document metadata."))})}),fy=()=>ri?.documentGuid?ri.documentGuid:window.crypto?.randomUUID?window.crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(Number(n)^Math.random()*16>>Number(n)/4).toString(16)),or=()=>ri?.documentGuid||rl()?.documentGuid||"",pi=()=>{const t=ni(),n=h();fa&&(fa.textContent=t?.title||"(Not connected)");ea&&(ea.textContent=n?dr(n):"(Not connected)");ya&&(ya.textContent=n?"":"Select a PlotDirector book before refreshing.");fs();tl()},ey=()=>{const t=Array.isArray(ct.characters)?ct.characters.length:0,i=Array.isArray(ct.assets)?ct.assets.length:0,r=Array.isArray(ct.locations)?ct.locations.length:0;n(lw,`Characters (${t})`);n(aw,`Assets (${i})`);n(vw,`Locations (${r})`)},io=n=>{const t=n?.styleBuiltIn||n?.style||"";return String(t).replace(/\s+/g,"").toLowerCase()},wi=(n,t)=>{const i=io(n);return i===`heading${t}`||i.endsWith(`.heading${t}`)||i.includes(`heading${t}`)},df=n=>{const t=String(n||"").trim().split(/\s+/).filter(Boolean);return t.length},cd=(n,t)=>String(n?.text||"").trim()===String(t?.text||"").trim()&&io(n)===io(t),oy=(n,t)=>{const r=String(n||"").match(new RegExp(`^${t}-(\\d+)$`,"i"));if(!r)return null;const i=Number.parseInt(r[1],10);return Number.isInteger(i)&&i>0?i:null},sy=n=>{try{return Array.isArray(n?.contentControls?.items)?n.contentControls.items:[]}catch(t){return console.warn("Word paragraph content controls were not available.",t),[]}},ps=(n,t)=>{const i=sy(n);for(const n of i){const i=oy(n.tag,t);if(i)return i}return null},ld=(n,t)=>{const u=[];let o=0,s=0,i=null,r=null;n.forEach((n,t)=>{const f=String(n.text||"").trim();if(f){if(wi(n,1)){o+=1;i={index:u.length+1,paragraphIndex:t,title:f,anchorId:ps(n,"PD-CHAPTER"),scenes:[]};u.push(i);r=null;return}if(wi(n,2)){if(s+=1,!i)return;r={index:i.scenes.length+1,paragraphIndex:t,title:f,anchorId:ps(n,"PD-SCENE"),wordCount:0};i.scenes.push(r);return}r&&(r.wordCount+=df(f))}});const h=t.find(n=>String(n.text||"").trim()),f=h?n.findIndex(n=>cd(n,h)):-1,e=f>=0?u.filter(n=>n.paragraphIndex<=f).at(-1)||null:null,c=e&&f>=0?e.scenes.filter(n=>n.paragraphIndex<=f).at(-1)||null:null;return{chapters:u,currentChapter:e,currentScene:c,paragraphCount:n.length,heading1Count:o,heading2Count:s}},ad=(n,t)=>{const r=[];let i=null,u=null,f=0;const e=[],s=new Set(["***","###"]),o=()=>{if(!i)return null;const n={title:`Scene ${i.scenes.length+1}`,sortOrder:(i.scenes.length+1)*10,wordCount:0};return i.scenes.push(n),n};return n.forEach(n=>{const h=String(n.text||"").trim();if(h){if(e.push(h),wi(n,1)){i={title:h,sortOrder:(r.length+1)*10,wordCount:0,scenes:[]};r.push(i);u=o();f+=df(h);return}if(i&&u){if(t&&s.has(h)){u=o();return}const c=df(h);i.wordCount+=c;u.wordCount+=c;f+=c}}}),{chapters:r,chapterCount:r.length,sceneCount:r.reduce((n,t)=>n+t.scenes.length,0),wordCount:f,documentText:e.join("\n")}},ws=new Set(["***","###"]),vd=(n,t)=>{const i=String(n?.text||"").trim();return{index:t,text:i,styleBuiltIn:n?.styleBuiltIn||"",style:n?.style||"",wordCount:df(i),chapterAnchorId:null,sceneAnchorId:null}},hy=(n,t)=>{n&&(n.endParagraphIndex=t)},cy=(n,t)=>{n&&(n.endParagraphIndex=t,hy(n.scenes.at(-1),t))},yd=(n,t)=>{const u=n.map(vd),f=[];let o=0,s=0,i=null,r=null,e=0;const h=(n,t=null,u=null)=>i?(hy(r,n.index-1),r={index:i.scenes.length+1,paragraphIndex:n.index,startParagraphIndex:n.index,endParagraphIndex:n.index,title:t||`Scene ${i.scenes.length+1}`,anchorId:u,wordCount:0},i.scenes.push(r),r):null;for(const n of u)if(n.text){if(wi(n,1)){cy(i,n.index-1);o+=1;i={index:f.length+1,paragraphIndex:n.index,startParagraphIndex:n.index,endParagraphIndex:n.index,title:n.text,anchorId:n.chapterAnchorId,wordCount:0,scenes:[]};f.push(i);r=null;h(n,t?"Scene 1":"Scene 1",n.sceneAnchorId);e+=n.wordCount;continue}if(i){if(t&&ws.has(n.text)){s+=1;h(n);continue}i.wordCount+=n.wordCount;r&&(r.wordCount+=n.wordCount);e+=n.wordCount}}return cy(i,u.length-1),{paragraphs:u,chapters:f,usesExplicitScenes:!!t,paragraphCount:u.length,heading1Count:o,heading2Count:s,documentWordCount:e,currentParagraphIndex:null,currentChapter:null,currentScene:null}},pu=(n,t,i)=>n?.[t]??n?.[i]??null,pd=n=>(Array.isArray(n)?n:[]).map((n,t)=>({temporaryCharacterKey:`character-${t+1}`,name:pu(n,"text","Text")||pu(n,"name","Name")||"",mentionCount:Number.parseInt(pu(n,"mentionCount","MentionCount")||"0",10)||0,qualityScore:Number.parseInt(pu(n,"qualityScore","QualityScore")||"0",10)||0,category:pu(n,"category","Category")||"PossibleCharacter",reason:pu(n,"reason","Reason")||"",isExistingCharacterMatch:!!pu(n,"isExistingCharacterMatch","IsExistingCharacterMatch"),suggestedImportance:null})).filter(n=>n.name),wd=(n,t)=>{const u=[],f=[],s=[];let i=null,r=null,e=0,h=0;const c=()=>{r=null},l=(n,t,r=false)=>(c(),i={temporaryChapterKey:`chapter-${u.length+1}`,chapterNumber:u.length+1,title:t,wordCount:0,chapterTextParagraphs:[],chapterText:"",startPosition:n?.index??null,existingChapterID:r?null:ps(n,"PD-CHAPTER")},u.push(i),o(n,null),i),o=(n,t=null)=>i?(c(),r={temporarySceneKey:`scene-${f.length+1}`,temporaryChapterKey:i.temporaryChapterKey,sceneNumberWithinChapter:f.filter(n=>n.temporaryChapterKey===i.temporaryChapterKey).length+1,title:t,wordCount:0,openingTextPreview:"",startPosition:n?.index??null,existingSceneID:n?ps(n,"PD-SCENE"):null},f.push(r),r):null,a=(n,t)=>{!i||!r||t<=0||(i.wordCount+=t,i.chapterTextParagraphs.push(n),r.wordCount+=t,r.openingTextPreview||!n||ws.has(n)||(r.openingTextPreview=n.length>180?`${n.slice(0,177)}...`:n))};if(n.forEach((n,t)=>{n.index=t;const r=String(n.text||"").trim();if(r){s.push(r);const u=df(r);if(wi(n,1)){h+=1;l(n,r);e+=u;i.wordCount+=u;i.chapterTextParagraphs.push(r);return}if(i||l(n,"Opening pages",!0),wi(n,2)){o(n,r);e+=u;a(r,u);return}if(ws.has(r)){o(n,null);return}e+=u;a(r,u)}}),e===0)throw new Error("The document appears to be empty. Add manuscript text, then try again.");if(h===0)throw new Error("No chapters were detected. Make sure your chapter headings use Heading 1, or add clear chapter headings.");u.forEach(n=>{n.chapterText=Array.isArray(n.chapterTextParagraphs)?n.chapterTextParagraphs.join("\n\n"):"",delete n.chapterTextParagraphs});const v=s.join("\n");return{previewID:"00000000-0000-0000-0000-000000000000",userID:nu(t,"userID","UserID","userId"),onboardingID:nu(t,"onboardingID","OnboardingID","onboardingId"),projectID:nu(t,"projectID","ProjectID","projectId"),bookID:nu(t,"bookID","BookID","bookId"),source:"WordCompanion",documentTitle:ny()||"Word manuscript",companionDocumentIdentifier:or(),totalWordCount:e,chapterCount:u.length,sceneCount:f.length,characterCandidateCount:0,createdUtc:(new Date).toISOString(),chapters:u,scenes:f,characterCandidates:[],documentTextForDiscovery:v}},nu=(n,...t)=>{for(const i of t)if(n?.[i]!==undefined&&n?.[i]!==null)return n[i];return null},gf=async(n,t,i,r={})=>{d&&d.state===signalR.HubConnectionState.Connected&&await d.invoke("ReportOnboardingScanProgress",{userID:nu(n,"userID","UserID","userId"),onboardingID:nu(n,"onboardingID","OnboardingID","onboardingId"),message:t,percentComplete:i,chapterCount:r.chapterCount||0,sceneCount:r.sceneCount||0,characterCandidateCount:r.characterCandidateCount||0,totalWordCount:r.totalWordCount||0})},ly=async(n,t)=>{d&&d.state===signalR.HubConnectionState.Connected&&await d.invoke("FailOnboardingScan",{userID:nu(n,"userID","UserID","userId"),onboardingID:nu(n,"onboardingID","OnboardingID","onboardingId"),message:t})},bd=async n=>{if(!nt||!window.Word){await ly(n,"Open your manuscript in Microsoft Word, then try the scan again.");return}try{await gf(n,"Preparing document scan",5);const i=await window.Word.run(async t=>{const i=t.document.body.paragraphs;i.load("items/text,items/style,items/styleBuiltIn");await t.sync();await gf(n,"Detecting chapters",20);for(const n of i.items)(wi(n,1)||wi(n,2))&&n.contentControls.load("items/tag,title");return await t.sync(),i.items}),t=wd(i,n);await gf(n,"Detecting scene breaks",50,t);await gf(n,`Scene ${t.sceneCount} of ${t.sceneCount} scanned`,70,t);await gf(n,"Finding character candidates",85,t);const r=t.documentTextForDiscovery||"";delete t.documentTextForDiscovery;try{const n=await st("/api/word-companion/manuscript/discover-characters",{projectId:t.projectID,documentText:r,includeExcluded:!0});t.characterCandidates=pd(n?.candidates);t.characterCandidateCount=t.characterCandidates.filter(n=>String(n.category||"").toLowerCase()!=="excluded").length}catch(u){console.warn("Unable to refine onboarding character candidates.",u);t.characterCandidates=[];t.characterCandidateCount=0}await gf(n,"Preparing preview",95,t);go=t;await d.invoke("CompleteOnboardingScan",t)}catch(t){console.error("Unable to complete onboarding scan.",t);await ly(n,dd(t))}},kd=async n=>{if(!go||!nt||!window.Word||typeof window.Word.run!="function")throw new Error("Word document access is unavailable.");const t=new Map((n?.chapterMappings||n?.ChapterMappings||[]).map(n=>[n.temporaryChapterKey||n.TemporaryChapterKey,n.chapterID||n.ChapterID])),i=new Map((n?.sceneMappings||n?.SceneMappings||[]).map(n=>[n.temporarySceneKey||n.TemporarySceneKey,n.sceneID||n.SceneID]));await window.Word.run(async n=>{const r=n.document.body.paragraphs;r.load("items/text,items/style,items/styleBuiltIn");await n.sync();for(const n of go.chapters||[]){const u=t.get(n.temporaryChapterKey),i=Number.parseInt(n.startPosition,10);u&&Number.isInteger(i)&&r.items[i]&&wu(r.items[i],"PlotDirector Chapter",`PD-CHAPTER-${u}`,"PD-CHAPTER")}for(const n of go.scenes||[]){const u=i.get(n.temporarySceneKey),t=Number.parseInt(n.startPosition,10);u&&Number.isInteger(t)&&r.items[t]&&wu(r.items[t],"PlotDirector Scene",`PD-SCENE-${u}`,"PD-SCENE")}await n.sync()})},dd=n=>{const t=e(n);return/No chapters were detected/i.test(t)?"No chapters were detected. Make sure your chapter headings use Heading 1, or add clear chapter headings.":/empty/i.test(t)?"The document appears to be empty. Add manuscript text, then try again.":/network|disconnect|connection/i.test(t)?"The Word Companion disconnected before the scan finished. Reopen Word and try again.":`The scan could not finish: ${t}`},gd=(n,t)=>String(n?.text||"").trim()===String(t?.text||"").trim()&&io(n)===io(t),ay=(n,t)=>{const r=(t||[]).find(n=>String(n.text||"").trim());if(!n||!r)return n?.currentParagraphIndex??-1;const i=n.paragraphs.filter(n=>gd(n,r)).map(n=>n.index);return i.length===0?n.currentParagraphIndex??-1:Number.isInteger(n.currentParagraphIndex)?i.reduce((t,i)=>Math.abs(i-n.currentParagraphIndex)<Math.abs(t-n.currentParagraphIndex)?i:t,i[0]):i[0]},ng=(n,t)=>!n||!Number.isInteger(t)||t<0?null:n.chapters.filter(n=>n.startParagraphIndex<=t).at(-1)||null,tg=(n,t)=>!n||!Number.isInteger(t)||t<0?null:n.scenes.filter(n=>n.startParagraphIndex<=t).at(-1)||null,vy=n=>{if(!l)return!1;const t=ng(l,n),i=tg(t,n),r=t?.startParagraphIndex!==l.currentChapter?.startParagraphIndex||i?.startParagraphIndex!==l.currentScene?.startParagraphIndex||t?.anchorId!==l.currentChapter?.anchorId||i?.anchorId!==l.currentScene?.anchorId;return(l.currentParagraphIndex=n,l.currentChapter=t,l.currentScene=i,!r)?!1:(yf(t?.title,i?.title,i?.wordCount,t?.anchorId,i?.anchorId,t?.index),r)},ul=n=>{if(ie){if(ie.innerHTML="",n.chapters.length===0){const n=document.createElement("p");n.textContent="No chapters detected. Use Heading 1 for chapter titles.";ie.append(n);return}const t=n.chapters.some(n=>n.scenes.length>0);if(!t){const n=document.createElement("p");n.textContent="No scenes detected. Use Heading 2 for scene titles.";ie.append(n)}for(const t of n.chapters){const n=document.createElement("div");n.className="word-companion-outline-chapter";const i=document.createElement("strong");if(i.textContent=t.title,n.append(i),t.scenes.length>0){const i=document.createElement("ul");for(const n of t.scenes){const t=document.createElement("li");t.textContent=n.title;i.append(t)}n.append(i)}ie.append(n)}}},yy=[{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"}],ig={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},rg={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},bs=(n,t)=>ut(n,t).toLocaleLowerCase(),fi=({category:i,action:n,type:s,wordTitle:l,match:r="",anchorStatus:t="None",matches:u=[],pdChapter:e=null,pdScene:o=null,wordChapter:h=null,wordScene:c=null,parentItem:f=null})=>({id:`${s}-${h?.index||0}-${c?.index||0}-${h?.paragraphIndex??c?.paragraphIndex??0}`,category:i,action:n,type:s,wordTitle:l,match:r,anchorStatus:t,matches:u,pdChapter:e,pdScene:o,wordChapter:h,wordScene:c,parentItem:f,result:"Pending",error:""}),ei=(n,t)=>{Array.isArray(n[t.category])&&n[t.category].push(t)},fl=n=>Array.isArray(n?.scenes)?n.scenes:[],ug=(n,t)=>{for(const i of n){const n=fl(i).find(n=>n.sceneId===t);if(n)return{chapter:i,scene:n}}return null},fg=(n,t,i)=>{const u=n.anchorId?`PD-CHAPTER-${n.anchorId}`:"None";if(n.anchorId){const r=t.find(t=>t.chapterId===n.anchorId);if(r){const t=fi({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:n.title,match:`Chapter ${r.chapterId}: ${r.title}`,anchorStatus:u,pdChapter:r,wordChapter:n});return ei(i,t),t}const f=fi({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:n.title,anchorStatus:`${u} not found`,matches:[],pdChapter:null,wordChapter:n});return ei(i,f),f}const r=t.filter(t=>bs(t.title,"chapter")===bs(n.title,"chapter"));if(r.length===1){const t=fi({category:"couldLink",action:"couldLink",type:"Chapter",wordTitle:n.title,match:`Chapter ${r[0].chapterId}: ${r[0].title}`,anchorStatus:u,pdChapter:r[0],wordChapter:n});return ei(i,t),t}if(r.length>1){const t=fi({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:n.title,anchorStatus:u,matches:r.map(n=>`Chapter ${n.chapterId}: ${n.title}`),pdChapter:null,wordChapter:n});return ei(i,t),t}const f=fi({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:n.title,anchorStatus:u,pdChapter:null,wordChapter:n});return ei(i,f),f},eg=(n,t,i,r)=>{const u=n.anchorId?`PD-SCENE-${n.anchorId}`:"None";if(n.anchorId){const f=ug(i,n.anchorId);if(f){ei(r,fi({category:"alreadyLinked",action:"alreadyLinked",type:"Scene",wordTitle:n.title,match:`Scene ${f.scene.sceneId}: ${f.scene.title}`,anchorStatus:u,pdChapter:f.chapter,pdScene:f.scene,wordChapter:t?.wordChapter,wordScene:n,parentItem:t}));return}ei(r,fi({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:n.title,anchorStatus:`${u} not found`,wordChapter:t?.wordChapter,wordScene:n,parentItem:t}));return}if(!t?.pdChapter&&t?.category==="manualReview"){ei(r,fi({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:n.title,anchorStatus:u,matches:["Parent chapter requires manual review."],wordChapter:t?.wordChapter,wordScene:n,parentItem:t}));return}if(!t?.pdChapter){ei(r,fi({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:n.title,anchorStatus:u,wordChapter:t?.wordChapter,wordScene:n,parentItem:t}));return}const f=fl(t.pdChapter).filter(t=>bs(t.title,"scene")===bs(n.title,"scene"));if(f.length===1){ei(r,fi({category:"couldLink",action:"couldLink",type:"Scene",wordTitle:n.title,match:`Scene ${f[0].sceneId}: ${f[0].title}`,anchorStatus:u,pdChapter:t.pdChapter,pdScene:f[0],wordChapter:t.wordChapter,wordScene:n,parentItem:t}));return}if(f.length>1){ei(r,fi({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:n.title,anchorStatus:u,matches:f.map(n=>`Scene ${n.sceneId}: ${n.title}`),wordChapter:t.wordChapter,wordScene:n,parentItem:t}));return}ei(r,fi({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:n.title,anchorStatus:u,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:n,parentItem:t}))},og=(n,t)=>{const i={alreadyLinked:[],couldLink:[],wouldCreateChapters:[],wouldCreateScenes:[],manualReview:[]},r=Array.isArray(t?.chapters)?t.chapters:[];for(const t of Array.isArray(n?.chapters)?n.chapters:[]){const n=fg(t,r,i);for(const u of fl(t))eg(u,n,r,i)}return i},sg=n=>{const t=document.createElement("article");t.className="word-companion-preview-item";const i=document.createElement("strong");i.textContent=`${rg[n.action]||""} ${n.type}: ${n.wordTitle}`;t.append(i);const r=document.createElement("span");if(r.textContent=`Anchor: ${n.anchorStatus||"None"}`,t.append(r),n.match){const i=document.createElement("span");i.textContent=`Match: ${n.match}`;t.append(i)}if(Array.isArray(n.matches)&&n.matches.length>0){const i=document.createElement("div");i.className="word-companion-preview-matches";const r=document.createElement("span");r.textContent="Matches:";i.append(r);const u=document.createElement("ul");for(const t of n.matches){const n=document.createElement("li");n.textContent=t;u.append(n)}i.append(u);t.append(i)}const u=document.createElement("span");if(u.textContent=`Action: ${ig[n.action]||n.action}`,t.append(u),n.result&&n.result!=="Pending"){const i=document.createElement("span");i.textContent=n.error?`Result: ${n.result} - ${n.error}`:`Result: ${n.result}`;t.append(i)}return t},py=n=>{if(rf){rf.innerHTML="";for(const t of yy){const i=document.createElement("section");i.className="word-companion-preview-group";const r=document.createElement("strong");r.textContent=t.title;i.append(r);const u=Array.isArray(n?.[t.key])?n[t.key]:[];if(u.length===0){const n=document.createElement("p");n.className="word-companion-empty-list";n.textContent="None";i.append(n)}else for(const n of u)i.append(sg(n));rf.append(i)}us()}},ne=async n=>{const t=n.document.body.paragraphs,i=n.document.getSelection().paragraphs;t.load("text,styleBuiltIn,style");i.load("text,styleBuiltIn,style");await n.sync();try{for(const n of t.items)(wi(n,1)||wi(n,2))&&n.contentControls.load("items/tag,title");await n.sync()}catch(u){console.warn("Unable to load Word heading content controls. Continuing without PlotDirector anchors.",u)}const r=ld(t.items,i.items);return r.bodyParagraphs=t.items,r},wy=async(n,t)=>{const u=n.document.body.paragraphs,f=n.document.getSelection().paragraphs;u.load("text,styleBuiltIn,style");f.load("text,styleBuiltIn,style");await n.sync();const r=yd(u.items,t),e=ay(r,f.items);return l=r,vy(e),i("Cache rebuilt."),r},dtt=async n=>{const t=n.document.getSelection().paragraphs;return t.load("text,styleBuiltIn,style"),await n.sync(),t.items},y=()=>window.performance&&typeof window.performance.now=="function"?window.performance.now():Date.now(),ti=n=>!!n&&!n.stale&&n.generation===ye&&n.documentGuid===or()&&n.sceneId===u,by=async(n={})=>{const r=!!n.includeSelection,w=n.updateDisplay!==!1,f=ye,b=y(),k=ni(),d=h(),e=l?.currentScene;if(!e||!Number.isInteger(e.startParagraphIndex)||!Number.isInteger(e.endParagraphIndex)||!kt||!nt||!window.Word||typeof window.Word.run!="function")return null;const g=y(),s=await window.Word.run(async n=>{const i=n.document.body.paragraphs;i.load("text");let t=null;return r&&(t=n.document.getSelection().paragraphs,t.load("text,styleBuiltIn,style")),await n.sync(),{bodyTexts:i.items.map(n=>String(n.text||"")),selectionParagraphs:r&&t?t.items.map(n=>({text:String(n.text||""),styleBuiltIn:n.styleBuiltIn,style:n.style})):[]}}),c=Math.round(y()-g);if(f!==ye)return ci(`Office snapshot: ${c}ms stale`),{stale:!0,generation:f};let a=!1;if(r){const n=ay(l,s.selectionParagraphs);a=vy(n)}const t=l?.currentScene;if(!t||!Number.isInteger(t.startParagraphIndex)||!Number.isInteger(t.endParagraphIndex))return null;const v=[];let i=0;const tt=Math.min(t.endParagraphIndex,s.bodyTexts.length-1),it=l.currentChapter?.startParagraphIndex;for(let n=t.startParagraphIndex;n<=tt;n+=1){const t=String(s.bodyTexts[n]||"").trim();t&&!ws.has(t)&&n!==it&&(v.push(t),i+=df(t))}t.wordCount=i;w&&yf(l.currentChapter?.title,t.title,i,l.currentChapter?.anchorId,t.anchorId,l.currentChapter?.index);const p={documentGuid:or(),projectId:k?.projectId||null,bookId:d?.bookId||null,chapterId:o,sceneId:u,chapterTitle:l.currentChapter?.title||"",sceneTitle:t.title||"",sceneText:v.join("\n"),wordCount:i,selectionSignature:`${l.currentParagraphIndex??-1}:${t.startParagraphIndex}:${t.endParagraphIndex}`,selectionChanged:a,generation:f};return pe=p,ci(`Office snapshot: ${c}ms; scene words: ${i}; total snapshot: ${Math.round(y()-b)}ms`),p},ky=async()=>ti(pe)?pe:await by(),dy=async()=>{if(t(""),!kt||!nt||!window.Word||typeof window.Word.run!="function")return yf(null,null,null),t("Word document access is unavailable."),f({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;tu&&(tu.disabled=!0,tu.textContent="Scanning...");t("Scanning document structure...");try{const n=await window.Word.run(async n=>{const t=h();return t?await wy(n,!!t.usesExplicitScenes):(l=null,await ne(n))});return l||yf(n.currentChapter?.title,n.currentScene?.title,n.currentScene?.wordCount,n.currentChapter?.anchorId,n.currentScene?.anchorId,n.currentChapter?.index),it("Not detected"),ul(n),t(""),f({lastScan:"Success",lastError:"-",paragraphs:String(n.paragraphCount),heading1:String(n.heading1Count),heading2:String(n.heading2Count)}),!0}catch(n){const i=e(n);return console.error("Unable to scan the Word document.",n),yf(null,null,null),t(`Unable to scan the Word document: ${i}`),f({lastScan:"Failure",lastError:i}),!1}finally{tu&&(tu.disabled=!1,tu.textContent="Refresh Document Structure")}},gy=async()=>{const n=h();if(!ni()||!n)return er("Select a project and book to analyse manuscript structure."),!1;if(!kt||!nt||!window.Word||typeof window.Word.run!="function")return er("Word document access is unavailable."),f({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;cr&&(cr.disabled=!0,cr.textContent="Analysing...");er("Analysing manuscript structure...");try{const t=await window.Word.run(async n=>await ne(n)),i=await at(`/api/word-companion/books/${n.bookId}/structure`);return yf(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),ul(t),vi=og(t,i),py(vi),er("Preview generated. No changes have been applied."),f({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),!0}catch(t){return console.error("Unable to analyse manuscript structure.",t),er("Unable to analyse manuscript structure."),f({lastScan:"Failure",lastError:e(t)}),!1}finally{cr&&(cr.textContent="Analyse Manuscript Structure",fs())}},hg=(n=vi)=>{const t=su(n),i=t.filter(n=>n.category==="couldLink"&&n.type==="Chapter").length,r=t.filter(n=>n.category==="couldLink"&&n.type==="Scene").length,u=t.filter(n=>n.category==="wouldCreateChapters").length,f=t.filter(n=>n.category==="wouldCreateScenes").length,e=Array.isArray(n?.manualReview)?n.manualReview.length:0;return{linkChapters:i,linkScenes:r,createChapters:u,createScenes:f,manualReview:e}},cg=n=>{if(ah){ah.innerHTML="";const i=[`Link ${n.linkChapters+n.linkScenes} chapters/scenes`,`Create ${n.createChapters} chapters`,`Create ${n.createScenes} scenes`],t=document.createElement("ul");for(const n of i){const i=document.createElement("li");i.textContent=n;t.append(i)}ah.append(t)}},el=n=>{ts&&(ts(n),ts=null),tr?.close?tr.close():tr&&(tr.hidden=!0)},lg=()=>{const n=hg();return(cg(n),!tr)?Promise.resolve(window.confirm(`Apply Structure Sync?
This will:
- Link ${n.linkChapters+n.linkScenes} chapters/scenes
- Create ${n.createChapters} chapters
- Create ${n.createScenes} scenes
Manual review items will be skipped.`)):new Promise(n=>{ts=n,tr.showModal?tr.showModal():tr.hidden=!1})},ro=(n,t,i="")=>{n.result=t,n.error=i},np=n=>Number.isInteger(n?.wordChapter?.index)&&n.wordChapter.index>0?n.wordChapter.index*10:null,tp=n=>Number.isInteger(n?.wordScene?.index)&&n.wordScene.index>0?n.wordScene.index*10:null,ag=async(n,t)=>{const i=await st(`/api/word-companion/books/${n}/chapters`,{title:au(t.wordTitle),sortOrder:np(t)});if(!i?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");hu();t.pdChapter={chapterId:i.chapterId,title:i.title||t.wordTitle,sortOrder:i.sortOrder||np(t)||0,scenes:[]};t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},vg=async(n,t)=>{const i=t.pdChapter||t.parentItem?.pdChapter;if(!i?.chapterId)throw new Error("Scene parent chapter is not available.");const r=await st(`/api/word-companion/books/${n}/chapters/${i.chapterId}/scenes`,{sceneTitle:au(t.wordTitle),sortOrder:tp(t)});if(!r?.sceneId)throw new Error("Scene creation did not return a scene ID.");hu();t.pdChapter=i;t.pdScene={sceneId:r.sceneId,title:t.wordTitle,sortOrder:tp(t)||0};t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},yg=async n=>{if(!kt||!nt||!window.Word||typeof window.Word.run!="function")throw new Error("Word document access is unavailable.");await window.Word.run(async t=>{const u=await ne(t),r=n.type==="Chapter"?n.wordChapter:n.wordScene,i=Number.isInteger(r?.paragraphIndex)?u.bodyParagraphs[r.paragraphIndex]:null;if(!i)throw new Error("Unable to locate the Word heading.");if(n.type==="Chapter"){const t=n.pdChapter?.chapterId;if(!t)throw new Error("Chapter ID is not available.");wu(i,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=n.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");wu(i,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()})},pg=n=>`Structure Sync Complete. Created: ${n.createdChapters} Chapters, ${n.createdScenes} Scenes. Linked: ${n.linkedChapters} Chapters, ${n.linkedScenes} Scenes. Skipped: ${n.skipped} Manual Review items. Failed: ${n.failed} Items.`,wg=async()=>{const r=h();if(!r||su().length===0||ve){us();return}const f=await lg();if(f){ve=!0;fs();er("Applying structure sync...");const n={createdChapters:0,createdScenes:0,linkedChapters:0,linkedScenes:0,skipped:Array.isArray(vi?.manualReview)?vi.manualReview.length:0,failed:0},o=su().filter(n=>n.category==="couldLink"&&n.type==="Chapter"),s=su().filter(n=>n.category==="wouldCreateChapters"),c=su().filter(n=>n.category==="couldLink"&&n.type==="Scene"),l=su().filter(n=>n.category==="wouldCreateScenes"),u=[];let t="";const i=(n,t)=>{u.push({item:n,counterName:t})},a=async(t,i)=>{try{await yg(t);ro(t,"Success");n[i]+=1}catch(r){ro(t,"Failed",e(r));n.failed+=1}};try{for(const n of o)i(n,"linkedChapters");for(const t of s)try{await ag(r.bookId,t);i(t,"createdChapters")}catch(u){ro(t,"Failed",e(u));n.failed+=1}for(const n of c)i(n,"linkedScenes");for(const t of l)try{await vg(r.bookId,t);i(t,"createdScenes")}catch(u){ro(t,"Failed",e(u));n.failed+=1}for(const n of u)await a(n.item,n.counterName);for(const n of vi.manualReview||[])ro(n,"Skipped");py(vi);t=pg(n);er(t)}finally{ve=!1;fs();t&&(hu(),await gy(),er(`${t} Preview refreshed.`))}}},bg=async()=>{ru&&(ru.disabled=!0,ru.textContent="Running...");try{if(await gv(),!kt||!nt||!window.Word||typeof window.Word.run!="function"){f({lastScan:"Failure",lastError:"Word document access is unavailable.",paragraphs:"-",heading1:"-",heading2:"-"});return}const n=await window.Word.run(async n=>{const t=n.document.body.paragraphs;return t.load("items"),await n.sync(),t.items.length});f({lastScan:"Success",lastError:"-",paragraphs:String(n)})}catch(n){console.error("Word Companion diagnostics failed.",n);const i=e(n);f({lastScan:"Failure",lastError:i});t(`Unable to scan the Word document: ${i}`)}finally{ru&&(ru.disabled=!1,ru.textContent="Run Diagnostics")}},at=async(n,t={})=>{const i=await window.fetch(n,{credentials:"same-origin",...t,headers:{Accept:"application/json",...(t.headers||{})}});if(!i.ok)throw new Error(`Request failed: ${i.status}`);return await i.json()},st=(n,t)=>at(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),kg=async()=>{const n=gr(),t=vu();if(!n||!t){lt("Select a Project and Book to begin.");return}if(!kt||!nt||!window.Word||typeof window.Word.run!="function"){lt("Word document access is unavailable.");return}sr&&(sr.disabled=!0,sr.textContent="Scanning...");ui("Scanning manuscript structure...");try{const i=await window.Word.run(async n=>{const i=n.document.body.paragraphs;return i.load("text,styleBuiltIn,style"),await n.sync(),ad(i.items,!!t.usesExplicitScenes)});ce=i;ns=!1;const u=await st("/api/word-companion/manuscript/analyse",{projectId:n.projectId,bookId:t.bookId,documentGuid:fy(),chapterCount:i.chapterCount,sceneCount:i.sceneCount,wordCount:i.wordCount});wr=u;od(u);try{const t=await st("/api/word-companion/manuscript/discover-characters",{projectId:n.projectId,documentText:i.documentText||""});hi=Array.isArray(t?.candidates)?t.candidates:[];r(ku,!0);r(gu,!0)}catch(e){console.error("Unable to discover character candidates.",e);hi=[];r(ku,!0);r(gu,!0)}f({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(i.chapterCount),heading2:"-"})}catch(i){console.error("Unable to scan manuscript for first-run import.",i);lt(`Unable to scan manuscript: ${e(i)}`);f({lastScan:"Failure",lastError:e(i)})}finally{sr&&(sr.textContent="Scan Manuscript");ft()}},dg=()=>new Promise(n=>{if(!nf||typeof nf.showModal!="function"){n(window.confirm("This Book already contains planned chapters and scenes.\n\nImporting this manuscript will replace the planned structure.\n\nContinue?"));return}const t=t=>{dl?.removeEventListener("click",i),gl?.removeEventListener("click",r),nf?.removeEventListener("cancel",u),nf?.close(),n(t)},i=()=>t(!0),r=()=>t(!1),u=n=>{n.preventDefault(),t(!1)};dl?.addEventListener("click",i);gl?.addEventListener("click",r);nf?.addEventListener("cancel",u);nf.showModal()}),gg=()=>new Promise(n=>{if(!tf||typeof tf.showModal!="function"){n(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?"));return}const t=t=>{na?.removeEventListener("click",i),ta?.removeEventListener("click",r),tf?.removeEventListener("cancel",u),tf?.close(),n(t)},i=()=>t(!0),r=()=>t(!1),u=n=>{n.preventDefault(),t(!1)};na?.addEventListener("click",i);ta?.addEventListener("click",r);tf?.addEventListener("cancel",u);tf.showModal()}),nn=async()=>{const i=gr(),u=vu();if(!i||!u||!ce||!wr?.canImport){ft();return}let n=!1;if(wr.requiresReplaceConfirmation&&(n=await dg(),!n)){ui("Import cancelled.");return}ae=!0;ft();ui("Importing manuscript structure...");try{const h=fy(),f=await st("/api/word-companion/manuscript/import",{projectId:i.projectId,bookId:u.bookId,documentGuid:h,bindingVersion:1,replacePlanned:n,chapters:ce.chapters});if(!f.imported){wr={...wr,canImport:!f.requiresReplaceConfirmation,requiresReplaceConfirmation:!!f.requiresReplaceConfirmation,message:f.message||wr.message};ui(f.message||"Import was not completed.");ft();return}const e=f.manuscriptDocument;await hd({documentGuid:e?.documentGuid||h,bookId:f.bookId,projectId:f.projectId,bindingVersion:e?.bindingVersion||1});ri={documentGuid:e?.documentGuid||h,bookId:f.bookId,projectId:f.projectId,bindingVersion:e?.bindingVersion||1};v(s.projectId,f.projectId);v(s.bookId,f.bookId);p&&(p.value=String(f.projectId));const o=hi;await bu(f.projectId,f.bookId);ge("Connected");ns=!0;ff=o.length>0;le=ff?Date.now():0;hi=o;o.length>0?(yu(!0),ed(o),r(rh,!0),r(gu,!1),ui(f.message||"Manuscript structure imported."),t(f.message||"Manuscript structure imported."),window.setTimeout(ft,750)):await ks(f.message||"Manuscript structure imported.")}catch(f){console.error("Unable to import manuscript structure.",f);ui(`Unable to import manuscript: ${e(f)}`)}finally{ae=!1;ft()}},ks=async(n="")=>{ff=!1;le=0;hi=[];ki&&(ki.innerHTML="");r(ku,!0);yu(!1);ui("");r(gu,!0);n&&t(n);const i=await ip();n&&i&&w&&t(n)},tn=async()=>{const i=gr()||ni(),r=ry();if(!ff||Date.now()-le<750||!i||r.length===0){ft();return}wh=!0;ft();n(du,"Creating selected characters...");try{const u=await st("/api/word-companion/manuscript/create-discovered-characters",{projectId:i.projectId,candidateNames:r});t(u.message||"Characters created.");n(du,`${u.createdCount||0} created, ${u.skippedCount||0} already existed.`);await ks(u.message||"Characters created.")}catch(u){console.error("Unable to create discovered characters.",u);n(du,`Unable to create characters: ${e(u)}`)}finally{wh=!1;ft()}},rn=async(n=u,t=o)=>{const f=ni(),e=h(),c=or(),r=Number.parseInt(n||"",10),s=Number.parseInt(t||"",10);if(f&&e&&c&&Number.isInteger(r)&&!(r<=0)&&Number.isInteger(s)&&!(s<=0)){const l=`${f.projectId}:${e.bookId}:${r}`;if(ac!==l){ac=l;try{await st("/api/word-companion/runtime/current-scene",{documentGuid:c,projectId:f.projectId,bookId:e.bookId,chapterId:s,sceneId:r});i("Current scene follow event sent.")}catch(a){ac="";console.debug("Unable to notify PlotDirector of current scene.",a)}}}},ip=async()=>{const n=h();if(!n||!kt||!nt||!window.Word||typeof window.Word.run!="function")return!1;t("Reading manuscript position...");try{hu();await Promise.all([hl(!0),cl(!0),ll(!0)]);await ls(n.bookId);const i=await window.Word.run(async t=>await wy(t,!!n.usesExplicitScenes));return(ul(i),f({lastScan:"Success",lastError:"-",paragraphs:String(i.paragraphCount),heading1:String(i.heading1Count),heading2:String(i.heading2Count)}),!w)?(it("Not detected"),li(!1),k("Live"),t("Manuscript linked. Click inside a chapter to show the current scene."),!0):(rt?await eo():await vl(),li(!1),k("Live"),t(""),!0)}catch(i){return console.error("Unable to initialise bound manuscript runtime.",i),l=null,k("Manual"),t(`Unable to read manuscript position: ${e(i)}`),f({lastScan:"Failure",lastError:e(i)}),!1}},un=async()=>{if(!uf||!nt){yu(!1);return}const n=rl();if(n)try{const t=await at(`/api/word-companion/runtime/book/${n.bookId}?documentGuid=${encodeURIComponent(n.documentGuid)}`),i=t?.manuscriptDocument;if(t?.bookId===n.bookId&&t?.projectId===n.projectId&&i&&String(i.documentGuid).toLowerCase()===n.documentGuid.toLowerCase()){ri=n;pv(t);v(s.projectId,t.projectId);v(s.bookId,t.bookId);p&&(p.value=String(t.projectId));await bu(t.projectId,t.bookId);yu(!1);ge("Connected");af("Bound manuscript detected.");await ip();return}}catch{}ri=null;bf();il();gr()?await bu(gr().projectId,null):c(g,"Select a project first");lt("Select a Project and Book to begin.");yu(!0)},rp=async n=>{ri=null,yp(),pf(),bf(),it("Not detected"),k("Manual"),ge("Connected"),v(s.projectId,null),v(s.bookId,null),p&&(p.value=""),c(ot,"Select a project first"),il(),et&&(et.value=""),c(g,"Select a project first"),lt(n||"Select a Project and Book to begin."),t(n||"Manuscript unlinked."),gt("No resolved PlotDirector scene."),yu(!0),bc()},fn=async()=>{console.debug("Word Companion unlink clicked");t("Preparing to unlink manuscript...");const n=sd();if(!n){t("This Word document is not linked.");return}if(!n.documentGuid||!Number.isInteger(n.bookId)||n.bookId<=0){t("Unable to unlink: bound document metadata is incomplete.");return}const r=await gg();if(!r){t("Unlink cancelled.");return}t("Unlinking manuscript...");lr&&(lr.disabled=!0,lr.textContent="Unlinking...");try{await st("/api/word-companion/manuscript/unlink",{documentGuid:n.documentGuid,bookId:n.bookId});await uy();await rp("Manuscript unlinked.")}catch(i){console.error("Unable to unlink manuscript binding.",i);t("Unable to unlink from PlotDirector.");const r=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?");if(r)try{await uy();await rp("Word metadata removed. Unlink the Book manually in PlotDirector if it still shows as linked.")}catch(n){console.error("Unable to remove Word document metadata.",n);t(`Unable to remove Word metadata: ${e(n)}`)}else t(`Unable to unlink manuscript: ${e(i)}`)}finally{lr&&(lr.disabled=!1,lr.textContent="Unlink this Word document");bc()}},gtt=(n,t)=>at(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),en=(n,t)=>at(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),ds=n=>n?[...n.querySelectorAll("input[type='checkbox']:checked")].map(n=>Number.parseInt(n.value||"",10)).filter(n=>Number.isInteger(n)&&n>0):[],up=()=>{const n=Number.parseInt(vr?.value||"",10);return Number.isInteger(n)&&n>0?n:null},on=()=>{const n=new Set(ds(re)),t=new Set(ds(ue));ct={characters:ct.characters.map(t=>({...t,linked:n.has(Number.parseInt(hs(t,"character"),10))})),assets:ct.assets.map(n=>({...n,linked:t.has(Number.parseInt(hs(n,"asset"),10))})),locations:ct.locations,primaryLocationId:up()}},sn=async()=>{if(!u)return!1;if(!kt||!nt||!window.Word||typeof window.Word.run!="function")return li(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1;try{const n=await window.Word.run(async n=>await ne(n)),r=n.currentChapter?.title||"",f=n.currentScene?.title||"",t=n.currentScene?.anchorId||null,i=n.currentChapter?.anchorId||null,e=Number.isInteger(t)&&t===u,s=Number.isInteger(i)&&i===o,h=ut(f,"scene").toLocaleLowerCase()===ut(rs||rt,"scene").toLocaleLowerCase(),c=ut(r,"chapter").toLocaleLowerCase()===ut(vc||w,"chapter").toLocaleLowerCase(),l=e||h&&(s||c);return l?(li(!1),!0):(li(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1)}catch(n){return console.error("Unable to verify current Word scene before saving.",n),f({lastError:e(n)}),li(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1}},hn=async()=>{if(!u){cu("Link a PlotDirector scene first.");return}if(ht||!await sn()){cu("The Word cursor is now in a different scene. Refresh Current Scene before saving.");return}di&&(di.disabled=!0,di.textContent="Saving...");try{await en(`/api/word-companion/scenes/${u}/links`,{characterIds:ds(re),assetIds:ds(ue),locationIds:[],primaryLocationId:up()});on();cu("Scene links saved successfully.");f({lastError:"-"})}catch(n){cu("Unable to save scene links.");f({lastError:e(n)})}finally{di&&(di.disabled=!u||ht,di.textContent="Save Scene Links")}},cn=(n,t)=>{const i=sy(n);return i.find(n=>oy(n.tag,t))||null},wu=(n,t,i,r)=>{const f=cn(n,r),u=f||n.getRange().insertContentControl();return u.title=t,u.tag=i,u.appearance="Hidden",u},fp=async(n="PlotDirector IDs attached successfully.")=>{if(!u||!o)return t("No resolved PlotDirector scene."),!1;const r=tt&&tt!==u||b&&b!==o;if(r&&!window.confirm("This scene is already linked. Replace the existing PlotDirector link?"))return!1;if(!kt||!nt||!window.Word||typeof window.Word.run!="function")return t("Word document access is unavailable."),!1;ai&&(ai.disabled=!0,ai.textContent="Attaching...");try{return await window.Word.run(async n=>{const t=await ne(n);if(!t.currentChapter||!t.currentScene)throw new Error("No scene detected in Word. Use Heading 2 for scenes.");const i=t.bodyParagraphs[t.currentChapter.paragraphIndex],r=t.bodyParagraphs[t.currentScene.paragraphIndex];if(!i||!r)throw new Error("Unable to locate the current Word headings.");wu(i,"PlotDirector Chapter",`PD-CHAPTER-${o}`,"PD-CHAPTER");wu(r,"PlotDirector Scene",`PD-SCENE-${u}`,"PD-SCENE");await n.sync()}),b=o,tt=u,dt=!1,rr="SceneID Anchor",ee="Anchor",t(n),f({lastError:"-"}),fr(),!0}catch(i){return console.error("Unable to attach PlotDirector IDs.",i),t("Unable to attach PlotDirector IDs."),f({lastError:e(i)}),fr(),!1}finally{ai&&(ai.textContent=tt===u?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",fr())}},ep=async n=>{if(!o)return yi("No resolved PlotDirector chapter."),!1;if(!kt||!nt||!window.Word||typeof window.Word.run!="function")return yi("Word document access is unavailable."),!1;try{return await window.Word.run(async n=>{const t=await ne(n);if(!t.currentChapter)throw new Error("No chapter detected in Word. Use Heading 1 for chapters.");const i=t.bodyParagraphs[t.currentChapter.paragraphIndex];if(!i)throw new Error("Unable to locate the current Word chapter heading.");wu(i,"PlotDirector Chapter",`PD-CHAPTER-${o}`,"PD-CHAPTER");await n.sync()}),b=o,dt=!1,rr="ChapterID Anchor",ee="Chapter anchor",yi(n),t(n),f({lastError:"-"}),fr(),!0}catch(i){return console.error("Unable to attach PlotDirector chapter ID.",i),yi("Unable to attach PlotDirector chapter ID."),f({lastError:e(i)}),fr(),!1}},ln=async()=>{await fp()},op=async n=>{no(),await eo(),t(n),yi(n)},ol=n=>{bo&&(bo(n),bo=null),nr?.close?nr.close():nr&&(nr.hidden=!0)},an=(t,i)=>(n(fb,`"${t}"`),n(eb,`"${i}"`),!nr)?Promise.resolve(window.confirm(`Create PlotDirector chapter:
"${t}"
in book:
"${i}"
?`)):new Promise(n=>{bo=n,nr.showModal?nr.showModal():nr.hidden=!1}),vn=async()=>{const n=h();if(!n||!w||o){os("Chapter not found in PlotDirector.");return}const t=au(w),i=await an(t,dr(n)||"selected book");if(i){yt&&(yt.disabled=!0,yt.textContent="Creating...");try{const r=Number.isInteger(fe)&&fe>0?fe*10:null,i=await st(`/api/word-companion/books/${n.bookId}/chapters`,{title:t,sortOrder:r});if(!i?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");hu();kr(null,i.chapterId,"Manual chapter link");const u=await ep("Chapter created and linked successfully.");if(!u)return;await op("Chapter created and linked successfully.")}catch(r){yi("Unable to create chapter.");f({lastError:e(r)})}finally{yt&&(yt.disabled=!gc(),yt.textContent="Create Chapter in PlotDirector")}}},sp=()=>{if(vo){const n=au(ao?.value||"").toLocaleLowerCase(),t=ph.filter(t=>!n||String(t.title||"").toLocaleLowerCase().includes(n));if(vo.innerHTML="",se=null,si&&(si.disabled=!0),t.length===0){const n=document.createElement("p");n.className="word-companion-empty-list";n.textContent="No chapters found.";vo.append(n);return}for(const n of t){const i=Number.parseInt(n.chapterId||"",10);if(Number.isInteger(i)&&!(i<=0)){const r=document.createElement("label");r.className="word-companion-scene-option";const t=document.createElement("input");t.type="radio";t.name="word-companion-link-chapter";t.value=String(i);t.addEventListener("change",()=>{se=i,si&&(si.disabled=!1)});const u=document.createElement("span");u.textContent=n.title||"Untitled chapter";r.append(t,u);vo.append(r)}}}},yn=async()=>{const t=h();if(!t||!w||o){os("Chapter not found in PlotDirector.");return}pt&&(pt.disabled=!0,pt.textContent="Loading...");try{ph=await bv(t.bookId);se=null;ao&&(ao.value="");n(lh,"");sp();pr?.showModal?pr.showModal():pr&&(pr.hidden=!1)}catch(i){yi("Unable to load chapters.");f({lastError:e(i)})}finally{pt&&(pt.disabled=!gc(),pt.textContent="Link to Existing Chapter")}},hp=()=>{pr?.close?pr.close():pr&&(pr.hidden=!0)},pn=async()=>{const t=ph.find(n=>n.chapterId===se);if(!t){n(lh,"Select a chapter.");return}si&&(si.disabled=!0,si.textContent="Linking...");try{kr(null,t.chapterId,"Manual chapter link");const n=await ep("Chapter linked successfully.");if(!n)return;hp();await op("Chapter linked successfully.")}catch(i){n(lh,"Unable to link chapter.");yi("Unable to link chapter.");f({lastError:e(i)})}finally{si&&(si.disabled=!se,si.textContent="Link Chapter")}},cp=async(n,t,i)=>{const r=h();if(!r)return lu("Select a PlotDirector book first."),!1;await as(r.bookId,n,t,"Manual link","Title Match");const u=await fp(i);return u?(lu(i),ss(),!0):!1},sl=n=>{wo&&(wo(n),wo=null),gi?.close?gi.close():gi&&(gi.hidden=!0)},wn=(t,i)=>(n(nb,`"${t}"`),n(tb,`"${i}"`),!gi)?Promise.resolve(window.confirm(`Create PlotDirector scene:
"${t}"
within chapter:
"${i}"
?`)):new Promise(n=>{wo=n,gi.showModal?gi.showModal():gi.hidden=!1}),bn=async()=>{const n=h();if(!n||!rt){to("Scene not found in PlotDirector.");return}const t=ut(rt,"scene"),i=ut(w,"chapter"),r=await wn(t,i);if(r){wt&&(wt.disabled=!0,wt.textContent="Creating...");try{const r=await dv();if(!r){to("This chapter does not exist in PlotDirector. Create or link the chapter first.");return}const i=await st(`/api/word-companion/books/${n.bookId}/chapters/${r.chapterId}/scenes`,{sceneTitle:t});if(!i?.sceneId||!i?.chapterId)throw new Error("Scene creation did not return a scene ID.");hu();await cp(i.sceneId,i.chapterId,"Scene created and linked successfully.")}catch(u){lu("Unable to create scene.");f({lastError:e(u)})}finally{wt&&(wt.disabled=!nl(),wt.textContent="Create Scene in PlotDirector")}}},lp=()=>{if(lo){const n=au(co?.value||"").toLocaleLowerCase(),t=yh.filter(t=>!n||String(t.title||"").toLocaleLowerCase().includes(n));if(lo.innerHTML="",oe=null,oi&&(oi.disabled=!0),t.length===0){const n=document.createElement("p");n.className="word-companion-empty-list";n.textContent="No scenes found.";lo.append(n);return}for(const n of t){const i=Number.parseInt(n.sceneId||"",10);if(Number.isInteger(i)&&!(i<=0)){const r=document.createElement("label");r.className="word-companion-scene-option";const t=document.createElement("input");t.type="radio";t.name="word-companion-link-scene";t.value=String(i);t.addEventListener("change",()=>{oe=i,oi&&(oi.disabled=!1)});const u=document.createElement("span");u.textContent=n.title||"Untitled scene";r.append(t,u);lo.append(r)}}}},kn=async()=>{const t=h();if(!t||!rt){to("Scene not found in PlotDirector.");return}bt&&(bt.disabled=!0,bt.textContent="Loading...");try{const r=await ls(t.bookId),i=kv(r);if(!i){to("This chapter does not exist in PlotDirector. Create or link the chapter first.");return}yh=Array.isArray(i.scenes)?i.scenes:[];oe=null;co&&(co.value="");n(ch,"");lp();yr?.showModal?yr.showModal():yr&&(yr.hidden=!1)}catch(i){lu("Unable to load scenes.");f({lastError:e(i)})}finally{bt&&(bt.disabled=!nl(),bt.textContent="Link to Existing Scene")}},ap=()=>{yr?.close?yr.close():yr&&(yr.hidden=!0)},dn=async()=>{const i=h(),t=yh.find(n=>n.sceneId===oe);if(!i||!t){n(ch,"Select a scene.");return}oi&&(oi.disabled=!0,oi.textContent="Linking...");try{const n=await dv();if(!n)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");ap();await cp(t.sceneId,n.chapterId,"Scene linked successfully.")}catch(r){n(ch,"Unable to link scene.");lu("Unable to link scene.");f({lastError:e(r)})}finally{oi&&(oi.disabled=!oe,oi.textContent="Link Scene")}},uo=()=>{sf=!1,dc(),ke&&(ke=!1,gs(1e3))},vp=async(t={})=>{const p=t.source||"manual",w=y();if(!u){gt("No resolved PlotDirector scene.");return}if(!o){gt("No resolved PlotDirector chapter.");return}if(ht){gt("Refresh Current Scene before syncing.");return}const c=h(),l=or();if(!c||!l){gt("Bound manuscript metadata is unavailable.");return}if(sf){ke=!0;i("Scene sync deferred; sync already running.");return}pf();sf=!0;ke=!1;let r=t.snapshot||null;try{r=ti(r)?r:await ky()}catch(v){gt("Sync failed");f({lastError:e(v)});i("Scene sync failed.");uo();return}if(!ti(r)){gt("Waiting for typing to pause");i("Scene sync skipped (stale snapshot).");uo();return}const s=r.wordCount;if(!Number.isInteger(s)||s<0){gt("Sync failed");i("Scene sync failed.");uo();return}if(dh===r.sceneId&&gh===s){gt("Synced");i("Sync skipped (count unchanged).");uo();return}i("Scene word count changed.");ar&&(ar.disabled=!0,ar.textContent="Syncing...");gt("Syncing...");i(`Scene sync started (${p}).`);try{const f=y(),e=await st("/api/word-companion/runtime/scene-word-count",{documentGuid:r.documentGuid||l,bookId:r.bookId||c.bookId,chapterId:r.chapterId,sceneId:r.sceneId,wordCount:s});if(ci(`Word count sync API: ${Math.round(y()-f)}ms`),!ti(r)){i("Scene sync result ignored (stale snapshot).");return}const t=e?.actualWords??s,u=new Date;dh=r.sceneId;gh=t;n(hh,a(t));n(eh,a(t));n(tv,es(u));n(nv,es(u));gt("Synced");i("Scene sync succeeded.");ci(`Total word count sync: ${Math.round(y()-w)}ms`)}catch(v){gt("Sync failed");f({lastError:e(v)});i("Scene sync failed.")}finally{ar&&(ar.textContent="Sync Current Scene");uo()}},gs=(n=4e3)=>{(pf(),u&&o&&!ht&&!sf)&&(be=window.setTimeout(()=>{be=null,void vp({source:"automatic"})},n))},fo=()=>{de&&(window.clearTimeout(de),de=null)},gn=()=>{nc=null,tc="",lf=[],ic=null,rc="",fo()},ntt=()=>{uc=null,fc="",fu=[],ec=null,oc=""},ttt=()=>{sc=null,hc="",eu=[],cc=null,lc=""},hl=async(n=false)=>{const t=ni(),r=or();if(!t||!r)return lf=[],[];if(!n&&nc===t.projectId&&tc===r&&lf.length>0)return lf;const u=await at(`/api/word-companion/runtime/characters?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(r)}`);return nc=t.projectId,tc=r,lf=Array.isArray(u?.characters)?u.characters:[],i("Character alias cache refreshed."),lf},cl=async(n=false)=>{const t=ni(),r=or();if(!t||!r)return fu=[],[];if(!n&&uc===t.projectId&&fc===r&&fu.length>0)return fu;const u=await at(`/api/word-companion/runtime/assets?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(r)}`);return uc=t.projectId,fc=r,fu=Array.isArray(u?.assets)?u.assets:[],i(`Asset cache loaded: ${fu.length} aliases.`),fu},ll=async(n=false)=>{const t=ni(),r=or();if(!t||!r)return eu=[],[];if(!n&&sc===t.projectId&&hc===r&&eu.length>0)return eu;const u=await at(`/api/word-companion/runtime/locations?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(r)}`);return sc=t.projectId,hc=r,eu=Array.isArray(u?.locations)?u.locations:[],i(`Location cache loaded: ${eu.length} aliases.`),eu},itt=n=>String(n||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),al=(n,t)=>{const i=String(t||"").trim();if(!i)return!1;const r=itt(i).replace(/\s+/g,"\\s+");return new RegExp(`(^|[^\\p{L}\\p{N}_])${r}(?=$|[^\\p{L}\\p{N}_])`,"iu").test(n)},rtt=(n,t)=>{if(!n||!Array.isArray(t)||t.length===0)return[];const i=new Map;for(const r of t){const t=Number.parseInt(r.characterId||"",10);!Number.isInteger(t)||t<=0||i.has(t)||al(n,r.matchText)&&i.set(t,r.name||r.matchText||"Character")}return[...i.entries()].map(([n,t])=>({characterId:n,name:t}))},utt=(n,t)=>{if(!n||!Array.isArray(t)||t.length===0)return[];const i=new Map;for(const r of t){const t=Number.parseInt(r.assetId||"",10);!Number.isInteger(t)||t<=0||i.has(t)||al(n,r.matchText)&&i.set(t,r.name||r.matchText||"Asset")}return[...i.entries()].map(([n,t])=>({assetId:n,name:t}))},ftt=n=>String(n||"").trim().split(/\s+/).filter(Boolean).length,ett=n=>{if(n?.excludeFromCompanionDetection)return!1;const t=Number.parseInt(n?.detectionPriority||"0",10);return ftt(n?.matchText)>=2||Number.isInteger(t)&&t>=75},ott=(n,t)=>{if(!n||!Array.isArray(t)||t.length===0)return[];const i=new Map;for(const r of t){const t=Number.parseInt(r.locationId||"",10);!Number.isInteger(t)||t<=0||i.has(t)||!ett(r)||al(n,r.matchText)&&i.set(t,r.name||r.matchText||"Location")}return[...i.entries()].map(([n,t])=>({locationId:n,name:t}))},stt=()=>{hf=!1,cf&&(cf=!1,nh(1500))},htt=async()=>{if(de=null,u&&!ht&&or()){if(hf){cf=!0;i("Character suggestion detection deferred; detection already running.");return}hf=!0;cf=!1;const r=y();try{const n=await ky();if(!ti(n)){i("Runtime suggestions skipped (stale snapshot).");return}const[w,b,k]=await Promise.all([hl(),cl(),ll()]);if(!ti(n)){i("Runtime suggestions skipped after cache load (stale snapshot).");return}const s=n.sceneText||"",d=y(),o=rtt(s,w);ci(`Character detection: ${Math.round(y()-d)}ms`);const a=o.map(n=>n.characterId),h=a.slice().sort((n,t)=>n-t).join(","),g=y(),f=utt(s,b);ci(`Asset detection: ${Math.round(y()-g)}ms`);const v=f.map(n=>n.assetId),c=v.slice().sort((n,t)=>n-t).join(","),nt=y(),e=ott(s,k);ci(`Location detection: ${Math.round(y()-nt)}ms`);const p=e.map(n=>n.locationId),l=p.slice().sort((n,t)=>n-t).join(",");if(h&&(ic!==u||rc!==h)){if(!ti(n)){i("Character suggestions skipped before submit (stale snapshot).");return}const u=y(),r=await st("/api/word-companion/runtime/character-suggestions",{documentGuid:n.documentGuid,sceneId:n.sceneId,characterIds:a});if(ci(`Character suggestion API: ${Math.round(y()-u)}ms`),!ti(n)){i("Character suggestion result ignored (stale snapshot).");return}if(ic=n.sceneId,rc=h,(r?.createdCount||0)>0){const n=o.slice(0,3).map(n=>n.name).join(", "),i=o.length>3?` +${o.length-3}`:"";t(n?`Characters detected: ${n}${i}`:r.message)}i(r?.message||"Character suggestions submitted.")}else i("Character suggestions skipped.");if(c&&(ec!==u||oc!==c)){if(!ti(n)){i("Asset suggestions skipped before submit (stale snapshot).");return}i(`Asset matches found: ${f.map(n=>n.name).join(", ")}`);const u=y(),r=await st("/api/word-companion/runtime/asset-suggestions",{documentGuid:n.documentGuid,sceneId:n.sceneId,assetIds:v});if(ci(`Asset suggestion API: ${Math.round(y()-u)}ms`),!ti(n)){i("Asset suggestion result ignored (stale snapshot).");return}if(ec=n.sceneId,oc=c,(r?.createdCount||0)>0){const n=f.slice(0,3).map(n=>n.name).join(", "),i=f.length>3?` +${f.length-3}`:"";t(n?`Assets detected: ${n}${i}`:r.message)}i(r?.message||"Asset suggestions submitted.")}else i("Asset suggestions skipped.");if(l&&(cc!==u||lc!==l)){if(!ti(n)){i("Location suggestions skipped before submit (stale snapshot).");return}i(`Location matches found: ${e.map(n=>n.name).join(", ")}`);const u=y(),r=await st("/api/word-companion/runtime/location-suggestions",{documentGuid:n.documentGuid,sceneId:n.sceneId,locationIds:p});if(ci(`Location suggestion API: ${Math.round(y()-u)}ms`),!ti(n)){i("Location suggestion result ignored (stale snapshot).");return}if(cc=n.sceneId,lc=l,(r?.createdCount||0)>0){const n=e.slice(0,3).map(n=>n.name).join(", "),i=e.length>3?` +${e.length-3}`:"";t(n?`Locations detected: ${n}${i}`:r.message)}i(r?.message||"Location suggestions submitted.")}else i("Location suggestions skipped.");ci(`Total suggestion pass: ${Math.round(y()-r)}ms`)}catch(n){console.error("Unable to detect runtime suggestions.",n);f({lastError:e(n)})}finally{stt()}}},nh=(n=2500)=>{if(fo(),!u||ht||hf){hf&&(cf=!0);return}de=window.setTimeout(()=>{void htt()},n)},vl=async()=>{const i=ni(),n=h(),r=ut(w,"chapter");if(vt({projectId:i?.projectId,projectTitle:i?.title,bookId:n?.bookId,bookTitle:n?dr(n):undefined,detectedChapter:w,detectedScene:rt,requestChapter:r,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!n)return it("Not detected"),t("Select a PlotDirector book first."),!1;if(!w)return it("Not detected"),t("No chapter detected in Word. Use Heading 1 for chapters."),!1;it("Not detected");try{const f=await bv(n.bookId),i=b?f.find(n=>n.chapterId===b):null,e=r.toLocaleLowerCase(),o=e?f.find(n=>ut(n.title,"chapter").toLocaleLowerCase()===e):null,u=i||o;return u?(no(),kr(null,u.chapterId,i?"Chapter anchor":"Chapter title"),rr=i?"ChapterID Anchor":"Title Match",vf("Chapter linked to PlotDirector"),t("No scene detected in Word. Use Heading 2 for scenes."),vt({result:"Chapter matched",chapterId:u.chapterId,sceneId:null}),!0):(kr(null),vf("Chapter not found in PlotDirector."),t("Chapter not found in PlotDirector."),vt({result:"Chapter not matched",chapterId:null,sceneId:null}),os("Chapter not found in PlotDirector."),!1)}catch(u){return it("Not found in PlotDirector"),f({lastError:e(u)}),t("Unable to load PlotDirector chapter data."),!1}},eo=async()=>{const r=ni(),n=h(),u=ut(w,"chapter"),i=ut(rt,"scene");if(vt({projectId:r?.projectId,projectTitle:r?.title,bookId:n?.bookId,bookTitle:n?dr(n):undefined,detectedChapter:w,detectedScene:rt,requestChapter:u,requestScene:i,result:"Not run",chapterId:null,sceneId:null}),wc({anchorType:tt?"SceneID Anchor":b?"ChapterID Anchor":"Title Match",storedSceneId:tt,storedChapterId:b,resolutionMethod:"-"}),!n)return it("Not detected"),t("Select a PlotDirector book first."),vt({result:"Error"}),!1;if(!w||!rt)return it("Not detected"),t("No scene detected in Word. Use Heading 2 for scenes."),vt({result:"Error"}),!1;iu&&(iu.disabled=!0,iu.textContent="Refreshing...");const s=()=>{iu&&(iu.disabled=!1,iu.textContent="Refresh PlotDirector Scene")};it("Not detected");t("Resolving PlotDirector scene...");try{if(tt){const i=await gk(n.bookId,(n,t)=>t.sceneId===tt);if(i)return vt({result:"Matched",chapterId:i.chapter.chapterId,sceneId:i.scene.sceneId}),await as(n.bookId,i.scene.sceneId,i.chapter.chapterId,"Anchor","SceneID Anchor"),!0;dt=!0;rr="SceneID Anchor";vf("Not found in PlotDirector");t("Stored PlotDirector ID is invalid.");vt({result:"Error",chapterId:b,sceneId:tt});wc({anchorType:"SceneID Anchor",storedSceneId:tt,storedChapterId:b,resolutionMethod:"Anchor"})}if(b){const u=await ls(n.bookId),t=u.find(n=>n.chapterId===b),r=t?(Array.isArray(t.scenes)?t.scenes:[]).find(n=>ut(n.title,"scene").toLocaleLowerCase()===i.toLocaleLowerCase()):null;if(r)return vt({result:"Matched",chapterId:t.chapterId,sceneId:r.sceneId}),await as(n.bookId,r.sceneId,t.chapterId,"Anchor","ChapterID Anchor"),!0;t&&!tt?(rr="ChapterID Anchor",kr(null,b,"Chapter anchor"),vt({result:"Chapter matched",chapterId:b,sceneId:null})):tt||(rr="ChapterID Anchor",vt({result:"Chapter anchor not found",chapterId:b,sceneId:null}))}const r=await st(`/api/word-companion/books/${n.bookId}/resolve-scene`,{chapterTitle:u,sceneTitle:i});if(!r?.matched||!r.sceneId){const u=dt,f=Number.parseInt(r?.chapterId||"",10),e=Number.isInteger(o)&&o>0?o:null,n=Number.isInteger(f)&&f>0?f:e,i=!!r?.chapterMatched||!!n;return it("Not found in PlotDirector"),dt=u,i&&(kr(null,n,n===e?"Chapter anchor":"Chapter title"),vf("Scene not found in PlotDirector.")),t(u?"Stored PlotDirector ID is invalid.":i?"Scene not found in PlotDirector.":"This chapter does not exist in PlotDirector. Create or link the chapter first."),vt({result:"Not matched",chapterId:i?n:r?.chapterId,sceneId:r?.sceneId}),u||(i?(no(),to("Scene not found in PlotDirector.")):(ss(),os("Chapter not found in PlotDirector."))),s(),!1}const f=dt;return vt({result:f?"Matched by title fallback":"Matched",chapterId:r.chapterId,sceneId:r.sceneId}),await as(n.bookId,r.sceneId,r.chapterId,f?"Title fallback":"Title","Title Match"),f&&(dt=!0,t("Stored PlotDirector ID is invalid."),fr()),!0}catch(c){const n=dt;return f({lastError:e(c)}),it("Not found in PlotDirector"),dt=n,t(n?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),vt({result:"Error"}),!1}finally{s()}},nit=n=>{const t=n.currentChapter?.title||"",i=n.currentScene?.title||"",r=n.currentChapter?.anchorId||null,u=n.currentScene?.anchorId||null;return ut(t,"chapter")!==ut(w,"chapter")||ut(i,"scene")!==ut(rt,"scene")||r!==b||u!==tt},ctt=async()=>{if(uu=null,is){ef=!0;i("Runtime update deferred; update already running.");return}if(!uf||!h()){br=!1;i("Runtime update skipped.");return}if(!kt||!nt||!window.Word||typeof window.Word.run!="function"){br=!1;k("Manual");t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");return}if(!l){br=!1;k("Manual");t("Document structure is not cached yet. Use Refresh Current Scene.");return}const n=Date.now()-hv;if(br&&n<we){i("Runtime update skipped (typing active).");yl(we-n);return}is=!0;br=!1;ef=!1;k("Updating...");i("Runtime update executed.");try{const n=await by({includeSelection:!0});if(!ti(n)){k("Waiting for typing to pause");i("Runtime update skipped (stale snapshot).");return}const r=!!n.selectionChanged;if(!r){li(!1);k("Current scene updated");gs();nh();return}rt?await eo():await vl();li(!1);k("Current scene updated");t("Current scene updated.");gs();nh()}catch(r){console.error("Unable to refresh current scene from Word selection.",r);f({lastError:e(r)});li(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving.")}finally{is=!1;(ef||br)&&(ef=!1,yl(we))}},yl=(n=we)=>{uu&&window.clearTimeout(uu),uu=window.setTimeout(ctt,Math.max(0,n)),k("Waiting for typing to pause"),i("Runtime update scheduled.")},ltt=(n="selection",t=we)=>{if(br=!0,hv=Date.now(),ye+=1,pe=null,pf(),fo(),sf&&(ke=!0),hf&&(cf=!0),i(`${n} changed.`),is){ef=!0;k("Waiting for typing to pause");return}yl(t)},yp=()=>{uu&&(window.clearTimeout(uu),uu=null),br=!1,ef=!1},pp=()=>{ltt("Selection")},att=()=>{if(kh&&window.Office?.context?.document&&typeof window.Office.context.document.removeHandlerAsync=="function"&&window.Office?.EventType?.DocumentSelectionChanged)try{window.Office.context.document.removeHandlerAsync(window.Office.EventType.DocumentSelectionChanged,{handler:pp});kh=!1}catch(n){console.warn("Unable to remove Word selection tracking handler.",n)}},vtt=()=>{if(uf){if(!window.Office?.context?.document||typeof window.Office.context.document.addHandlerAsync!="function"||!window.Office?.EventType?.DocumentSelectionChanged){k("Manual");t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");return}try{window.Office.context.document.addHandlerAsync(window.Office.EventType.DocumentSelectionChanged,pp,n=>{n?.status===window.Office.AsyncResultStatus.Succeeded?(kh=!0,k("Live")):(k("Manual"),t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))});window.addEventListener("beforeunload",att)}catch(n){console.warn("Unable to register Word selection tracking handler.",n);k("Manual");t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}},ytt=async()=>{if(!h()){t("Select a PlotDirector book first.");it("Not detected");return}yp();yv(!0);k("Updating...");try{await Promise.all([hl(!0),cl(!0),ll(!0)]);const n=await dy();if(!n)return;if(li(!1),!rt){await vl();k("Current scene updated");return}await eo();k("Current scene updated")}finally{yv(!1)}},bu=async(n,t)=>{if(l=null,hu(),!n){ii=[];c(ot,"Select a project first");c(g,"Select a project first");af("");v(s.bookId,null);pi();it("Not detected");wf();return}c(ot,"Loading books...");af("");it("Not detected");wf("Select a book to analyse manuscript structure.");try{const r=await at(`/api/word-companion/projects/${n}/books`);if(ii=Array.isArray(r.books)?r.books:[],ii.length===0){c(ot,"No books available.");c(g,"No books available.");af("No books available.");v(s.bookId,null);pi();lt("No books available.");return}ys(ot,"Choose a book",ii.map(n=>({...n,displayTitle:dr(n)})),"bookId","displayTitle");const i=ii.find(n=>n.bookId===t);i&&ot?(ot.value=String(i.bookId),v(s.bookId,i.bookId)):v(s.bookId,null);fd(i?.bookId||t);pi();it(h()?"Not detected":"Not detected");wf(h()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure.");lt(vu()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{ii=[];c(ot,"Unable to load books.");c(g,"Unable to load books.");af("Unable to load books.");v(s.bookId,null);pi();it("Not detected");wf("Unable to load books.");lt("Unable to load books.")}},ptt=async()=>{c(p,"Loading projects...");c(ot,"Select a project first");c(et,"Loading projects...");c(g,"Select a project first");pc("");af("");try{const t=await at("/api/word-companion/projects");if(ir=Array.isArray(t.projects)?t.projects:[],ir.length===0){c(p,"No projects available.");c(et,"No projects available.");pc("No projects available.");v(s.projectId,null);v(s.bookId,null);pi();lt("No projects available.");return}ys(p,"Choose a project",ir,"projectId","title");il();const i=vs(s.projectId),n=ir.find(n=>n.projectId===i);n&&p?(p.value=String(n.projectId),et&&(et.value=String(n.projectId)),v(s.projectId,n.projectId),await bu(n.projectId,vs(s.bookId))):(v(s.projectId,null),v(s.bookId,null),pi(),lt("Select a Project and Book to begin."))}catch{ir=[];ii=[];c(p,"Unable to connect to PlotDirector.");c(ot,"Select a project first");c(et,"Unable to connect to PlotDirector.");c(g,"Select a project first");ge("Unable to connect to PlotDirector.");pc("Unable to connect to PlotDirector.");v(s.projectId,null);v(s.bookId,null);pi();lt("Unable to connect to PlotDirector.")}};for(const n of ih)n.addEventListener("click",()=>av(n.dataset.tabButton));vv();p?.addEventListener("change",async()=>{const n=Number.parseInt(p.value||"",10);bf();et&&Number.isInteger(n)&&n>0&&(et.value=String(n));v(s.projectId,Number.isInteger(n)&&n>0?n:null);v(s.bookId,null);it("Not detected");wf();lt("Select a Book to begin.");await bu(n,null);kf()});ot?.addEventListener("change",()=>{const n=Number.parseInt(ot.value||"",10);bf();v(s.bookId,Number.isInteger(n)&&n>0?n:null);g&&Number.isInteger(n)&&n>0&&(g.value=String(n));pi();it("Not detected");wf(h()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure.");lt(vu()?"Ready to scan manuscript structure.":"Select a Book to begin.");kf()});et?.addEventListener("change",async()=>{const n=Number.parseInt(et.value||"",10);bf();p&&Number.isInteger(n)&&n>0&&(p.value=String(n));v(s.projectId,Number.isInteger(n)&&n>0?n:null);v(s.bookId,null);lt("Select a Book to begin.");await bu(n,null);kf()});g?.addEventListener("change",()=>{const n=Number.parseInt(g.value||"",10);bf();ot&&Number.isInteger(n)&&n>0&&(ot.value=String(n));v(s.bookId,Number.isInteger(n)&&n>0?n:null);pi();lt(vu()?"Ready to scan manuscript structure.":"Select a Book to begin.");kf()});te?.addEventListener("input",ft);oo?.addEventListener("click",async()=>{const n=gr(),t=String(te?.value||"").trim();if(!n||!t){ft();return}oo.disabled=!0;ui("Creating Book...");try{const i=await st(`/api/word-companion/projects/${n.projectId}/books`,{title:t});te&&(te.value="");p&&(p.value=String(n.projectId));await bu(n.projectId,i.bookId);g&&(g.value=String(i.bookId));ui("Ready to scan manuscript structure.")}catch(i){console.error("Unable to create Book from Word Companion.",i);ui(`Unable to create Book: ${e(i)}`)}finally{ft()}});sr?.addEventListener("click",kg);uh?.addEventListener("click",nn);so?.addEventListener("click",tn);bl?.addEventListener("click",()=>ks("Character creation skipped."));kl?.addEventListener("click",()=>ks());nw?.addEventListener("click",()=>yu(!1));iw?.addEventListener("click",()=>lt("Import cancelled."));tu?.addEventListener("click",dy);cr?.addEventListener("click",gy);fh?.addEventListener("click",wg);hb?.addEventListener("click",()=>el(!0));cb?.addEventListener("click",()=>el(!1));tr?.addEventListener("cancel",n=>{n.preventDefault(),el(!1)});iu?.addEventListener("click",eo);ho?.addEventListener("click",ytt);ar?.addEventListener("click",()=>vp({source:"manual"}));di?.addEventListener("click",hn);ai?.addEventListener("click",ln);lr?.addEventListener("click",fn);yt?.addEventListener("click",vn);pt?.addEventListener("click",yn);ao?.addEventListener("input",sp);si?.addEventListener("click",pn);ub?.addEventListener("click",hp);ob?.addEventListener("click",()=>ol(!0));sb?.addEventListener("click",()=>ol(!1));nr?.addEventListener("cancel",n=>{n.preventDefault(),ol(!1)});wt?.addEventListener("click",bn);bt?.addEventListener("click",kn);co?.addEventListener("input",lp);oi?.addEventListener("click",dn);gw?.addEventListener("click",ap);ib?.addEventListener("click",()=>sl(!0));rb?.addEventListener("click",()=>sl(!1));gi?.addEventListener("cancel",n=>{n.preventDefault(),sl(!1)});ru?.addEventListener("click",bg);const wtt=uf?ptt():Promise.resolve();if(uf||(c(p,"Please sign in to PlotDirector."),c(ot,"Please sign in to PlotDirector."),c(et,"Please sign in to PlotDirector."),c(g,"Please sign in to PlotDirector."),pi()),!window.Office||typeof window.Office.onReady!="function"){yc("Word Companion ready");t("Word document access is unavailable.");k("Manual");f({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"});iy().catch(n=>{console.debug("Word Companion presence unavailable.",n)});return}gv().then(async()=>{yc("Word Companion ready"),await wtt,await un(),await iy(),nt?vtt():(t("Word document access is unavailable."),k("Manual"))}).catch(n=>{console.error("Office readiness check failed.",n),ge("Unable to connect to PlotDirector."),yc("Word Companion unavailable"),t("Word document access is unavailable."),f({ready:"No",wordApi:"No",lastScan:"Failure"})})})();