25 lines
66 KiB
JavaScript
25 lines
66 KiB
JavaScript
(()=>{const f={projectId:"plotdirector.word.projectId",bookId:"plotdirector.word.bookId",activeTab:"plotdirector.word.activeTab"},pi={documentGuid:"plotdirector.word.documentGuid",bookId:"plotdirector.word.boundBookId",projectId:"plotdirector.word.boundProjectId",bindingVersion:"plotdirector.word.bindingVersion"},es=new Set(["scene","links","structure","diagnostics"]),fl=document.querySelector(".word-companion-shell"),el=document.querySelector(".word-companion-tabs"),le=[...document.querySelectorAll("[data-tab-button]")],os=[...document.querySelectorAll("[data-tab-panel]")],ol=document.querySelector("[data-first-run-wizard]"),tt=document.querySelector("[data-first-run-project-select]"),y=document.querySelector("[data-first-run-book-select]"),uu=document.querySelector("[data-first-run-new-book-title]"),uf=document.querySelector("[data-first-run-create-book]"),wi=document.querySelector("[data-first-run-scan]"),sl=document.querySelector("[data-first-run-cancel]"),hl=document.querySelector("[data-first-run-status]"),bi=document.querySelector("[data-first-run-summary]"),ae=document.querySelector("[data-first-run-character-section]"),ur=document.querySelector("[data-first-run-character-status]"),fr=document.querySelector("[data-first-run-character-candidates]"),ff=document.querySelector("[data-first-run-character-actions]"),ve=document.querySelector("[data-first-run-create-characters]"),cl=document.querySelector("[data-first-run-skip-characters]"),ye=document.querySelector("[data-first-run-import-actions]"),pe=document.querySelector("[data-first-run-import]"),ll=document.querySelector("[data-first-run-import-cancel]"),kr=document.querySelector("[data-first-run-replace-dialog]"),ss=document.querySelector("[data-first-run-replace-confirm]"),hs=document.querySelector("[data-first-run-replace-cancel]"),cs=document.querySelector("[data-office-status]"),ls=document.querySelector("[data-connection-status]"),as=document.querySelector("[data-summary-connection]"),vs=document.querySelector("[data-summary-project]"),ys=document.querySelector("[data-summary-book]"),v=document.querySelector("[data-project-select]"),g=document.querySelector("[data-book-select]"),ps=document.querySelector("[data-project-message]"),ws=document.querySelector("[data-book-message]"),ef=document.querySelector("[data-refresh-current-scene]"),er=document.querySelector("[data-refresh-document]"),bs=document.querySelector("[data-current-chapter]"),ks=document.querySelector("[data-current-scene]"),ds=document.querySelector("[data-current-word-count]"),gs=document.querySelector("[data-scene-tracking-status]"),nh=document.querySelector("[data-document-message]"),th=document.querySelector("[data-sync-note]"),fu=document.querySelector("[data-document-outline]"),ki=document.querySelector("[data-analyse-manuscript-structure]"),we=document.querySelector("[data-apply-structure-sync]"),al=document.querySelector("[data-structure-preview-status]"),dr=document.querySelector("[data-structure-preview-results]"),or=document.querySelector("[data-refresh-plotdirector-scene]"),ih=document.querySelector("[data-plotdirector-scene-status]"),vl=document.querySelector("[data-anchor-status]"),yl=document.querySelector("[data-anchor-book-id]"),pl=document.querySelector("[data-anchor-chapter-id]"),wl=document.querySelector("[data-anchor-scene-id]"),ui=document.querySelector("[data-attach-plotdirector-ids]"),rh=document.querySelector("[data-plotdirector-scene-details]"),uh=document.querySelector("[data-plotdirector-scene-title]"),fh=document.querySelector("[data-plotdirector-revision-status]"),eh=document.querySelector("[data-plotdirector-estimated-words]"),be=document.querySelector("[data-plotdirector-actual-words]"),oh=document.querySelector("[data-plotdirector-blocked-status]"),ke=document.querySelector("[data-plotdirector-blocked-reason-row]"),de=document.querySelector("[data-plotdirector-blocked-reason]"),fi=document.querySelector("[data-sync-scene-progress]"),bl=document.querySelector("[data-sync-word-count]"),ge=document.querySelector("[data-sync-plotdirector-count]"),kl=document.querySelector("[data-sync-last-synced]"),dl=document.querySelector("[data-sync-status]"),sh=document.querySelector("[data-writing-brief-block]"),hh=document.querySelector("[data-writing-brief]"),ch=document.querySelector("[data-plotdirector-link-groups]"),eu=document.querySelector("[data-character-chips]"),ou=document.querySelector("[data-asset-chips]"),pw=document.querySelector("[data-location-chips]"),di=document.querySelector("[data-primary-location-select]"),ei=document.querySelector("[data-save-scene-links]"),gl=document.querySelector("[data-scene-links-status]"),lh=document.querySelector("[data-links-editing-scene]"),ah=document.querySelector("[data-chapter-create-link]"),na=document.querySelector("[data-chapter-create-link-chapter]"),ft=document.querySelector("[data-create-plotdirector-chapter]"),et=document.querySelector("[data-link-existing-chapter]"),ta=document.querySelector("[data-chapter-create-link-status]"),vh=document.querySelector("[data-scene-create-link]"),ia=document.querySelector("[data-create-link-chapter]"),ra=document.querySelector("[data-create-link-scene]"),ot=document.querySelector("[data-create-plotdirector-scene]"),st=document.querySelector("[data-link-existing-scene]"),ua=document.querySelector("[data-create-link-status]"),gi=document.querySelector("[data-link-existing-dialog]"),sf=document.querySelector("[data-link-scene-search]"),hf=document.querySelector("[data-link-scene-options]"),wt=document.querySelector("[data-link-selected-scene]"),fa=document.querySelector("[data-link-dialog-cancel]"),no=document.querySelector("[data-link-dialog-status]"),oi=document.querySelector("[data-create-scene-dialog]"),ea=document.querySelector("[data-create-dialog-scene]"),oa=document.querySelector("[data-create-dialog-chapter]"),sa=document.querySelector("[data-create-dialog-confirm]"),ha=document.querySelector("[data-create-dialog-cancel]"),nr=document.querySelector("[data-link-existing-chapter-dialog]"),cf=document.querySelector("[data-link-chapter-search]"),lf=document.querySelector("[data-link-chapter-options]"),bt=document.querySelector("[data-link-selected-chapter]"),ca=document.querySelector("[data-link-chapter-dialog-cancel]"),to=document.querySelector("[data-link-chapter-dialog-status]"),si=document.querySelector("[data-create-chapter-dialog]"),la=document.querySelector("[data-create-chapter-dialog-chapter]"),aa=document.querySelector("[data-create-chapter-dialog-book]"),va=document.querySelector("[data-create-chapter-dialog-confirm]"),ya=document.querySelector("[data-create-chapter-dialog-cancel]"),hi=document.querySelector("[data-apply-structure-sync-dialog]"),io=document.querySelector("[data-apply-structure-sync-summary]"),pa=document.querySelector("[data-apply-structure-sync-confirm]"),wa=document.querySelector("[data-apply-structure-sync-cancel]"),ba=document.querySelector("[data-resolve-project-id]"),ka=document.querySelector("[data-resolve-project-title]"),da=document.querySelector("[data-resolve-book-id]"),ga=document.querySelector("[data-resolve-book-title]"),nv=document.querySelector("[data-resolve-detected-chapter]"),tv=document.querySelector("[data-resolve-detected-scene]"),iv=document.querySelector("[data-resolve-request-chapter]"),rv=document.querySelector("[data-resolve-request-scene]"),uv=document.querySelector("[data-resolve-result]"),fv=document.querySelector("[data-resolve-chapter-id]"),ev=document.querySelector("[data-resolve-scene-id]"),sr=document.querySelector("[data-run-diagnostics]"),ov=document.querySelector("[data-diagnostic-host]"),sv=document.querySelector("[data-diagnostic-platform]"),hv=document.querySelector("[data-diagnostic-ready]"),cv=document.querySelector("[data-diagnostic-word-api]"),lv=document.querySelector("[data-diagnostic-last-scan]"),av=document.querySelector("[data-diagnostic-last-error]"),vv=document.querySelector("[data-diagnostic-anchor-type]"),yv=document.querySelector("[data-diagnostic-stored-scene-id]"),pv=document.querySelector("[data-diagnostic-stored-chapter-id]"),wv=document.querySelector("[data-diagnostic-resolution-method]"),bv=document.querySelector("[data-diagnostic-paragraphs]"),kv=document.querySelector("[data-diagnostic-heading1]"),dv=document.querySelector("[data-diagnostic-heading2]"),su=fl?.dataset.authenticated==="true";let ci=[],ct=[],kt=!1,rt=!1,af="Unknown",vf="Unknown",p="",nt="",hu=null,yf=null,a=null,w=null,r=null,e=null,cu="",li="Title Match",lt=!1,ro=[],lu=null,pf=null,uo=[],au=null,wf=null,dt=null,vu=null,tr=null,yu=null,ir=[],bf=!1,pu=!1,fo=!1,wu=!1,kf=null,eo="Manual",ht=!1,oo=null,so=!1,ho=!1,df="",co="",gt={characters:[],assets:[],locations:[],primaryLocationId:null};const lo=n=>{cs&&(cs.textContent=n)},gv=n=>{try{return window.localStorage.getItem(n)||""}catch{return""}},ny=(n,t)=>{try{t?window.localStorage.setItem(n,String(t)):window.localStorage.removeItem(n)}catch{}},yh=(n,t=true)=>{const i=es.has(n)&&le.some(t=>t.dataset.tabButton===n)?n:"scene";for(const n of le){const t=n.dataset.tabButton===i;n.classList.toggle("is-active",t);n.setAttribute("aria-selected",t?"true":"false")}for(const n of os){const t=n.dataset.tabPanel===i;n.classList.toggle("is-active",t);n.hidden=!t}t&&ny(f.activeTab,i)},ph=()=>{const n=gv(f.activeTab);yh(es.has(n)?n:"scene",!1)},gf=n=>{ls&&(ls.textContent=n),as&&(as.textContent=n)},ao=n=>{ps&&(ps.textContent=n)},bu=n=>{ws&&(ws.textContent=n)},t=n=>{nh&&(nh.textContent=n)},gr=n=>{ih&&(ih.textContent=n)},vo=t=>{const i=n=>Object.prototype.hasOwnProperty.call(t,n);i("anchorType")&&n(vv,o(t.anchorType));i("storedSceneId")&&n(yv,o(t.storedSceneId));i("storedChapterId")&&n(pv,o(t.storedChapterId));i("resolutionMethod")&&n(wv,o(t.resolutionMethod))},ai=()=>{const i=l(),u=Number.isInteger(r)&&r>0&&w===r,f=!Number.isInteger(e)||e<=0||a===e,t=u&&f;n(vl,t?"Attached to PlotDirector":"Not attached");n(yl,i?.bookId?String(i.bookId):"-");n(pl,Number.isInteger(e)&&e>0?String(e):"-");n(wl,Number.isInteger(r)&&r>0?String(r):"-");ui&&(ui.disabled=!r||t&&!lt,ui.textContent=w&&!t?"Reattach PlotDirector IDs":"Attach PlotDirector IDs");vo({anchorType:li||"Title Match",storedSceneId:w,storedChapterId:a,resolutionMethod:cu})},ku=(t,i,r,u=null,f=null,e=null)=>{p=t||"",nt=i||"",hu=Number.isInteger(r)?r:null,yf=Number.isInteger(e)&&e>0?e:null,a=Number.isInteger(u)&&u>0?u:null,w=Number.isInteger(f)&&f>0?f:null,bs&&(bs.textContent=t||"Not detected"),ks&&(ks.textContent=i||"Not detected"),ds&&(ds.textContent=Number.isInteger(r)?String(r):"-"),n(bl,Number.isInteger(r)?String(r):"-"),ai()},u=(n,t)=>{n&&(n.hidden=t)},nu=t=>{n(dl,t)},vi=t=>{n(al,t)},tu=(n="Select a project and book to analyse manuscript structure.")=>{if(dt=null,dr){dr.innerHTML="";const n=document.createElement("p");n.textContent="No preview generated.";dr.append(n)}vi(n);ne()},ty=(n=dt)=>sc.flatMap(t=>Array.isArray(n?.[t.key])?n[t.key]:[]),hr=(n=dt)=>ty(n).filter(n=>n.category==="couldLink"||n.category==="wouldCreateChapters"||n.category==="wouldCreateScenes"),ne=()=>{we&&(we.disabled=wu||hr().length===0)},te=()=>{ki&&(ki.disabled=wu||!iu()||!l()),ne()},yo=()=>{lh&&(lh.textContent=r?`Editing links for: ${df||nt||"Current scene"}`:"Link a PlotDirector scene first.")},wh=()=>{const n=ht||!r;fi&&(fi.disabled=n);ei&&(ei.disabled=n);di&&(di.disabled=n);for(const t of[eu,ou])for(const i of t?[...t.querySelectorAll("input[type='checkbox']")]:[])i.disabled=n},ni=t=>{(t==="Live"||t==="Manual")&&(eo=t),n(gs,t||eo||"Manual")},yi=(i,r="")=>{ht=!!i,n(gs,ht?"Stale":eo),wh(),r&&(t(r),cr(r))},rr=(n,t=null,i="")=>{r=Number.isInteger(n)&&n>0?n:null,e=Number.isInteger(t)&&t>0?t:null,cu=i||"",wh(),nu(ht?"Refresh Current Scene before syncing.":r?"Ready to sync.":"No resolved PlotDirector scene."),cr(ht?"Refresh Current Scene before saving.":r?"Ready to save.":"Link a PlotDirector scene first."),yo(),ai()},bh=n=>{ef&&(ef.disabled=n,ef.textContent=n?"Refreshing...":"Refresh Current Scene")},o=n=>n===null||n===undefined||n===""?"-":String(n),cr=t=>{n(gl,t)},lr=t=>{n(ua,t)},ti=t=>{n(ta,t)},po=()=>!!l()&&!!p&&!e,wo=()=>!!l()&&!!nt&&Number.isInteger(e)&&e>0,du=()=>{u(ah,!0),ti(""),ft&&(ft.disabled=!0,ft.textContent="Create Chapter in PlotDirector"),et&&(et.disabled=!0,et.textContent="Link to Existing Chapter")},ie=(t="")=>{n(na,o(p));u(ah,!1);ti(t);const i=po();ft&&(ft.disabled=!i,ft.textContent="Create Chapter in PlotDirector");et&&(et.disabled=!i,et.textContent="Link to Existing Chapter")},re=()=>{u(vh,!0),lr(""),ot&&(ot.disabled=!0,ot.textContent="Create Scene in PlotDirector"),st&&(st.disabled=!0,st.textContent="Link to Existing Scene")},gu=(t="")=>{n(ia,o(p));n(ra,o(nt));u(vh,!1);lr(t);const i=wo();ot&&(ot.disabled=!i,ot.textContent="Create Scene in PlotDirector");st&&(st.disabled=!i,st.textContent="Link to Existing Scene")},k=t=>{gr(t),u(rh,!0),u(sh,!0),u(ch,!1),du(),re(),cu="",df="",co="",li=w?"SceneID Anchor":a?"ChapterID Anchor":"Title Match",lt=!1,gt={characters:[],assets:[],locations:[],primaryLocationId:null},fe(eu,[],"character"),fe(ou,[],"asset"),kh([],null,!1),rr(null),n(ge,"-"),n(uh,"-"),n(fh,"-"),n(eh,"-"),n(be,"-"),n(oh,"-"),n(de,"-"),u(ke,!0),ai(),yo()},ue=(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,fe=(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(ue(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)}}}},kh=(n,t,i=false)=>{if(di){di.innerHTML="";const r=document.createElement("option");r.value="";r.textContent="None";di.append(r);const u=Number.parseInt(t||"",10);for(const t of Array.isArray(n)?n:[]){const n=Number.parseInt(ue(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;di.append(i)}}di.disabled=!i}},iy=t=>{df=t?.sceneTitle||nt||"",co=t?.chapterTitle||p||"",n(uh,o(t?.sceneTitle)),n(fh,o(t?.revisionStatus||t?.revisionStatusName||"Not provided")),n(eh,o(t?.estimatedWords)),n(be,o(t?.actualWords)),n(ge,o(t?.actualWords)),n(oh,t?.blocked?"Blocked":"Not blocked"),t?.blockedReason?(n(de,t.blockedReason),u(ke,!1)):(n(de,"-"),u(ke,!0)),hh&&(hh.textContent=t?.writingBrief||"No writing brief has been added for this scene."),gt={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},fe(eu,gt.characters,"character",!!r&&!ht),fe(ou,gt.assets,"asset",!!r&&!ht),kh(gt.locations,gt.primaryLocationId,!!r&&!ht),yo(),cr(ht?"Refresh Current Scene before saving.":r?"Ready to save.":"No resolved PlotDirector scene."),u(rh,!1),u(sh,!1),u(ch,!1)},ar=n=>String(n||"").trim().replace(/\s+/g," "),b=(n,t)=>{const i=ar(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=ar(i.replace(u,""));return f||i},ut=t=>{const i=n=>Object.prototype.hasOwnProperty.call(t,n);i("projectId")&&n(ba,o(t.projectId));i("projectTitle")&&n(ka,o(t.projectTitle));i("bookId")&&n(da,o(t.bookId));i("bookTitle")&&n(ga,o(t.bookTitle));i("detectedChapter")&&n(nv,o(t.detectedChapter));i("detectedScene")&&n(tv,o(t.detectedScene));i("requestChapter")&&n(iv,o(t.requestChapter));i("requestScene")&&n(rv,o(t.requestScene));i("result")&&n(uv,o(t.result));i("chapterId")&&n(fv,o(t.chapterId));i("sceneId")&&n(ev,o(t.sceneId))},ry=async(n,t)=>{const i=await pt(`/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""},uy=async(n,t)=>{const i=await pt(`/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},bo=async n=>{const t=await pt(`/api/word-companion/books/${n}/structure`);return Array.isArray(t?.chapters)?t.chapters:[]},dh=async n=>{const t=await pt(`/api/word-companion/books/${n}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},gh=n=>{if(Number.isInteger(e)&&e>0){const t=n.find(n=>n.chapterId===e);if(t)return t}const t=b(p,"chapter").toLocaleLowerCase();return t?n.find(n=>b(n.title,"chapter").toLocaleLowerCase()===t)||null:null},nc=async()=>{const n=l();return n?gh(await bo(n.bookId)):null},ee=async(n,i,r,u,f)=>{const e=await pt(`/api/word-companion/scenes/${i}/companion`);try{e.revisionStatus=await ry(n,i)}catch{e.revisionStatus=""}li=f||"Title Match";lt=!1;yi(!1);gr("Linked to PlotDirector");t("");du();re();rr(i,r,u);iy(e)},n=(n,t)=>{n&&(n.textContent=t)},i=t=>{const i=n=>Object.prototype.hasOwnProperty.call(t,n);i("host")&&n(ov,t.host);i("platform")&&n(sv,t.platform);i("ready")&&n(hv,t.ready);i("wordApi")&&n(cv,t.wordApi);i("lastScan")&&n(lv,t.lastScan);i("lastError")&&n(av,t.lastError);i("paragraphs")&&n(bv,t.paragraphs);i("heading1")&&n(kv,t.heading1);i("heading2")&&n(dv,t.heading2)},s=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)},tc=async()=>{if(!window.Office||typeof window.Office.onReady!="function")return kt=!1,rt=!1,af="Unavailable",vf="Unavailable",i({host:af,platform:vf,ready:"No",wordApi:"No"}),null;const n=await window.Office.onReady();return kt=!0,af=n?.host||"Unknown",vf=n?.platform||"Unknown",rt=!!window.Word&&!!window.Office.HostType&&n?.host===window.Office.HostType.Word,i({host:af,platform:vf,ready:"Yes",wordApi:rt?"Yes":"No"}),n},ic=n=>{try{const i=window.localStorage.getItem(n),t=Number.parseInt(i||"",10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},c=(n,t)=>{try{t?window.localStorage.setItem(n,String(t)):window.localStorage.removeItem(n)}catch{}},h=(n,t)=>{if(n){n.innerHTML="";const i=document.createElement("option");i.value="";i.textContent=t;n.append(i);n.disabled=!0}},oe=(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}},vr=n=>{const t=String(n?.title||"").trim(),i=String(n?.subtitle||"").trim();return i?`${t}: ${i}`:t},iu=()=>{const n=Number.parseInt(v?.value||"",10);return ci.find(t=>t.projectId===n)||null},l=()=>{const n=Number.parseInt(g?.value||"",10);return ct.find(t=>t.bookId===n)||null},yr=()=>{const n=Number.parseInt(tt?.value||"",10);return ci.find(t=>t.projectId===n)||null},ru=()=>{const n=Number.parseInt(y?.value||"",10);return ct.find(t=>t.bookId===n)||null},at=t=>n(hl,t),d=()=>{const n=yr(),t=ru();wi&&(wi.disabled=!n||!t||pu);uf&&(uf.disabled=!n||!String(uu?.value||"").trim()||pu);pe&&(pe.disabled=!tr?.canImport||!yu||pu);ve&&(ve.disabled=fo||uc().length===0)},pr=n=>{u(ol,!n);u(el,n);for(const t of os)u(t,n?!0:t.dataset.tabPanel!=="scene"&&!t.classList.contains("is-active"));n||ph()},rc=()=>{if(tt){if(ci.length===0){h(tt,"No projects available.");return}oe(tt,"Choose a project",ci,"projectId","title");const n=Number.parseInt(v?.value||"",10);Number.isInteger(n)&&n>0&&(tt.value=String(n))}},fy=(n=null)=>{if(y){if(ct.length===0){h(y,"No books available.");return}oe(y,"Choose a book",ct.map(n=>({...n,displayTitle:vr(n)})),"bookId","displayTitle");const i=n||Number.parseInt(g?.value||"",10),t=ct.find(n=>n.bookId===i);t&&(y.value=String(t.bookId));d()}},it=(t="Select a Project and Book to begin.")=>{tr=null,yu=null,ir=[],bf=!1,u(bi,!0),u(ye,!0),u(ae,!0),u(ff,!0),bi&&(bi.innerHTML=""),fr&&(fr.innerHTML=""),n(ur,""),at(t),d()},uc=()=>fr?[...fr.querySelectorAll("input[type='checkbox']:checked")].map(n=>String(n.value||"").trim()).filter(Boolean):[],ko=t=>{if(ir=Array.isArray(t)?t:[],ae&&fr){if(fr.innerHTML="",u(ae,!1),u(ff,!bf||ir.length===0),ir.length===0){n(ur,"No likely major characters found.");d();return}n(ur,`${ir.length} likely major characters found.`);for(const n of ir){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||"").toLowerCase()==="high";t.addEventListener("change",d);const r=document.createElement("strong");r.textContent=n.text||"";const u=document.createElement("em"),f=String(n.reason||"").trim();u.textContent=f?`${Number(n.mentionCount||0).toLocaleString()} mentions, ${f.toLowerCase()}`:`${Number(n.mentionCount||0).toLocaleString()} mentions`;i.append(t,r,u);fr.append(i)}d()}},ey=n=>{if(bi){bi.innerHTML="";const t=document.createElement("strong");t.textContent="Manuscript Analysis";bi.append(t);const i=document.createElement("dl"),r=[["Project",n.projectTitle],["Book",vr({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 r){const r=document.createElement("dt");r.textContent=n;const u=document.createElement("dd");u.textContent=t||"-";i.append(r,u)}bi.append(i);u(bi,!1);u(ye,!1);at(n.message||"Preview generated.");d()}},oy=()=>{const n=window.Office?.context?.document?.settings;if(!n)return null;const u=String(n.get(pi.documentGuid)||"").trim(),t=Number.parseInt(n.get(pi.bookId)||"",10),i=Number.parseInt(n.get(pi.projectId)||"",10),r=Number.parseInt(n.get(pi.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}},sy=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(pi.documentGuid,n.documentGuid);r.set(pi.bookId,String(n.bookId));r.set(pi.projectId,String(n.projectId));r.set(pi.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."))})}),fc=()=>vu?.documentGuid?vu.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)),ii=()=>{const t=iu(),n=l();vs&&(vs.textContent=t?.title||"(Not connected)");ys&&(ys.textContent=n?vr(n):"(Not connected)");th&&(th.textContent=n?"":"Select a PlotDirector book before refreshing.");te()},go=n=>{const t=n?.styleBuiltIn||n?.style||"";return String(t).replace(/\s+/g,"").toLowerCase()},nf=(n,t)=>{const i=go(n);return i===`heading${t}`||i.endsWith(`.heading${t}`)||i.includes(`heading${t}`)},ns=n=>{const t=String(n||"").trim().split(/\s+/).filter(Boolean);return t.length},hy=(n,t)=>String(n?.text||"").trim()===String(t?.text||"").trim()&&go(n)===go(t),ec=(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},oc=(n,t)=>{const i=Array.isArray(n?.contentControls?.items)?n.contentControls.items:[];for(const n of i){const i=ec(n.tag,t);if(i)return i}return null},cy=(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(nf(n,1)){o+=1;i={index:u.length+1,paragraphIndex:t,title:f,anchorId:oc(n,"PD-CHAPTER"),scenes:[]};u.push(i);r=null;return}if(nf(n,2)){if(s+=1,!i)return;r={index:i.scenes.length+1,paragraphIndex:t,title:f,anchorId:oc(n,"PD-SCENE"),wordCount:0};i.scenes.push(r);return}r&&(r.wordCount+=ns(f))}});const h=t.find(n=>String(n.text||"").trim()),f=h?n.findIndex(n=>hy(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}},ly=(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),nf(n,1)){i={title:h,sortOrder:(r.length+1)*10,wordCount:0,scenes:[]};r.push(i);u=o();f+=ns(h);return}if(i&&u){if(t&&s.has(h)){u=o();return}const c=ns(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")}},ts=n=>{if(fu){if(fu.innerHTML="",n.chapters.length===0){const n=document.createElement("p");n.textContent="No chapters detected. Use Heading 1 for chapter titles.";fu.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.";fu.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)}fu.append(n)}}},sc=[{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"}],ay={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},vy={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},se=(n,t)=>b(n,t).toLocaleLowerCase(),vt=({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:""}),yt=(n,t)=>{Array.isArray(n[t.category])&&n[t.category].push(t)},is=n=>Array.isArray(n?.scenes)?n.scenes:[],yy=(n,t)=>{for(const i of n){const n=is(i).find(n=>n.sceneId===t);if(n)return{chapter:i,scene:n}}return null},py=(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=vt({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:n.title,match:`Chapter ${r.chapterId}: ${r.title}`,anchorStatus:u,pdChapter:r,wordChapter:n});return yt(i,t),t}const f=vt({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:n.title,anchorStatus:`${u} not found`,matches:[],pdChapter:null,wordChapter:n});return yt(i,f),f}const r=t.filter(t=>se(t.title,"chapter")===se(n.title,"chapter"));if(r.length===1){const t=vt({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 yt(i,t),t}if(r.length>1){const t=vt({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 yt(i,t),t}const f=vt({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:n.title,anchorStatus:u,pdChapter:null,wordChapter:n});return yt(i,f),f},wy=(n,t,i,r)=>{const u=n.anchorId?`PD-SCENE-${n.anchorId}`:"None";if(n.anchorId){const f=yy(i,n.anchorId);if(f){yt(r,vt({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}yt(r,vt({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"){yt(r,vt({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){yt(r,vt({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:n.title,anchorStatus:u,wordChapter:t?.wordChapter,wordScene:n,parentItem:t}));return}const f=is(t.pdChapter).filter(t=>se(t.title,"scene")===se(n.title,"scene"));if(f.length===1){yt(r,vt({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){yt(r,vt({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}yt(r,vt({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:n.title,anchorStatus:u,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:n,parentItem:t}))},by=(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=py(t,r,i);for(const u of is(t))wy(u,n,r,i)}return i},ky=n=>{const t=document.createElement("article");t.className="word-companion-preview-item";const i=document.createElement("strong");i.textContent=`${vy[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: ${ay[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},hc=n=>{if(dr){dr.innerHTML="";for(const t of sc){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(ky(n));dr.append(i)}ne()}},wr=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();for(const n of t.items)(nf(n,1)||nf(n,2))&&n.contentControls.load("items/tag,title");await n.sync();const r=cy(t.items,i.items);return r.bodyParagraphs=t.items,r},cc=async()=>{if(t(""),!kt||!rt||!window.Word||typeof window.Word.run!="function")return ku(null,null,null),t("Word document access is unavailable."),i({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;er&&(er.disabled=!0,er.textContent="Scanning...");t("Scanning document structure...");try{const n=await window.Word.run(async n=>await wr(n));return ku(n.currentChapter?.title,n.currentScene?.title,n.currentScene?.wordCount,n.currentChapter?.anchorId,n.currentScene?.anchorId,n.currentChapter?.index),k("Not detected"),ts(n),t(""),i({lastScan:"Success",lastError:"-",paragraphs:String(n.paragraphCount),heading1:String(n.heading1Count),heading2:String(n.heading2Count)}),!0}catch(n){const r=s(n);return console.error("Unable to scan the Word document.",n),ku(null,null,null),t(`Unable to scan the Word document: ${r}`),i({lastScan:"Failure",lastError:r}),!1}finally{er&&(er.disabled=!1,er.textContent="Refresh Document Structure")}},lc=async()=>{const n=l();if(!iu()||!n)return vi("Select a project and book to analyse manuscript structure."),!1;if(!kt||!rt||!window.Word||typeof window.Word.run!="function")return vi("Word document access is unavailable."),i({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;ki&&(ki.disabled=!0,ki.textContent="Analysing...");vi("Analysing manuscript structure...");try{const t=await window.Word.run(async n=>await wr(n)),r=await pt(`/api/word-companion/books/${n.bookId}/structure`);return ku(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),ts(t),dt=by(t,r),hc(dt),vi("Preview generated. No changes have been applied."),i({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),vi("Unable to analyse manuscript structure."),i({lastScan:"Failure",lastError:s(t)}),!1}finally{ki&&(ki.textContent="Analyse Manuscript Structure",te())}},dy=(n=dt)=>{const t=hr(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}},gy=n=>{if(io){io.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)}io.append(t)}},rs=n=>{kf&&(kf(n),kf=null),hi?.close?hi.close():hi&&(hi.hidden=!0)},np=()=>{const n=dy();return(gy(n),!hi)?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=>{kf=n,hi.showModal?hi.showModal():hi.hidden=!1})},tf=(n,t,i="")=>{n.result=t,n.error=i},ac=n=>Number.isInteger(n?.wordChapter?.index)&&n.wordChapter.index>0?n.wordChapter.index*10:null,vc=n=>Number.isInteger(n?.wordScene?.index)&&n.wordScene.index>0?n.wordScene.index*10:null,tp=async(n,t)=>{const i=await ri(`/api/word-companion/books/${n}/chapters`,{title:ar(t.wordTitle),sortOrder:ac(t)});if(!i?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");t.pdChapter={chapterId:i.chapterId,title:i.title||t.wordTitle,sortOrder:i.sortOrder||ac(t)||0,scenes:[]};t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},ip=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 ri(`/api/word-companion/books/${n}/chapters/${i.chapterId}/scenes`,{sceneTitle:ar(t.wordTitle),sortOrder:vc(t)});if(!r?.sceneId)throw new Error("Scene creation did not return a scene ID.");t.pdChapter=i;t.pdScene={sceneId:r.sceneId,title:t.wordTitle,sortOrder:vc(t)||0};t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},rp=async n=>{if(!kt||!rt||!window.Word||typeof window.Word.run!="function")throw new Error("Word document access is unavailable.");await window.Word.run(async t=>{const u=await wr(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.");rf(i,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=n.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");rf(i,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()})},up=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.`,fp=async()=>{const r=l();if(!r||hr().length===0||wu){ne();return}const f=await np();if(f){wu=!0;te();vi("Applying structure sync...");const n={createdChapters:0,createdScenes:0,linkedChapters:0,linkedScenes:0,skipped:Array.isArray(dt?.manualReview)?dt.manualReview.length:0,failed:0},e=hr().filter(n=>n.category==="couldLink"&&n.type==="Chapter"),o=hr().filter(n=>n.category==="wouldCreateChapters"),h=hr().filter(n=>n.category==="couldLink"&&n.type==="Scene"),c=hr().filter(n=>n.category==="wouldCreateScenes"),u=[];let t="";const i=(n,t)=>{u.push({item:n,counterName:t})},a=async(t,i)=>{try{await rp(t);tf(t,"Success");n[i]+=1}catch(r){tf(t,"Failed",s(r));n.failed+=1}};try{for(const n of e)i(n,"linkedChapters");for(const t of o)try{await tp(r.bookId,t);i(t,"createdChapters")}catch(u){tf(t,"Failed",s(u));n.failed+=1}for(const n of h)i(n,"linkedScenes");for(const t of c)try{await ip(r.bookId,t);i(t,"createdScenes")}catch(u){tf(t,"Failed",s(u));n.failed+=1}for(const n of u)await a(n.item,n.counterName);for(const n of dt.manualReview||[])tf(n,"Skipped");hc(dt);t=up(n);vi(t)}finally{wu=!1;te();t&&(await lc(),vi(`${t} Preview refreshed.`))}}},ep=async()=>{sr&&(sr.disabled=!0,sr.textContent="Running...");try{if(await tc(),!kt||!rt||!window.Word||typeof window.Word.run!="function"){i({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});i({lastScan:"Success",lastError:"-",paragraphs:String(n)})}catch(n){console.error("Word Companion diagnostics failed.",n);const r=s(n);i({lastScan:"Failure",lastError:r});t(`Unable to scan the Word document: ${r}`)}finally{sr&&(sr.disabled=!1,sr.textContent="Run Diagnostics")}},pt=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()},ri=(n,t)=>pt(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),op=async()=>{const t=yr(),r=ru();if(!t||!r){it("Select a Project and Book to begin.");return}if(!kt||!rt||!window.Word||typeof window.Word.run!="function"){it("Word document access is unavailable.");return}wi&&(wi.disabled=!0,wi.textContent="Scanning...");at("Scanning manuscript structure...");try{const u=await window.Word.run(async n=>{const t=n.document.body.paragraphs;return t.load("text,styleBuiltIn,style"),await n.sync(),ly(t.items,!!r.usesExplicitScenes)});yu=u;bf=!1;const f=await ri("/api/word-companion/manuscript/analyse",{projectId:t.projectId,bookId:r.bookId,documentGuid:fc(),chapterCount:u.chapterCount,sceneCount:u.sceneCount,wordCount:u.wordCount});tr=f;ey(f);try{const n=await ri("/api/word-companion/manuscript/discover-characters",{projectId:t.projectId,documentText:u.documentText||""});ko(n?.candidates||[])}catch(e){console.error("Unable to discover character candidates.",e);ko([]);n(ur,"Character discovery is unavailable.")}i({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(u.chapterCount),heading2:"-"})}catch(u){console.error("Unable to scan manuscript for first-run import.",u);it(`Unable to scan manuscript: ${s(u)}`);i({lastScan:"Failure",lastError:s(u)})}finally{wi&&(wi.textContent="Scan Manuscript");d()}},sp=()=>new Promise(n=>{if(!kr||typeof kr.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=>{ss?.removeEventListener("click",i),hs?.removeEventListener("click",r),kr?.removeEventListener("cancel",u),kr?.close(),n(t)},i=()=>t(!0),r=()=>t(!1),u=n=>{n.preventDefault(),t(!1)};ss?.addEventListener("click",i);hs?.addEventListener("click",r);kr?.addEventListener("cancel",u);kr.showModal()}),hp=async()=>{const i=yr(),r=ru();if(!i||!r||!yu||!tr?.canImport){d();return}let n=!1;if(tr.requiresReplaceConfirmation&&(n=await sp(),!n)){at("Import cancelled.");return}pu=!0;d();at("Importing manuscript structure...");try{const s=fc(),e=await ri("/api/word-companion/manuscript/import",{projectId:i.projectId,bookId:r.bookId,documentGuid:s,bindingVersion:1,replacePlanned:n,chapters:yu.chapters});if(!e.imported){tr={...tr,canImport:!e.requiresReplaceConfirmation,requiresReplaceConfirmation:!!e.requiresReplaceConfirmation,message:e.message||tr.message};at(e.message||"Import was not completed.");d();return}const o=e.manuscriptDocument;await sy({documentGuid:o?.documentGuid||s,bookId:e.bookId,projectId:e.projectId,bindingVersion:o?.bindingVersion||1});vu={documentGuid:o?.documentGuid||s,bookId:e.bookId,projectId:e.projectId,bindingVersion:o?.bindingVersion||1};c(f.projectId,e.projectId);c(f.bookId,e.bookId);v&&(v.value=String(e.projectId));const h=ir;await br(e.projectId,e.bookId);gf("Connected");bf=!0;ir=h;h.length>0?(pr(!0),ko(h),u(ye,!0),u(ff,!1),at(e.message||"Manuscript structure imported."),t(e.message||"Manuscript structure imported.")):(pr(!1),t(e.message||"Manuscript structure imported."))}catch(e){console.error("Unable to import manuscript structure.",e);at(`Unable to import manuscript: ${s(e)}`)}finally{pu=!1;d()}},yc=()=>{pr(!1),at(""),u(ff,!0)},cp=async()=>{const i=yr()||iu(),r=uc();if(!i||r.length===0){d();return}fo=!0;d();n(ur,"Creating selected characters...");try{const u=await ri("/api/word-companion/manuscript/create-discovered-characters",{projectId:i.projectId,candidateNames:r});t(u.message||"Characters created.");n(ur,`${u.createdCount||0} created, ${u.skippedCount||0} already existed.`);yc()}catch(u){console.error("Unable to create discovered characters.",u);n(ur,`Unable to create characters: ${s(u)}`)}finally{fo=!1;d()}},lp=async()=>{if(!su||!rt){pr(!1);return}const n=oy();if(n)try{const i=await pt(`/api/word-companion/manuscript/book/${n.bookId}`),t=i?.manuscriptDocument;if(t&&String(t.documentGuid).toLowerCase()===n.documentGuid.toLowerCase()){vu=n;c(f.projectId,n.projectId);c(f.bookId,n.bookId);v&&(v.value=String(n.projectId));await br(n.projectId,n.bookId);pr(!1);gf("Connected");return}}catch{}vu=null;rc();yr()?await br(yr().projectId,null):h(y,"Select a project first");it("Select a Project and Book to begin.");pr(!0)},ap=(n,t)=>pt(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),vp=(n,t)=>pt(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),he=n=>n?[...n.querySelectorAll("input[type='checkbox']:checked")].map(n=>Number.parseInt(n.value||"",10)).filter(n=>Number.isInteger(n)&&n>0):[],pc=()=>{const n=Number.parseInt(di?.value||"",10);return Number.isInteger(n)&&n>0?n:null},yp=()=>{const n=new Set(he(eu)),t=new Set(he(ou));gt={characters:gt.characters.map(t=>({...t,linked:n.has(Number.parseInt(ue(t,"character"),10))})),assets:gt.assets.map(n=>({...n,linked:t.has(Number.parseInt(ue(n,"asset"),10))})),locations:gt.locations,primaryLocationId:pc()}},pp=async()=>{if(!r)return!1;if(!kt||!rt||!window.Word||typeof window.Word.run!="function")return yi(!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 wr(n)),u=n.currentChapter?.title||"",f=n.currentScene?.title||"",t=n.currentScene?.anchorId||null,i=n.currentChapter?.anchorId||null,o=Number.isInteger(t)&&t===r,s=Number.isInteger(i)&&i===e,h=b(f,"scene").toLocaleLowerCase()===b(df||nt,"scene").toLocaleLowerCase(),c=b(u,"chapter").toLocaleLowerCase()===b(co||p,"chapter").toLocaleLowerCase(),l=o||h&&(s||c);return l?(yi(!1),!0):(yi(!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),i({lastError:s(n)}),yi(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1}},wp=async()=>{if(!r){cr("Link a PlotDirector scene first.");return}if(ht||!await pp()){cr("The Word cursor is now in a different scene. Refresh Current Scene before saving.");return}ei&&(ei.disabled=!0,ei.textContent="Saving...");try{await vp(`/api/word-companion/scenes/${r}/links`,{characterIds:he(eu),assetIds:he(ou),locationIds:[],primaryLocationId:pc()});yp();cr("Scene links saved successfully.");i({lastError:"-"})}catch(n){cr("Unable to save scene links.");i({lastError:s(n)})}finally{ei&&(ei.disabled=!r||ht,ei.textContent="Save Scene Links")}},bp=(n,t)=>{const i=Array.isArray(n?.contentControls?.items)?n.contentControls.items:[];return i.find(n=>ec(n.tag,t))||null},rf=(n,t,i,r)=>{const f=bp(n,r),u=f||n.getRange().insertContentControl();return u.title=t,u.tag=i,u.appearance="Hidden",u},wc=async(n="PlotDirector IDs attached successfully.")=>{if(!r||!e)return t("No resolved PlotDirector scene."),!1;const f=w&&w!==r||a&&a!==e;if(f&&!window.confirm("This scene is already linked. Replace the existing PlotDirector link?"))return!1;if(!kt||!rt||!window.Word||typeof window.Word.run!="function")return t("Word document access is unavailable."),!1;ui&&(ui.disabled=!0,ui.textContent="Attaching...");try{return await window.Word.run(async n=>{const t=await wr(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],u=t.bodyParagraphs[t.currentScene.paragraphIndex];if(!i||!u)throw new Error("Unable to locate the current Word headings.");rf(i,"PlotDirector Chapter",`PD-CHAPTER-${e}`,"PD-CHAPTER");rf(u,"PlotDirector Scene",`PD-SCENE-${r}`,"PD-SCENE");await n.sync()}),a=e,w=r,lt=!1,li="SceneID Anchor",cu="Anchor",t(n),i({lastError:"-"}),ai(),!0}catch(u){return console.error("Unable to attach PlotDirector IDs.",u),t("Unable to attach PlotDirector IDs."),i({lastError:s(u)}),ai(),!1}finally{ui&&(ui.textContent=w===r?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",ai())}},bc=async n=>{if(!e)return ti("No resolved PlotDirector chapter."),!1;if(!kt||!rt||!window.Word||typeof window.Word.run!="function")return ti("Word document access is unavailable."),!1;try{return await window.Word.run(async n=>{const t=await wr(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.");rf(i,"PlotDirector Chapter",`PD-CHAPTER-${e}`,"PD-CHAPTER");await n.sync()}),a=e,lt=!1,li="ChapterID Anchor",cu="Chapter anchor",ti(n),t(n),i({lastError:"-"}),ai(),!0}catch(r){return console.error("Unable to attach PlotDirector chapter ID.",r),ti("Unable to attach PlotDirector chapter ID."),i({lastError:s(r)}),ai(),!1}},kp=async()=>{await wc()},kc=async n=>{du(),await ce(),t(n),ti(n)},us=n=>{wf&&(wf(n),wf=null),si?.close?si.close():si&&(si.hidden=!0)},dp=(t,i)=>(n(la,`"${t}"`),n(aa,`"${i}"`),!si)?Promise.resolve(window.confirm(`Create PlotDirector chapter:
|
|
|
|
"${t}"
|
|
|
|
in book:
|
|
|
|
"${i}"
|
|
|
|
?`)):new Promise(n=>{wf=n,si.showModal?si.showModal():si.hidden=!1}),gp=async()=>{const n=l();if(!n||!p||e){ie("Chapter not found in PlotDirector.");return}const t=ar(p),r=await dp(t,vr(n)||"selected book");if(r){ft&&(ft.disabled=!0,ft.textContent="Creating...");try{const r=Number.isInteger(yf)&&yf>0?yf*10:null,i=await ri(`/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.");rr(null,i.chapterId,"Manual chapter link");const u=await bc("Chapter created and linked successfully.");if(!u)return;await kc("Chapter created and linked successfully.")}catch(u){ti("Unable to create chapter.");i({lastError:s(u)})}finally{ft&&(ft.disabled=!po(),ft.textContent="Create Chapter in PlotDirector")}}},dc=()=>{if(lf){const n=ar(cf?.value||"").toLocaleLowerCase(),t=uo.filter(t=>!n||String(t.title||"").toLocaleLowerCase().includes(n));if(lf.innerHTML="",au=null,bt&&(bt.disabled=!0),t.length===0){const n=document.createElement("p");n.className="word-companion-empty-list";n.textContent="No chapters found.";lf.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",()=>{au=i,bt&&(bt.disabled=!1)});const u=document.createElement("span");u.textContent=n.title||"Untitled chapter";r.append(t,u);lf.append(r)}}}},nw=async()=>{const t=l();if(!t||!p||e){ie("Chapter not found in PlotDirector.");return}et&&(et.disabled=!0,et.textContent="Loading...");try{uo=await dh(t.bookId);au=null;cf&&(cf.value="");n(to,"");dc();nr?.showModal?nr.showModal():nr&&(nr.hidden=!1)}catch(r){ti("Unable to load chapters.");i({lastError:s(r)})}finally{et&&(et.disabled=!po(),et.textContent="Link to Existing Chapter")}},gc=()=>{nr?.close?nr.close():nr&&(nr.hidden=!0)},tw=async()=>{const t=uo.find(n=>n.chapterId===au);if(!t){n(to,"Select a chapter.");return}bt&&(bt.disabled=!0,bt.textContent="Linking...");try{rr(null,t.chapterId,"Manual chapter link");const n=await bc("Chapter linked successfully.");if(!n)return;gc();await kc("Chapter linked successfully.")}catch(r){n(to,"Unable to link chapter.");ti("Unable to link chapter.");i({lastError:s(r)})}finally{bt&&(bt.disabled=!au,bt.textContent="Link Chapter")}},nl=async(n,t,i)=>{const r=l();if(!r)return lr("Select a PlotDirector book first."),!1;await ee(r.bookId,n,t,"Manual link","Title Match");const u=await wc(i);return u?(lr(i),re(),!0):!1},fs=n=>{pf&&(pf(n),pf=null),oi?.close?oi.close():oi&&(oi.hidden=!0)},iw=(t,i)=>(n(ea,`"${t}"`),n(oa,`"${i}"`),!oi)?Promise.resolve(window.confirm(`Create PlotDirector scene:
|
|
|
|
"${t}"
|
|
|
|
within chapter:
|
|
|
|
"${i}"
|
|
|
|
?`)):new Promise(n=>{pf=n,oi.showModal?oi.showModal():oi.hidden=!1}),rw=async()=>{const n=l();if(!n||!nt){gu("Scene not found in PlotDirector.");return}const t=b(nt,"scene"),r=b(p,"chapter"),u=await iw(t,r);if(u){ot&&(ot.disabled=!0,ot.textContent="Creating...");try{const r=await nc();if(!r){gu("This chapter does not exist in PlotDirector. Create or link the chapter first.");return}const i=await ri(`/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.");await nl(i.sceneId,i.chapterId,"Scene created and linked successfully.")}catch(f){lr("Unable to create scene.");i({lastError:s(f)})}finally{ot&&(ot.disabled=!wo(),ot.textContent="Create Scene in PlotDirector")}}},tl=()=>{if(hf){const n=ar(sf?.value||"").toLocaleLowerCase(),t=ro.filter(t=>!n||String(t.title||"").toLocaleLowerCase().includes(n));if(hf.innerHTML="",lu=null,wt&&(wt.disabled=!0),t.length===0){const n=document.createElement("p");n.className="word-companion-empty-list";n.textContent="No scenes found.";hf.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",()=>{lu=i,wt&&(wt.disabled=!1)});const u=document.createElement("span");u.textContent=n.title||"Untitled scene";r.append(t,u);hf.append(r)}}}},uw=async()=>{const t=l();if(!t||!nt){gu("Scene not found in PlotDirector.");return}st&&(st.disabled=!0,st.textContent="Loading...");try{const r=await bo(t.bookId),i=gh(r);if(!i){gu("This chapter does not exist in PlotDirector. Create or link the chapter first.");return}ro=Array.isArray(i.scenes)?i.scenes:[];lu=null;sf&&(sf.value="");n(no,"");tl();gi?.showModal?gi.showModal():gi&&(gi.hidden=!1)}catch(r){lr("Unable to load scenes.");i({lastError:s(r)})}finally{st&&(st.disabled=!wo(),st.textContent="Link to Existing Scene")}},il=()=>{gi?.close?gi.close():gi&&(gi.hidden=!0)},fw=async()=>{const r=l(),t=ro.find(n=>n.sceneId===lu);if(!r||!t){n(no,"Select a scene.");return}wt&&(wt.disabled=!0,wt.textContent="Linking...");try{const n=await nc();if(!n)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");il();await nl(t.sceneId,n.chapterId,"Scene linked successfully.")}catch(u){n(no,"Unable to link scene.");lr("Unable to link scene.");i({lastError:s(u)})}finally{wt&&(wt.disabled=!lu,wt.textContent="Link Scene")}},ew=async()=>{if(!r){nu("No resolved PlotDirector scene.");return}if(ht){nu("Refresh Current Scene before syncing.");return}if(!Number.isInteger(hu)){nu("Unable to sync progress.");return}fi&&(fi.disabled=!0,fi.textContent="Syncing...");const t=(new Date).toISOString();try{const i=await ap(`/api/word-companion/scenes/${r}/word-count`,{actualWordCount:hu,lastWorkedOn:t});n(ge,o(i?.actualWords??hu));n(be,o(i?.actualWords??hu));n(kl,(new Date).toLocaleString());nu("Progress synced successfully.")}catch{nu("Unable to sync progress.")}finally{fi&&(fi.disabled=!r||ht,fi.textContent="Sync Progress")}},rl=async()=>{const r=iu(),n=l(),u=b(p,"chapter");if(ut({projectId:r?.projectId,projectTitle:r?.title,bookId:n?.bookId,bookTitle:n?vr(n):undefined,detectedChapter:p,detectedScene:nt,requestChapter:u,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!n)return k("Not detected"),t("Select a PlotDirector book first."),!1;if(!p)return k("Not detected"),t("No chapter detected in Word. Use Heading 1 for chapters."),!1;k("Not detected");try{const f=await dh(n.bookId),i=a?f.find(n=>n.chapterId===a):null,e=u.toLocaleLowerCase(),o=e?f.find(n=>b(n.title,"chapter").toLocaleLowerCase()===e):null,r=i||o;return r?(du(),rr(null,r.chapterId,i?"Chapter anchor":"Chapter title"),li=i?"ChapterID Anchor":"Title Match",gr("Chapter linked to PlotDirector"),t("No scene detected in Word. Use Heading 2 for scenes."),ut({result:"Chapter matched",chapterId:r.chapterId,sceneId:null}),!0):(rr(null),gr("Chapter not found in PlotDirector."),t("Chapter not found in PlotDirector."),ut({result:"Chapter not matched",chapterId:null,sceneId:null}),ie("Chapter not found in PlotDirector."),!1)}catch(f){return k("Not found in PlotDirector"),i({lastError:s(f)}),t("Unable to load PlotDirector chapter data."),!1}},ce=async()=>{const u=iu(),n=l(),f=b(p,"chapter"),r=b(nt,"scene");if(ut({projectId:u?.projectId,projectTitle:u?.title,bookId:n?.bookId,bookTitle:n?vr(n):undefined,detectedChapter:p,detectedScene:nt,requestChapter:f,requestScene:r,result:"Not run",chapterId:null,sceneId:null}),vo({anchorType:w?"SceneID Anchor":a?"ChapterID Anchor":"Title Match",storedSceneId:w,storedChapterId:a,resolutionMethod:"-"}),!n)return k("Not detected"),t("Select a PlotDirector book first."),ut({result:"Error"}),!1;if(!p||!nt)return k("Not detected"),t("No scene detected in Word. Use Heading 2 for scenes."),ut({result:"Error"}),!1;or&&(or.disabled=!0,or.textContent="Refreshing...");const o=()=>{or&&(or.disabled=!1,or.textContent="Refresh PlotDirector Scene")};k("Not detected");t("Resolving PlotDirector scene...");try{if(w){const i=await uy(n.bookId,(n,t)=>t.sceneId===w);if(i)return ut({result:"Matched",chapterId:i.chapter.chapterId,sceneId:i.scene.sceneId}),await ee(n.bookId,i.scene.sceneId,i.chapter.chapterId,"Anchor","SceneID Anchor"),!0;lt=!0;li="SceneID Anchor";gr("Not found in PlotDirector");t("Stored PlotDirector ID is invalid.");ut({result:"Error",chapterId:a,sceneId:w});vo({anchorType:"SceneID Anchor",storedSceneId:w,storedChapterId:a,resolutionMethod:"Anchor"})}if(a){const u=await bo(n.bookId),t=u.find(n=>n.chapterId===a),i=t?(Array.isArray(t.scenes)?t.scenes:[]).find(n=>b(n.title,"scene").toLocaleLowerCase()===r.toLocaleLowerCase()):null;if(i)return ut({result:"Matched",chapterId:t.chapterId,sceneId:i.sceneId}),await ee(n.bookId,i.sceneId,t.chapterId,"Anchor","ChapterID Anchor"),!0;t&&!w?(li="ChapterID Anchor",rr(null,a,"Chapter anchor"),ut({result:"Chapter matched",chapterId:a,sceneId:null})):w||(li="ChapterID Anchor",ut({result:"Chapter anchor not found",chapterId:a,sceneId:null}))}const i=await ri(`/api/word-companion/books/${n.bookId}/resolve-scene`,{chapterTitle:f,sceneTitle:r});if(!i?.matched||!i.sceneId){const u=lt,f=Number.parseInt(i?.chapterId||"",10),s=Number.isInteger(e)&&e>0?e:null,n=Number.isInteger(f)&&f>0?f:s,r=!!i?.chapterMatched||!!n;return k("Not found in PlotDirector"),lt=u,r&&(rr(null,n,n===s?"Chapter anchor":"Chapter title"),gr("Scene not found in PlotDirector.")),t(u?"Stored PlotDirector ID is invalid.":r?"Scene not found in PlotDirector.":"This chapter does not exist in PlotDirector. Create or link the chapter first."),ut({result:"Not matched",chapterId:r?n:i?.chapterId,sceneId:i?.sceneId}),u||(r?(du(),gu("Scene not found in PlotDirector.")):(re(),ie("Chapter not found in PlotDirector."))),o(),!1}const u=lt;return ut({result:u?"Matched by title fallback":"Matched",chapterId:i.chapterId,sceneId:i.sceneId}),await ee(n.bookId,i.sceneId,i.chapterId,u?"Title fallback":"Title","Title Match"),u&&(lt=!0,t("Stored PlotDirector ID is invalid."),ai()),!0}catch(h){const n=lt;return i({lastError:s(h)}),k("Not found in PlotDirector"),lt=n,t(n?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),ut({result:"Error"}),!1}finally{o()}},ow=n=>{const t=n.currentChapter?.title||"",i=n.currentScene?.title||"",r=n.currentChapter?.anchorId||null,u=n.currentScene?.anchorId||null;return b(t,"chapter")!==b(p,"chapter")||b(i,"scene")!==b(nt,"scene")||r!==a||u!==w},sw=async()=>{if(!ho&&su&&l()){if(!kt||!rt||!window.Word||typeof window.Word.run!="function"){ni("Manual");t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");return}ho=!0;ni("Refreshing");t("Updating current scene...");try{const n=await window.Word.run(async n=>await wr(n)),r=ow(n);if(ku(n.currentChapter?.title,n.currentScene?.title,n.currentScene?.wordCount,n.currentChapter?.anchorId,n.currentScene?.anchorId,n.currentChapter?.index),ts(n),i({lastScan:"Success",lastError:"-",paragraphs:String(n.paragraphCount),heading1:String(n.heading1Count),heading2:String(n.heading2Count)}),!r){yi(!1);ni("Live");t("Current scene updated.");return}nt?await ce():await rl();yi(!1);ni("Live");t("Current scene updated.")}catch(n){console.error("Unable to refresh current scene from Word selection.",n);i({lastScan:"Failure",lastError:s(n)});yi(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving.")}finally{ho=!1}}},hw=()=>{oo&&window.clearTimeout(oo),oo=window.setTimeout(sw,850)},ul=()=>{hw()},cw=()=>{if(so&&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:ul});so=!1}catch(n){console.warn("Unable to remove Word selection tracking handler.",n)}},lw=()=>{if(su){if(!window.Office?.context?.document||typeof window.Office.context.document.addHandlerAsync!="function"||!window.Office?.EventType?.DocumentSelectionChanged){ni("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,ul,n=>{n?.status===window.Office.AsyncResultStatus.Succeeded?(so=!0,ni("Live")):(ni("Manual"),t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))});window.addEventListener("beforeunload",cw)}catch(n){console.warn("Unable to register Word selection tracking handler.",n);ni("Manual");t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}},aw=async()=>{if(!l()){t("Select a PlotDirector book first.");k("Not detected");return}bh(!0);try{const n=await cc();if(!n)return;if(yi(!1),!nt){await rl();return}await ce()}finally{bh(!1)}},br=async(n,t)=>{if(!n){ct=[];h(g,"Select a project first");h(y,"Select a project first");bu("");c(f.bookId,null);ii();k("Not detected");tu();return}h(g,"Loading books...");bu("");k("Not detected");tu("Select a book to analyse manuscript structure.");try{const r=await pt(`/api/word-companion/projects/${n}/books`);if(ct=Array.isArray(r.books)?r.books:[],ct.length===0){h(g,"No books available.");h(y,"No books available.");bu("No books available.");c(f.bookId,null);ii();it("No books available.");return}oe(g,"Choose a book",ct.map(n=>({...n,displayTitle:vr(n)})),"bookId","displayTitle");const i=ct.find(n=>n.bookId===t);i&&g?(g.value=String(i.bookId),c(f.bookId,i.bookId)):c(f.bookId,null);fy(i?.bookId||t);ii();k(l()?"Not detected":"Not detected");tu(l()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure.");it(ru()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{ct=[];h(g,"Unable to load books.");h(y,"Unable to load books.");bu("Unable to load books.");c(f.bookId,null);ii();k("Not detected");tu("Unable to load books.");it("Unable to load books.")}},vw=async()=>{h(v,"Loading projects...");h(g,"Select a project first");h(tt,"Loading projects...");h(y,"Select a project first");ao("");bu("");try{const t=await pt("/api/word-companion/projects");if(ci=Array.isArray(t.projects)?t.projects:[],ci.length===0){h(v,"No projects available.");h(tt,"No projects available.");ao("No projects available.");c(f.projectId,null);c(f.bookId,null);ii();it("No projects available.");return}oe(v,"Choose a project",ci,"projectId","title");rc();const i=ic(f.projectId),n=ci.find(n=>n.projectId===i);n&&v?(v.value=String(n.projectId),tt&&(tt.value=String(n.projectId)),c(f.projectId,n.projectId),await br(n.projectId,ic(f.bookId))):(c(f.projectId,null),c(f.bookId,null),ii(),it("Select a Project and Book to begin."))}catch{ci=[];ct=[];h(v,"Unable to connect to PlotDirector.");h(g,"Select a project first");h(tt,"Unable to connect to PlotDirector.");h(y,"Select a project first");gf("Unable to connect to PlotDirector.");ao("Unable to connect to PlotDirector.");c(f.projectId,null);c(f.bookId,null);ii();it("Unable to connect to PlotDirector.")}};for(const n of le)n.addEventListener("click",()=>yh(n.dataset.tabButton));ph();v?.addEventListener("change",async()=>{const n=Number.parseInt(v.value||"",10);tt&&Number.isInteger(n)&&n>0&&(tt.value=String(n));c(f.projectId,Number.isInteger(n)&&n>0?n:null);c(f.bookId,null);k("Not detected");tu();it("Select a Book to begin.");await br(n,null)});g?.addEventListener("change",()=>{const n=Number.parseInt(g.value||"",10);c(f.bookId,Number.isInteger(n)&&n>0?n:null);y&&Number.isInteger(n)&&n>0&&(y.value=String(n));ii();k("Not detected");tu(l()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure.");it(ru()?"Ready to scan manuscript structure.":"Select a Book to begin.")});tt?.addEventListener("change",async()=>{const n=Number.parseInt(tt.value||"",10);v&&Number.isInteger(n)&&n>0&&(v.value=String(n));c(f.projectId,Number.isInteger(n)&&n>0?n:null);c(f.bookId,null);it("Select a Book to begin.");await br(n,null)});y?.addEventListener("change",()=>{const n=Number.parseInt(y.value||"",10);g&&Number.isInteger(n)&&n>0&&(g.value=String(n));c(f.bookId,Number.isInteger(n)&&n>0?n:null);ii();it(ru()?"Ready to scan manuscript structure.":"Select a Book to begin.")});uu?.addEventListener("input",d);uf?.addEventListener("click",async()=>{const n=yr(),t=String(uu?.value||"").trim();if(!n||!t){d();return}uf.disabled=!0;at("Creating Book...");try{const i=await ri(`/api/word-companion/projects/${n.projectId}/books`,{title:t});uu&&(uu.value="");v&&(v.value=String(n.projectId));await br(n.projectId,i.bookId);y&&(y.value=String(i.bookId));at("Ready to scan manuscript structure.")}catch(i){console.error("Unable to create Book from Word Companion.",i);at(`Unable to create Book: ${s(i)}`)}finally{d()}});wi?.addEventListener("click",op);pe?.addEventListener("click",hp);ve?.addEventListener("click",cp);cl?.addEventListener("click",yc);sl?.addEventListener("click",()=>pr(!1));ll?.addEventListener("click",()=>it("Import cancelled."));er?.addEventListener("click",cc);ki?.addEventListener("click",lc);we?.addEventListener("click",fp);pa?.addEventListener("click",()=>rs(!0));wa?.addEventListener("click",()=>rs(!1));hi?.addEventListener("cancel",n=>{n.preventDefault(),rs(!1)});or?.addEventListener("click",ce);ef?.addEventListener("click",aw);fi?.addEventListener("click",ew);ei?.addEventListener("click",wp);ui?.addEventListener("click",kp);ft?.addEventListener("click",gp);et?.addEventListener("click",nw);cf?.addEventListener("input",dc);bt?.addEventListener("click",tw);ca?.addEventListener("click",gc);va?.addEventListener("click",()=>us(!0));ya?.addEventListener("click",()=>us(!1));si?.addEventListener("cancel",n=>{n.preventDefault(),us(!1)});ot?.addEventListener("click",rw);st?.addEventListener("click",uw);sf?.addEventListener("input",tl);wt?.addEventListener("click",fw);fa?.addEventListener("click",il);sa?.addEventListener("click",()=>fs(!0));ha?.addEventListener("click",()=>fs(!1));oi?.addEventListener("cancel",n=>{n.preventDefault(),fs(!1)});sr?.addEventListener("click",ep);const yw=su?vw():Promise.resolve();if(su||(h(v,"Please sign in to PlotDirector."),h(g,"Please sign in to PlotDirector."),h(tt,"Please sign in to PlotDirector."),h(y,"Please sign in to PlotDirector."),ii()),!window.Office||typeof window.Office.onReady!="function"){lo("Word Companion ready");t("Word document access is unavailable.");ni("Manual");i({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"});return}tc().then(async()=>{lo("Word Companion ready"),await yw,await lp(),rt?lw():(t("Word document access is unavailable."),ni("Manual"))}).catch(n=>{console.error("Office readiness check failed.",n),gf("Unable to connect to PlotDirector."),lo("Word Companion unavailable"),t("Word document access is unavailable."),i({ready:"No",wordApi:"No",lastScan:"Failure"})})})(); |