diff --git a/PlotLine/wwwroot/js/word-companion-host.js b/PlotLine/wwwroot/js/word-companion-host.js index 4075124..3438418 100644 --- a/PlotLine/wwwroot/js/word-companion-host.js +++ b/PlotLine/wwwroot/js/word-companion-host.js @@ -199,6 +199,8 @@ let runtimeSelectionDirty = false; let runtimeLastActivityAt = 0; let runtimeUpdatePending = false; + let runtimeGeneration = 0; + let lastCurrentSceneSnapshot = null; const runtimeIdleDelayMs = 1200; let selectionHandlerRegistered = false; let isAutoRefreshingScene = false; @@ -244,6 +246,9 @@ runtimeLastDebugAt = now; console.debug(`[Word Companion Runtime] ${message}`); }; + const runtimeTiming = (message) => { + console.debug(`[Word Companion Timing] ${message}`); + }; const setOfficeStatus = (message) => { if (officeStatus) { @@ -586,6 +591,8 @@ documentStructureCache = null; plotDirectorStructureCache = null; plotDirectorStructureBookId = null; + runtimeGeneration += 1; + lastCurrentSceneSnapshot = null; resetRuntimeCharacterAliasCache(); resetRuntimeAssetAliasCache(); resetRuntimeLocationAliasCache(); @@ -2207,73 +2214,122 @@ return selectionParagraphs.items; }; - const recountCachedCurrentScene = async () => { + const runtimePerformanceNow = () => + window.performance && typeof window.performance.now === "function" ? window.performance.now() : Date.now(); + + const isSnapshotFresh = (snapshot) => !!snapshot + && !snapshot.stale + && snapshot.generation === runtimeGeneration + && snapshot.documentGuid === currentDocumentGuid() + && snapshot.sceneId === resolvedSceneId; + + const captureCurrentSceneSnapshot = async (options = {}) => { + const includeSelection = !!options.includeSelection; + const updateDisplay = options.updateDisplay !== false; + const generation = runtimeGeneration; + const startedAt = runtimePerformanceNow(); + const project = selectedProject(); + const book = selectedBook(); + const scene = documentStructureCache?.currentScene; if (!scene || !Number.isInteger(scene.startParagraphIndex) || !Number.isInteger(scene.endParagraphIndex)) { - return detectedSceneWordCount; + return null; } if (!officeReady || !wordHostAvailable || !window.Word || typeof window.Word.run !== "function") { - return detectedSceneWordCount; + return null; } - return await window.Word.run(async (context) => { + const officeStartedAt = runtimePerformanceNow(); + const wordSnapshot = await window.Word.run(async (context) => { const bodyParagraphs = context.document.body.paragraphs; bodyParagraphs.load("text"); + let selectionParagraphs = null; + if (includeSelection) { + selectionParagraphs = context.document.getSelection().paragraphs; + selectionParagraphs.load("text,styleBuiltIn,style"); + } await context.sync(); - let wordCount = 0; - const endIndex = Math.min(scene.endParagraphIndex, bodyParagraphs.items.length - 1); - const chapterHeadingIndex = documentStructureCache.currentChapter?.startParagraphIndex; - for (let index = scene.startParagraphIndex; index <= endIndex; index += 1) { - const text = String(bodyParagraphs.items[index]?.text || "").trim(); - if (!text || sceneSeparatorTexts.has(text) || index === chapterHeadingIndex) { - continue; - } - wordCount += countWords(text); - } + return { + bodyTexts: bodyParagraphs.items.map((paragraph) => String(paragraph.text || "")), + selectionParagraphs: includeSelection && selectionParagraphs + ? selectionParagraphs.items.map((paragraph) => ({ + text: String(paragraph.text || ""), + styleBuiltIn: paragraph.styleBuiltIn, + style: paragraph.style + })) + : [] + }; + }); + const officeMs = Math.round(runtimePerformanceNow() - officeStartedAt); - scene.wordCount = wordCount; + if (generation !== runtimeGeneration) { + runtimeTiming(`Office snapshot: ${officeMs}ms stale`); + return { stale: true, generation }; + } + + let selectionChanged = false; + if (includeSelection) { + const selectedIndex = findSelectedParagraphIndex(documentStructureCache, wordSnapshot.selectionParagraphs); + selectionChanged = applyRuntimeSelection(selectedIndex); + } + + const currentSceneItem = documentStructureCache?.currentScene; + if (!currentSceneItem || !Number.isInteger(currentSceneItem.startParagraphIndex) || !Number.isInteger(currentSceneItem.endParagraphIndex)) { + return null; + } + + const texts = []; + let wordCount = 0; + const endIndex = Math.min(currentSceneItem.endParagraphIndex, wordSnapshot.bodyTexts.length - 1); + const chapterHeadingIndex = documentStructureCache.currentChapter?.startParagraphIndex; + for (let index = currentSceneItem.startParagraphIndex; index <= endIndex; index += 1) { + const text = String(wordSnapshot.bodyTexts[index] || "").trim(); + if (!text || sceneSeparatorTexts.has(text) || index === chapterHeadingIndex) { + continue; + } + texts.push(text); + wordCount += countWords(text); + } + + currentSceneItem.wordCount = wordCount; + if (updateDisplay) { setCurrentStructure( documentStructureCache.currentChapter?.title, - scene.title, + currentSceneItem.title, wordCount, documentStructureCache.currentChapter?.anchorId, - scene.anchorId, + currentSceneItem.anchorId, documentStructureCache.currentChapter?.index ); - return wordCount; - }); + } + + const snapshot = { + documentGuid: currentDocumentGuid(), + projectId: project?.projectId || null, + bookId: book?.bookId || null, + chapterId: resolvedChapterId, + sceneId: resolvedSceneId, + chapterTitle: documentStructureCache.currentChapter?.title || "", + sceneTitle: currentSceneItem.title || "", + sceneText: texts.join("\n"), + wordCount, + selectionSignature: `${documentStructureCache.currentParagraphIndex ?? -1}:${currentSceneItem.startParagraphIndex}:${currentSceneItem.endParagraphIndex}`, + selectionChanged, + generation + }; + lastCurrentSceneSnapshot = snapshot; + runtimeTiming(`Office snapshot: ${officeMs}ms; scene words: ${wordCount}; total snapshot: ${Math.round(runtimePerformanceNow() - startedAt)}ms`); + return snapshot; }; - const readCachedCurrentSceneText = async () => { - const scene = documentStructureCache?.currentScene; - if (!scene || !Number.isInteger(scene.startParagraphIndex) || !Number.isInteger(scene.endParagraphIndex)) { - return ""; + const getFreshCurrentSceneSnapshot = async () => { + if (isSnapshotFresh(lastCurrentSceneSnapshot)) { + return lastCurrentSceneSnapshot; } - if (!officeReady || !wordHostAvailable || !window.Word || typeof window.Word.run !== "function") { - return ""; - } - - return await window.Word.run(async (context) => { - const bodyParagraphs = context.document.body.paragraphs; - bodyParagraphs.load("text"); - await context.sync(); - - const texts = []; - const endIndex = Math.min(scene.endParagraphIndex, bodyParagraphs.items.length - 1); - const chapterHeadingIndex = documentStructureCache.currentChapter?.startParagraphIndex; - for (let index = scene.startParagraphIndex; index <= endIndex; index += 1) { - const text = String(bodyParagraphs.items[index]?.text || "").trim(); - if (!text || sceneSeparatorTexts.has(text) || index === chapterHeadingIndex) { - continue; - } - texts.push(text); - } - - return texts.join("\n"); - }); + return await captureCurrentSceneSnapshot(); }; const refreshDocumentStructure = async () => { @@ -3788,6 +3844,7 @@ const syncSceneProgress = async (options = {}) => { const source = options.source || "manual"; + const totalStartedAt = runtimePerformanceNow(); if (!resolvedSceneId) { setSyncStatus("No resolved PlotDirector scene."); return; @@ -3820,9 +3877,9 @@ sceneWordCountSyncInFlight = true; sceneWordCountSyncPending = false; - let wordCount = detectedSceneWordCount; + let snapshot = options.snapshot || null; try { - wordCount = await recountCachedCurrentScene(); + snapshot = isSnapshotFresh(snapshot) ? snapshot : await getFreshCurrentSceneSnapshot(); } catch (error) { setSyncStatus("Sync failed"); setDiagnostics({ lastError: errorText(error) }); @@ -3831,6 +3888,14 @@ return; } + if (!isSnapshotFresh(snapshot)) { + setSyncStatus("Waiting for typing to pause"); + runtimeDebug("Scene sync skipped (stale snapshot)."); + finishSceneWordCountSync(); + return; + } + + const wordCount = snapshot.wordCount; if (!Number.isInteger(wordCount) || wordCount < 0) { setSyncStatus("Sync failed"); runtimeDebug("Scene sync failed."); @@ -3838,7 +3903,7 @@ return; } - if (lastSyncedSceneId === resolvedSceneId && lastSyncedWordCount === wordCount) { + if (lastSyncedSceneId === snapshot.sceneId && lastSyncedWordCount === wordCount) { setSyncStatus("Synced"); runtimeDebug("Sync skipped (count unchanged)."); finishSceneWordCountSync(); @@ -3855,16 +3920,22 @@ setSyncStatus("Syncing..."); runtimeDebug(`Scene sync started (${source}).`); try { + const apiStartedAt = runtimePerformanceNow(); const response = await postJson("/api/word-companion/runtime/scene-word-count", { - documentGuid, - bookId: book.bookId, - chapterId: resolvedChapterId, - sceneId: resolvedSceneId, + documentGuid: snapshot.documentGuid || documentGuid, + bookId: snapshot.bookId || book.bookId, + chapterId: snapshot.chapterId, + sceneId: snapshot.sceneId, wordCount }); + runtimeTiming(`Word count sync API: ${Math.round(runtimePerformanceNow() - apiStartedAt)}ms`); + if (!isSnapshotFresh(snapshot)) { + runtimeDebug("Scene sync result ignored (stale snapshot)."); + return; + } const actualWords = response?.actualWords ?? wordCount; const syncedAt = new Date(); - lastSyncedSceneId = resolvedSceneId; + lastSyncedSceneId = snapshot.sceneId; lastSyncedWordCount = actualWords; setText(syncPlotDirectorCount, displayValue(actualWords)); setText(plotDirectorActualWords, displayValue(actualWords)); @@ -3872,6 +3943,7 @@ setText(runtimeLastSync, formatLastSynced(syncedAt)); setSyncStatus("Synced"); runtimeDebug("Scene sync succeeded."); + runtimeTiming(`Total word count sync: ${Math.round(runtimePerformanceNow() - totalStartedAt)}ms`); } catch (error) { setSyncStatus("Sync failed"); setDiagnostics({ lastError: errorText(error) }); @@ -4106,34 +4178,62 @@ characterSuggestionInFlight = true; characterSuggestionPending = false; + const totalStartedAt = runtimePerformanceNow(); try { - const [sceneText, characterAliases, assetAliases, locationAliases] = await Promise.all([ - readCachedCurrentSceneText(), + const snapshot = await getFreshCurrentSceneSnapshot(); + if (!isSnapshotFresh(snapshot)) { + runtimeDebug("Runtime suggestions skipped (stale snapshot)."); + return; + } + + const [characterAliases, assetAliases, locationAliases] = await Promise.all([ loadRuntimeCharacterAliases(), loadRuntimeAssetAliases(), loadRuntimeLocationAliases() ]); + if (!isSnapshotFresh(snapshot)) { + runtimeDebug("Runtime suggestions skipped after cache load (stale snapshot)."); + return; + } + + const sceneText = snapshot.sceneText || ""; + const characterStartedAt = runtimePerformanceNow(); const detected = detectCharactersInSceneText(sceneText, characterAliases); + runtimeTiming(`Character detection: ${Math.round(runtimePerformanceNow() - characterStartedAt)}ms`); const characterIds = detected.map((item) => item.characterId); const signature = characterIds.slice().sort((left, right) => left - right).join(","); + const assetStartedAt = runtimePerformanceNow(); const detectedAssets = detectAssetsInSceneText(sceneText, assetAliases); + runtimeTiming(`Asset detection: ${Math.round(runtimePerformanceNow() - assetStartedAt)}ms`); const assetIds = detectedAssets.map((item) => item.assetId); const assetSignature = assetIds.slice().sort((left, right) => left - right).join(","); + const locationStartedAt = runtimePerformanceNow(); const detectedLocations = detectLocationsInSceneText(sceneText, locationAliases); + runtimeTiming(`Location detection: ${Math.round(runtimePerformanceNow() - locationStartedAt)}ms`); const locationIds = detectedLocations.map((item) => item.locationId); const locationSignature = locationIds.slice().sort((left, right) => left - right).join(","); if (!signature || (lastSuggestedSceneId === resolvedSceneId && lastSuggestedCharacterSignature === signature)) { runtimeDebug("Character suggestions skipped."); } else { + if (!isSnapshotFresh(snapshot)) { + runtimeDebug("Character suggestions skipped before submit (stale snapshot)."); + return; + } + const apiStartedAt = runtimePerformanceNow(); const response = await postJson("/api/word-companion/runtime/character-suggestions", { - documentGuid: currentDocumentGuid(), - sceneId: resolvedSceneId, + documentGuid: snapshot.documentGuid, + sceneId: snapshot.sceneId, characterIds }); + runtimeTiming(`Character suggestion API: ${Math.round(runtimePerformanceNow() - apiStartedAt)}ms`); + if (!isSnapshotFresh(snapshot)) { + runtimeDebug("Character suggestion result ignored (stale snapshot)."); + return; + } - lastSuggestedSceneId = resolvedSceneId; + lastSuggestedSceneId = snapshot.sceneId; lastSuggestedCharacterSignature = signature; if ((response?.createdCount || 0) > 0) { const names = detected.slice(0, 3).map((item) => item.name).join(", "); @@ -4146,14 +4246,24 @@ if (!assetSignature || (lastSuggestedAssetSceneId === resolvedSceneId && lastSuggestedAssetSignature === assetSignature)) { runtimeDebug("Asset suggestions skipped."); } else { + if (!isSnapshotFresh(snapshot)) { + runtimeDebug("Asset suggestions skipped before submit (stale snapshot)."); + return; + } runtimeDebug(`Asset matches found: ${detectedAssets.map((item) => item.name).join(", ")}`); + const apiStartedAt = runtimePerformanceNow(); const assetResponse = await postJson("/api/word-companion/runtime/asset-suggestions", { - documentGuid: currentDocumentGuid(), - sceneId: resolvedSceneId, + documentGuid: snapshot.documentGuid, + sceneId: snapshot.sceneId, assetIds }); + runtimeTiming(`Asset suggestion API: ${Math.round(runtimePerformanceNow() - apiStartedAt)}ms`); + if (!isSnapshotFresh(snapshot)) { + runtimeDebug("Asset suggestion result ignored (stale snapshot)."); + return; + } - lastSuggestedAssetSceneId = resolvedSceneId; + lastSuggestedAssetSceneId = snapshot.sceneId; lastSuggestedAssetSignature = assetSignature; if ((assetResponse?.createdCount || 0) > 0) { const names = detectedAssets.slice(0, 3).map((item) => item.name).join(", "); @@ -4166,14 +4276,24 @@ if (!locationSignature || (lastSuggestedLocationSceneId === resolvedSceneId && lastSuggestedLocationSignature === locationSignature)) { runtimeDebug("Location suggestions skipped."); } else { + if (!isSnapshotFresh(snapshot)) { + runtimeDebug("Location suggestions skipped before submit (stale snapshot)."); + return; + } runtimeDebug(`Location matches found: ${detectedLocations.map((item) => item.name).join(", ")}`); + const apiStartedAt = runtimePerformanceNow(); const locationResponse = await postJson("/api/word-companion/runtime/location-suggestions", { - documentGuid: currentDocumentGuid(), - sceneId: resolvedSceneId, + documentGuid: snapshot.documentGuid, + sceneId: snapshot.sceneId, locationIds }); + runtimeTiming(`Location suggestion API: ${Math.round(runtimePerformanceNow() - apiStartedAt)}ms`); + if (!isSnapshotFresh(snapshot)) { + runtimeDebug("Location suggestion result ignored (stale snapshot)."); + return; + } - lastSuggestedLocationSceneId = resolvedSceneId; + lastSuggestedLocationSceneId = snapshot.sceneId; lastSuggestedLocationSignature = locationSignature; if ((locationResponse?.createdCount || 0) > 0) { const names = detectedLocations.slice(0, 3).map((item) => item.name).join(", "); @@ -4182,6 +4302,7 @@ } runtimeDebug(locationResponse?.message || "Location suggestions submitted."); } + runtimeTiming(`Total suggestion pass: ${Math.round(runtimePerformanceNow() - totalStartedAt)}ms`); } catch (error) { console.error("Unable to detect runtime suggestions.", error); setDiagnostics({ lastError: errorText(error) }); @@ -4522,10 +4643,13 @@ runtimeDebug("Runtime update executed."); try { - const selectionParagraphs = await window.Word.run(async (context) => await readSelectionParagraphs(context)); - const selectedIndex = findSelectedParagraphIndex(documentStructureCache, selectionParagraphs); - const changed = applyRuntimeSelection(selectedIndex); - await recountCachedCurrentScene(); + const snapshot = await captureCurrentSceneSnapshot({ includeSelection: true }); + if (!isSnapshotFresh(snapshot)) { + setSceneTrackingState("Waiting for typing to pause"); + runtimeDebug("Runtime update skipped (stale snapshot)."); + return; + } + const changed = !!snapshot.selectionChanged; if (!changed) { setSceneContextStale(false); @@ -4570,8 +4694,16 @@ const markRuntimeDirty = (reason = "selection", delayMs = runtimeIdleDelayMs) => { runtimeSelectionDirty = true; runtimeLastActivityAt = Date.now(); + runtimeGeneration += 1; + lastCurrentSceneSnapshot = null; clearPendingSceneWordCountSync(); clearPendingCharacterSuggestionDetection(); + if (sceneWordCountSyncInFlight) { + sceneWordCountSyncPending = true; + } + if (characterSuggestionInFlight) { + characterSuggestionPending = true; + } runtimeDebug(`${reason} changed.`); if (isAutoRefreshingScene) { diff --git a/PlotLine/wwwroot/js/word-companion-host.min.js b/PlotLine/wwwroot/js/word-companion-host.min.js index 614c61f..6267666 100644 --- a/PlotLine/wwwroot/js/word-companion-host.min.js +++ b/PlotLine/wwwroot/js/word-companion-host.min.js @@ -1 +1 @@ -(()=>{const e="plotdirector.word.projectId",t="plotdirector.word.bookId",n="plotdirector.word.activeTab",r="plotdirector.word.documentGuid",a="plotdirector.word.boundBookId",o="plotdirector.word.boundProjectId",c="plotdirector.word.bindingVersion",i=new Set(["scene","links","structure","diagnostics"]),s=document.querySelector(".word-companion-shell"),d=document.querySelector(".word-companion-tabs"),l=[...document.querySelectorAll("[data-tab-button]")],u=[...document.querySelectorAll("[data-tab-panel]")],p=document.querySelector("[data-first-run-wizard]"),h=document.querySelector("[data-first-run-project-select]"),m=document.querySelector("[data-first-run-book-select]"),y=document.querySelector("[data-first-run-new-book-title]"),w=document.querySelector("[data-first-run-create-book]"),g=document.querySelector("[data-first-run-scan]"),f=document.querySelector("[data-first-run-cancel]"),S=document.querySelector("[data-first-run-status]"),I=document.querySelector("[data-first-run-summary]"),C=document.querySelector("[data-first-run-character-section]"),b=document.querySelector("[data-first-run-character-status]"),k=document.querySelector("[data-first-run-character-candidates]"),v=document.querySelector("[data-first-run-character-actions]"),x=document.querySelector("[data-first-run-create-characters]"),N=document.querySelector("[data-first-run-skip-characters]"),E=document.querySelector("[data-first-run-continue]"),L=document.querySelector("[data-first-run-import-actions]"),P=document.querySelector("[data-first-run-import]"),q=document.querySelector("[data-first-run-import-cancel]"),D=document.querySelector("[data-first-run-replace-dialog]"),A=document.querySelector("[data-first-run-replace-confirm]"),$=document.querySelector("[data-first-run-replace-cancel]"),T=document.querySelector("[data-office-status]"),j=document.querySelector("[data-connection-status]"),R=document.querySelector("[data-summary-connection]"),W=document.querySelector("[data-summary-project]"),U=document.querySelector("[data-summary-book]"),M=document.querySelector("[data-project-select]"),O=document.querySelector("[data-book-select]"),H=document.querySelector("[data-project-message]"),B=document.querySelector("[data-book-message]"),G=document.querySelector("[data-refresh-current-scene]"),F=document.querySelector("[data-refresh-document]"),V=document.querySelector("[data-current-chapter]"),J=document.querySelector("[data-current-scene]"),Y=document.querySelector("[data-current-word-count]"),_=document.querySelector("[data-scene-tracking-status]"),z=document.querySelector("[data-document-message]"),K=document.querySelector("[data-sync-note]"),Q=document.querySelector("[data-document-outline]"),X=document.querySelector("[data-analyse-manuscript-structure]"),Z=document.querySelector("[data-apply-structure-sync]"),ee=document.querySelector("[data-structure-preview-status]"),te=document.querySelector("[data-structure-preview-results]"),ne=document.querySelector("[data-refresh-plotdirector-scene]"),re=document.querySelector("[data-plotdirector-scene-status]"),ae=document.querySelector("[data-anchor-status]"),oe=document.querySelector("[data-anchor-book-id]"),ce=document.querySelector("[data-anchor-chapter-id]"),ie=document.querySelector("[data-anchor-scene-id]"),se=document.querySelector("[data-attach-plotdirector-ids]"),de=document.querySelector("[data-plotdirector-scene-details]"),le=document.querySelector("[data-plotdirector-scene-title]"),ue=document.querySelector("[data-plotdirector-revision-status]"),pe=document.querySelector("[data-plotdirector-estimated-words]"),he=document.querySelector("[data-plotdirector-actual-words]"),me=document.querySelector("[data-plotdirector-blocked-status]"),ye=document.querySelector("[data-plotdirector-blocked-reason-row]"),we=document.querySelector("[data-plotdirector-blocked-reason]"),ge=document.querySelector("[data-runtime-last-sync]"),fe=document.querySelector("[data-sync-scene-progress]"),Se=document.querySelector("[data-sync-word-count]"),Ie=document.querySelector("[data-sync-plotdirector-count]"),Ce=document.querySelector("[data-sync-last-synced]"),be=document.querySelector("[data-sync-status]"),ke=document.querySelector("[data-writing-brief-block]"),ve=document.querySelector("[data-writing-brief]"),xe=document.querySelector("[data-plotdirector-link-groups]"),Ne=document.querySelector("[data-character-chips]"),Ee=document.querySelector("[data-asset-chips]"),Le=(document.querySelector("[data-location-chips]"),document.querySelector("[data-primary-location-select]")),Pe=document.querySelector("[data-save-scene-links]"),qe=document.querySelector("[data-scene-links-status]"),De=document.querySelector("[data-links-editing-scene]"),Ae=document.querySelector("[data-chapter-create-link]"),$e=document.querySelector("[data-chapter-create-link-chapter]"),Te=document.querySelector("[data-create-plotdirector-chapter]"),je=document.querySelector("[data-link-existing-chapter]"),Re=document.querySelector("[data-chapter-create-link-status]"),We=document.querySelector("[data-scene-create-link]"),Ue=document.querySelector("[data-create-link-chapter]"),Me=document.querySelector("[data-create-link-scene]"),Oe=document.querySelector("[data-create-plotdirector-scene]"),He=document.querySelector("[data-link-existing-scene]"),Be=document.querySelector("[data-create-link-status]"),Ge=document.querySelector("[data-link-existing-dialog]"),Fe=document.querySelector("[data-link-scene-search]"),Ve=document.querySelector("[data-link-scene-options]"),Je=document.querySelector("[data-link-selected-scene]"),Ye=document.querySelector("[data-link-dialog-cancel]"),_e=document.querySelector("[data-link-dialog-status]"),ze=document.querySelector("[data-create-scene-dialog]"),Ke=document.querySelector("[data-create-dialog-scene]"),Qe=document.querySelector("[data-create-dialog-chapter]"),Xe=document.querySelector("[data-create-dialog-confirm]"),Ze=document.querySelector("[data-create-dialog-cancel]"),et=document.querySelector("[data-link-existing-chapter-dialog]"),tt=document.querySelector("[data-link-chapter-search]"),nt=document.querySelector("[data-link-chapter-options]"),rt=document.querySelector("[data-link-selected-chapter]"),at=document.querySelector("[data-link-chapter-dialog-cancel]"),ot=document.querySelector("[data-link-chapter-dialog-status]"),ct=document.querySelector("[data-create-chapter-dialog]"),it=document.querySelector("[data-create-chapter-dialog-chapter]"),st=document.querySelector("[data-create-chapter-dialog-book]"),dt=document.querySelector("[data-create-chapter-dialog-confirm]"),lt=document.querySelector("[data-create-chapter-dialog-cancel]"),ut=document.querySelector("[data-apply-structure-sync-dialog]"),pt=document.querySelector("[data-apply-structure-sync-summary]"),ht=document.querySelector("[data-apply-structure-sync-confirm]"),mt=document.querySelector("[data-apply-structure-sync-cancel]"),yt=document.querySelector("[data-resolve-project-id]"),wt=document.querySelector("[data-resolve-project-title]"),gt=document.querySelector("[data-resolve-book-id]"),ft=document.querySelector("[data-resolve-book-title]"),St=document.querySelector("[data-resolve-detected-chapter]"),It=document.querySelector("[data-resolve-detected-scene]"),Ct=document.querySelector("[data-resolve-request-chapter]"),bt=document.querySelector("[data-resolve-request-scene]"),kt=document.querySelector("[data-resolve-result]"),vt=document.querySelector("[data-resolve-chapter-id]"),xt=document.querySelector("[data-resolve-scene-id]"),Nt=document.querySelector("[data-run-diagnostics]"),Et=document.querySelector("[data-diagnostic-host]"),Lt=document.querySelector("[data-diagnostic-platform]"),Pt=document.querySelector("[data-diagnostic-ready]"),qt=document.querySelector("[data-diagnostic-word-api]"),Dt=document.querySelector("[data-diagnostic-last-scan]"),At=document.querySelector("[data-diagnostic-last-error]"),$t=document.querySelector("[data-diagnostic-anchor-type]"),Tt=document.querySelector("[data-diagnostic-stored-scene-id]"),jt=document.querySelector("[data-diagnostic-stored-chapter-id]"),Rt=document.querySelector("[data-diagnostic-resolution-method]"),Wt=document.querySelector("[data-diagnostic-paragraphs]"),Ut=document.querySelector("[data-diagnostic-heading1]"),Mt=document.querySelector("[data-diagnostic-heading2]"),Ot="true"===s?.dataset.authenticated;let Ht=[],Bt=[],Gt=!1,Ft=!1,Vt="Unknown",Jt="Unknown",Yt="",_t="",zt=null,Kt=null,Qt=null,Xt=null,Zt=null,en=null,tn="",nn="Title Match",rn=!1,an=[],on=null,cn=null,sn=[],dn=null,ln=null,un=null,pn=null,hn=null,mn=null,yn=null,wn=null,gn=null,fn=null,Sn=[],In=!1,Cn=!1,bn=0,kn=!1,vn=!1,xn=!1,Nn=null,En="Manual",Ln=!1,Pn=null,qn=!1,Dn=0,An=!1;const $n=1200;let Tn=!1,jn=!1,Rn=null,Wn=!1,Un=!1,Mn=null,On=null,Hn=null,Bn=!1,Gn=!1,Fn=null,Vn="",Jn=[],Yn=null,_n="",zn=null,Kn="",Qn=[],Xn=null,Zn="",er=null,tr="",nr=[],rr=null,ar="",or="",cr="",ir="",sr=0,dr={characters:[],assets:[],locations:[],primaryLocationId:null};const lr=e=>{const t=Date.now();t-sr<1e3||(sr=t,console.debug(`[Word Companion Runtime] ${e}`))},ur=e=>{T&&(T.textContent=e)},pr=(e,t=!0)=>{const r=i.has(e)&&l.some(t=>t.dataset.tabButton===e)?e:"scene";for(const e of l){const t=e.dataset.tabButton===r;e.classList.toggle("is-active",t),e.setAttribute("aria-selected",t?"true":"false")}for(const e of u){const t=e.dataset.tabPanel===r;e.classList.toggle("is-active",t),e.hidden=!t}t&&((e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}})(n,r)},hr=()=>{const e=(e=>{try{return window.localStorage.getItem(e)||""}catch{return""}})(n);pr(i.has(e)?e:"scene",!1)},mr=e=>{j&&(j.textContent=e),R&&(R.textContent=e)},yr=e=>{H&&(H.textContent=e)},wr=e=>{B&&(B.textContent=e)},gr=e=>{z&&(z.textContent=e)},fr=e=>{re&&(re.textContent=e)},Sr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("anchorType")&&sa($t,Rr(e.anchorType)),t("storedSceneId")&&sa(Tt,Rr(e.storedSceneId)),t("storedChapterId")&&sa(jt,Rr(e.storedChapterId)),t("resolutionMethod")&&sa(Rt,Rr(e.resolutionMethod))},Ir=()=>{const e=fa(),t=Number.isInteger(Zt)&&Zt>0&&Xt===Zt,n=!Number.isInteger(en)||en<=0||Qt===en,r=t&&n;sa(ae,r?"Attached to PlotDirector":"Not attached"),sa(oe,e?.bookId?String(e.bookId):"-"),sa(ce,Number.isInteger(en)&&en>0?String(en):"-"),sa(ie,Number.isInteger(Zt)&&Zt>0?String(Zt):"-"),se&&(se.disabled=!Zt||r&&!rn,se.textContent=Xt&&!r?"Reattach PlotDirector IDs":"Attach PlotDirector IDs"),Sr({anchorType:nn||"Title Match",storedSceneId:Xt,storedChapterId:Qt,resolutionMethod:tn})},Cr=(e,t,n,r=null,a=null,o=null)=>{const c=e||"",i=t||"",s=Number.isInteger(n)?n:null,d=Number.isInteger(o)&&o>0?o:null,l=Number.isInteger(r)&&r>0?r:null,u=Number.isInteger(a)&&a>0?a:null,p=Yt===c&&_t===i&&zt===s&&Kt===d&&Qt===l&&Xt===u;Yt=e||"",_t=t||"",zt=Number.isInteger(n)?n:null,Kt=Number.isInteger(o)&&o>0?o:null,Qt=Number.isInteger(r)&&r>0?r:null,Xt=Number.isInteger(a)&&a>0?a:null,p||(V&&(V.textContent=e||"Not detected"),J&&(J.textContent=t||"Not detected"),Y&&(Y.textContent=Number.isInteger(n)?String(n):"-"),sa(Se,Number.isInteger(n)?String(n):"-"),Ir())},br=()=>{Rn&&(window.clearTimeout(Rn),Rn=null)},kr=(e,t)=>{e&&(e.hidden=t)},vr=e=>{sa(be,e)},xr=e=>{sa(ee,e)},Nr=(e="Select a project and book to analyse manuscript structure.")=>{if(un=null,te){te.innerHTML="";const e=document.createElement("p");e.textContent="No preview generated.",te.append(e)}xr(e),Lr()},Er=(e=un)=>((e=un)=>Ja.flatMap(t=>Array.isArray(e?.[t.key])?e[t.key]:[]))(e).filter(e=>"couldLink"===e.category||"wouldCreateChapters"===e.category||"wouldCreateScenes"===e.category),Lr=()=>{Z&&(Z.disabled=xn||0===Er().length)},Pr=()=>{X&&(X.disabled=xn||!ga()||!fa()),Lr()},qr=()=>{De&&(De.textContent=Zt?`Editing links for: ${cr||_t||"Current scene"}`:"Link a PlotDirector scene first.")},Dr=()=>{const e=Ln||!Zt,t=e||!en||Wn;fe&&(fe.disabled=t),Pe&&(Pe.disabled=e),Le&&(Le.disabled=e);for(const t of[Ne,Ee])for(const n of t?[...t.querySelectorAll("input[type='checkbox']")]:[])n.disabled=e},Ar=e=>{"Live"!==e&&"Manual"!==e||(En=e),sa(_,e||En||"Manual")},$r=(e,t="")=>{Ln=!!e,Ln&&(br(),Uo()),sa(_,Ln?"Stale":En),Dr(),t&&(gr(t),Hr(t))},Tr=(e,t=null,n="")=>{Zt=Number.isInteger(e)&&e>0?e:null,en=Number.isInteger(t)&&t>0?t:null,tn=n||"",Zt!==Mn&&(On=null),Zt||(br(),Uo()),Dr(),vr(Ln?"Refresh Current Scene before syncing.":Zt?"Ready to sync.":"No resolved PlotDirector scene."),Hr(Ln?"Refresh Current Scene before saving.":Zt?"Ready to save.":"Link a PlotDirector scene first."),qr(),Ir()},jr=e=>{G&&(G.disabled=e,G.textContent=e?"Refreshing...":"Refresh Current Scene")},Rr=e=>null==e||""===e?"-":String(e),Wr=e=>{if(!e)return"-";const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))return"-";const n=new Date;return`Last synced: ${t.toDateString()===n.toDateString()?"Today":t.toLocaleDateString()} ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`},Ur=e=>{hn=e||null;const t=hn?.lastSyncUtc||hn?.manuscriptDocument?.lastSyncUtc;sa(ge,Wr(t)),sa(Ce,Wr(t))},Mr=()=>{mn=null,yn=null,wn=null,Mo(),Oo(),Ho(),Ur(null)},Or=()=>{yn=null,wn=null},Hr=e=>{sa(qe,e)},Br=e=>{sa(Be,e)},Gr=e=>{sa(Re,e)},Fr=()=>!!fa()&&!!Yt&&!en,Vr=()=>!!fa()&&!!_t&&Number.isInteger(en)&&en>0,Jr=()=>{kr(Ae,!0),Gr(""),Te&&(Te.disabled=!0,Te.textContent="Create Chapter in PlotDirector"),je&&(je.disabled=!0,je.textContent="Link to Existing Chapter")},Yr=(e="")=>{sa($e,Rr(Yt)),kr(Ae,!1),Gr(e);const t=Fr();Te&&(Te.disabled=!t,Te.textContent="Create Chapter in PlotDirector"),je&&(je.disabled=!t,je.textContent="Link to Existing Chapter")},_r=()=>{kr(We,!0),Br(""),Oe&&(Oe.disabled=!0,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!0,He.textContent="Link to Existing Scene")},zr=(e="")=>{sa(Ue,Rr(Yt)),sa(Me,Rr(_t)),kr(We,!1),Br(e);const t=Vr();Oe&&(Oe.disabled=!t,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!t,He.textContent="Link to Existing Scene")},Kr=e=>{fr(e),kr(de,!0),kr(ke,!0),kr(xe,!1),Jr(),_r(),tn="",cr="",ir="",nn=Xt?"SceneID Anchor":Qt?"ChapterID Anchor":"Title Match",rn=!1,dr={characters:[],assets:[],locations:[],primaryLocationId:null},Xr(Ne,[],"character"),Xr(Ee,[],"asset"),Zr([],null,!1),Tr(null),sa(Ie,"-"),sa(le,"-"),sa(ue,"-"),sa(pe,"-"),sa(he,"-"),sa(me,"-"),sa(we,"-"),kr(ye,!0),Ir(),qr()},Qr=(e,t)=>"asset"===t?e?.assetId||e?.AssetId||e?.storyAssetId||e?.StoryAssetId||0:"location"===t?e?.locationId||e?.LocationId||0:e?.characterId||e?.CharacterId||0,Xr=(e,t,n,r=!1)=>{if(!e)return;e.innerHTML="";const a=Array.isArray(t)?t:[];if(0===a.length){const t=document.createElement("p");return t.className="word-companion-empty-list",t.textContent="None",void e.append(t)}for(const t of a){const a=Number.parseInt(Qr(t,n),10);if(!Number.isInteger(a)||a<=0)continue;const o=document.createElement("label");o.className="word-companion-check-item";const c=document.createElement("input");c.type="checkbox",c.value=String(a),c.checked=!!t.linked,c.disabled=!r;const i=document.createElement("span");i.textContent=t.name||"Unnamed",o.append(c,i),e.append(o)}},Zr=(e,t,n=!1)=>{if(!Le)return;Le.innerHTML="";const r=document.createElement("option");r.value="",r.textContent="None",Le.append(r);const a=Number.parseInt(t||"",10);for(const t of Array.isArray(e)?e:[]){const e=Number.parseInt(Qr(t,"location"),10);if(!Number.isInteger(e)||e<=0)continue;const n=document.createElement("option");n.value=String(e),n.textContent=t.name||"Unnamed",n.selected=e===a,Le.append(n)}Le.disabled=!n},ea=e=>String(e||"").trim().replace(/\s+/g," "),ta=(e,t)=>{const n=ea(e);if(!n)return"";const r=new RegExp(`^${"scene"===t?"scene":"chapter"}\\s+(?:\\d+|[ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)\\s*(?::|-|\\u2013|\\u2014)\\s*`,"i");return ea(n.replace(r,""))||n},na=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("projectId")&&sa(yt,Rr(e.projectId)),t("projectTitle")&&sa(wt,Rr(e.projectTitle)),t("bookId")&&sa(gt,Rr(e.bookId)),t("bookTitle")&&sa(ft,Rr(e.bookTitle)),t("detectedChapter")&&sa(St,Rr(e.detectedChapter)),t("detectedScene")&&sa(It,Rr(e.detectedScene)),t("requestChapter")&&sa(Ct,Rr(e.requestChapter)),t("requestScene")&&sa(bt,Rr(e.requestScene)),t("result")&&sa(kt,Rr(e.result)),t("chapterId")&&sa(vt,Rr(e.chapterId)),t("sceneId")&&sa(xt,Rr(e.sceneId))},ra=async e=>{if(wn===e&&Array.isArray(yn?.chapters))return yn.chapters;const t=await go(`/api/word-companion/books/${e}/structure`);return wn=e,yn=t||null,Array.isArray(t?.chapters)?t.chapters:[]},aa=async e=>{const t=await go(`/api/word-companion/books/${e}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},oa=e=>{if(Number.isInteger(en)&&en>0){const t=e.find(e=>e.chapterId===en);if(t)return t}const t=ta(Yt,"chapter").toLocaleLowerCase();return t&&e.find(e=>ta(e.title,"chapter").toLocaleLowerCase()===t)||null},ca=async()=>{const e=fa();return e?oa(await ra(e.bookId)):null},ia=async(e,t,n,r,a)=>{const o=await go(`/api/word-companion/scenes/${t}/companion`);try{o.revisionStatus=await(async(e,t)=>{const n=await go(`/api/word-companion/books/${e}/structure`),r=Array.isArray(n?.chapters)?n.chapters:[];for(const e of r){const n=(Array.isArray(e.scenes)?e.scenes:[]).find(e=>e.sceneId===t);if(n)return n.revisionStatus||""}return""})(e,t)}catch{o.revisionStatus=""}var c;nn=a||"Title Match",rn=!1,$r(!1),fr("Linked to PlotDirector"),gr(""),Jr(),_r(),Tr(t,n,r),c=o,cr=c?.sceneTitle||_t||"",ir=c?.chapterTitle||Yt||"",sa(le,Rr(c?.sceneTitle)),sa(ue,Rr(c?.revisionStatus||c?.revisionStatusName||"Not provided")),sa(pe,Rr(c?.estimatedWords)),sa(he,Rr(c?.actualWords)),sa(Ie,Rr(c?.actualWords)),sa(me,c?.blocked?"Blocked":"Not blocked"),c?.blockedReason?(sa(we,c.blockedReason),kr(ye,!1)):(sa(we,"-"),kr(ye,!0)),ve&&(ve.textContent=c?.writingBrief||"No writing brief has been added for this scene."),dr={characters:Array.isArray(c?.characters)?c.characters:[],assets:Array.isArray(c?.assets)?c.assets:[],locations:Array.isArray(c?.locations)?c.locations:[],primaryLocationId:c?.primaryLocationId??null},Xr(Ne,dr.characters,"character",!!Zt&&!Ln),Xr(Ee,dr.assets,"asset",!!Zt&&!Ln),Zr(dr.locations,dr.primaryLocationId,!!Zt&&!Ln),qr(),Hr(Ln?"Refresh Current Scene before saving.":Zt?"Ready to save.":"No resolved PlotDirector scene."),kr(de,!1),kr(ke,!1),kr(xe,!1),Io(t,n),Wo(),_o()},sa=(e,t)=>{if(e){const n=null==t?"":String(t);e.textContent!==n&&(e.textContent=n)}},da=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("host")&&sa(Et,e.host),t("platform")&&sa(Lt,e.platform),t("ready")&&sa(Pt,e.ready),t("wordApi")&&sa(qt,e.wordApi),t("lastScan")&&sa(Dt,e.lastScan),t("lastError")&&sa(At,e.lastError),t("paragraphs")&&sa(Wt,e.paragraphs),t("heading1")&&sa(Ut,e.heading1),t("heading2")&&sa(Mt,e.heading2)},la=e=>{const t=[];return e?.name&&t.push(e.name),e?.code&&e.code!==e.name&&t.push(e.code),e?.message&&t.push(e.message),e?.debugInfo?.errorLocation&&t.push(`Location: ${e.debugInfo.errorLocation}`),t.length>0?t.join(": "):String(e)},ua=async()=>{if(!window.Office||"function"!=typeof window.Office.onReady)return Gt=!1,Ft=!1,Vt="Unavailable",Jt="Unavailable",da({host:Vt,platform:Jt,ready:"No",wordApi:"No"}),null;const e=await window.Office.onReady();return Gt=!0,Vt=e?.host||"Unknown",Jt=e?.platform||"Unknown",Ft=!!window.Word&&!!window.Office.HostType&&e?.host===window.Office.HostType.Word,da({host:Vt,platform:Jt,ready:"Yes",wordApi:Ft?"Yes":"No"}),e},pa=e=>{try{const t=window.localStorage.getItem(e),n=Number.parseInt(t||"",10);return Number.isInteger(n)&&n>0?n:null}catch{return null}},ha=(e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}},ma=(e,t)=>{if(!e)return;e.innerHTML="";const n=document.createElement("option");n.value="",n.textContent=t,e.append(n),e.disabled=!0},ya=(e,t,n,r,a)=>{if(!e)return;e.innerHTML="";const o=document.createElement("option");o.value="",o.textContent=t,e.append(o);for(const t of n){const n=document.createElement("option");n.value=String(t[r]),n.textContent=t[a],e.append(n)}e.disabled=0===n.length},wa=e=>{const t=String(e?.title||"").trim(),n=String(e?.subtitle||"").trim();return n?`${t}: ${n}`:t},ga=()=>{const e=Number.parseInt(M?.value||"",10);return Ht.find(t=>t.projectId===e)||null},fa=()=>{const e=Number.parseInt(O?.value||"",10);return Bt.find(t=>t.bookId===e)||null},Sa=()=>{const e=Number.parseInt(h?.value||"",10);return Ht.find(t=>t.projectId===e)||null},Ia=()=>{const e=Number.parseInt(m?.value||"",10);return Bt.find(t=>t.bookId===e)||null},Ca=e=>sa(S,e),ba=()=>{const e=Sa(),t=Ia(),n=Cn&&Date.now()-bn>=750;g&&(g.disabled=!e||!t||kn),w&&(w.disabled=!e||!String(y?.value||"").trim()||kn),P&&(P.disabled=!gn?.canImport||!fn||kn),x&&(x.disabled=!n||vn||0===Na().length)},ka=e=>{kr(p,!e),kr(d,e);for(const t of u)kr(t,!!e||"scene"!==t.dataset.tabPanel&&!t.classList.contains("is-active"));e||hr()},va=()=>{if(!h)return;if(0===Ht.length)return void ma(h,"No projects available.");ya(h,"Choose a project",Ht,"projectId","title");const e=Number.parseInt(M?.value||"",10);Number.isInteger(e)&&e>0&&(h.value=String(e))},xa=(e="Select a Project and Book to begin.")=>{gn=null,fn=null,Sn=[],In=!1,Cn=!1,bn=0,kr(I,!0),kr(L,!0),kr(C,!0),kr(v,!0),I&&(I.innerHTML=""),k&&(k.innerHTML=""),sa(b,""),Ca(e),ba()},Na=()=>k?[...k.querySelectorAll("input[type='checkbox']:checked")].map(e=>String(e.value||"").trim()).filter(Boolean):[],Ea=e=>{if(Sn=Array.isArray(e)?e:[],C&&k){if(k.innerHTML="",kr(C,!1),kr(v,!In||0===Sn.length),kr(x,!1),kr(N,!1),kr(E,!0),0===Sn.length)return sa(b,"No likely major characters found."),void ba();sa(b,`${Sn.length} likely major characters found.`);for(const e of Sn){const t=document.createElement("label");t.className="word-companion-character-candidate";const n=document.createElement("input");n.type="checkbox",n.value=e.text||"",n.checked="high"===String(e.confidence||"").trim().toLowerCase(),n.addEventListener("change",ba);const r=document.createElement("strong");r.textContent=e.text||"";const a=document.createElement("em"),o=String(e.reason||"").trim();a.textContent=o?`${Number(e.mentionCount||0).toLocaleString()} mentions · ${o}`:`${Number(e.mentionCount||0).toLocaleString()} mentions`;const c=document.createElement("span");c.className="word-companion-character-candidate-text",c.append(r,a),t.append(n,c),k.append(t)}ba()}},La=()=>{const e=window.Office?.context?.document?.settings;if(!e)return null;const t=String(e.get(r)||"").trim(),n=Number.parseInt(e.get(a)||"",10),i=Number.parseInt(e.get(o)||"",10),s=Number.parseInt(e.get(c)||"",10);return!t||!Number.isInteger(n)||n<=0||!Number.isInteger(i)||i<=0?null:{documentGuid:t,bookId:n,projectId:i,bindingVersion:Number.isInteger(s)&&s>0?s:1}},Pa=()=>pn?.documentGuid?pn.documentGuid:window.crypto?.randomUUID?window.crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(Number(e)^16*Math.random()>>Number(e)/4).toString(16)),qa=()=>pn?.documentGuid||La()?.documentGuid||"",Da=()=>{const e=ga(),t=fa();W&&(W.textContent=e?.title||"(Not connected)"),U&&(U.textContent=t?wa(t):"(Not connected)"),K&&(K.textContent=t?"":"Select a PlotDirector book before refreshing."),Pr()},Aa=e=>String(e?.styleBuiltIn||e?.style||"").replace(/\s+/g,"").toLowerCase(),$a=(e,t)=>{const n=Aa(e);return n===`heading${t}`||n.endsWith(`.heading${t}`)||n.includes(`heading${t}`)},Ta=e=>String(e||"").trim().split(/\s+/).filter(Boolean).length,ja=(e,t)=>{const n=String(e||"").match(new RegExp(`^${t}-(\\d+)$`,"i"));if(!n)return null;const r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null},Ra=e=>{try{return Array.isArray(e?.contentControls?.items)?e.contentControls.items:[]}catch(e){return console.warn("Word paragraph content controls were not available.",e),[]}},Wa=(e,t)=>{const n=Ra(e);for(const e of n){const n=ja(e.tag,t);if(n)return n}return null},Ua=(e,t)=>{const n=[];let r=0,a=0,o=null,c=null;e.forEach((e,t)=>{const i=String(e.text||"").trim();if(i){if($a(e,1))return r+=1,o={index:n.length+1,paragraphIndex:t,title:i,anchorId:Wa(e,"PD-CHAPTER"),scenes:[]},n.push(o),void(c=null);if($a(e,2)){if(a+=1,!o)return;return c={index:o.scenes.length+1,paragraphIndex:t,title:i,anchorId:Wa(e,"PD-SCENE"),wordCount:0},void o.scenes.push(c)}c&&(c.wordCount+=Ta(i))}});const i=t.find(e=>String(e.text||"").trim()),s=i?e.findIndex(e=>{return t=e,n=i,String(t?.text||"").trim()===String(n?.text||"").trim()&&Aa(t)===Aa(n);var t,n}):-1,d=s>=0&&n.filter(e=>e.paragraphIndex<=s).at(-1)||null,l=d&&s>=0&&d.scenes.filter(e=>e.paragraphIndex<=s).at(-1)||null;return{chapters:n,currentChapter:d,currentScene:l,paragraphCount:e.length,heading1Count:r,heading2Count:a}},Ma=new Set(["***","###"]),Oa=(e,t)=>{const n=String(e?.text||"").trim();return{index:t,text:n,styleBuiltIn:e?.styleBuiltIn||"",style:e?.style||"",wordCount:Ta(n),chapterAnchorId:null,sceneAnchorId:null}},Ha=(e,t)=>{e&&(e.endParagraphIndex=t)},Ba=(e,t)=>{e&&(e.endParagraphIndex=t,Ha(e.scenes.at(-1),t))},Ga=(e,t)=>{const n=(t||[]).find(e=>String(e.text||"").trim());if(!e||!n)return e?.currentParagraphIndex??-1;const r=e.paragraphs.filter(e=>((e,t)=>String(e?.text||"").trim()===String(t?.text||"").trim()&&Aa(e)===Aa(t))(e,n)).map(e=>e.index);return 0===r.length?e.currentParagraphIndex??-1:Number.isInteger(e.currentParagraphIndex)?r.reduce((t,n)=>Math.abs(n-e.currentParagraphIndex){if(!mn)return!1;const t=((e,t)=>!e||!Number.isInteger(t)||t<0?null:e.chapters.filter(e=>e.startParagraphIndex<=t).at(-1)||null)(mn,e),n=((e,t)=>!e||!Number.isInteger(t)||t<0?null:e.scenes.filter(e=>e.startParagraphIndex<=t).at(-1)||null)(t,e),r=t?.startParagraphIndex!==mn.currentChapter?.startParagraphIndex||n?.startParagraphIndex!==mn.currentScene?.startParagraphIndex||t?.anchorId!==mn.currentChapter?.anchorId||n?.anchorId!==mn.currentScene?.anchorId;return mn.currentParagraphIndex=e,mn.currentChapter=t,mn.currentScene=n,!!r&&(Cr(t?.title,n?.title,n?.wordCount,t?.anchorId,n?.anchorId,t?.index),r)},Va=e=>{if(!Q)return;if(Q.innerHTML="",0===e.chapters.length){const e=document.createElement("p");return e.textContent="No chapters detected. Use Heading 1 for chapter titles.",void Q.append(e)}if(!e.chapters.some(e=>e.scenes.length>0)){const e=document.createElement("p");e.textContent="No scenes detected. Use Heading 2 for scene titles.",Q.append(e)}for(const t of e.chapters){const e=document.createElement("div");e.className="word-companion-outline-chapter";const n=document.createElement("strong");if(n.textContent=t.title,e.append(n),t.scenes.length>0){const n=document.createElement("ul");for(const e of t.scenes){const t=document.createElement("li");t.textContent=e.title,n.append(t)}e.append(n)}Q.append(e)}},Ja=[{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"}],Ya={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},_a={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},za=(e,t)=>ta(e,t).toLocaleLowerCase(),Ka=({category:e,action:t,type:n,wordTitle:r,match:a="",anchorStatus:o="None",matches:c=[],pdChapter:i=null,pdScene:s=null,wordChapter:d=null,wordScene:l=null,parentItem:u=null})=>({id:`${n}-${d?.index||0}-${l?.index||0}-${d?.paragraphIndex??l?.paragraphIndex??0}`,category:e,action:t,type:n,wordTitle:r,match:a,anchorStatus:o,matches:c,pdChapter:i,pdScene:s,wordChapter:d,wordScene:l,parentItem:u,result:"Pending",error:""}),Qa=(e,t)=>{Array.isArray(e[t.category])&&e[t.category].push(t)},Xa=e=>Array.isArray(e?.scenes)?e.scenes:[],Za=(e,t,n)=>{const r=e.anchorId?`PD-CHAPTER-${e.anchorId}`:"None";if(e.anchorId){const a=t.find(t=>t.chapterId===e.anchorId);if(a){const t=Ka({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:e.title,match:`Chapter ${a.chapterId}: ${a.title}`,anchorStatus:r,pdChapter:a,wordChapter:e});return Qa(n,t),t}const o=Ka({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:`${r} not found`,matches:[],pdChapter:null,wordChapter:e});return Qa(n,o),o}const a=t.filter(t=>za(t.title,"chapter")===za(e.title,"chapter"));if(1===a.length){const t=Ka({category:"couldLink",action:"couldLink",type:"Chapter",wordTitle:e.title,match:`Chapter ${a[0].chapterId}: ${a[0].title}`,anchorStatus:r,pdChapter:a[0],wordChapter:e});return Qa(n,t),t}if(a.length>1){const t=Ka({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:r,matches:a.map(e=>`Chapter ${e.chapterId}: ${e.title}`),pdChapter:null,wordChapter:e});return Qa(n,t),t}const o=Ka({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:e.title,anchorStatus:r,pdChapter:null,wordChapter:e});return Qa(n,o),o},eo=(e,t,n,r)=>{const a=e.anchorId?`PD-SCENE-${e.anchorId}`:"None";if(e.anchorId){const o=((e,t)=>{for(const n of e){const e=Xa(n).find(e=>e.sceneId===t);if(e)return{chapter:n,scene:e}}return null})(n,e.anchorId);return o?void Qa(r,Ka({category:"alreadyLinked",action:"alreadyLinked",type:"Scene",wordTitle:e.title,match:`Scene ${o.scene.sceneId}: ${o.scene.title}`,anchorStatus:a,pdChapter:o.chapter,pdScene:o.scene,wordChapter:t?.wordChapter,wordScene:e,parentItem:t})):void Qa(r,Ka({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:`${a} not found`,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}))}if(!t?.pdChapter&&"manualReview"===t?.category)return void Qa(r,Ka({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:a,matches:["Parent chapter requires manual review."],wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));if(!t?.pdChapter)return void Qa(r,Ka({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:a,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));const o=Xa(t.pdChapter).filter(t=>za(t.title,"scene")===za(e.title,"scene"));1!==o.length?o.length>1?Qa(r,Ka({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:a,matches:o.map(e=>`Scene ${e.sceneId}: ${e.title}`),wordChapter:t.wordChapter,wordScene:e,parentItem:t})):Qa(r,Ka({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:a,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:e,parentItem:t})):Qa(r,Ka({category:"couldLink",action:"couldLink",type:"Scene",wordTitle:e.title,match:`Scene ${o[0].sceneId}: ${o[0].title}`,anchorStatus:a,pdChapter:t.pdChapter,pdScene:o[0],wordChapter:t.wordChapter,wordScene:e,parentItem:t}))},to=e=>{const t=document.createElement("article");t.className="word-companion-preview-item";const n=document.createElement("strong");n.textContent=`${_a[e.action]||""} ${e.type}: ${e.wordTitle}`,t.append(n);const r=document.createElement("span");if(r.textContent=`Anchor: ${e.anchorStatus||"None"}`,t.append(r),e.match){const n=document.createElement("span");n.textContent=`Match: ${e.match}`,t.append(n)}if(Array.isArray(e.matches)&&e.matches.length>0){const n=document.createElement("div");n.className="word-companion-preview-matches";const r=document.createElement("span");r.textContent="Matches:",n.append(r);const a=document.createElement("ul");for(const t of e.matches){const e=document.createElement("li");e.textContent=t,a.append(e)}n.append(a),t.append(n)}const a=document.createElement("span");if(a.textContent=`Action: ${Ya[e.action]||e.action}`,t.append(a),e.result&&"Pending"!==e.result){const n=document.createElement("span");n.textContent=e.error?`Result: ${e.result} - ${e.error}`:`Result: ${e.result}`,t.append(n)}return t},no=e=>{if(te){te.innerHTML="";for(const t of Ja){const n=document.createElement("section");n.className="word-companion-preview-group";const r=document.createElement("strong");r.textContent=t.title,n.append(r);const a=Array.isArray(e?.[t.key])?e[t.key]:[];if(0===a.length){const e=document.createElement("p");e.className="word-companion-empty-list",e.textContent="None",n.append(e)}else for(const e of a)n.append(to(e));te.append(n)}Lr()}},ro=async e=>{const t=e.document.body.paragraphs,n=e.document.getSelection().paragraphs;t.load("text,styleBuiltIn,style"),n.load("text,styleBuiltIn,style"),await e.sync();try{for(const e of t.items)($a(e,1)||$a(e,2))&&e.contentControls.load("items/tag,title");await e.sync()}catch(e){console.warn("Unable to load Word heading content controls. Continuing without PlotDirector anchors.",e)}const r=Ua(t.items,n.items);return r.bodyParagraphs=t.items,r},ao=async(e,t)=>{const n=e.document.body.paragraphs,r=e.document.getSelection().paragraphs;n.load("text,styleBuiltIn,style"),r.load("text,styleBuiltIn,style"),await e.sync();const a=((e,t)=>{const n=e.map(Oa),r=[];let a=0,o=0,c=null,i=null,s=0;const d=(e,t=null,n=null)=>c?(Ha(i,e.index-1),i={index:c.scenes.length+1,paragraphIndex:e.index,startParagraphIndex:e.index,endParagraphIndex:e.index,title:t||`Scene ${c.scenes.length+1}`,anchorId:n,wordCount:0},c.scenes.push(i),i):null;for(const e of n)e.text&&($a(e,1)?(Ba(c,e.index-1),a+=1,c={index:r.length+1,paragraphIndex:e.index,startParagraphIndex:e.index,endParagraphIndex:e.index,title:e.text,anchorId:e.chapterAnchorId,wordCount:0,scenes:[]},r.push(c),i=null,d(e,"Scene 1",e.sceneAnchorId),s+=e.wordCount):c&&(t&&Ma.has(e.text)?(o+=1,d(e)):(c.wordCount+=e.wordCount,i&&(i.wordCount+=e.wordCount),s+=e.wordCount)));return Ba(c,n.length-1),{paragraphs:n,chapters:r,usesExplicitScenes:!!t,paragraphCount:n.length,heading1Count:a,heading2Count:o,documentWordCount:s,currentParagraphIndex:null,currentChapter:null,currentScene:null}})(n.items,t),o=Ga(a,r.items);return mn=a,Fa(o),lr("Cache rebuilt."),a},oo=async()=>{const e=mn?.currentScene;return e&&Number.isInteger(e.startParagraphIndex)&&Number.isInteger(e.endParagraphIndex)&&Gt&&Ft&&window.Word&&"function"==typeof window.Word.run?await window.Word.run(async t=>{const n=t.document.body.paragraphs;n.load("text"),await t.sync();let r=0;const a=Math.min(e.endParagraphIndex,n.items.length-1),o=mn.currentChapter?.startParagraphIndex;for(let t=e.startParagraphIndex;t<=a;t+=1){const e=String(n.items[t]?.text||"").trim();e&&!Ma.has(e)&&t!==o&&(r+=Ta(e))}return e.wordCount=r,Cr(mn.currentChapter?.title,e.title,r,mn.currentChapter?.anchorId,e.anchorId,mn.currentChapter?.index),r}):zt},co=async()=>{const e=mn?.currentScene;return e&&Number.isInteger(e.startParagraphIndex)&&Number.isInteger(e.endParagraphIndex)&&Gt&&Ft&&window.Word&&"function"==typeof window.Word.run?await window.Word.run(async t=>{const n=t.document.body.paragraphs;n.load("text"),await t.sync();const r=[],a=Math.min(e.endParagraphIndex,n.items.length-1),o=mn.currentChapter?.startParagraphIndex;for(let t=e.startParagraphIndex;t<=a;t+=1){const e=String(n.items[t]?.text||"").trim();e&&!Ma.has(e)&&t!==o&&r.push(e)}return r.join("\n")}):""},io=async()=>{if(gr(""),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Cr(null,null,null),gr("Word document access is unavailable."),da({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;F&&(F.disabled=!0,F.textContent="Scanning..."),gr("Scanning document structure...");try{const e=await window.Word.run(async e=>{const t=fa();return t?await ao(e,!!t.usesExplicitScenes):(mn=null,await ro(e))});return mn||Cr(e.currentChapter?.title,e.currentScene?.title,e.currentScene?.wordCount,e.currentChapter?.anchorId,e.currentScene?.anchorId,e.currentChapter?.index),Kr("Not detected"),Va(e),gr(""),da({lastScan:"Success",lastError:"-",paragraphs:String(e.paragraphCount),heading1:String(e.heading1Count),heading2:String(e.heading2Count)}),!0}catch(e){const t=la(e);return console.error("Unable to scan the Word document.",e),Cr(null,null,null),gr(`Unable to scan the Word document: ${t}`),da({lastScan:"Failure",lastError:t}),!1}finally{F&&(F.disabled=!1,F.textContent="Refresh Document Structure")}},so=async()=>{const e=fa();if(!ga()||!e)return xr("Select a project and book to analyse manuscript structure."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return xr("Word document access is unavailable."),da({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;X&&(X.disabled=!0,X.textContent="Analysing..."),xr("Analysing manuscript structure...");try{const t=await window.Word.run(async e=>await ro(e)),n=await go(`/api/word-companion/books/${e.bookId}/structure`);return Cr(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),Va(t),un=((e,t)=>{const n={alreadyLinked:[],couldLink:[],wouldCreateChapters:[],wouldCreateScenes:[],manualReview:[]},r=Array.isArray(t?.chapters)?t.chapters:[];for(const t of Array.isArray(e?.chapters)?e.chapters:[]){const e=Za(t,r,n);for(const a of Xa(t))eo(a,e,r,n)}return n})(t,n),no(un),xr("Preview generated. No changes have been applied."),da({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),!0}catch(e){return console.error("Unable to analyse manuscript structure.",e),xr("Unable to analyse manuscript structure."),da({lastScan:"Failure",lastError:la(e)}),!1}finally{X&&(X.textContent="Analyse Manuscript Structure",Pr())}},lo=e=>{Nn&&(Nn(e),Nn=null),ut?.close?ut.close():ut&&(ut.hidden=!0)},uo=()=>{const e=((e=un)=>{const t=Er(e);return{linkChapters:t.filter(e=>"couldLink"===e.category&&"Chapter"===e.type).length,linkScenes:t.filter(e=>"couldLink"===e.category&&"Scene"===e.type).length,createChapters:t.filter(e=>"wouldCreateChapters"===e.category).length,createScenes:t.filter(e=>"wouldCreateScenes"===e.category).length,manualReview:Array.isArray(e?.manualReview)?e.manualReview.length:0}})();return(e=>{if(!pt)return;pt.innerHTML="";const t=[`Link ${e.linkChapters+e.linkScenes} chapters/scenes`,`Create ${e.createChapters} chapters`,`Create ${e.createScenes} scenes`],n=document.createElement("ul");for(const e of t){const t=document.createElement("li");t.textContent=e,n.append(t)}pt.append(n)})(e),ut?new Promise(e=>{Nn=e,ut.showModal?ut.showModal():ut.hidden=!1}):Promise.resolve(window.confirm(`Apply Structure Sync?\n\nThis will:\n\n- Link ${e.linkChapters+e.linkScenes} chapters/scenes\n- Create ${e.createChapters} chapters\n- Create ${e.createScenes} scenes\n\nManual review items will be skipped.`))},po=(e,t,n="")=>{e.result=t,e.error=n},ho=e=>Number.isInteger(e?.wordChapter?.index)&&e.wordChapter.index>0?10*e.wordChapter.index:null,mo=e=>Number.isInteger(e?.wordScene?.index)&&e.wordScene.index>0?10*e.wordScene.index:null,yo=async(e,t)=>{const n=await fo(`/api/word-companion/books/${e}/chapters`,{title:ea(t.wordTitle),sortOrder:ho(t)});if(!n?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");Or(),t.pdChapter={chapterId:n.chapterId,title:n.title||t.wordTitle,sortOrder:n.sortOrder||ho(t)||0,scenes:[]},t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},wo=async(e,t)=>{const n=t.pdChapter||t.parentItem?.pdChapter;if(!n?.chapterId)throw new Error("Scene parent chapter is not available.");const r=await fo(`/api/word-companion/books/${e}/chapters/${n.chapterId}/scenes`,{sceneTitle:ea(t.wordTitle),sortOrder:mo(t)});if(!r?.sceneId)throw new Error("Scene creation did not return a scene ID.");Or(),t.pdChapter=n,t.pdScene={sceneId:r.sceneId,title:t.wordTitle,sortOrder:mo(t)||0},t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},go=async(e,t={})=>{const n=await window.fetch(e,{credentials:"same-origin",...t,headers:{Accept:"application/json",...t.headers||{}}});if(!n.ok)throw new Error(`Request failed: ${n.status}`);return await n.json()},fo=(e,t)=>go(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),So=async(e="")=>{Cn=!1,bn=0,Sn=[],k&&(k.innerHTML=""),kr(C,!0),ka(!1),Ca(""),kr(v,!0),e&&gr(e);const t=await Co();e&&t&&Yt&&gr(e)},Io=async(e=Zt,t=en)=>{const n=ga(),r=fa(),a=qa(),o=Number.parseInt(e||"",10),c=Number.parseInt(t||"",10);if(!n||!r||!a||!Number.isInteger(o)||o<=0||!Number.isInteger(c)||c<=0)return;const i=`${n.projectId}:${r.bookId}:${o}`;if(or!==i){or=i;try{await fo("/api/word-companion/runtime/current-scene",{documentGuid:a,projectId:n.projectId,bookId:r.bookId,chapterId:c,sceneId:o}),lr("Current scene follow event sent.")}catch(e){or="",console.debug("Unable to notify PlotDirector of current scene.",e)}}},Co=async()=>{const e=fa();if(!(e&&Gt&&Ft&&window.Word&&"function"==typeof window.Word.run))return!1;gr("Reading manuscript position...");try{Or(),await Promise.all([Bo(!0),Go(!0),Fo(!0)]),await ra(e.bookId);const t=await window.Word.run(async t=>await ao(t,!!e.usesExplicitScenes));return Va(t),da({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),Yt?(_t?await Ko():await zo(),$r(!1),Ar("Live"),gr(""),!0):(Kr("Not detected"),$r(!1),Ar("Live"),gr("Manuscript linked. Click inside a chapter to show the current scene."),!0)}catch(e){return console.error("Unable to initialise bound manuscript runtime.",e),mn=null,Ar("Manual"),gr(`Unable to read manuscript position: ${la(e)}`),da({lastScan:"Failure",lastError:la(e)}),!1}},bo=e=>e?[...e.querySelectorAll("input[type='checkbox']:checked")].map(e=>Number.parseInt(e.value||"",10)).filter(e=>Number.isInteger(e)&&e>0):[],ko=()=>{const e=Number.parseInt(Le?.value||"",10);return Number.isInteger(e)&&e>0?e:null},vo=(e,t,n,r)=>{const a=((e,t)=>Ra(e).find(e=>ja(e.tag,t))||null)(e,r),o=a||e.getRange().insertContentControl();return o.title=t,o.tag=n,o.appearance="Hidden",o},xo=async(e="PlotDirector IDs attached successfully.")=>{if(!Zt||!en)return gr("No resolved PlotDirector scene."),!1;if((Xt&&Xt!==Zt||Qt&&Qt!==en)&&!window.confirm("This scene is already linked. Replace the existing PlotDirector link?"))return!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return gr("Word document access is unavailable."),!1;se&&(se.disabled=!0,se.textContent="Attaching...");try{return await window.Word.run(async e=>{const t=await ro(e);if(!t.currentChapter||!t.currentScene)throw new Error("No scene detected in Word. Use Heading 2 for scenes.");const n=t.bodyParagraphs[t.currentChapter.paragraphIndex],r=t.bodyParagraphs[t.currentScene.paragraphIndex];if(!n||!r)throw new Error("Unable to locate the current Word headings.");vo(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),vo(r,"PlotDirector Scene",`PD-SCENE-${Zt}`,"PD-SCENE"),await e.sync()}),Qt=en,Xt=Zt,rn=!1,nn="SceneID Anchor",tn="Anchor",gr(e),da({lastError:"-"}),Ir(),!0}catch(e){return console.error("Unable to attach PlotDirector IDs.",e),gr("Unable to attach PlotDirector IDs."),da({lastError:la(e)}),Ir(),!1}finally{se&&(se.textContent=Xt===Zt?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",Ir())}},No=async e=>{if(!en)return Gr("No resolved PlotDirector chapter."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Gr("Word document access is unavailable."),!1;try{return await window.Word.run(async e=>{const t=await ro(e);if(!t.currentChapter)throw new Error("No chapter detected in Word. Use Heading 1 for chapters.");const n=t.bodyParagraphs[t.currentChapter.paragraphIndex];if(!n)throw new Error("Unable to locate the current Word chapter heading.");vo(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),await e.sync()}),Qt=en,rn=!1,nn="ChapterID Anchor",tn="Chapter anchor",Gr(e),gr(e),da({lastError:"-"}),Ir(),!0}catch(e){return console.error("Unable to attach PlotDirector chapter ID.",e),Gr("Unable to attach PlotDirector chapter ID."),da({lastError:la(e)}),Ir(),!1}},Eo=async e=>{Jr(),await Ko(),gr(e),Gr(e)},Lo=e=>{ln&&(ln(e),ln=null),ct?.close?ct.close():ct&&(ct.hidden=!0)},Po=()=>{if(!nt)return;const e=ea(tt?.value||"").toLocaleLowerCase(),t=sn.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(nt.innerHTML="",dn=null,rt&&(rt.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No chapters found.",void nt.append(e)}for(const e of t){const t=Number.parseInt(e.chapterId||"",10);if(!Number.isInteger(t)||t<=0)continue;const n=document.createElement("label");n.className="word-companion-scene-option";const r=document.createElement("input");r.type="radio",r.name="word-companion-link-chapter",r.value=String(t),r.addEventListener("change",()=>{dn=t,rt&&(rt.disabled=!1)});const a=document.createElement("span");a.textContent=e.title||"Untitled chapter",n.append(r,a),nt.append(n)}},qo=()=>{et?.close?et.close():et&&(et.hidden=!0)},Do=async(e,t,n)=>{const r=fa();if(!r)return Br("Select a PlotDirector book first."),!1;await ia(r.bookId,e,t,"Manual link","Title Match");return!!await xo(n)&&(Br(n),_r(),!0)},Ao=e=>{cn&&(cn(e),cn=null),ze?.close?ze.close():ze&&(ze.hidden=!0)},$o=()=>{if(!Ve)return;const e=ea(Fe?.value||"").toLocaleLowerCase(),t=an.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(Ve.innerHTML="",on=null,Je&&(Je.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No scenes found.",void Ve.append(e)}for(const e of t){const t=Number.parseInt(e.sceneId||"",10);if(!Number.isInteger(t)||t<=0)continue;const n=document.createElement("label");n.className="word-companion-scene-option";const r=document.createElement("input");r.type="radio",r.name="word-companion-link-scene",r.value=String(t),r.addEventListener("change",()=>{on=t,Je&&(Je.disabled=!1)});const a=document.createElement("span");a.textContent=e.title||"Untitled scene",n.append(r,a),Ve.append(n)}},To=()=>{Ge?.close?Ge.close():Ge&&(Ge.hidden=!0)},jo=()=>{Wn=!1,Dr(),Un&&(Un=!1,Wo(1e3))},Ro=async(e={})=>{const t=e.source||"manual";if(!Zt)return void vr("No resolved PlotDirector scene.");if(!en)return void vr("No resolved PlotDirector chapter.");if(Ln)return void vr("Refresh Current Scene before syncing.");const n=fa(),r=qa();if(!n||!r)return void vr("Bound manuscript metadata is unavailable.");if(Wn)return Un=!0,void lr("Scene sync deferred; sync already running.");br(),Wn=!0,Un=!1;let a=zt;try{a=await oo()}catch(e){return vr("Sync failed"),da({lastError:la(e)}),lr("Scene sync failed."),void jo()}if(!Number.isInteger(a)||a<0)return vr("Sync failed"),lr("Scene sync failed."),void jo();if(Mn===Zt&&On===a)return vr("Synced"),lr("Sync skipped (count unchanged)."),void jo();lr("Scene word count changed."),fe&&(fe.disabled=!0,fe.textContent="Syncing..."),vr("Syncing..."),lr(`Scene sync started (${t}).`);try{const e=await fo("/api/word-companion/runtime/scene-word-count",{documentGuid:r,bookId:n.bookId,chapterId:en,sceneId:Zt,wordCount:a}),t=e?.actualWords??a,o=new Date;Mn=Zt,On=t,sa(Ie,Rr(t)),sa(he,Rr(t)),sa(Ce,Wr(o)),sa(ge,Wr(o)),vr("Synced"),lr("Scene sync succeeded.")}catch(e){vr("Sync failed"),da({lastError:la(e)}),lr("Scene sync failed.")}finally{fe&&(fe.textContent="Sync Current Scene"),jo()}},Wo=(e=4e3)=>{br(),Zt&&en&&!Ln&&!Wn&&(Rn=window.setTimeout(()=>{Rn=null,Ro({source:"automatic"})},e))},Uo=()=>{Hn&&(window.clearTimeout(Hn),Hn=null)},Mo=()=>{Fn=null,Vn="",Jn=[],Yn=null,_n="",Uo()},Oo=()=>{zn=null,Kn="",Qn=[],Xn=null,Zn=""},Ho=()=>{er=null,tr="",nr=[],rr=null,ar=""},Bo=async(e=!1)=>{const t=ga(),n=qa();if(!t||!n)return Jn=[],[];if(!e&&Fn===t.projectId&&Vn===n&&Jn.length>0)return Jn;const r=await go(`/api/word-companion/runtime/characters?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(n)}`);return Fn=t.projectId,Vn=n,Jn=Array.isArray(r?.characters)?r.characters:[],lr("Character alias cache refreshed."),Jn},Go=async(e=!1)=>{const t=ga(),n=qa();if(!t||!n)return Qn=[],[];if(!e&&zn===t.projectId&&Kn===n&&Qn.length>0)return Qn;const r=await go(`/api/word-companion/runtime/assets?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(n)}`);return zn=t.projectId,Kn=n,Qn=Array.isArray(r?.assets)?r.assets:[],lr(`Asset cache loaded: ${Qn.length} aliases.`),Qn},Fo=async(e=!1)=>{const t=ga(),n=qa();if(!t||!n)return nr=[],[];if(!e&&er===t.projectId&&tr===n&&nr.length>0)return nr;const r=await go(`/api/word-companion/runtime/locations?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(n)}`);return er=t.projectId,tr=n,nr=Array.isArray(r?.locations)?r.locations:[],lr(`Location cache loaded: ${nr.length} aliases.`),nr},Vo=(e,t)=>{const n=String(t||"").trim();if(!n)return!1;const r=(a=n,String(a||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).replace(/\s+/g,"\\s+");var a;return new RegExp(`(^|[^\\p{L}\\p{N}_])${r}(?=$|[^\\p{L}\\p{N}_])`,"iu").test(e)},Jo=e=>{if(e?.excludeFromCompanionDetection)return!1;const t=Number.parseInt(e?.detectionPriority||"0",10);return n=e?.matchText,String(n||"").trim().split(/\s+/).filter(Boolean).length>=2||Number.isInteger(t)&&t>=75;var n},Yo=async()=>{if(Hn=null,Zt&&!Ln&&qa()){if(Bn)return Gn=!0,void lr("Character suggestion detection deferred; detection already running.");Bn=!0,Gn=!1;try{const[e,t,n,r]=await Promise.all([co(),Bo(),Go(),Fo()]),a=((e,t)=>{if(!e||!Array.isArray(t)||0===t.length)return[];const n=new Map;for(const r of t){const t=Number.parseInt(r.characterId||"",10);!Number.isInteger(t)||t<=0||n.has(t)||Vo(e,r.matchText)&&n.set(t,r.name||r.matchText||"Character")}return[...n.entries()].map(([e,t])=>({characterId:e,name:t}))})(e,t),o=a.map(e=>e.characterId),c=o.slice().sort((e,t)=>e-t).join(","),i=((e,t)=>{if(!e||!Array.isArray(t)||0===t.length)return[];const n=new Map;for(const r of t){const t=Number.parseInt(r.assetId||"",10);!Number.isInteger(t)||t<=0||n.has(t)||Vo(e,r.matchText)&&n.set(t,r.name||r.matchText||"Asset")}return[...n.entries()].map(([e,t])=>({assetId:e,name:t}))})(e,n),s=i.map(e=>e.assetId),d=s.slice().sort((e,t)=>e-t).join(","),l=((e,t)=>{if(!e||!Array.isArray(t)||0===t.length)return[];const n=new Map;for(const r of t){const t=Number.parseInt(r.locationId||"",10);!Number.isInteger(t)||t<=0||n.has(t)||!Jo(r)||Vo(e,r.matchText)&&n.set(t,r.name||r.matchText||"Location")}return[...n.entries()].map(([e,t])=>({locationId:e,name:t}))})(e,r),u=l.map(e=>e.locationId),p=u.slice().sort((e,t)=>e-t).join(",");if(!c||Yn===Zt&&_n===c)lr("Character suggestions skipped.");else{const e=await fo("/api/word-companion/runtime/character-suggestions",{documentGuid:qa(),sceneId:Zt,characterIds:o});if(Yn=Zt,_n=c,(e?.createdCount||0)>0){const t=a.slice(0,3).map(e=>e.name).join(", "),n=a.length>3?" +"+(a.length-3):"";gr(t?`Characters detected: ${t}${n}`:e.message)}lr(e?.message||"Character suggestions submitted.")}if(!d||Xn===Zt&&Zn===d)lr("Asset suggestions skipped.");else{lr(`Asset matches found: ${i.map(e=>e.name).join(", ")}`);const e=await fo("/api/word-companion/runtime/asset-suggestions",{documentGuid:qa(),sceneId:Zt,assetIds:s});if(Xn=Zt,Zn=d,(e?.createdCount||0)>0){const t=i.slice(0,3).map(e=>e.name).join(", "),n=i.length>3?" +"+(i.length-3):"";gr(t?`Assets detected: ${t}${n}`:e.message)}lr(e?.message||"Asset suggestions submitted.")}if(!p||rr===Zt&&ar===p)lr("Location suggestions skipped.");else{lr(`Location matches found: ${l.map(e=>e.name).join(", ")}`);const e=await fo("/api/word-companion/runtime/location-suggestions",{documentGuid:qa(),sceneId:Zt,locationIds:u});if(rr=Zt,ar=p,(e?.createdCount||0)>0){const t=l.slice(0,3).map(e=>e.name).join(", "),n=l.length>3?" +"+(l.length-3):"";gr(t?`Locations detected: ${t}${n}`:e.message)}lr(e?.message||"Location suggestions submitted.")}}catch(e){console.error("Unable to detect runtime suggestions.",e),da({lastError:la(e)})}finally{Bn=!1,Gn&&(Gn=!1,_o(1500))}}},_o=(e=2500)=>{Uo(),!Zt||Ln||Bn?Bn&&(Gn=!0):Hn=window.setTimeout(()=>{Yo()},e)},zo=async()=>{const e=ga(),t=fa(),n=ta(Yt,"chapter");if(na({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?wa(t):void 0,detectedChapter:Yt,detectedScene:_t,requestChapter:n,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!t)return Kr("Not detected"),gr("Select a PlotDirector book first."),!1;if(!Yt)return Kr("Not detected"),gr("No chapter detected in Word. Use Heading 1 for chapters."),!1;Kr("Not detected");try{const e=await aa(t.bookId),r=Qt?e.find(e=>e.chapterId===Qt):null,a=n.toLocaleLowerCase(),o=a?e.find(e=>ta(e.title,"chapter").toLocaleLowerCase()===a):null,c=r||o;return c?(Jr(),Tr(null,c.chapterId,r?"Chapter anchor":"Chapter title"),nn=r?"ChapterID Anchor":"Title Match",fr("Chapter linked to PlotDirector"),gr("No scene detected in Word. Use Heading 2 for scenes."),na({result:"Chapter matched",chapterId:c.chapterId,sceneId:null}),!0):(Tr(null),fr("Chapter not found in PlotDirector."),gr("Chapter not found in PlotDirector."),na({result:"Chapter not matched",chapterId:null,sceneId:null}),Yr("Chapter not found in PlotDirector."),!1)}catch(e){return Kr("Not found in PlotDirector"),da({lastError:la(e)}),gr("Unable to load PlotDirector chapter data."),!1}},Ko=async()=>{const e=ga(),t=fa(),n=ta(Yt,"chapter"),r=ta(_t,"scene");if(na({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?wa(t):void 0,detectedChapter:Yt,detectedScene:_t,requestChapter:n,requestScene:r,result:"Not run",chapterId:null,sceneId:null}),Sr({anchorType:Xt?"SceneID Anchor":Qt?"ChapterID Anchor":"Title Match",storedSceneId:Xt,storedChapterId:Qt,resolutionMethod:"-"}),!t)return Kr("Not detected"),gr("Select a PlotDirector book first."),na({result:"Error"}),!1;if(!Yt||!_t)return Kr("Not detected"),gr("No scene detected in Word. Use Heading 2 for scenes."),na({result:"Error"}),!1;ne&&(ne.disabled=!0,ne.textContent="Refreshing...");const a=()=>{ne&&(ne.disabled=!1,ne.textContent="Refresh PlotDirector Scene")};Kr("Not detected"),gr("Resolving PlotDirector scene...");try{if(Xt){const e=await(async(e,t)=>{const n=await go(`/api/word-companion/books/${e}/structure`),r=Array.isArray(n?.chapters)?n.chapters:[];for(const e of r){const n=Array.isArray(e.scenes)?e.scenes:[];for(const r of n)if(t(e,r))return{chapter:e,scene:r}}return null})(t.bookId,(e,t)=>t.sceneId===Xt);if(e)return na({result:"Matched",chapterId:e.chapter.chapterId,sceneId:e.scene.sceneId}),await ia(t.bookId,e.scene.sceneId,e.chapter.chapterId,"Anchor","SceneID Anchor"),!0;rn=!0,nn="SceneID Anchor",fr("Not found in PlotDirector"),gr("Stored PlotDirector ID is invalid."),na({result:"Error",chapterId:Qt,sceneId:Xt}),Sr({anchorType:"SceneID Anchor",storedSceneId:Xt,storedChapterId:Qt,resolutionMethod:"Anchor"})}if(Qt){const e=(await ra(t.bookId)).find(e=>e.chapterId===Qt),n=e?(Array.isArray(e.scenes)?e.scenes:[]).find(e=>ta(e.title,"scene").toLocaleLowerCase()===r.toLocaleLowerCase()):null;if(n)return na({result:"Matched",chapterId:e.chapterId,sceneId:n.sceneId}),await ia(t.bookId,n.sceneId,e.chapterId,"Anchor","ChapterID Anchor"),!0;e&&!Xt?(nn="ChapterID Anchor",Tr(null,Qt,"Chapter anchor"),na({result:"Chapter matched",chapterId:Qt,sceneId:null})):Xt||(nn="ChapterID Anchor",na({result:"Chapter anchor not found",chapterId:Qt,sceneId:null}))}const e=await fo(`/api/word-companion/books/${t.bookId}/resolve-scene`,{chapterTitle:n,sceneTitle:r});if(!e?.matched||!e.sceneId){const t=rn,n=Number.parseInt(e?.chapterId||"",10),r=Number.isInteger(en)&&en>0?en:null,o=Number.isInteger(n)&&n>0?n:r,c=!!e?.chapterMatched||!!o;return Kr("Not found in PlotDirector"),rn=t,c&&(Tr(null,o,o===r?"Chapter anchor":"Chapter title"),fr("Scene not found in PlotDirector.")),gr(t?"Stored PlotDirector ID is invalid.":c?"Scene not found in PlotDirector.":"This chapter does not exist in PlotDirector. Create or link the chapter first."),na({result:"Not matched",chapterId:c?o:e?.chapterId,sceneId:e?.sceneId}),t||(c?(Jr(),zr("Scene not found in PlotDirector.")):(_r(),Yr("Chapter not found in PlotDirector."))),a(),!1}const o=rn;return na({result:o?"Matched by title fallback":"Matched",chapterId:e.chapterId,sceneId:e.sceneId}),await ia(t.bookId,e.sceneId,e.chapterId,o?"Title fallback":"Title","Title Match"),o&&(rn=!0,gr("Stored PlotDirector ID is invalid."),Ir()),!0}catch(e){const t=rn;return da({lastError:la(e)}),Kr("Not found in PlotDirector"),rn=t,gr(t?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),na({result:"Error"}),!1}finally{a()}},Qo=async()=>{if(Pn=null,jn)return An=!0,void lr("Runtime update deferred; update already running.");if(!Ot||!fa())return qn=!1,void lr("Runtime update skipped.");if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return qn=!1,Ar("Manual"),void gr("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");if(!mn)return qn=!1,Ar("Manual"),void gr("Document structure is not cached yet. Use Refresh Current Scene.");const e=Date.now()-Dn;if(qn&&e<$n)return lr("Runtime update skipped (typing active)."),void Xo($n-e);jn=!0,qn=!1,An=!1,Ar("Updating..."),lr("Runtime update executed.");try{const e=await window.Word.run(async e=>await(async e=>{const t=e.document.getSelection().paragraphs;return t.load("text,styleBuiltIn,style"),await e.sync(),t.items})(e)),t=Ga(mn,e),n=Fa(t);if(await oo(),!n)return $r(!1),Ar("Current scene updated"),Wo(),void _o();_t?await Ko():await zo(),$r(!1),Ar("Current scene updated"),gr("Current scene updated."),Wo(),_o()}catch(e){console.error("Unable to refresh current scene from Word selection.",e),da({lastError:la(e)}),$r(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving.")}finally{jn=!1,(An||qn)&&(An=!1,Xo($n))}},Xo=(e=1200)=>{Pn&&window.clearTimeout(Pn),Pn=window.setTimeout(Qo,Math.max(0,e)),Ar("Waiting for typing to pause"),lr("Runtime update scheduled.")},Zo=()=>{((e="selection",t=1200)=>{if(qn=!0,Dn=Date.now(),br(),Uo(),lr(`${e} changed.`),jn)return An=!0,void Ar("Waiting for typing to pause");Xo(t)})("Selection")},ec=()=>{if(Tn&&window.Office?.context?.document&&"function"==typeof window.Office.context.document.removeHandlerAsync&&window.Office?.EventType?.DocumentSelectionChanged)try{window.Office.context.document.removeHandlerAsync(window.Office.EventType.DocumentSelectionChanged,{handler:Zo}),Tn=!1}catch(e){console.warn("Unable to remove Word selection tracking handler.",e)}},tc=async(e,n)=>{if(mn=null,Or(),!e)return Bt=[],ma(O,"Select a project first"),ma(m,"Select a project first"),wr(""),ha(t,null),Da(),Kr("Not detected"),void Nr();ma(O,"Loading books..."),wr(""),Kr("Not detected"),Nr("Select a book to analyse manuscript structure.");try{const r=await go(`/api/word-companion/projects/${e}/books`);if(Bt=Array.isArray(r.books)?r.books:[],0===Bt.length)return ma(O,"No books available."),ma(m,"No books available."),wr("No books available."),ha(t,null),Da(),void xa("No books available.");ya(O,"Choose a book",Bt.map(e=>({...e,displayTitle:wa(e)})),"bookId","displayTitle");const a=Bt.find(e=>e.bookId===n);a&&O?(O.value=String(a.bookId),ha(t,a.bookId)):ha(t,null),((e=null)=>{if(!m)return;if(0===Bt.length)return void ma(m,"No books available.");ya(m,"Choose a book",Bt.map(e=>({...e,displayTitle:wa(e)})),"bookId","displayTitle");const t=e||Number.parseInt(O?.value||"",10),n=Bt.find(e=>e.bookId===t);n&&(m.value=String(n.bookId)),ba()})(a?.bookId||n),Da(),Kr((fa(),"Not detected")),Nr(fa()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),xa(Ia()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{Bt=[],ma(O,"Unable to load books."),ma(m,"Unable to load books."),wr("Unable to load books."),ha(t,null),Da(),Kr("Not detected"),Nr("Unable to load books."),xa("Unable to load books.")}};for(const e of l)e.addEventListener("click",()=>pr(e.dataset.tabButton));hr(),M?.addEventListener("change",async()=>{const n=Number.parseInt(M.value||"",10);Mr(),h&&Number.isInteger(n)&&n>0&&(h.value=String(n)),ha(e,Number.isInteger(n)&&n>0?n:null),ha(t,null),Kr("Not detected"),Nr(),xa("Select a Book to begin."),await tc(n,null)}),O?.addEventListener("change",()=>{const e=Number.parseInt(O.value||"",10);Mr(),ha(t,Number.isInteger(e)&&e>0?e:null),m&&Number.isInteger(e)&&e>0&&(m.value=String(e)),Da(),Kr("Not detected"),Nr(fa()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),xa(Ia()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),h?.addEventListener("change",async()=>{const n=Number.parseInt(h.value||"",10);Mr(),M&&Number.isInteger(n)&&n>0&&(M.value=String(n)),ha(e,Number.isInteger(n)&&n>0?n:null),ha(t,null),xa("Select a Book to begin."),await tc(n,null)}),m?.addEventListener("change",()=>{const e=Number.parseInt(m.value||"",10);Mr(),O&&Number.isInteger(e)&&e>0&&(O.value=String(e)),ha(t,Number.isInteger(e)&&e>0?e:null),Da(),xa(Ia()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),y?.addEventListener("input",ba),w?.addEventListener("click",async()=>{const e=Sa(),t=String(y?.value||"").trim();if(e&&t){w.disabled=!0,Ca("Creating Book...");try{const n=await fo(`/api/word-companion/projects/${e.projectId}/books`,{title:t});y&&(y.value=""),M&&(M.value=String(e.projectId)),await tc(e.projectId,n.bookId),m&&(m.value=String(n.bookId)),Ca("Ready to scan manuscript structure.")}catch(e){console.error("Unable to create Book from Word Companion.",e),Ca(`Unable to create Book: ${la(e)}`)}finally{ba()}}else ba()}),g?.addEventListener("click",async()=>{const e=Sa(),t=Ia();if(e&&t)if(Gt&&Ft&&window.Word&&"function"==typeof window.Word.run){g&&(g.disabled=!0,g.textContent="Scanning..."),Ca("Scanning manuscript structure...");try{const n=await window.Word.run(async e=>{const n=e.document.body.paragraphs;return n.load("text,styleBuiltIn,style"),await e.sync(),((e,t)=>{const n=[];let r=null,a=null,o=0;const c=[],i=new Set(["***","###"]),s=()=>{if(!r)return null;const e={title:`Scene ${r.scenes.length+1}`,sortOrder:10*(r.scenes.length+1),wordCount:0};return r.scenes.push(e),e};return e.forEach(e=>{const d=String(e.text||"").trim();if(!d)return;if(c.push(d),$a(e,1))return r={title:d,sortOrder:10*(n.length+1),wordCount:0,scenes:[]},n.push(r),a=s(),void(o+=Ta(d));if(!r||!a)return;if(t&&i.has(d))return void(a=s());const l=Ta(d);r.wordCount+=l,a.wordCount+=l,o+=l}),{chapters:n,chapterCount:n.length,sceneCount:n.reduce((e,t)=>e+t.scenes.length,0),wordCount:o,documentText:c.join("\n")}})(n.items,!!t.usesExplicitScenes)});fn=n,In=!1;const r=await fo("/api/word-companion/manuscript/analyse",{projectId:e.projectId,bookId:t.bookId,documentGuid:Pa(),chapterCount:n.chapterCount,sceneCount:n.sceneCount,wordCount:n.wordCount});gn=r,(e=>{if(!I)return;I.innerHTML="";const t=document.createElement("strong");t.textContent="Manuscript Analysis",I.append(t);const n=document.createElement("dl"),r=[["Project",e.projectTitle],["Book",wa({title:e.bookTitle,subtitle:e.bookSubtitle})],["Chapters",Number(e.chapterCount||0).toLocaleString()],["Scenes",Number(e.sceneCount||0).toLocaleString()],["Words",Number(e.wordCount||0).toLocaleString()]];for(const[e,t]of r){const r=document.createElement("dt");r.textContent=e;const a=document.createElement("dd");a.textContent=t||"-",n.append(r,a)}I.append(n),kr(I,!1),kr(L,!1),Ca(e.message||"Preview generated."),ba()})(r);try{const t=await fo("/api/word-companion/manuscript/discover-characters",{projectId:e.projectId,documentText:n.documentText||""});Sn=Array.isArray(t?.candidates)?t.candidates:[],kr(C,!0),kr(v,!0)}catch(e){console.error("Unable to discover character candidates.",e),Sn=[],kr(C,!0),kr(v,!0)}da({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(n.chapterCount),heading2:"-"})}catch(e){console.error("Unable to scan manuscript for first-run import.",e),xa(`Unable to scan manuscript: ${la(e)}`),da({lastScan:"Failure",lastError:la(e)})}finally{g&&(g.textContent="Scan Manuscript"),ba()}}else xa("Word document access is unavailable.");else xa("Select a Project and Book to begin.")}),P?.addEventListener("click",async()=>{const n=Sa(),i=Ia();if(!(n&&i&&fn&&gn?.canImport))return void ba();let s=!1;if(!gn.requiresReplaceConfirmation||(s=await new Promise(e=>{if(!D||"function"!=typeof D.showModal)return void e(window.confirm("This Book already contains planned chapters and scenes.\n\nImporting this manuscript will replace the planned structure.\n\nContinue?"));const t=t=>{A?.removeEventListener("click",n),$?.removeEventListener("click",r),D?.removeEventListener("cancel",a),D?.close(),e(t)},n=()=>t(!0),r=()=>t(!1),a=e=>{e.preventDefault(),t(!1)};A?.addEventListener("click",n),$?.addEventListener("click",r),D?.addEventListener("cancel",a),D.showModal()}),s)){kn=!0,ba(),Ca("Importing manuscript structure...");try{const l=Pa(),u=await fo("/api/word-companion/manuscript/import",{projectId:n.projectId,bookId:i.bookId,documentGuid:l,bindingVersion:1,replacePlanned:s,chapters:fn.chapters});if(!u.imported)return gn={...gn,canImport:!u.requiresReplaceConfirmation,requiresReplaceConfirmation:!!u.requiresReplaceConfirmation,message:u.message||gn.message},Ca(u.message||"Import was not completed."),void ba();const p=u.manuscriptDocument;await(d={documentGuid:p?.documentGuid||l,bookId:u.bookId,projectId:u.projectId,bindingVersion:p?.bindingVersion||1},new Promise((e,t)=>{const n=window.Office?.context?.document?.settings;n?(n.set(r,d.documentGuid),n.set(a,String(d.bookId)),n.set(o,String(d.projectId)),n.set(c,String(d.bindingVersion||1)),n.saveAsync(n=>{n.status===window.Office.AsyncResultStatus.Succeeded?e():t(n.error||new Error("Unable to save Word document metadata."))})):t(new Error("Word document settings are unavailable."))})),pn={documentGuid:p?.documentGuid||l,bookId:u.bookId,projectId:u.projectId,bindingVersion:p?.bindingVersion||1},ha(e,u.projectId),ha(t,u.bookId),M&&(M.value=String(u.projectId));const h=Sn;await tc(u.projectId,u.bookId),mr("Connected"),In=!0,Cn=h.length>0,bn=Cn?Date.now():0,Sn=h,h.length>0?(ka(!0),Ea(h),kr(L,!0),kr(v,!1),Ca(u.message||"Manuscript structure imported."),gr(u.message||"Manuscript structure imported."),window.setTimeout(ba,750)):await So(u.message||"Manuscript structure imported.")}catch(e){console.error("Unable to import manuscript structure.",e),Ca(`Unable to import manuscript: ${la(e)}`)}finally{kn=!1,ba()}var d}else Ca("Import cancelled.")}),x?.addEventListener("click",async()=>{const e=Sa()||ga(),t=Na();if(!Cn||Date.now()-bn<750||!e||0===t.length)ba();else{vn=!0,ba(),sa(b,"Creating selected characters...");try{const n=await fo("/api/word-companion/manuscript/create-discovered-characters",{projectId:e.projectId,candidateNames:t});gr(n.message||"Characters created."),sa(b,`${n.createdCount||0} created, ${n.skippedCount||0} already existed.`),await So(n.message||"Characters created.")}catch(e){console.error("Unable to create discovered characters.",e),sa(b,`Unable to create characters: ${la(e)}`)}finally{vn=!1,ba()}}}),N?.addEventListener("click",()=>So("Character creation skipped.")),E?.addEventListener("click",()=>So()),f?.addEventListener("click",()=>ka(!1)),q?.addEventListener("click",()=>xa("Import cancelled.")),F?.addEventListener("click",io),X?.addEventListener("click",so),Z?.addEventListener("click",async()=>{const e=fa();if(!e||0===Er().length||xn)return void Lr();if(!await uo())return;xn=!0,Pr(),xr("Applying structure sync...");const t={createdChapters:0,createdScenes:0,linkedChapters:0,linkedScenes:0,skipped:Array.isArray(un?.manualReview)?un.manualReview.length:0,failed:0},n=Er().filter(e=>"couldLink"===e.category&&"Chapter"===e.type),r=Er().filter(e=>"wouldCreateChapters"===e.category),a=Er().filter(e=>"couldLink"===e.category&&"Scene"===e.type),o=Er().filter(e=>"wouldCreateScenes"===e.category),c=[];let i="";const s=(e,t)=>{c.push({item:e,counterName:t})},d=async(e,n)=>{try{await(async e=>{if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)throw new Error("Word document access is unavailable.");await window.Word.run(async t=>{const n=await ro(t),r="Chapter"===e.type?e.wordChapter:e.wordScene,a=Number.isInteger(r?.paragraphIndex)?n.bodyParagraphs[r.paragraphIndex]:null;if(!a)throw new Error("Unable to locate the Word heading.");if("Chapter"===e.type){const t=e.pdChapter?.chapterId;if(!t)throw new Error("Chapter ID is not available.");vo(a,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=e.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");vo(a,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()})})(e),po(e,"Success"),t[n]+=1}catch(n){po(e,"Failed",la(n)),t.failed+=1}};try{for(const e of n)s(e,"linkedChapters");for(const n of r)try{await yo(e.bookId,n),s(n,"createdChapters")}catch(e){po(n,"Failed",la(e)),t.failed+=1}for(const e of a)s(e,"linkedScenes");for(const n of o)try{await wo(e.bookId,n),s(n,"createdScenes")}catch(e){po(n,"Failed",la(e)),t.failed+=1}for(const e of c)await d(e.item,e.counterName);for(const e of un.manualReview||[])po(e,"Skipped");no(un),i=(e=>`Structure Sync Complete. Created: ${e.createdChapters} Chapters, ${e.createdScenes} Scenes. Linked: ${e.linkedChapters} Chapters, ${e.linkedScenes} Scenes. Skipped: ${e.skipped} Manual Review items. Failed: ${e.failed} Items.`)(t),xr(i)}finally{xn=!1,Pr(),i&&(Or(),await so(),xr(`${i} Preview refreshed.`))}}),ht?.addEventListener("click",()=>lo(!0)),mt?.addEventListener("click",()=>lo(!1)),ut?.addEventListener("cancel",e=>{e.preventDefault(),lo(!1)}),ne?.addEventListener("click",Ko),G?.addEventListener("click",async()=>{if(!fa())return gr("Select a PlotDirector book first."),void Kr("Not detected");Pn&&(window.clearTimeout(Pn),Pn=null),qn=!1,An=!1,jr(!0),Ar("Updating...");try{await Promise.all([Bo(!0),Go(!0),Fo(!0)]);if(!await io())return;if($r(!1),!_t)return await zo(),void Ar("Current scene updated");await Ko(),Ar("Current scene updated")}finally{jr(!1)}}),fe?.addEventListener("click",()=>Ro({source:"manual"})),Pe?.addEventListener("click",async()=>{if(Zt)if(!Ln&&await(async()=>{if(!Zt)return!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return $r(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1;try{const e=await window.Word.run(async e=>await ro(e)),t=e.currentChapter?.title||"",n=e.currentScene?.title||"",r=e.currentScene?.anchorId||null,a=e.currentChapter?.anchorId||null,o=Number.isInteger(r)&&r===Zt,c=Number.isInteger(a)&&a===en,i=ta(n,"scene").toLocaleLowerCase()===ta(cr||_t,"scene").toLocaleLowerCase(),s=ta(t,"chapter").toLocaleLowerCase()===ta(ir||Yt,"chapter").toLocaleLowerCase();return o||i&&(c||s)?($r(!1),!0):($r(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1)}catch(e){return console.error("Unable to verify current Word scene before saving.",e),da({lastError:la(e)}),$r(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1}})()){Pe&&(Pe.disabled=!0,Pe.textContent="Saving...");try{await(e=`/api/word-companion/scenes/${Zt}/links`,t={characterIds:bo(Ne),assetIds:bo(Ee),locationIds:[],primaryLocationId:ko()},go(e,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})),(()=>{const e=new Set(bo(Ne)),t=new Set(bo(Ee));dr={characters:dr.characters.map(t=>({...t,linked:e.has(Number.parseInt(Qr(t,"character"),10))})),assets:dr.assets.map(e=>({...e,linked:t.has(Number.parseInt(Qr(e,"asset"),10))})),locations:dr.locations,primaryLocationId:ko()}})(),Hr("Scene links saved successfully."),da({lastError:"-"})}catch(e){Hr("Unable to save scene links."),da({lastError:la(e)})}finally{Pe&&(Pe.disabled=!Zt||Ln,Pe.textContent="Save Scene Links")}var e,t}else Hr("The Word cursor is now in a different scene. Refresh Current Scene before saving.");else Hr("Link a PlotDirector scene first.")}),se?.addEventListener("click",async()=>{await xo()}),Te?.addEventListener("click",async()=>{const e=fa();if(!e||!Yt||en)return void Yr("Chapter not found in PlotDirector.");const t=ea(Yt),n=await((e,t)=>(sa(it,`"${e}"`),sa(st,`"${t}"`),ct?new Promise(e=>{ln=e,ct.showModal?ct.showModal():ct.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector chapter:\n\n"${e}"\n\nin book:\n\n"${t}"\n\n?`))))(t,wa(e)||"selected book");if(n){Te&&(Te.disabled=!0,Te.textContent="Creating...");try{const n=Number.isInteger(Kt)&&Kt>0?10*Kt:null,r=await fo(`/api/word-companion/books/${e.bookId}/chapters`,{title:t,sortOrder:n});if(!r?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");Or(),Tr(null,r.chapterId,"Manual chapter link");if(!await No("Chapter created and linked successfully."))return;await Eo("Chapter created and linked successfully.")}catch(e){Gr("Unable to create chapter."),da({lastError:la(e)})}finally{Te&&(Te.disabled=!Fr(),Te.textContent="Create Chapter in PlotDirector")}}}),je?.addEventListener("click",async()=>{const e=fa();if(e&&Yt&&!en){je&&(je.disabled=!0,je.textContent="Loading...");try{sn=await aa(e.bookId),dn=null,tt&&(tt.value=""),sa(ot,""),Po(),et?.showModal?et.showModal():et&&(et.hidden=!1)}catch(e){Gr("Unable to load chapters."),da({lastError:la(e)})}finally{je&&(je.disabled=!Fr(),je.textContent="Link to Existing Chapter")}}else Yr("Chapter not found in PlotDirector.")}),tt?.addEventListener("input",Po),rt?.addEventListener("click",async()=>{const e=sn.find(e=>e.chapterId===dn);if(e){rt&&(rt.disabled=!0,rt.textContent="Linking...");try{Tr(null,e.chapterId,"Manual chapter link");if(!await No("Chapter linked successfully."))return;qo(),await Eo("Chapter linked successfully.")}catch(e){sa(ot,"Unable to link chapter."),Gr("Unable to link chapter."),da({lastError:la(e)})}finally{rt&&(rt.disabled=!dn,rt.textContent="Link Chapter")}}else sa(ot,"Select a chapter.")}),at?.addEventListener("click",qo),dt?.addEventListener("click",()=>Lo(!0)),lt?.addEventListener("click",()=>Lo(!1)),ct?.addEventListener("cancel",e=>{e.preventDefault(),Lo(!1)}),Oe?.addEventListener("click",async()=>{const e=fa();if(!e||!_t)return void zr("Scene not found in PlotDirector.");const t=ta(_t,"scene"),n=ta(Yt,"chapter"),r=await((e,t)=>(sa(Ke,`"${e}"`),sa(Qe,`"${t}"`),ze?new Promise(e=>{cn=e,ze.showModal?ze.showModal():ze.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector scene:\n\n"${e}"\n\nwithin chapter:\n\n"${t}"\n\n?`))))(t,n);if(r){Oe&&(Oe.disabled=!0,Oe.textContent="Creating...");try{const n=await ca();if(!n)return void zr("This chapter does not exist in PlotDirector. Create or link the chapter first.");const r=await fo(`/api/word-companion/books/${e.bookId}/chapters/${n.chapterId}/scenes`,{sceneTitle:t});if(!r?.sceneId||!r?.chapterId)throw new Error("Scene creation did not return a scene ID.");Or(),await Do(r.sceneId,r.chapterId,"Scene created and linked successfully.")}catch(e){Br("Unable to create scene."),da({lastError:la(e)})}finally{Oe&&(Oe.disabled=!Vr(),Oe.textContent="Create Scene in PlotDirector")}}}),He?.addEventListener("click",async()=>{const e=fa();if(e&&_t){He&&(He.disabled=!0,He.textContent="Loading...");try{const t=await ra(e.bookId),n=oa(t);if(!n)return void zr("This chapter does not exist in PlotDirector. Create or link the chapter first.");an=Array.isArray(n.scenes)?n.scenes:[],on=null,Fe&&(Fe.value=""),sa(_e,""),$o(),Ge?.showModal?Ge.showModal():Ge&&(Ge.hidden=!1)}catch(e){Br("Unable to load scenes."),da({lastError:la(e)})}finally{He&&(He.disabled=!Vr(),He.textContent="Link to Existing Scene")}}else zr("Scene not found in PlotDirector.")}),Fe?.addEventListener("input",$o),Je?.addEventListener("click",async()=>{const e=fa(),t=an.find(e=>e.sceneId===on);if(e&&t){Je&&(Je.disabled=!0,Je.textContent="Linking...");try{const e=await ca();if(!e)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");To(),await Do(t.sceneId,e.chapterId,"Scene linked successfully.")}catch(e){sa(_e,"Unable to link scene."),Br("Unable to link scene."),da({lastError:la(e)})}finally{Je&&(Je.disabled=!on,Je.textContent="Link Scene")}}else sa(_e,"Select a scene.")}),Ye?.addEventListener("click",To),Xe?.addEventListener("click",()=>Ao(!0)),Ze?.addEventListener("click",()=>Ao(!1)),ze?.addEventListener("cancel",e=>{e.preventDefault(),Ao(!1)}),Nt?.addEventListener("click",async()=>{Nt&&(Nt.disabled=!0,Nt.textContent="Running...");try{if(await ua(),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return void da({lastScan:"Failure",lastError:"Word document access is unavailable.",paragraphs:"-",heading1:"-",heading2:"-"});const e=await window.Word.run(async e=>{const t=e.document.body.paragraphs;return t.load("items"),await e.sync(),t.items.length});da({lastScan:"Success",lastError:"-",paragraphs:String(e)})}catch(e){console.error("Word Companion diagnostics failed.",e);const t=la(e);da({lastScan:"Failure",lastError:t}),gr(`Unable to scan the Word document: ${t}`)}finally{Nt&&(Nt.disabled=!1,Nt.textContent="Run Diagnostics")}});const nc=Ot?(async()=>{ma(M,"Loading projects..."),ma(O,"Select a project first"),ma(h,"Loading projects..."),ma(m,"Select a project first"),yr(""),wr("");try{const n=await go("/api/word-companion/projects");if(Ht=Array.isArray(n.projects)?n.projects:[],0===Ht.length)return ma(M,"No projects available."),ma(h,"No projects available."),yr("No projects available."),ha(e,null),ha(t,null),Da(),void xa("No projects available.");ya(M,"Choose a project",Ht,"projectId","title"),va();const r=pa(e),a=Ht.find(e=>e.projectId===r);a&&M?(M.value=String(a.projectId),h&&(h.value=String(a.projectId)),ha(e,a.projectId),await tc(a.projectId,pa(t))):(ha(e,null),ha(t,null),Da(),xa("Select a Project and Book to begin."))}catch{Ht=[],Bt=[],ma(M,"Unable to connect to PlotDirector."),ma(O,"Select a project first"),ma(h,"Unable to connect to PlotDirector."),ma(m,"Select a project first"),mr("Unable to connect to PlotDirector."),yr("Unable to connect to PlotDirector."),ha(e,null),ha(t,null),Da(),xa("Unable to connect to PlotDirector.")}})():Promise.resolve();if(Ot||(ma(M,"Please sign in to PlotDirector."),ma(O,"Please sign in to PlotDirector."),ma(h,"Please sign in to PlotDirector."),ma(m,"Please sign in to PlotDirector."),Da()),!window.Office||"function"!=typeof window.Office.onReady)return ur("Word Companion ready"),gr("Word document access is unavailable."),Ar("Manual"),void da({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"});ua().then(async()=>{ur("Word Companion ready"),await nc,await(async()=>{if(!Ot||!Ft)return void ka(!1);const n=La();if(n)try{const r=await go(`/api/word-companion/runtime/book/${n.bookId}?documentGuid=${encodeURIComponent(n.documentGuid)}`),a=r?.manuscriptDocument;if(r?.bookId===n.bookId&&r?.projectId===n.projectId&&a&&String(a.documentGuid).toLowerCase()===n.documentGuid.toLowerCase())return pn=n,Ur(r),ha(e,r.projectId),ha(t,r.bookId),M&&(M.value=String(r.projectId)),await tc(r.projectId,r.bookId),ka(!1),mr("Connected"),wr("Bound manuscript detected."),void await Co()}catch{}pn=null,Mr(),va(),Sa()?await tc(Sa().projectId,null):ma(m,"Select a project first"),xa("Select a Project and Book to begin."),ka(!0)})(),Ft?(()=>{if(Ot){if(!window.Office?.context?.document||"function"!=typeof window.Office.context.document.addHandlerAsync||!window.Office?.EventType?.DocumentSelectionChanged)return Ar("Manual"),void gr("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");try{window.Office.context.document.addHandlerAsync(window.Office.EventType.DocumentSelectionChanged,Zo,e=>{e?.status===window.Office.AsyncResultStatus.Succeeded?(Tn=!0,Ar("Live")):(Ar("Manual"),gr("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))}),window.addEventListener("beforeunload",ec)}catch(e){console.warn("Unable to register Word selection tracking handler.",e),Ar("Manual"),gr("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}})():(gr("Word document access is unavailable."),Ar("Manual"))}).catch(e=>{console.error("Office readiness check failed.",e),mr("Unable to connect to PlotDirector."),ur("Word Companion unavailable"),gr("Word document access is unavailable."),da({ready:"No",wordApi:"No",lastScan:"Failure"})})})(); \ No newline at end of file +(()=>{const e="plotdirector.word.projectId",t="plotdirector.word.bookId",n="plotdirector.word.activeTab",r="plotdirector.word.documentGuid",o="plotdirector.word.boundBookId",a="plotdirector.word.boundProjectId",c="plotdirector.word.bindingVersion",i=new Set(["scene","links","structure","diagnostics"]),s=document.querySelector(".word-companion-shell"),d=document.querySelector(".word-companion-tabs"),l=[...document.querySelectorAll("[data-tab-button]")],u=[...document.querySelectorAll("[data-tab-panel]")],p=document.querySelector("[data-first-run-wizard]"),h=document.querySelector("[data-first-run-project-select]"),m=document.querySelector("[data-first-run-book-select]"),y=document.querySelector("[data-first-run-new-book-title]"),g=document.querySelector("[data-first-run-create-book]"),f=document.querySelector("[data-first-run-scan]"),w=document.querySelector("[data-first-run-cancel]"),S=document.querySelector("[data-first-run-status]"),I=document.querySelector("[data-first-run-summary]"),b=document.querySelector("[data-first-run-character-section]"),C=document.querySelector("[data-first-run-character-status]"),k=document.querySelector("[data-first-run-character-candidates]"),v=document.querySelector("[data-first-run-character-actions]"),x=document.querySelector("[data-first-run-create-characters]"),N=document.querySelector("[data-first-run-skip-characters]"),E=document.querySelector("[data-first-run-continue]"),L=document.querySelector("[data-first-run-import-actions]"),P=document.querySelector("[data-first-run-import]"),q=document.querySelector("[data-first-run-import-cancel]"),D=document.querySelector("[data-first-run-replace-dialog]"),A=document.querySelector("[data-first-run-replace-confirm]"),$=document.querySelector("[data-first-run-replace-cancel]"),T=document.querySelector("[data-office-status]"),j=document.querySelector("[data-connection-status]"),R=document.querySelector("[data-summary-connection]"),W=document.querySelector("[data-summary-project]"),U=document.querySelector("[data-summary-book]"),M=document.querySelector("[data-project-select]"),O=document.querySelector("[data-book-select]"),H=document.querySelector("[data-project-message]"),B=document.querySelector("[data-book-message]"),G=document.querySelector("[data-refresh-current-scene]"),F=document.querySelector("[data-refresh-document]"),V=document.querySelector("[data-current-chapter]"),J=document.querySelector("[data-current-scene]"),Y=document.querySelector("[data-current-word-count]"),_=document.querySelector("[data-scene-tracking-status]"),z=document.querySelector("[data-document-message]"),K=document.querySelector("[data-sync-note]"),Q=document.querySelector("[data-document-outline]"),X=document.querySelector("[data-analyse-manuscript-structure]"),Z=document.querySelector("[data-apply-structure-sync]"),ee=document.querySelector("[data-structure-preview-status]"),te=document.querySelector("[data-structure-preview-results]"),ne=document.querySelector("[data-refresh-plotdirector-scene]"),re=document.querySelector("[data-plotdirector-scene-status]"),oe=document.querySelector("[data-anchor-status]"),ae=document.querySelector("[data-anchor-book-id]"),ce=document.querySelector("[data-anchor-chapter-id]"),ie=document.querySelector("[data-anchor-scene-id]"),se=document.querySelector("[data-attach-plotdirector-ids]"),de=document.querySelector("[data-plotdirector-scene-details]"),le=document.querySelector("[data-plotdirector-scene-title]"),ue=document.querySelector("[data-plotdirector-revision-status]"),pe=document.querySelector("[data-plotdirector-estimated-words]"),he=document.querySelector("[data-plotdirector-actual-words]"),me=document.querySelector("[data-plotdirector-blocked-status]"),ye=document.querySelector("[data-plotdirector-blocked-reason-row]"),ge=document.querySelector("[data-plotdirector-blocked-reason]"),fe=document.querySelector("[data-runtime-last-sync]"),we=document.querySelector("[data-sync-scene-progress]"),Se=document.querySelector("[data-sync-word-count]"),Ie=document.querySelector("[data-sync-plotdirector-count]"),be=document.querySelector("[data-sync-last-synced]"),Ce=document.querySelector("[data-sync-status]"),ke=document.querySelector("[data-writing-brief-block]"),ve=document.querySelector("[data-writing-brief]"),xe=document.querySelector("[data-plotdirector-link-groups]"),Ne=document.querySelector("[data-character-chips]"),Ee=document.querySelector("[data-asset-chips]"),Le=(document.querySelector("[data-location-chips]"),document.querySelector("[data-primary-location-select]")),Pe=document.querySelector("[data-save-scene-links]"),qe=document.querySelector("[data-scene-links-status]"),De=document.querySelector("[data-links-editing-scene]"),Ae=document.querySelector("[data-chapter-create-link]"),$e=document.querySelector("[data-chapter-create-link-chapter]"),Te=document.querySelector("[data-create-plotdirector-chapter]"),je=document.querySelector("[data-link-existing-chapter]"),Re=document.querySelector("[data-chapter-create-link-status]"),We=document.querySelector("[data-scene-create-link]"),Ue=document.querySelector("[data-create-link-chapter]"),Me=document.querySelector("[data-create-link-scene]"),Oe=document.querySelector("[data-create-plotdirector-scene]"),He=document.querySelector("[data-link-existing-scene]"),Be=document.querySelector("[data-create-link-status]"),Ge=document.querySelector("[data-link-existing-dialog]"),Fe=document.querySelector("[data-link-scene-search]"),Ve=document.querySelector("[data-link-scene-options]"),Je=document.querySelector("[data-link-selected-scene]"),Ye=document.querySelector("[data-link-dialog-cancel]"),_e=document.querySelector("[data-link-dialog-status]"),ze=document.querySelector("[data-create-scene-dialog]"),Ke=document.querySelector("[data-create-dialog-scene]"),Qe=document.querySelector("[data-create-dialog-chapter]"),Xe=document.querySelector("[data-create-dialog-confirm]"),Ze=document.querySelector("[data-create-dialog-cancel]"),et=document.querySelector("[data-link-existing-chapter-dialog]"),tt=document.querySelector("[data-link-chapter-search]"),nt=document.querySelector("[data-link-chapter-options]"),rt=document.querySelector("[data-link-selected-chapter]"),ot=document.querySelector("[data-link-chapter-dialog-cancel]"),at=document.querySelector("[data-link-chapter-dialog-status]"),ct=document.querySelector("[data-create-chapter-dialog]"),it=document.querySelector("[data-create-chapter-dialog-chapter]"),st=document.querySelector("[data-create-chapter-dialog-book]"),dt=document.querySelector("[data-create-chapter-dialog-confirm]"),lt=document.querySelector("[data-create-chapter-dialog-cancel]"),ut=document.querySelector("[data-apply-structure-sync-dialog]"),pt=document.querySelector("[data-apply-structure-sync-summary]"),ht=document.querySelector("[data-apply-structure-sync-confirm]"),mt=document.querySelector("[data-apply-structure-sync-cancel]"),yt=document.querySelector("[data-resolve-project-id]"),gt=document.querySelector("[data-resolve-project-title]"),ft=document.querySelector("[data-resolve-book-id]"),wt=document.querySelector("[data-resolve-book-title]"),St=document.querySelector("[data-resolve-detected-chapter]"),It=document.querySelector("[data-resolve-detected-scene]"),bt=document.querySelector("[data-resolve-request-chapter]"),Ct=document.querySelector("[data-resolve-request-scene]"),kt=document.querySelector("[data-resolve-result]"),vt=document.querySelector("[data-resolve-chapter-id]"),xt=document.querySelector("[data-resolve-scene-id]"),Nt=document.querySelector("[data-run-diagnostics]"),Et=document.querySelector("[data-diagnostic-host]"),Lt=document.querySelector("[data-diagnostic-platform]"),Pt=document.querySelector("[data-diagnostic-ready]"),qt=document.querySelector("[data-diagnostic-word-api]"),Dt=document.querySelector("[data-diagnostic-last-scan]"),At=document.querySelector("[data-diagnostic-last-error]"),$t=document.querySelector("[data-diagnostic-anchor-type]"),Tt=document.querySelector("[data-diagnostic-stored-scene-id]"),jt=document.querySelector("[data-diagnostic-stored-chapter-id]"),Rt=document.querySelector("[data-diagnostic-resolution-method]"),Wt=document.querySelector("[data-diagnostic-paragraphs]"),Ut=document.querySelector("[data-diagnostic-heading1]"),Mt=document.querySelector("[data-diagnostic-heading2]"),Ot="true"===s?.dataset.authenticated;let Ht=[],Bt=[],Gt=!1,Ft=!1,Vt="Unknown",Jt="Unknown",Yt="",_t="",zt=null,Kt=null,Qt=null,Xt=null,Zt=null,en=null,tn="",nn="Title Match",rn=!1,on=[],an=null,cn=null,sn=[],dn=null,ln=null,un=null,pn=null,hn=null,mn=null,yn=null,gn=null,fn=null,wn=null,Sn=[],In=!1,bn=!1,Cn=0,kn=!1,vn=!1,xn=!1,Nn=null,En="Manual",Ln=!1,Pn=null,qn=!1,Dn=0,An=!1,$n=0,Tn=null;const jn=1200;let Rn=!1,Wn=!1,Un=null,Mn=!1,On=!1,Hn=null,Bn=null,Gn=null,Fn=!1,Vn=!1,Jn=null,Yn="",_n=[],zn=null,Kn="",Qn=null,Xn="",Zn=[],er=null,tr="",nr=null,rr="",or=[],ar=null,cr="",ir="",sr="",dr="",lr=0,ur={characters:[],assets:[],locations:[],primaryLocationId:null};const pr=e=>{const t=Date.now();t-lr<1e3||(lr=t,console.debug(`[Word Companion Runtime] ${e}`))},hr=e=>{console.debug(`[Word Companion Timing] ${e}`)},mr=e=>{T&&(T.textContent=e)},yr=(e,t=!0)=>{const r=i.has(e)&&l.some(t=>t.dataset.tabButton===e)?e:"scene";for(const e of l){const t=e.dataset.tabButton===r;e.classList.toggle("is-active",t),e.setAttribute("aria-selected",t?"true":"false")}for(const e of u){const t=e.dataset.tabPanel===r;e.classList.toggle("is-active",t),e.hidden=!t}t&&((e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}})(n,r)},gr=()=>{const e=(e=>{try{return window.localStorage.getItem(e)||""}catch{return""}})(n);yr(i.has(e)?e:"scene",!1)},fr=e=>{j&&(j.textContent=e),R&&(R.textContent=e)},wr=e=>{H&&(H.textContent=e)},Sr=e=>{B&&(B.textContent=e)},Ir=e=>{z&&(z.textContent=e)},br=e=>{re&&(re.textContent=e)},Cr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("anchorType")&&po($t,Mr(e.anchorType)),t("storedSceneId")&&po(Tt,Mr(e.storedSceneId)),t("storedChapterId")&&po(jt,Mr(e.storedChapterId)),t("resolutionMethod")&&po(Rt,Mr(e.resolutionMethod))},kr=()=>{const e=Co(),t=Number.isInteger(Zt)&&Zt>0&&Xt===Zt,n=!Number.isInteger(en)||en<=0||Qt===en,r=t&&n;po(oe,r?"Attached to PlotDirector":"Not attached"),po(ae,e?.bookId?String(e.bookId):"-"),po(ce,Number.isInteger(en)&&en>0?String(en):"-"),po(ie,Number.isInteger(Zt)&&Zt>0?String(Zt):"-"),se&&(se.disabled=!Zt||r&&!rn,se.textContent=Xt&&!r?"Reattach PlotDirector IDs":"Attach PlotDirector IDs"),Cr({anchorType:nn||"Title Match",storedSceneId:Xt,storedChapterId:Qt,resolutionMethod:tn})},vr=(e,t,n,r=null,o=null,a=null)=>{const c=e||"",i=t||"",s=Number.isInteger(n)?n:null,d=Number.isInteger(a)&&a>0?a:null,l=Number.isInteger(r)&&r>0?r:null,u=Number.isInteger(o)&&o>0?o:null,p=Yt===c&&_t===i&&zt===s&&Kt===d&&Qt===l&&Xt===u;Yt=e||"",_t=t||"",zt=Number.isInteger(n)?n:null,Kt=Number.isInteger(a)&&a>0?a:null,Qt=Number.isInteger(r)&&r>0?r:null,Xt=Number.isInteger(o)&&o>0?o:null,p||(V&&(V.textContent=e||"Not detected"),J&&(J.textContent=t||"Not detected"),Y&&(Y.textContent=Number.isInteger(n)?String(n):"-"),po(Se,Number.isInteger(n)?String(n):"-"),kr())},xr=()=>{Un&&(window.clearTimeout(Un),Un=null)},Nr=(e,t)=>{e&&(e.hidden=t)},Er=e=>{po(Ce,e)},Lr=e=>{po(ee,e)},Pr=(e="Select a project and book to analyse manuscript structure.")=>{if(un=null,te){te.innerHTML="";const e=document.createElement("p");e.textContent="No preview generated.",te.append(e)}Lr(e),Dr()},qr=(e=un)=>((e=un)=>Ko.flatMap(t=>Array.isArray(e?.[t.key])?e[t.key]:[]))(e).filter(e=>"couldLink"===e.category||"wouldCreateChapters"===e.category||"wouldCreateScenes"===e.category),Dr=()=>{Z&&(Z.disabled=xn||0===qr().length)},Ar=()=>{X&&(X.disabled=xn||!bo()||!Co()),Dr()},$r=()=>{De&&(De.textContent=Zt?`Editing links for: ${sr||_t||"Current scene"}`:"Link a PlotDirector scene first.")},Tr=()=>{const e=Ln||!Zt,t=e||!en||Mn;we&&(we.disabled=t),Pe&&(Pe.disabled=e),Le&&(Le.disabled=e);for(const t of[Ne,Ee])for(const n of t?[...t.querySelectorAll("input[type='checkbox']")]:[])n.disabled=e},jr=e=>{"Live"!==e&&"Manual"!==e||(En=e),po(_,e||En||"Manual")},Rr=(e,t="")=>{Ln=!!e,Ln&&(xr(),Ga()),po(_,Ln?"Stale":En),Tr(),t&&(Ir(t),Fr(t))},Wr=(e,t=null,n="")=>{Zt=Number.isInteger(e)&&e>0?e:null,en=Number.isInteger(t)&&t>0?t:null,tn=n||"",Zt!==Hn&&(Bn=null),Zt||(xr(),Ga()),Tr(),Er(Ln?"Refresh Current Scene before syncing.":Zt?"Ready to sync.":"No resolved PlotDirector scene."),Fr(Ln?"Refresh Current Scene before saving.":Zt?"Ready to save.":"Link a PlotDirector scene first."),$r(),kr()},Ur=e=>{G&&(G.disabled=e,G.textContent=e?"Refreshing...":"Refresh Current Scene")},Mr=e=>null==e||""===e?"-":String(e),Or=e=>{if(!e)return"-";const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))return"-";const n=new Date;return`Last synced: ${t.toDateString()===n.toDateString()?"Today":t.toLocaleDateString()} ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`},Hr=e=>{hn=e||null;const t=hn?.lastSyncUtc||hn?.manuscriptDocument?.lastSyncUtc;po(fe,Or(t)),po(be,Or(t))},Br=()=>{mn=null,yn=null,gn=null,$n+=1,Tn=null,Fa(),Va(),Ja(),Hr(null)},Gr=()=>{yn=null,gn=null},Fr=e=>{po(qe,e)},Vr=e=>{po(Be,e)},Jr=e=>{po(Re,e)},Yr=()=>!!Co()&&!!Yt&&!en,_r=()=>!!Co()&&!!_t&&Number.isInteger(en)&&en>0,zr=()=>{Nr(Ae,!0),Jr(""),Te&&(Te.disabled=!0,Te.textContent="Create Chapter in PlotDirector"),je&&(je.disabled=!0,je.textContent="Link to Existing Chapter")},Kr=(e="")=>{po($e,Mr(Yt)),Nr(Ae,!1),Jr(e);const t=Yr();Te&&(Te.disabled=!t,Te.textContent="Create Chapter in PlotDirector"),je&&(je.disabled=!t,je.textContent="Link to Existing Chapter")},Qr=()=>{Nr(We,!0),Vr(""),Oe&&(Oe.disabled=!0,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!0,He.textContent="Link to Existing Scene")},Xr=(e="")=>{po(Ue,Mr(Yt)),po(Me,Mr(_t)),Nr(We,!1),Vr(e);const t=_r();Oe&&(Oe.disabled=!t,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!t,He.textContent="Link to Existing Scene")},Zr=e=>{br(e),Nr(de,!0),Nr(ke,!0),Nr(xe,!1),zr(),Qr(),tn="",sr="",dr="",nn=Xt?"SceneID Anchor":Qt?"ChapterID Anchor":"Title Match",rn=!1,ur={characters:[],assets:[],locations:[],primaryLocationId:null},to(Ne,[],"character"),to(Ee,[],"asset"),no([],null,!1),Wr(null),po(Ie,"-"),po(le,"-"),po(ue,"-"),po(pe,"-"),po(he,"-"),po(me,"-"),po(ge,"-"),Nr(ye,!0),kr(),$r()},eo=(e,t)=>"asset"===t?e?.assetId||e?.AssetId||e?.storyAssetId||e?.StoryAssetId||0:"location"===t?e?.locationId||e?.LocationId||0:e?.characterId||e?.CharacterId||0,to=(e,t,n,r=!1)=>{if(!e)return;e.innerHTML="";const o=Array.isArray(t)?t:[];if(0===o.length){const t=document.createElement("p");return t.className="word-companion-empty-list",t.textContent="None",void e.append(t)}for(const t of o){const o=Number.parseInt(eo(t,n),10);if(!Number.isInteger(o)||o<=0)continue;const a=document.createElement("label");a.className="word-companion-check-item";const c=document.createElement("input");c.type="checkbox",c.value=String(o),c.checked=!!t.linked,c.disabled=!r;const i=document.createElement("span");i.textContent=t.name||"Unnamed",a.append(c,i),e.append(a)}},no=(e,t,n=!1)=>{if(!Le)return;Le.innerHTML="";const r=document.createElement("option");r.value="",r.textContent="None",Le.append(r);const o=Number.parseInt(t||"",10);for(const t of Array.isArray(e)?e:[]){const e=Number.parseInt(eo(t,"location"),10);if(!Number.isInteger(e)||e<=0)continue;const n=document.createElement("option");n.value=String(e),n.textContent=t.name||"Unnamed",n.selected=e===o,Le.append(n)}Le.disabled=!n},ro=e=>String(e||"").trim().replace(/\s+/g," "),oo=(e,t)=>{const n=ro(e);if(!n)return"";const r=new RegExp(`^${"scene"===t?"scene":"chapter"}\\s+(?:\\d+|[ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)\\s*(?::|-|\\u2013|\\u2014)\\s*`,"i");return ro(n.replace(r,""))||n},ao=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("projectId")&&po(yt,Mr(e.projectId)),t("projectTitle")&&po(gt,Mr(e.projectTitle)),t("bookId")&&po(ft,Mr(e.bookId)),t("bookTitle")&&po(wt,Mr(e.bookTitle)),t("detectedChapter")&&po(St,Mr(e.detectedChapter)),t("detectedScene")&&po(It,Mr(e.detectedScene)),t("requestChapter")&&po(bt,Mr(e.requestChapter)),t("requestScene")&&po(Ct,Mr(e.requestScene)),t("result")&&po(kt,Mr(e.result)),t("chapterId")&&po(vt,Mr(e.chapterId)),t("sceneId")&&po(xt,Mr(e.sceneId))},co=async e=>{if(gn===e&&Array.isArray(yn?.chapters))return yn.chapters;const t=await Ca(`/api/word-companion/books/${e}/structure`);return gn=e,yn=t||null,Array.isArray(t?.chapters)?t.chapters:[]},io=async e=>{const t=await Ca(`/api/word-companion/books/${e}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},so=e=>{if(Number.isInteger(en)&&en>0){const t=e.find(e=>e.chapterId===en);if(t)return t}const t=oo(Yt,"chapter").toLocaleLowerCase();return t&&e.find(e=>oo(e.title,"chapter").toLocaleLowerCase()===t)||null},lo=async()=>{const e=Co();return e?so(await co(e.bookId)):null},uo=async(e,t,n,r,o)=>{const a=await Ca(`/api/word-companion/scenes/${t}/companion`);try{a.revisionStatus=await(async(e,t)=>{const n=await Ca(`/api/word-companion/books/${e}/structure`),r=Array.isArray(n?.chapters)?n.chapters:[];for(const e of r){const n=(Array.isArray(e.scenes)?e.scenes:[]).find(e=>e.sceneId===t);if(n)return n.revisionStatus||""}return""})(e,t)}catch{a.revisionStatus=""}var c;nn=o||"Title Match",rn=!1,Rr(!1),br("Linked to PlotDirector"),Ir(""),zr(),Qr(),Wr(t,n,r),c=a,sr=c?.sceneTitle||_t||"",dr=c?.chapterTitle||Yt||"",po(le,Mr(c?.sceneTitle)),po(ue,Mr(c?.revisionStatus||c?.revisionStatusName||"Not provided")),po(pe,Mr(c?.estimatedWords)),po(he,Mr(c?.actualWords)),po(Ie,Mr(c?.actualWords)),po(me,c?.blocked?"Blocked":"Not blocked"),c?.blockedReason?(po(ge,c.blockedReason),Nr(ye,!1)):(po(ge,"-"),Nr(ye,!0)),ve&&(ve.textContent=c?.writingBrief||"No writing brief has been added for this scene."),ur={characters:Array.isArray(c?.characters)?c.characters:[],assets:Array.isArray(c?.assets)?c.assets:[],locations:Array.isArray(c?.locations)?c.locations:[],primaryLocationId:c?.primaryLocationId??null},to(Ne,ur.characters,"character",!!Zt&&!Ln),to(Ee,ur.assets,"asset",!!Zt&&!Ln),no(ur.locations,ur.primaryLocationId,!!Zt&&!Ln),$r(),Fr(Ln?"Refresh Current Scene before saving.":Zt?"Ready to save.":"No resolved PlotDirector scene."),Nr(de,!1),Nr(ke,!1),Nr(xe,!1),xa(t,n),Ba(),Za()},po=(e,t)=>{if(e){const n=null==t?"":String(t);e.textContent!==n&&(e.textContent=n)}},ho=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("host")&&po(Et,e.host),t("platform")&&po(Lt,e.platform),t("ready")&&po(Pt,e.ready),t("wordApi")&&po(qt,e.wordApi),t("lastScan")&&po(Dt,e.lastScan),t("lastError")&&po(At,e.lastError),t("paragraphs")&&po(Wt,e.paragraphs),t("heading1")&&po(Ut,e.heading1),t("heading2")&&po(Mt,e.heading2)},mo=e=>{const t=[];return e?.name&&t.push(e.name),e?.code&&e.code!==e.name&&t.push(e.code),e?.message&&t.push(e.message),e?.debugInfo?.errorLocation&&t.push(`Location: ${e.debugInfo.errorLocation}`),t.length>0?t.join(": "):String(e)},yo=async()=>{if(!window.Office||"function"!=typeof window.Office.onReady)return Gt=!1,Ft=!1,Vt="Unavailable",Jt="Unavailable",ho({host:Vt,platform:Jt,ready:"No",wordApi:"No"}),null;const e=await window.Office.onReady();return Gt=!0,Vt=e?.host||"Unknown",Jt=e?.platform||"Unknown",Ft=!!window.Word&&!!window.Office.HostType&&e?.host===window.Office.HostType.Word,ho({host:Vt,platform:Jt,ready:"Yes",wordApi:Ft?"Yes":"No"}),e},go=e=>{try{const t=window.localStorage.getItem(e),n=Number.parseInt(t||"",10);return Number.isInteger(n)&&n>0?n:null}catch{return null}},fo=(e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}},wo=(e,t)=>{if(!e)return;e.innerHTML="";const n=document.createElement("option");n.value="",n.textContent=t,e.append(n),e.disabled=!0},So=(e,t,n,r,o)=>{if(!e)return;e.innerHTML="";const a=document.createElement("option");a.value="",a.textContent=t,e.append(a);for(const t of n){const n=document.createElement("option");n.value=String(t[r]),n.textContent=t[o],e.append(n)}e.disabled=0===n.length},Io=e=>{const t=String(e?.title||"").trim(),n=String(e?.subtitle||"").trim();return n?`${t}: ${n}`:t},bo=()=>{const e=Number.parseInt(M?.value||"",10);return Ht.find(t=>t.projectId===e)||null},Co=()=>{const e=Number.parseInt(O?.value||"",10);return Bt.find(t=>t.bookId===e)||null},ko=()=>{const e=Number.parseInt(h?.value||"",10);return Ht.find(t=>t.projectId===e)||null},vo=()=>{const e=Number.parseInt(m?.value||"",10);return Bt.find(t=>t.bookId===e)||null},xo=e=>po(S,e),No=()=>{const e=ko(),t=vo(),n=bn&&Date.now()-Cn>=750;f&&(f.disabled=!e||!t||kn),g&&(g.disabled=!e||!String(y?.value||"").trim()||kn),P&&(P.disabled=!fn?.canImport||!wn||kn),x&&(x.disabled=!n||vn||0===qo().length)},Eo=e=>{Nr(p,!e),Nr(d,e);for(const t of u)Nr(t,!!e||"scene"!==t.dataset.tabPanel&&!t.classList.contains("is-active"));e||gr()},Lo=()=>{if(!h)return;if(0===Ht.length)return void wo(h,"No projects available.");So(h,"Choose a project",Ht,"projectId","title");const e=Number.parseInt(M?.value||"",10);Number.isInteger(e)&&e>0&&(h.value=String(e))},Po=(e="Select a Project and Book to begin.")=>{fn=null,wn=null,Sn=[],In=!1,bn=!1,Cn=0,Nr(I,!0),Nr(L,!0),Nr(b,!0),Nr(v,!0),I&&(I.innerHTML=""),k&&(k.innerHTML=""),po(C,""),xo(e),No()},qo=()=>k?[...k.querySelectorAll("input[type='checkbox']:checked")].map(e=>String(e.value||"").trim()).filter(Boolean):[],Do=e=>{if(Sn=Array.isArray(e)?e:[],b&&k){if(k.innerHTML="",Nr(b,!1),Nr(v,!In||0===Sn.length),Nr(x,!1),Nr(N,!1),Nr(E,!0),0===Sn.length)return po(C,"No likely major characters found."),void No();po(C,`${Sn.length} likely major characters found.`);for(const e of Sn){const t=document.createElement("label");t.className="word-companion-character-candidate";const n=document.createElement("input");n.type="checkbox",n.value=e.text||"",n.checked="high"===String(e.confidence||"").trim().toLowerCase(),n.addEventListener("change",No);const r=document.createElement("strong");r.textContent=e.text||"";const o=document.createElement("em"),a=String(e.reason||"").trim();o.textContent=a?`${Number(e.mentionCount||0).toLocaleString()} mentions · ${a}`:`${Number(e.mentionCount||0).toLocaleString()} mentions`;const c=document.createElement("span");c.className="word-companion-character-candidate-text",c.append(r,o),t.append(n,c),k.append(t)}No()}},Ao=()=>{const e=window.Office?.context?.document?.settings;if(!e)return null;const t=String(e.get(r)||"").trim(),n=Number.parseInt(e.get(o)||"",10),i=Number.parseInt(e.get(a)||"",10),s=Number.parseInt(e.get(c)||"",10);return!t||!Number.isInteger(n)||n<=0||!Number.isInteger(i)||i<=0?null:{documentGuid:t,bookId:n,projectId:i,bindingVersion:Number.isInteger(s)&&s>0?s:1}},$o=()=>pn?.documentGuid?pn.documentGuid:window.crypto?.randomUUID?window.crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(Number(e)^16*Math.random()>>Number(e)/4).toString(16)),To=()=>pn?.documentGuid||Ao()?.documentGuid||"",jo=()=>{const e=bo(),t=Co();W&&(W.textContent=e?.title||"(Not connected)"),U&&(U.textContent=t?Io(t):"(Not connected)"),K&&(K.textContent=t?"":"Select a PlotDirector book before refreshing."),Ar()},Ro=e=>String(e?.styleBuiltIn||e?.style||"").replace(/\s+/g,"").toLowerCase(),Wo=(e,t)=>{const n=Ro(e);return n===`heading${t}`||n.endsWith(`.heading${t}`)||n.includes(`heading${t}`)},Uo=e=>String(e||"").trim().split(/\s+/).filter(Boolean).length,Mo=(e,t)=>{const n=String(e||"").match(new RegExp(`^${t}-(\\d+)$`,"i"));if(!n)return null;const r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null},Oo=e=>{try{return Array.isArray(e?.contentControls?.items)?e.contentControls.items:[]}catch(e){return console.warn("Word paragraph content controls were not available.",e),[]}},Ho=(e,t)=>{const n=Oo(e);for(const e of n){const n=Mo(e.tag,t);if(n)return n}return null},Bo=(e,t)=>{const n=[];let r=0,o=0,a=null,c=null;e.forEach((e,t)=>{const i=String(e.text||"").trim();if(i){if(Wo(e,1))return r+=1,a={index:n.length+1,paragraphIndex:t,title:i,anchorId:Ho(e,"PD-CHAPTER"),scenes:[]},n.push(a),void(c=null);if(Wo(e,2)){if(o+=1,!a)return;return c={index:a.scenes.length+1,paragraphIndex:t,title:i,anchorId:Ho(e,"PD-SCENE"),wordCount:0},void a.scenes.push(c)}c&&(c.wordCount+=Uo(i))}});const i=t.find(e=>String(e.text||"").trim()),s=i?e.findIndex(e=>{return t=e,n=i,String(t?.text||"").trim()===String(n?.text||"").trim()&&Ro(t)===Ro(n);var t,n}):-1,d=s>=0&&n.filter(e=>e.paragraphIndex<=s).at(-1)||null,l=d&&s>=0&&d.scenes.filter(e=>e.paragraphIndex<=s).at(-1)||null;return{chapters:n,currentChapter:d,currentScene:l,paragraphCount:e.length,heading1Count:r,heading2Count:o}},Go=new Set(["***","###"]),Fo=(e,t)=>{const n=String(e?.text||"").trim();return{index:t,text:n,styleBuiltIn:e?.styleBuiltIn||"",style:e?.style||"",wordCount:Uo(n),chapterAnchorId:null,sceneAnchorId:null}},Vo=(e,t)=>{e&&(e.endParagraphIndex=t)},Jo=(e,t)=>{e&&(e.endParagraphIndex=t,Vo(e.scenes.at(-1),t))},Yo=(e,t)=>{const n=(t||[]).find(e=>String(e.text||"").trim());if(!e||!n)return e?.currentParagraphIndex??-1;const r=e.paragraphs.filter(e=>((e,t)=>String(e?.text||"").trim()===String(t?.text||"").trim()&&Ro(e)===Ro(t))(e,n)).map(e=>e.index);return 0===r.length?e.currentParagraphIndex??-1:Number.isInteger(e.currentParagraphIndex)?r.reduce((t,n)=>Math.abs(n-e.currentParagraphIndex){if(!mn)return!1;const t=((e,t)=>!e||!Number.isInteger(t)||t<0?null:e.chapters.filter(e=>e.startParagraphIndex<=t).at(-1)||null)(mn,e),n=((e,t)=>!e||!Number.isInteger(t)||t<0?null:e.scenes.filter(e=>e.startParagraphIndex<=t).at(-1)||null)(t,e),r=t?.startParagraphIndex!==mn.currentChapter?.startParagraphIndex||n?.startParagraphIndex!==mn.currentScene?.startParagraphIndex||t?.anchorId!==mn.currentChapter?.anchorId||n?.anchorId!==mn.currentScene?.anchorId;return mn.currentParagraphIndex=e,mn.currentChapter=t,mn.currentScene=n,!!r&&(vr(t?.title,n?.title,n?.wordCount,t?.anchorId,n?.anchorId,t?.index),r)},zo=e=>{if(!Q)return;if(Q.innerHTML="",0===e.chapters.length){const e=document.createElement("p");return e.textContent="No chapters detected. Use Heading 1 for chapter titles.",void Q.append(e)}if(!e.chapters.some(e=>e.scenes.length>0)){const e=document.createElement("p");e.textContent="No scenes detected. Use Heading 2 for scene titles.",Q.append(e)}for(const t of e.chapters){const e=document.createElement("div");e.className="word-companion-outline-chapter";const n=document.createElement("strong");if(n.textContent=t.title,e.append(n),t.scenes.length>0){const n=document.createElement("ul");for(const e of t.scenes){const t=document.createElement("li");t.textContent=e.title,n.append(t)}e.append(n)}Q.append(e)}},Ko=[{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"}],Qo={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},Xo={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},Zo=(e,t)=>oo(e,t).toLocaleLowerCase(),ea=({category:e,action:t,type:n,wordTitle:r,match:o="",anchorStatus:a="None",matches:c=[],pdChapter:i=null,pdScene:s=null,wordChapter:d=null,wordScene:l=null,parentItem:u=null})=>({id:`${n}-${d?.index||0}-${l?.index||0}-${d?.paragraphIndex??l?.paragraphIndex??0}`,category:e,action:t,type:n,wordTitle:r,match:o,anchorStatus:a,matches:c,pdChapter:i,pdScene:s,wordChapter:d,wordScene:l,parentItem:u,result:"Pending",error:""}),ta=(e,t)=>{Array.isArray(e[t.category])&&e[t.category].push(t)},na=e=>Array.isArray(e?.scenes)?e.scenes:[],ra=(e,t,n)=>{const r=e.anchorId?`PD-CHAPTER-${e.anchorId}`:"None";if(e.anchorId){const o=t.find(t=>t.chapterId===e.anchorId);if(o){const t=ea({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:e.title,match:`Chapter ${o.chapterId}: ${o.title}`,anchorStatus:r,pdChapter:o,wordChapter:e});return ta(n,t),t}const a=ea({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:`${r} not found`,matches:[],pdChapter:null,wordChapter:e});return ta(n,a),a}const o=t.filter(t=>Zo(t.title,"chapter")===Zo(e.title,"chapter"));if(1===o.length){const t=ea({category:"couldLink",action:"couldLink",type:"Chapter",wordTitle:e.title,match:`Chapter ${o[0].chapterId}: ${o[0].title}`,anchorStatus:r,pdChapter:o[0],wordChapter:e});return ta(n,t),t}if(o.length>1){const t=ea({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:r,matches:o.map(e=>`Chapter ${e.chapterId}: ${e.title}`),pdChapter:null,wordChapter:e});return ta(n,t),t}const a=ea({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:e.title,anchorStatus:r,pdChapter:null,wordChapter:e});return ta(n,a),a},oa=(e,t,n,r)=>{const o=e.anchorId?`PD-SCENE-${e.anchorId}`:"None";if(e.anchorId){const a=((e,t)=>{for(const n of e){const e=na(n).find(e=>e.sceneId===t);if(e)return{chapter:n,scene:e}}return null})(n,e.anchorId);return a?void ta(r,ea({category:"alreadyLinked",action:"alreadyLinked",type:"Scene",wordTitle:e.title,match:`Scene ${a.scene.sceneId}: ${a.scene.title}`,anchorStatus:o,pdChapter:a.chapter,pdScene:a.scene,wordChapter:t?.wordChapter,wordScene:e,parentItem:t})):void ta(r,ea({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:`${o} not found`,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}))}if(!t?.pdChapter&&"manualReview"===t?.category)return void ta(r,ea({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:o,matches:["Parent chapter requires manual review."],wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));if(!t?.pdChapter)return void ta(r,ea({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:o,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));const a=na(t.pdChapter).filter(t=>Zo(t.title,"scene")===Zo(e.title,"scene"));1!==a.length?a.length>1?ta(r,ea({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:o,matches:a.map(e=>`Scene ${e.sceneId}: ${e.title}`),wordChapter:t.wordChapter,wordScene:e,parentItem:t})):ta(r,ea({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:o,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:e,parentItem:t})):ta(r,ea({category:"couldLink",action:"couldLink",type:"Scene",wordTitle:e.title,match:`Scene ${a[0].sceneId}: ${a[0].title}`,anchorStatus:o,pdChapter:t.pdChapter,pdScene:a[0],wordChapter:t.wordChapter,wordScene:e,parentItem:t}))},aa=e=>{const t=document.createElement("article");t.className="word-companion-preview-item";const n=document.createElement("strong");n.textContent=`${Xo[e.action]||""} ${e.type}: ${e.wordTitle}`,t.append(n);const r=document.createElement("span");if(r.textContent=`Anchor: ${e.anchorStatus||"None"}`,t.append(r),e.match){const n=document.createElement("span");n.textContent=`Match: ${e.match}`,t.append(n)}if(Array.isArray(e.matches)&&e.matches.length>0){const n=document.createElement("div");n.className="word-companion-preview-matches";const r=document.createElement("span");r.textContent="Matches:",n.append(r);const o=document.createElement("ul");for(const t of e.matches){const e=document.createElement("li");e.textContent=t,o.append(e)}n.append(o),t.append(n)}const o=document.createElement("span");if(o.textContent=`Action: ${Qo[e.action]||e.action}`,t.append(o),e.result&&"Pending"!==e.result){const n=document.createElement("span");n.textContent=e.error?`Result: ${e.result} - ${e.error}`:`Result: ${e.result}`,t.append(n)}return t},ca=e=>{if(te){te.innerHTML="";for(const t of Ko){const n=document.createElement("section");n.className="word-companion-preview-group";const r=document.createElement("strong");r.textContent=t.title,n.append(r);const o=Array.isArray(e?.[t.key])?e[t.key]:[];if(0===o.length){const e=document.createElement("p");e.className="word-companion-empty-list",e.textContent="None",n.append(e)}else for(const e of o)n.append(aa(e));te.append(n)}Dr()}},ia=async e=>{const t=e.document.body.paragraphs,n=e.document.getSelection().paragraphs;t.load("text,styleBuiltIn,style"),n.load("text,styleBuiltIn,style"),await e.sync();try{for(const e of t.items)(Wo(e,1)||Wo(e,2))&&e.contentControls.load("items/tag,title");await e.sync()}catch(e){console.warn("Unable to load Word heading content controls. Continuing without PlotDirector anchors.",e)}const r=Bo(t.items,n.items);return r.bodyParagraphs=t.items,r},sa=async(e,t)=>{const n=e.document.body.paragraphs,r=e.document.getSelection().paragraphs;n.load("text,styleBuiltIn,style"),r.load("text,styleBuiltIn,style"),await e.sync();const o=((e,t)=>{const n=e.map(Fo),r=[];let o=0,a=0,c=null,i=null,s=0;const d=(e,t=null,n=null)=>c?(Vo(i,e.index-1),i={index:c.scenes.length+1,paragraphIndex:e.index,startParagraphIndex:e.index,endParagraphIndex:e.index,title:t||`Scene ${c.scenes.length+1}`,anchorId:n,wordCount:0},c.scenes.push(i),i):null;for(const e of n)e.text&&(Wo(e,1)?(Jo(c,e.index-1),o+=1,c={index:r.length+1,paragraphIndex:e.index,startParagraphIndex:e.index,endParagraphIndex:e.index,title:e.text,anchorId:e.chapterAnchorId,wordCount:0,scenes:[]},r.push(c),i=null,d(e,"Scene 1",e.sceneAnchorId),s+=e.wordCount):c&&(t&&Go.has(e.text)?(a+=1,d(e)):(c.wordCount+=e.wordCount,i&&(i.wordCount+=e.wordCount),s+=e.wordCount)));return Jo(c,n.length-1),{paragraphs:n,chapters:r,usesExplicitScenes:!!t,paragraphCount:n.length,heading1Count:o,heading2Count:a,documentWordCount:s,currentParagraphIndex:null,currentChapter:null,currentScene:null}})(n.items,t),a=Yo(o,r.items);return mn=o,_o(a),pr("Cache rebuilt."),o},da=()=>window.performance&&"function"==typeof window.performance.now?window.performance.now():Date.now(),la=e=>!!e&&!e.stale&&e.generation===$n&&e.documentGuid===To()&&e.sceneId===Zt,ua=async(e={})=>{const t=!!e.includeSelection,n=!1!==e.updateDisplay,r=$n,o=da(),a=bo(),c=Co(),i=mn?.currentScene;if(!i||!Number.isInteger(i.startParagraphIndex)||!Number.isInteger(i.endParagraphIndex))return null;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return null;const s=da(),d=await window.Word.run(async e=>{const n=e.document.body.paragraphs;n.load("text");let r=null;return t&&(r=e.document.getSelection().paragraphs,r.load("text,styleBuiltIn,style")),await e.sync(),{bodyTexts:n.items.map(e=>String(e.text||"")),selectionParagraphs:t&&r?r.items.map(e=>({text:String(e.text||""),styleBuiltIn:e.styleBuiltIn,style:e.style})):[]}}),l=Math.round(da()-s);if(r!==$n)return hr(`Office snapshot: ${l}ms stale`),{stale:!0,generation:r};let u=!1;if(t){const e=Yo(mn,d.selectionParagraphs);u=_o(e)}const p=mn?.currentScene;if(!p||!Number.isInteger(p.startParagraphIndex)||!Number.isInteger(p.endParagraphIndex))return null;const h=[];let m=0;const y=Math.min(p.endParagraphIndex,d.bodyTexts.length-1),g=mn.currentChapter?.startParagraphIndex;for(let e=p.startParagraphIndex;e<=y;e+=1){const t=String(d.bodyTexts[e]||"").trim();t&&!Go.has(t)&&e!==g&&(h.push(t),m+=Uo(t))}p.wordCount=m,n&&vr(mn.currentChapter?.title,p.title,m,mn.currentChapter?.anchorId,p.anchorId,mn.currentChapter?.index);const f={documentGuid:To(),projectId:a?.projectId||null,bookId:c?.bookId||null,chapterId:en,sceneId:Zt,chapterTitle:mn.currentChapter?.title||"",sceneTitle:p.title||"",sceneText:h.join("\n"),wordCount:m,selectionSignature:`${mn.currentParagraphIndex??-1}:${p.startParagraphIndex}:${p.endParagraphIndex}`,selectionChanged:u,generation:r};return Tn=f,hr(`Office snapshot: ${l}ms; scene words: ${m}; total snapshot: ${Math.round(da()-o)}ms`),f},pa=async()=>la(Tn)?Tn:await ua(),ha=async()=>{if(Ir(""),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return vr(null,null,null),Ir("Word document access is unavailable."),ho({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;F&&(F.disabled=!0,F.textContent="Scanning..."),Ir("Scanning document structure...");try{const e=await window.Word.run(async e=>{const t=Co();return t?await sa(e,!!t.usesExplicitScenes):(mn=null,await ia(e))});return mn||vr(e.currentChapter?.title,e.currentScene?.title,e.currentScene?.wordCount,e.currentChapter?.anchorId,e.currentScene?.anchorId,e.currentChapter?.index),Zr("Not detected"),zo(e),Ir(""),ho({lastScan:"Success",lastError:"-",paragraphs:String(e.paragraphCount),heading1:String(e.heading1Count),heading2:String(e.heading2Count)}),!0}catch(e){const t=mo(e);return console.error("Unable to scan the Word document.",e),vr(null,null,null),Ir(`Unable to scan the Word document: ${t}`),ho({lastScan:"Failure",lastError:t}),!1}finally{F&&(F.disabled=!1,F.textContent="Refresh Document Structure")}},ma=async()=>{const e=Co();if(!bo()||!e)return Lr("Select a project and book to analyse manuscript structure."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Lr("Word document access is unavailable."),ho({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;X&&(X.disabled=!0,X.textContent="Analysing..."),Lr("Analysing manuscript structure...");try{const t=await window.Word.run(async e=>await ia(e)),n=await Ca(`/api/word-companion/books/${e.bookId}/structure`);return vr(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),zo(t),un=((e,t)=>{const n={alreadyLinked:[],couldLink:[],wouldCreateChapters:[],wouldCreateScenes:[],manualReview:[]},r=Array.isArray(t?.chapters)?t.chapters:[];for(const t of Array.isArray(e?.chapters)?e.chapters:[]){const e=ra(t,r,n);for(const o of na(t))oa(o,e,r,n)}return n})(t,n),ca(un),Lr("Preview generated. No changes have been applied."),ho({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),!0}catch(e){return console.error("Unable to analyse manuscript structure.",e),Lr("Unable to analyse manuscript structure."),ho({lastScan:"Failure",lastError:mo(e)}),!1}finally{X&&(X.textContent="Analyse Manuscript Structure",Ar())}},ya=e=>{Nn&&(Nn(e),Nn=null),ut?.close?ut.close():ut&&(ut.hidden=!0)},ga=()=>{const e=((e=un)=>{const t=qr(e);return{linkChapters:t.filter(e=>"couldLink"===e.category&&"Chapter"===e.type).length,linkScenes:t.filter(e=>"couldLink"===e.category&&"Scene"===e.type).length,createChapters:t.filter(e=>"wouldCreateChapters"===e.category).length,createScenes:t.filter(e=>"wouldCreateScenes"===e.category).length,manualReview:Array.isArray(e?.manualReview)?e.manualReview.length:0}})();return(e=>{if(!pt)return;pt.innerHTML="";const t=[`Link ${e.linkChapters+e.linkScenes} chapters/scenes`,`Create ${e.createChapters} chapters`,`Create ${e.createScenes} scenes`],n=document.createElement("ul");for(const e of t){const t=document.createElement("li");t.textContent=e,n.append(t)}pt.append(n)})(e),ut?new Promise(e=>{Nn=e,ut.showModal?ut.showModal():ut.hidden=!1}):Promise.resolve(window.confirm(`Apply Structure Sync?\n\nThis will:\n\n- Link ${e.linkChapters+e.linkScenes} chapters/scenes\n- Create ${e.createChapters} chapters\n- Create ${e.createScenes} scenes\n\nManual review items will be skipped.`))},fa=(e,t,n="")=>{e.result=t,e.error=n},wa=e=>Number.isInteger(e?.wordChapter?.index)&&e.wordChapter.index>0?10*e.wordChapter.index:null,Sa=e=>Number.isInteger(e?.wordScene?.index)&&e.wordScene.index>0?10*e.wordScene.index:null,Ia=async(e,t)=>{const n=await ka(`/api/word-companion/books/${e}/chapters`,{title:ro(t.wordTitle),sortOrder:wa(t)});if(!n?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");Gr(),t.pdChapter={chapterId:n.chapterId,title:n.title||t.wordTitle,sortOrder:n.sortOrder||wa(t)||0,scenes:[]},t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},ba=async(e,t)=>{const n=t.pdChapter||t.parentItem?.pdChapter;if(!n?.chapterId)throw new Error("Scene parent chapter is not available.");const r=await ka(`/api/word-companion/books/${e}/chapters/${n.chapterId}/scenes`,{sceneTitle:ro(t.wordTitle),sortOrder:Sa(t)});if(!r?.sceneId)throw new Error("Scene creation did not return a scene ID.");Gr(),t.pdChapter=n,t.pdScene={sceneId:r.sceneId,title:t.wordTitle,sortOrder:Sa(t)||0},t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},Ca=async(e,t={})=>{const n=await window.fetch(e,{credentials:"same-origin",...t,headers:{Accept:"application/json",...t.headers||{}}});if(!n.ok)throw new Error(`Request failed: ${n.status}`);return await n.json()},ka=(e,t)=>Ca(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),va=async(e="")=>{bn=!1,Cn=0,Sn=[],k&&(k.innerHTML=""),Nr(b,!0),Eo(!1),xo(""),Nr(v,!0),e&&Ir(e);const t=await Na();e&&t&&Yt&&Ir(e)},xa=async(e=Zt,t=en)=>{const n=bo(),r=Co(),o=To(),a=Number.parseInt(e||"",10),c=Number.parseInt(t||"",10);if(!n||!r||!o||!Number.isInteger(a)||a<=0||!Number.isInteger(c)||c<=0)return;const i=`${n.projectId}:${r.bookId}:${a}`;if(ir!==i){ir=i;try{await ka("/api/word-companion/runtime/current-scene",{documentGuid:o,projectId:n.projectId,bookId:r.bookId,chapterId:c,sceneId:a}),pr("Current scene follow event sent.")}catch(e){ir="",console.debug("Unable to notify PlotDirector of current scene.",e)}}},Na=async()=>{const e=Co();if(!(e&&Gt&&Ft&&window.Word&&"function"==typeof window.Word.run))return!1;Ir("Reading manuscript position...");try{Gr(),await Promise.all([Ya(!0),_a(!0),za(!0)]),await co(e.bookId);const t=await window.Word.run(async t=>await sa(t,!!e.usesExplicitScenes));return zo(t),ho({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),Yt?(_t?await tc():await ec(),Rr(!1),jr("Live"),Ir(""),!0):(Zr("Not detected"),Rr(!1),jr("Live"),Ir("Manuscript linked. Click inside a chapter to show the current scene."),!0)}catch(e){return console.error("Unable to initialise bound manuscript runtime.",e),mn=null,jr("Manual"),Ir(`Unable to read manuscript position: ${mo(e)}`),ho({lastScan:"Failure",lastError:mo(e)}),!1}},Ea=e=>e?[...e.querySelectorAll("input[type='checkbox']:checked")].map(e=>Number.parseInt(e.value||"",10)).filter(e=>Number.isInteger(e)&&e>0):[],La=()=>{const e=Number.parseInt(Le?.value||"",10);return Number.isInteger(e)&&e>0?e:null},Pa=(e,t,n,r)=>{const o=((e,t)=>Oo(e).find(e=>Mo(e.tag,t))||null)(e,r),a=o||e.getRange().insertContentControl();return a.title=t,a.tag=n,a.appearance="Hidden",a},qa=async(e="PlotDirector IDs attached successfully.")=>{if(!Zt||!en)return Ir("No resolved PlotDirector scene."),!1;if((Xt&&Xt!==Zt||Qt&&Qt!==en)&&!window.confirm("This scene is already linked. Replace the existing PlotDirector link?"))return!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Ir("Word document access is unavailable."),!1;se&&(se.disabled=!0,se.textContent="Attaching...");try{return await window.Word.run(async e=>{const t=await ia(e);if(!t.currentChapter||!t.currentScene)throw new Error("No scene detected in Word. Use Heading 2 for scenes.");const n=t.bodyParagraphs[t.currentChapter.paragraphIndex],r=t.bodyParagraphs[t.currentScene.paragraphIndex];if(!n||!r)throw new Error("Unable to locate the current Word headings.");Pa(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),Pa(r,"PlotDirector Scene",`PD-SCENE-${Zt}`,"PD-SCENE"),await e.sync()}),Qt=en,Xt=Zt,rn=!1,nn="SceneID Anchor",tn="Anchor",Ir(e),ho({lastError:"-"}),kr(),!0}catch(e){return console.error("Unable to attach PlotDirector IDs.",e),Ir("Unable to attach PlotDirector IDs."),ho({lastError:mo(e)}),kr(),!1}finally{se&&(se.textContent=Xt===Zt?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",kr())}},Da=async e=>{if(!en)return Jr("No resolved PlotDirector chapter."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Jr("Word document access is unavailable."),!1;try{return await window.Word.run(async e=>{const t=await ia(e);if(!t.currentChapter)throw new Error("No chapter detected in Word. Use Heading 1 for chapters.");const n=t.bodyParagraphs[t.currentChapter.paragraphIndex];if(!n)throw new Error("Unable to locate the current Word chapter heading.");Pa(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),await e.sync()}),Qt=en,rn=!1,nn="ChapterID Anchor",tn="Chapter anchor",Jr(e),Ir(e),ho({lastError:"-"}),kr(),!0}catch(e){return console.error("Unable to attach PlotDirector chapter ID.",e),Jr("Unable to attach PlotDirector chapter ID."),ho({lastError:mo(e)}),kr(),!1}},Aa=async e=>{zr(),await tc(),Ir(e),Jr(e)},$a=e=>{ln&&(ln(e),ln=null),ct?.close?ct.close():ct&&(ct.hidden=!0)},Ta=()=>{if(!nt)return;const e=ro(tt?.value||"").toLocaleLowerCase(),t=sn.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(nt.innerHTML="",dn=null,rt&&(rt.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No chapters found.",void nt.append(e)}for(const e of t){const t=Number.parseInt(e.chapterId||"",10);if(!Number.isInteger(t)||t<=0)continue;const n=document.createElement("label");n.className="word-companion-scene-option";const r=document.createElement("input");r.type="radio",r.name="word-companion-link-chapter",r.value=String(t),r.addEventListener("change",()=>{dn=t,rt&&(rt.disabled=!1)});const o=document.createElement("span");o.textContent=e.title||"Untitled chapter",n.append(r,o),nt.append(n)}},ja=()=>{et?.close?et.close():et&&(et.hidden=!0)},Ra=async(e,t,n)=>{const r=Co();if(!r)return Vr("Select a PlotDirector book first."),!1;await uo(r.bookId,e,t,"Manual link","Title Match");return!!await qa(n)&&(Vr(n),Qr(),!0)},Wa=e=>{cn&&(cn(e),cn=null),ze?.close?ze.close():ze&&(ze.hidden=!0)},Ua=()=>{if(!Ve)return;const e=ro(Fe?.value||"").toLocaleLowerCase(),t=on.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(Ve.innerHTML="",an=null,Je&&(Je.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No scenes found.",void Ve.append(e)}for(const e of t){const t=Number.parseInt(e.sceneId||"",10);if(!Number.isInteger(t)||t<=0)continue;const n=document.createElement("label");n.className="word-companion-scene-option";const r=document.createElement("input");r.type="radio",r.name="word-companion-link-scene",r.value=String(t),r.addEventListener("change",()=>{an=t,Je&&(Je.disabled=!1)});const o=document.createElement("span");o.textContent=e.title||"Untitled scene",n.append(r,o),Ve.append(n)}},Ma=()=>{Ge?.close?Ge.close():Ge&&(Ge.hidden=!0)},Oa=()=>{Mn=!1,Tr(),On&&(On=!1,Ba(1e3))},Ha=async(e={})=>{const t=e.source||"manual",n=da();if(!Zt)return void Er("No resolved PlotDirector scene.");if(!en)return void Er("No resolved PlotDirector chapter.");if(Ln)return void Er("Refresh Current Scene before syncing.");const r=Co(),o=To();if(!r||!o)return void Er("Bound manuscript metadata is unavailable.");if(Mn)return On=!0,void pr("Scene sync deferred; sync already running.");xr(),Mn=!0,On=!1;let a=e.snapshot||null;try{a=la(a)?a:await pa()}catch(e){return Er("Sync failed"),ho({lastError:mo(e)}),pr("Scene sync failed."),void Oa()}if(!la(a))return Er("Waiting for typing to pause"),pr("Scene sync skipped (stale snapshot)."),void Oa();const c=a.wordCount;if(!Number.isInteger(c)||c<0)return Er("Sync failed"),pr("Scene sync failed."),void Oa();if(Hn===a.sceneId&&Bn===c)return Er("Synced"),pr("Sync skipped (count unchanged)."),void Oa();pr("Scene word count changed."),we&&(we.disabled=!0,we.textContent="Syncing..."),Er("Syncing..."),pr(`Scene sync started (${t}).`);try{const e=da(),t=await ka("/api/word-companion/runtime/scene-word-count",{documentGuid:a.documentGuid||o,bookId:a.bookId||r.bookId,chapterId:a.chapterId,sceneId:a.sceneId,wordCount:c});if(hr(`Word count sync API: ${Math.round(da()-e)}ms`),!la(a))return void pr("Scene sync result ignored (stale snapshot).");const i=t?.actualWords??c,s=new Date;Hn=a.sceneId,Bn=i,po(Ie,Mr(i)),po(he,Mr(i)),po(be,Or(s)),po(fe,Or(s)),Er("Synced"),pr("Scene sync succeeded."),hr(`Total word count sync: ${Math.round(da()-n)}ms`)}catch(e){Er("Sync failed"),ho({lastError:mo(e)}),pr("Scene sync failed.")}finally{we&&(we.textContent="Sync Current Scene"),Oa()}},Ba=(e=4e3)=>{xr(),Zt&&en&&!Ln&&!Mn&&(Un=window.setTimeout(()=>{Un=null,Ha({source:"automatic"})},e))},Ga=()=>{Gn&&(window.clearTimeout(Gn),Gn=null)},Fa=()=>{Jn=null,Yn="",_n=[],zn=null,Kn="",Ga()},Va=()=>{Qn=null,Xn="",Zn=[],er=null,tr=""},Ja=()=>{nr=null,rr="",or=[],ar=null,cr=""},Ya=async(e=!1)=>{const t=bo(),n=To();if(!t||!n)return _n=[],[];if(!e&&Jn===t.projectId&&Yn===n&&_n.length>0)return _n;const r=await Ca(`/api/word-companion/runtime/characters?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(n)}`);return Jn=t.projectId,Yn=n,_n=Array.isArray(r?.characters)?r.characters:[],pr("Character alias cache refreshed."),_n},_a=async(e=!1)=>{const t=bo(),n=To();if(!t||!n)return Zn=[],[];if(!e&&Qn===t.projectId&&Xn===n&&Zn.length>0)return Zn;const r=await Ca(`/api/word-companion/runtime/assets?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(n)}`);return Qn=t.projectId,Xn=n,Zn=Array.isArray(r?.assets)?r.assets:[],pr(`Asset cache loaded: ${Zn.length} aliases.`),Zn},za=async(e=!1)=>{const t=bo(),n=To();if(!t||!n)return or=[],[];if(!e&&nr===t.projectId&&rr===n&&or.length>0)return or;const r=await Ca(`/api/word-companion/runtime/locations?projectId=${encodeURIComponent(t.projectId)}&documentGuid=${encodeURIComponent(n)}`);return nr=t.projectId,rr=n,or=Array.isArray(r?.locations)?r.locations:[],pr(`Location cache loaded: ${or.length} aliases.`),or},Ka=(e,t)=>{const n=String(t||"").trim();if(!n)return!1;const r=(o=n,String(o||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).replace(/\s+/g,"\\s+");var o;return new RegExp(`(^|[^\\p{L}\\p{N}_])${r}(?=$|[^\\p{L}\\p{N}_])`,"iu").test(e)},Qa=e=>{if(e?.excludeFromCompanionDetection)return!1;const t=Number.parseInt(e?.detectionPriority||"0",10);return n=e?.matchText,String(n||"").trim().split(/\s+/).filter(Boolean).length>=2||Number.isInteger(t)&&t>=75;var n},Xa=async()=>{if(Gn=null,!Zt||Ln||!To())return;if(Fn)return Vn=!0,void pr("Character suggestion detection deferred; detection already running.");Fn=!0,Vn=!1;const e=da();try{const t=await pa();if(!la(t))return void pr("Runtime suggestions skipped (stale snapshot).");const[n,r,o]=await Promise.all([Ya(),_a(),za()]);if(!la(t))return void pr("Runtime suggestions skipped after cache load (stale snapshot).");const a=t.sceneText||"",c=da(),i=((e,t)=>{if(!e||!Array.isArray(t)||0===t.length)return[];const n=new Map;for(const r of t){const t=Number.parseInt(r.characterId||"",10);!Number.isInteger(t)||t<=0||n.has(t)||Ka(e,r.matchText)&&n.set(t,r.name||r.matchText||"Character")}return[...n.entries()].map(([e,t])=>({characterId:e,name:t}))})(a,n);hr(`Character detection: ${Math.round(da()-c)}ms`);const s=i.map(e=>e.characterId),d=s.slice().sort((e,t)=>e-t).join(","),l=da(),u=((e,t)=>{if(!e||!Array.isArray(t)||0===t.length)return[];const n=new Map;for(const r of t){const t=Number.parseInt(r.assetId||"",10);!Number.isInteger(t)||t<=0||n.has(t)||Ka(e,r.matchText)&&n.set(t,r.name||r.matchText||"Asset")}return[...n.entries()].map(([e,t])=>({assetId:e,name:t}))})(a,r);hr(`Asset detection: ${Math.round(da()-l)}ms`);const p=u.map(e=>e.assetId),h=p.slice().sort((e,t)=>e-t).join(","),m=da(),y=((e,t)=>{if(!e||!Array.isArray(t)||0===t.length)return[];const n=new Map;for(const r of t){const t=Number.parseInt(r.locationId||"",10);!Number.isInteger(t)||t<=0||n.has(t)||!Qa(r)||Ka(e,r.matchText)&&n.set(t,r.name||r.matchText||"Location")}return[...n.entries()].map(([e,t])=>({locationId:e,name:t}))})(a,o);hr(`Location detection: ${Math.round(da()-m)}ms`);const g=y.map(e=>e.locationId),f=g.slice().sort((e,t)=>e-t).join(",");if(!d||zn===Zt&&Kn===d)pr("Character suggestions skipped.");else{if(!la(t))return void pr("Character suggestions skipped before submit (stale snapshot).");const e=da(),n=await ka("/api/word-companion/runtime/character-suggestions",{documentGuid:t.documentGuid,sceneId:t.sceneId,characterIds:s});if(hr(`Character suggestion API: ${Math.round(da()-e)}ms`),!la(t))return void pr("Character suggestion result ignored (stale snapshot).");if(zn=t.sceneId,Kn=d,(n?.createdCount||0)>0){const e=i.slice(0,3).map(e=>e.name).join(", "),t=i.length>3?" +"+(i.length-3):"";Ir(e?`Characters detected: ${e}${t}`:n.message)}pr(n?.message||"Character suggestions submitted.")}if(!h||er===Zt&&tr===h)pr("Asset suggestions skipped.");else{if(!la(t))return void pr("Asset suggestions skipped before submit (stale snapshot).");pr(`Asset matches found: ${u.map(e=>e.name).join(", ")}`);const e=da(),n=await ka("/api/word-companion/runtime/asset-suggestions",{documentGuid:t.documentGuid,sceneId:t.sceneId,assetIds:p});if(hr(`Asset suggestion API: ${Math.round(da()-e)}ms`),!la(t))return void pr("Asset suggestion result ignored (stale snapshot).");if(er=t.sceneId,tr=h,(n?.createdCount||0)>0){const e=u.slice(0,3).map(e=>e.name).join(", "),t=u.length>3?" +"+(u.length-3):"";Ir(e?`Assets detected: ${e}${t}`:n.message)}pr(n?.message||"Asset suggestions submitted.")}if(!f||ar===Zt&&cr===f)pr("Location suggestions skipped.");else{if(!la(t))return void pr("Location suggestions skipped before submit (stale snapshot).");pr(`Location matches found: ${y.map(e=>e.name).join(", ")}`);const e=da(),n=await ka("/api/word-companion/runtime/location-suggestions",{documentGuid:t.documentGuid,sceneId:t.sceneId,locationIds:g});if(hr(`Location suggestion API: ${Math.round(da()-e)}ms`),!la(t))return void pr("Location suggestion result ignored (stale snapshot).");if(ar=t.sceneId,cr=f,(n?.createdCount||0)>0){const e=y.slice(0,3).map(e=>e.name).join(", "),t=y.length>3?" +"+(y.length-3):"";Ir(e?`Locations detected: ${e}${t}`:n.message)}pr(n?.message||"Location suggestions submitted.")}hr(`Total suggestion pass: ${Math.round(da()-e)}ms`)}catch(e){console.error("Unable to detect runtime suggestions.",e),ho({lastError:mo(e)})}finally{Fn=!1,Vn&&(Vn=!1,Za(1500))}},Za=(e=2500)=>{Ga(),!Zt||Ln||Fn?Fn&&(Vn=!0):Gn=window.setTimeout(()=>{Xa()},e)},ec=async()=>{const e=bo(),t=Co(),n=oo(Yt,"chapter");if(ao({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Io(t):void 0,detectedChapter:Yt,detectedScene:_t,requestChapter:n,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!t)return Zr("Not detected"),Ir("Select a PlotDirector book first."),!1;if(!Yt)return Zr("Not detected"),Ir("No chapter detected in Word. Use Heading 1 for chapters."),!1;Zr("Not detected");try{const e=await io(t.bookId),r=Qt?e.find(e=>e.chapterId===Qt):null,o=n.toLocaleLowerCase(),a=o?e.find(e=>oo(e.title,"chapter").toLocaleLowerCase()===o):null,c=r||a;return c?(zr(),Wr(null,c.chapterId,r?"Chapter anchor":"Chapter title"),nn=r?"ChapterID Anchor":"Title Match",br("Chapter linked to PlotDirector"),Ir("No scene detected in Word. Use Heading 2 for scenes."),ao({result:"Chapter matched",chapterId:c.chapterId,sceneId:null}),!0):(Wr(null),br("Chapter not found in PlotDirector."),Ir("Chapter not found in PlotDirector."),ao({result:"Chapter not matched",chapterId:null,sceneId:null}),Kr("Chapter not found in PlotDirector."),!1)}catch(e){return Zr("Not found in PlotDirector"),ho({lastError:mo(e)}),Ir("Unable to load PlotDirector chapter data."),!1}},tc=async()=>{const e=bo(),t=Co(),n=oo(Yt,"chapter"),r=oo(_t,"scene");if(ao({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Io(t):void 0,detectedChapter:Yt,detectedScene:_t,requestChapter:n,requestScene:r,result:"Not run",chapterId:null,sceneId:null}),Cr({anchorType:Xt?"SceneID Anchor":Qt?"ChapterID Anchor":"Title Match",storedSceneId:Xt,storedChapterId:Qt,resolutionMethod:"-"}),!t)return Zr("Not detected"),Ir("Select a PlotDirector book first."),ao({result:"Error"}),!1;if(!Yt||!_t)return Zr("Not detected"),Ir("No scene detected in Word. Use Heading 2 for scenes."),ao({result:"Error"}),!1;ne&&(ne.disabled=!0,ne.textContent="Refreshing...");const o=()=>{ne&&(ne.disabled=!1,ne.textContent="Refresh PlotDirector Scene")};Zr("Not detected"),Ir("Resolving PlotDirector scene...");try{if(Xt){const e=await(async(e,t)=>{const n=await Ca(`/api/word-companion/books/${e}/structure`),r=Array.isArray(n?.chapters)?n.chapters:[];for(const e of r){const n=Array.isArray(e.scenes)?e.scenes:[];for(const r of n)if(t(e,r))return{chapter:e,scene:r}}return null})(t.bookId,(e,t)=>t.sceneId===Xt);if(e)return ao({result:"Matched",chapterId:e.chapter.chapterId,sceneId:e.scene.sceneId}),await uo(t.bookId,e.scene.sceneId,e.chapter.chapterId,"Anchor","SceneID Anchor"),!0;rn=!0,nn="SceneID Anchor",br("Not found in PlotDirector"),Ir("Stored PlotDirector ID is invalid."),ao({result:"Error",chapterId:Qt,sceneId:Xt}),Cr({anchorType:"SceneID Anchor",storedSceneId:Xt,storedChapterId:Qt,resolutionMethod:"Anchor"})}if(Qt){const e=(await co(t.bookId)).find(e=>e.chapterId===Qt),n=e?(Array.isArray(e.scenes)?e.scenes:[]).find(e=>oo(e.title,"scene").toLocaleLowerCase()===r.toLocaleLowerCase()):null;if(n)return ao({result:"Matched",chapterId:e.chapterId,sceneId:n.sceneId}),await uo(t.bookId,n.sceneId,e.chapterId,"Anchor","ChapterID Anchor"),!0;e&&!Xt?(nn="ChapterID Anchor",Wr(null,Qt,"Chapter anchor"),ao({result:"Chapter matched",chapterId:Qt,sceneId:null})):Xt||(nn="ChapterID Anchor",ao({result:"Chapter anchor not found",chapterId:Qt,sceneId:null}))}const e=await ka(`/api/word-companion/books/${t.bookId}/resolve-scene`,{chapterTitle:n,sceneTitle:r});if(!e?.matched||!e.sceneId){const t=rn,n=Number.parseInt(e?.chapterId||"",10),r=Number.isInteger(en)&&en>0?en:null,a=Number.isInteger(n)&&n>0?n:r,c=!!e?.chapterMatched||!!a;return Zr("Not found in PlotDirector"),rn=t,c&&(Wr(null,a,a===r?"Chapter anchor":"Chapter title"),br("Scene not found in PlotDirector.")),Ir(t?"Stored PlotDirector ID is invalid.":c?"Scene not found in PlotDirector.":"This chapter does not exist in PlotDirector. Create or link the chapter first."),ao({result:"Not matched",chapterId:c?a:e?.chapterId,sceneId:e?.sceneId}),t||(c?(zr(),Xr("Scene not found in PlotDirector.")):(Qr(),Kr("Chapter not found in PlotDirector."))),o(),!1}const a=rn;return ao({result:a?"Matched by title fallback":"Matched",chapterId:e.chapterId,sceneId:e.sceneId}),await uo(t.bookId,e.sceneId,e.chapterId,a?"Title fallback":"Title","Title Match"),a&&(rn=!0,Ir("Stored PlotDirector ID is invalid."),kr()),!0}catch(e){const t=rn;return ho({lastError:mo(e)}),Zr("Not found in PlotDirector"),rn=t,Ir(t?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),ao({result:"Error"}),!1}finally{o()}},nc=async()=>{if(Pn=null,Wn)return An=!0,void pr("Runtime update deferred; update already running.");if(!Ot||!Co())return qn=!1,void pr("Runtime update skipped.");if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return qn=!1,jr("Manual"),void Ir("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");if(!mn)return qn=!1,jr("Manual"),void Ir("Document structure is not cached yet. Use Refresh Current Scene.");const e=Date.now()-Dn;if(qn&&e{Pn&&window.clearTimeout(Pn),Pn=window.setTimeout(nc,Math.max(0,e)),jr("Waiting for typing to pause"),pr("Runtime update scheduled.")},oc=()=>{((e="selection",t=1200)=>{if(qn=!0,Dn=Date.now(),$n+=1,Tn=null,xr(),Ga(),Mn&&(On=!0),Fn&&(Vn=!0),pr(`${e} changed.`),Wn)return An=!0,void jr("Waiting for typing to pause");rc(t)})("Selection")},ac=()=>{if(Rn&&window.Office?.context?.document&&"function"==typeof window.Office.context.document.removeHandlerAsync&&window.Office?.EventType?.DocumentSelectionChanged)try{window.Office.context.document.removeHandlerAsync(window.Office.EventType.DocumentSelectionChanged,{handler:oc}),Rn=!1}catch(e){console.warn("Unable to remove Word selection tracking handler.",e)}},cc=async(e,n)=>{if(mn=null,Gr(),!e)return Bt=[],wo(O,"Select a project first"),wo(m,"Select a project first"),Sr(""),fo(t,null),jo(),Zr("Not detected"),void Pr();wo(O,"Loading books..."),Sr(""),Zr("Not detected"),Pr("Select a book to analyse manuscript structure.");try{const r=await Ca(`/api/word-companion/projects/${e}/books`);if(Bt=Array.isArray(r.books)?r.books:[],0===Bt.length)return wo(O,"No books available."),wo(m,"No books available."),Sr("No books available."),fo(t,null),jo(),void Po("No books available.");So(O,"Choose a book",Bt.map(e=>({...e,displayTitle:Io(e)})),"bookId","displayTitle");const o=Bt.find(e=>e.bookId===n);o&&O?(O.value=String(o.bookId),fo(t,o.bookId)):fo(t,null),((e=null)=>{if(!m)return;if(0===Bt.length)return void wo(m,"No books available.");So(m,"Choose a book",Bt.map(e=>({...e,displayTitle:Io(e)})),"bookId","displayTitle");const t=e||Number.parseInt(O?.value||"",10),n=Bt.find(e=>e.bookId===t);n&&(m.value=String(n.bookId)),No()})(o?.bookId||n),jo(),Zr((Co(),"Not detected")),Pr(Co()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),Po(vo()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{Bt=[],wo(O,"Unable to load books."),wo(m,"Unable to load books."),Sr("Unable to load books."),fo(t,null),jo(),Zr("Not detected"),Pr("Unable to load books."),Po("Unable to load books.")}};for(const e of l)e.addEventListener("click",()=>yr(e.dataset.tabButton));gr(),M?.addEventListener("change",async()=>{const n=Number.parseInt(M.value||"",10);Br(),h&&Number.isInteger(n)&&n>0&&(h.value=String(n)),fo(e,Number.isInteger(n)&&n>0?n:null),fo(t,null),Zr("Not detected"),Pr(),Po("Select a Book to begin."),await cc(n,null)}),O?.addEventListener("change",()=>{const e=Number.parseInt(O.value||"",10);Br(),fo(t,Number.isInteger(e)&&e>0?e:null),m&&Number.isInteger(e)&&e>0&&(m.value=String(e)),jo(),Zr("Not detected"),Pr(Co()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),Po(vo()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),h?.addEventListener("change",async()=>{const n=Number.parseInt(h.value||"",10);Br(),M&&Number.isInteger(n)&&n>0&&(M.value=String(n)),fo(e,Number.isInteger(n)&&n>0?n:null),fo(t,null),Po("Select a Book to begin."),await cc(n,null)}),m?.addEventListener("change",()=>{const e=Number.parseInt(m.value||"",10);Br(),O&&Number.isInteger(e)&&e>0&&(O.value=String(e)),fo(t,Number.isInteger(e)&&e>0?e:null),jo(),Po(vo()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),y?.addEventListener("input",No),g?.addEventListener("click",async()=>{const e=ko(),t=String(y?.value||"").trim();if(e&&t){g.disabled=!0,xo("Creating Book...");try{const n=await ka(`/api/word-companion/projects/${e.projectId}/books`,{title:t});y&&(y.value=""),M&&(M.value=String(e.projectId)),await cc(e.projectId,n.bookId),m&&(m.value=String(n.bookId)),xo("Ready to scan manuscript structure.")}catch(e){console.error("Unable to create Book from Word Companion.",e),xo(`Unable to create Book: ${mo(e)}`)}finally{No()}}else No()}),f?.addEventListener("click",async()=>{const e=ko(),t=vo();if(e&&t)if(Gt&&Ft&&window.Word&&"function"==typeof window.Word.run){f&&(f.disabled=!0,f.textContent="Scanning..."),xo("Scanning manuscript structure...");try{const n=await window.Word.run(async e=>{const n=e.document.body.paragraphs;return n.load("text,styleBuiltIn,style"),await e.sync(),((e,t)=>{const n=[];let r=null,o=null,a=0;const c=[],i=new Set(["***","###"]),s=()=>{if(!r)return null;const e={title:`Scene ${r.scenes.length+1}`,sortOrder:10*(r.scenes.length+1),wordCount:0};return r.scenes.push(e),e};return e.forEach(e=>{const d=String(e.text||"").trim();if(!d)return;if(c.push(d),Wo(e,1))return r={title:d,sortOrder:10*(n.length+1),wordCount:0,scenes:[]},n.push(r),o=s(),void(a+=Uo(d));if(!r||!o)return;if(t&&i.has(d))return void(o=s());const l=Uo(d);r.wordCount+=l,o.wordCount+=l,a+=l}),{chapters:n,chapterCount:n.length,sceneCount:n.reduce((e,t)=>e+t.scenes.length,0),wordCount:a,documentText:c.join("\n")}})(n.items,!!t.usesExplicitScenes)});wn=n,In=!1;const r=await ka("/api/word-companion/manuscript/analyse",{projectId:e.projectId,bookId:t.bookId,documentGuid:$o(),chapterCount:n.chapterCount,sceneCount:n.sceneCount,wordCount:n.wordCount});fn=r,(e=>{if(!I)return;I.innerHTML="";const t=document.createElement("strong");t.textContent="Manuscript Analysis",I.append(t);const n=document.createElement("dl"),r=[["Project",e.projectTitle],["Book",Io({title:e.bookTitle,subtitle:e.bookSubtitle})],["Chapters",Number(e.chapterCount||0).toLocaleString()],["Scenes",Number(e.sceneCount||0).toLocaleString()],["Words",Number(e.wordCount||0).toLocaleString()]];for(const[e,t]of r){const r=document.createElement("dt");r.textContent=e;const o=document.createElement("dd");o.textContent=t||"-",n.append(r,o)}I.append(n),Nr(I,!1),Nr(L,!1),xo(e.message||"Preview generated."),No()})(r);try{const t=await ka("/api/word-companion/manuscript/discover-characters",{projectId:e.projectId,documentText:n.documentText||""});Sn=Array.isArray(t?.candidates)?t.candidates:[],Nr(b,!0),Nr(v,!0)}catch(e){console.error("Unable to discover character candidates.",e),Sn=[],Nr(b,!0),Nr(v,!0)}ho({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(n.chapterCount),heading2:"-"})}catch(e){console.error("Unable to scan manuscript for first-run import.",e),Po(`Unable to scan manuscript: ${mo(e)}`),ho({lastScan:"Failure",lastError:mo(e)})}finally{f&&(f.textContent="Scan Manuscript"),No()}}else Po("Word document access is unavailable.");else Po("Select a Project and Book to begin.")}),P?.addEventListener("click",async()=>{const n=ko(),i=vo();if(!(n&&i&&wn&&fn?.canImport))return void No();let s=!1;if(!fn.requiresReplaceConfirmation||(s=await new Promise(e=>{if(!D||"function"!=typeof D.showModal)return void e(window.confirm("This Book already contains planned chapters and scenes.\n\nImporting this manuscript will replace the planned structure.\n\nContinue?"));const t=t=>{A?.removeEventListener("click",n),$?.removeEventListener("click",r),D?.removeEventListener("cancel",o),D?.close(),e(t)},n=()=>t(!0),r=()=>t(!1),o=e=>{e.preventDefault(),t(!1)};A?.addEventListener("click",n),$?.addEventListener("click",r),D?.addEventListener("cancel",o),D.showModal()}),s)){kn=!0,No(),xo("Importing manuscript structure...");try{const l=$o(),u=await ka("/api/word-companion/manuscript/import",{projectId:n.projectId,bookId:i.bookId,documentGuid:l,bindingVersion:1,replacePlanned:s,chapters:wn.chapters});if(!u.imported)return fn={...fn,canImport:!u.requiresReplaceConfirmation,requiresReplaceConfirmation:!!u.requiresReplaceConfirmation,message:u.message||fn.message},xo(u.message||"Import was not completed."),void No();const p=u.manuscriptDocument;await(d={documentGuid:p?.documentGuid||l,bookId:u.bookId,projectId:u.projectId,bindingVersion:p?.bindingVersion||1},new Promise((e,t)=>{const n=window.Office?.context?.document?.settings;n?(n.set(r,d.documentGuid),n.set(o,String(d.bookId)),n.set(a,String(d.projectId)),n.set(c,String(d.bindingVersion||1)),n.saveAsync(n=>{n.status===window.Office.AsyncResultStatus.Succeeded?e():t(n.error||new Error("Unable to save Word document metadata."))})):t(new Error("Word document settings are unavailable."))})),pn={documentGuid:p?.documentGuid||l,bookId:u.bookId,projectId:u.projectId,bindingVersion:p?.bindingVersion||1},fo(e,u.projectId),fo(t,u.bookId),M&&(M.value=String(u.projectId));const h=Sn;await cc(u.projectId,u.bookId),fr("Connected"),In=!0,bn=h.length>0,Cn=bn?Date.now():0,Sn=h,h.length>0?(Eo(!0),Do(h),Nr(L,!0),Nr(v,!1),xo(u.message||"Manuscript structure imported."),Ir(u.message||"Manuscript structure imported."),window.setTimeout(No,750)):await va(u.message||"Manuscript structure imported.")}catch(e){console.error("Unable to import manuscript structure.",e),xo(`Unable to import manuscript: ${mo(e)}`)}finally{kn=!1,No()}var d}else xo("Import cancelled.")}),x?.addEventListener("click",async()=>{const e=ko()||bo(),t=qo();if(!bn||Date.now()-Cn<750||!e||0===t.length)No();else{vn=!0,No(),po(C,"Creating selected characters...");try{const n=await ka("/api/word-companion/manuscript/create-discovered-characters",{projectId:e.projectId,candidateNames:t});Ir(n.message||"Characters created."),po(C,`${n.createdCount||0} created, ${n.skippedCount||0} already existed.`),await va(n.message||"Characters created.")}catch(e){console.error("Unable to create discovered characters.",e),po(C,`Unable to create characters: ${mo(e)}`)}finally{vn=!1,No()}}}),N?.addEventListener("click",()=>va("Character creation skipped.")),E?.addEventListener("click",()=>va()),w?.addEventListener("click",()=>Eo(!1)),q?.addEventListener("click",()=>Po("Import cancelled.")),F?.addEventListener("click",ha),X?.addEventListener("click",ma),Z?.addEventListener("click",async()=>{const e=Co();if(!e||0===qr().length||xn)return void Dr();if(!await ga())return;xn=!0,Ar(),Lr("Applying structure sync...");const t={createdChapters:0,createdScenes:0,linkedChapters:0,linkedScenes:0,skipped:Array.isArray(un?.manualReview)?un.manualReview.length:0,failed:0},n=qr().filter(e=>"couldLink"===e.category&&"Chapter"===e.type),r=qr().filter(e=>"wouldCreateChapters"===e.category),o=qr().filter(e=>"couldLink"===e.category&&"Scene"===e.type),a=qr().filter(e=>"wouldCreateScenes"===e.category),c=[];let i="";const s=(e,t)=>{c.push({item:e,counterName:t})},d=async(e,n)=>{try{await(async e=>{if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)throw new Error("Word document access is unavailable.");await window.Word.run(async t=>{const n=await ia(t),r="Chapter"===e.type?e.wordChapter:e.wordScene,o=Number.isInteger(r?.paragraphIndex)?n.bodyParagraphs[r.paragraphIndex]:null;if(!o)throw new Error("Unable to locate the Word heading.");if("Chapter"===e.type){const t=e.pdChapter?.chapterId;if(!t)throw new Error("Chapter ID is not available.");Pa(o,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=e.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");Pa(o,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()})})(e),fa(e,"Success"),t[n]+=1}catch(n){fa(e,"Failed",mo(n)),t.failed+=1}};try{for(const e of n)s(e,"linkedChapters");for(const n of r)try{await Ia(e.bookId,n),s(n,"createdChapters")}catch(e){fa(n,"Failed",mo(e)),t.failed+=1}for(const e of o)s(e,"linkedScenes");for(const n of a)try{await ba(e.bookId,n),s(n,"createdScenes")}catch(e){fa(n,"Failed",mo(e)),t.failed+=1}for(const e of c)await d(e.item,e.counterName);for(const e of un.manualReview||[])fa(e,"Skipped");ca(un),i=(e=>`Structure Sync Complete. Created: ${e.createdChapters} Chapters, ${e.createdScenes} Scenes. Linked: ${e.linkedChapters} Chapters, ${e.linkedScenes} Scenes. Skipped: ${e.skipped} Manual Review items. Failed: ${e.failed} Items.`)(t),Lr(i)}finally{xn=!1,Ar(),i&&(Gr(),await ma(),Lr(`${i} Preview refreshed.`))}}),ht?.addEventListener("click",()=>ya(!0)),mt?.addEventListener("click",()=>ya(!1)),ut?.addEventListener("cancel",e=>{e.preventDefault(),ya(!1)}),ne?.addEventListener("click",tc),G?.addEventListener("click",async()=>{if(!Co())return Ir("Select a PlotDirector book first."),void Zr("Not detected");Pn&&(window.clearTimeout(Pn),Pn=null),qn=!1,An=!1,Ur(!0),jr("Updating...");try{await Promise.all([Ya(!0),_a(!0),za(!0)]);if(!await ha())return;if(Rr(!1),!_t)return await ec(),void jr("Current scene updated");await tc(),jr("Current scene updated")}finally{Ur(!1)}}),we?.addEventListener("click",()=>Ha({source:"manual"})),Pe?.addEventListener("click",async()=>{if(Zt)if(!Ln&&await(async()=>{if(!Zt)return!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Rr(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1;try{const e=await window.Word.run(async e=>await ia(e)),t=e.currentChapter?.title||"",n=e.currentScene?.title||"",r=e.currentScene?.anchorId||null,o=e.currentChapter?.anchorId||null,a=Number.isInteger(r)&&r===Zt,c=Number.isInteger(o)&&o===en,i=oo(n,"scene").toLocaleLowerCase()===oo(sr||_t,"scene").toLocaleLowerCase(),s=oo(t,"chapter").toLocaleLowerCase()===oo(dr||Yt,"chapter").toLocaleLowerCase();return a||i&&(c||s)?(Rr(!1),!0):(Rr(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1)}catch(e){return console.error("Unable to verify current Word scene before saving.",e),ho({lastError:mo(e)}),Rr(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1}})()){Pe&&(Pe.disabled=!0,Pe.textContent="Saving...");try{await(e=`/api/word-companion/scenes/${Zt}/links`,t={characterIds:Ea(Ne),assetIds:Ea(Ee),locationIds:[],primaryLocationId:La()},Ca(e,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})),(()=>{const e=new Set(Ea(Ne)),t=new Set(Ea(Ee));ur={characters:ur.characters.map(t=>({...t,linked:e.has(Number.parseInt(eo(t,"character"),10))})),assets:ur.assets.map(e=>({...e,linked:t.has(Number.parseInt(eo(e,"asset"),10))})),locations:ur.locations,primaryLocationId:La()}})(),Fr("Scene links saved successfully."),ho({lastError:"-"})}catch(e){Fr("Unable to save scene links."),ho({lastError:mo(e)})}finally{Pe&&(Pe.disabled=!Zt||Ln,Pe.textContent="Save Scene Links")}var e,t}else Fr("The Word cursor is now in a different scene. Refresh Current Scene before saving.");else Fr("Link a PlotDirector scene first.")}),se?.addEventListener("click",async()=>{await qa()}),Te?.addEventListener("click",async()=>{const e=Co();if(!e||!Yt||en)return void Kr("Chapter not found in PlotDirector.");const t=ro(Yt),n=await((e,t)=>(po(it,`"${e}"`),po(st,`"${t}"`),ct?new Promise(e=>{ln=e,ct.showModal?ct.showModal():ct.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector chapter:\n\n"${e}"\n\nin book:\n\n"${t}"\n\n?`))))(t,Io(e)||"selected book");if(n){Te&&(Te.disabled=!0,Te.textContent="Creating...");try{const n=Number.isInteger(Kt)&&Kt>0?10*Kt:null,r=await ka(`/api/word-companion/books/${e.bookId}/chapters`,{title:t,sortOrder:n});if(!r?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");Gr(),Wr(null,r.chapterId,"Manual chapter link");if(!await Da("Chapter created and linked successfully."))return;await Aa("Chapter created and linked successfully.")}catch(e){Jr("Unable to create chapter."),ho({lastError:mo(e)})}finally{Te&&(Te.disabled=!Yr(),Te.textContent="Create Chapter in PlotDirector")}}}),je?.addEventListener("click",async()=>{const e=Co();if(e&&Yt&&!en){je&&(je.disabled=!0,je.textContent="Loading...");try{sn=await io(e.bookId),dn=null,tt&&(tt.value=""),po(at,""),Ta(),et?.showModal?et.showModal():et&&(et.hidden=!1)}catch(e){Jr("Unable to load chapters."),ho({lastError:mo(e)})}finally{je&&(je.disabled=!Yr(),je.textContent="Link to Existing Chapter")}}else Kr("Chapter not found in PlotDirector.")}),tt?.addEventListener("input",Ta),rt?.addEventListener("click",async()=>{const e=sn.find(e=>e.chapterId===dn);if(e){rt&&(rt.disabled=!0,rt.textContent="Linking...");try{Wr(null,e.chapterId,"Manual chapter link");if(!await Da("Chapter linked successfully."))return;ja(),await Aa("Chapter linked successfully.")}catch(e){po(at,"Unable to link chapter."),Jr("Unable to link chapter."),ho({lastError:mo(e)})}finally{rt&&(rt.disabled=!dn,rt.textContent="Link Chapter")}}else po(at,"Select a chapter.")}),ot?.addEventListener("click",ja),dt?.addEventListener("click",()=>$a(!0)),lt?.addEventListener("click",()=>$a(!1)),ct?.addEventListener("cancel",e=>{e.preventDefault(),$a(!1)}),Oe?.addEventListener("click",async()=>{const e=Co();if(!e||!_t)return void Xr("Scene not found in PlotDirector.");const t=oo(_t,"scene"),n=oo(Yt,"chapter"),r=await((e,t)=>(po(Ke,`"${e}"`),po(Qe,`"${t}"`),ze?new Promise(e=>{cn=e,ze.showModal?ze.showModal():ze.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector scene:\n\n"${e}"\n\nwithin chapter:\n\n"${t}"\n\n?`))))(t,n);if(r){Oe&&(Oe.disabled=!0,Oe.textContent="Creating...");try{const n=await lo();if(!n)return void Xr("This chapter does not exist in PlotDirector. Create or link the chapter first.");const r=await ka(`/api/word-companion/books/${e.bookId}/chapters/${n.chapterId}/scenes`,{sceneTitle:t});if(!r?.sceneId||!r?.chapterId)throw new Error("Scene creation did not return a scene ID.");Gr(),await Ra(r.sceneId,r.chapterId,"Scene created and linked successfully.")}catch(e){Vr("Unable to create scene."),ho({lastError:mo(e)})}finally{Oe&&(Oe.disabled=!_r(),Oe.textContent="Create Scene in PlotDirector")}}}),He?.addEventListener("click",async()=>{const e=Co();if(e&&_t){He&&(He.disabled=!0,He.textContent="Loading...");try{const t=await co(e.bookId),n=so(t);if(!n)return void Xr("This chapter does not exist in PlotDirector. Create or link the chapter first.");on=Array.isArray(n.scenes)?n.scenes:[],an=null,Fe&&(Fe.value=""),po(_e,""),Ua(),Ge?.showModal?Ge.showModal():Ge&&(Ge.hidden=!1)}catch(e){Vr("Unable to load scenes."),ho({lastError:mo(e)})}finally{He&&(He.disabled=!_r(),He.textContent="Link to Existing Scene")}}else Xr("Scene not found in PlotDirector.")}),Fe?.addEventListener("input",Ua),Je?.addEventListener("click",async()=>{const e=Co(),t=on.find(e=>e.sceneId===an);if(e&&t){Je&&(Je.disabled=!0,Je.textContent="Linking...");try{const e=await lo();if(!e)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");Ma(),await Ra(t.sceneId,e.chapterId,"Scene linked successfully.")}catch(e){po(_e,"Unable to link scene."),Vr("Unable to link scene."),ho({lastError:mo(e)})}finally{Je&&(Je.disabled=!an,Je.textContent="Link Scene")}}else po(_e,"Select a scene.")}),Ye?.addEventListener("click",Ma),Xe?.addEventListener("click",()=>Wa(!0)),Ze?.addEventListener("click",()=>Wa(!1)),ze?.addEventListener("cancel",e=>{e.preventDefault(),Wa(!1)}),Nt?.addEventListener("click",async()=>{Nt&&(Nt.disabled=!0,Nt.textContent="Running...");try{if(await yo(),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return void ho({lastScan:"Failure",lastError:"Word document access is unavailable.",paragraphs:"-",heading1:"-",heading2:"-"});const e=await window.Word.run(async e=>{const t=e.document.body.paragraphs;return t.load("items"),await e.sync(),t.items.length});ho({lastScan:"Success",lastError:"-",paragraphs:String(e)})}catch(e){console.error("Word Companion diagnostics failed.",e);const t=mo(e);ho({lastScan:"Failure",lastError:t}),Ir(`Unable to scan the Word document: ${t}`)}finally{Nt&&(Nt.disabled=!1,Nt.textContent="Run Diagnostics")}});const ic=Ot?(async()=>{wo(M,"Loading projects..."),wo(O,"Select a project first"),wo(h,"Loading projects..."),wo(m,"Select a project first"),wr(""),Sr("");try{const n=await Ca("/api/word-companion/projects");if(Ht=Array.isArray(n.projects)?n.projects:[],0===Ht.length)return wo(M,"No projects available."),wo(h,"No projects available."),wr("No projects available."),fo(e,null),fo(t,null),jo(),void Po("No projects available.");So(M,"Choose a project",Ht,"projectId","title"),Lo();const r=go(e),o=Ht.find(e=>e.projectId===r);o&&M?(M.value=String(o.projectId),h&&(h.value=String(o.projectId)),fo(e,o.projectId),await cc(o.projectId,go(t))):(fo(e,null),fo(t,null),jo(),Po("Select a Project and Book to begin."))}catch{Ht=[],Bt=[],wo(M,"Unable to connect to PlotDirector."),wo(O,"Select a project first"),wo(h,"Unable to connect to PlotDirector."),wo(m,"Select a project first"),fr("Unable to connect to PlotDirector."),wr("Unable to connect to PlotDirector."),fo(e,null),fo(t,null),jo(),Po("Unable to connect to PlotDirector.")}})():Promise.resolve();if(Ot||(wo(M,"Please sign in to PlotDirector."),wo(O,"Please sign in to PlotDirector."),wo(h,"Please sign in to PlotDirector."),wo(m,"Please sign in to PlotDirector."),jo()),!window.Office||"function"!=typeof window.Office.onReady)return mr("Word Companion ready"),Ir("Word document access is unavailable."),jr("Manual"),void ho({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"});yo().then(async()=>{mr("Word Companion ready"),await ic,await(async()=>{if(!Ot||!Ft)return void Eo(!1);const n=Ao();if(n)try{const r=await Ca(`/api/word-companion/runtime/book/${n.bookId}?documentGuid=${encodeURIComponent(n.documentGuid)}`),o=r?.manuscriptDocument;if(r?.bookId===n.bookId&&r?.projectId===n.projectId&&o&&String(o.documentGuid).toLowerCase()===n.documentGuid.toLowerCase())return pn=n,Hr(r),fo(e,r.projectId),fo(t,r.bookId),M&&(M.value=String(r.projectId)),await cc(r.projectId,r.bookId),Eo(!1),fr("Connected"),Sr("Bound manuscript detected."),void await Na()}catch{}pn=null,Br(),Lo(),ko()?await cc(ko().projectId,null):wo(m,"Select a project first"),Po("Select a Project and Book to begin."),Eo(!0)})(),Ft?(()=>{if(Ot){if(!window.Office?.context?.document||"function"!=typeof window.Office.context.document.addHandlerAsync||!window.Office?.EventType?.DocumentSelectionChanged)return jr("Manual"),void Ir("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");try{window.Office.context.document.addHandlerAsync(window.Office.EventType.DocumentSelectionChanged,oc,e=>{e?.status===window.Office.AsyncResultStatus.Succeeded?(Rn=!0,jr("Live")):(jr("Manual"),Ir("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))}),window.addEventListener("beforeunload",ac)}catch(e){console.warn("Unable to register Word selection tracking handler.",e),jr("Manual"),Ir("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}})():(Ir("Word document access is unavailable."),jr("Manual"))}).catch(e=>{console.error("Office readiness check failed.",e),fr("Unable to connect to PlotDirector."),mr("Word Companion unavailable"),Ir("Word document access is unavailable."),ho({ready:"No",wordApi:"No",lastScan:"Failure"})})})(); \ No newline at end of file