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