From 8be690857e1848e84271b4be0dd1a807b04bcd38 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sun, 28 Jun 2026 10:31:07 +0100 Subject: [PATCH] Phase 16H - Live Character Detection While Writing --- .../Controllers/WordCompanionController.cs | 14 ++ PlotLine/Data/WordCompanionRepository.cs | 27 +++ PlotLine/Models/WordCompanionApiModels.cs | 29 +++ PlotLine/Services/WordCompanionService.cs | 32 +++ ...e16H_WordCompanionCharacterSuggestions.sql | 185 +++++++++++++++++ PlotLine/wwwroot/js/word-companion-host.js | 190 ++++++++++++++++++ .../wwwroot/js/word-companion-host.min.js | 2 +- 7 files changed, 478 insertions(+), 1 deletion(-) create mode 100644 PlotLine/Sql/098_Phase16H_WordCompanionCharacterSuggestions.sql diff --git a/PlotLine/Controllers/WordCompanionController.cs b/PlotLine/Controllers/WordCompanionController.cs index 6ec12ba..2b3a8c6 100644 --- a/PlotLine/Controllers/WordCompanionController.cs +++ b/PlotLine/Controllers/WordCompanionController.cs @@ -116,6 +116,20 @@ public sealed class WordCompanionController(IWordCompanionService wordCompanion) return response is null ? BadRequest() : Ok(response); } + [HttpGet("runtime/characters")] + public async Task GetRuntimeCharacters([FromQuery] int projectId, [FromQuery] Guid documentGuid) + { + var response = await wordCompanion.ListRuntimeCharacterAliasesAsync(projectId, documentGuid); + return response is null ? BadRequest() : Ok(response); + } + + [HttpPost("runtime/character-suggestions")] + public async Task CreateRuntimeCharacterSuggestions(WordCompanionRuntimeCharacterSuggestionsRequest request) + { + var response = await wordCompanion.CreateRuntimeCharacterSuggestionsAsync(request); + return response is null ? BadRequest() : Ok(response); + } + [HttpGet("manuscript/book/{bookId:int}")] public async Task GetManuscriptForBook(int bookId) { diff --git a/PlotLine/Data/WordCompanionRepository.cs b/PlotLine/Data/WordCompanionRepository.cs index c050bbc..8561a3e 100644 --- a/PlotLine/Data/WordCompanionRepository.cs +++ b/PlotLine/Data/WordCompanionRepository.cs @@ -20,6 +20,8 @@ public interface IWordCompanionRepository Task UpdateSceneLinksAsync(int sceneId, int userId, WordCompanionUpdateSceneLinksRequest request); Task UpdateWordCountAsync(int sceneId, int userId, int actualWords, DateTime? lastWorkedOn); Task UpdateRuntimeSceneWordCountAsync(int userId, WordCompanionRuntimeSceneWordCountRequest request); + Task> ListRuntimeCharacterAliasesAsync(int userId, int projectId, Guid documentGuid); + Task CreateRuntimeCharacterSuggestionsAsync(int userId, WordCompanionRuntimeCharacterSuggestionsRequest request); Task AnalyseManuscriptAsync(int userId, WordCompanionManuscriptAnalyseRequest request); Task ImportManuscriptAsync(int userId, WordCompanionManuscriptImportRequest request); Task HasProjectAccessAsync(int projectId, int userId); @@ -253,6 +255,31 @@ public sealed class WordCompanionRepository(ISqlConnectionFactory connectionFact commandType: CommandType.StoredProcedure); } + public async Task> ListRuntimeCharacterAliasesAsync(int userId, int projectId, Guid documentGuid) + { + using var connection = connectionFactory.CreateConnection(); + var rows = await connection.QueryAsync( + "dbo.WordCompanion_Runtime_CharacterAlias_List", + new { UserID = userId, ProjectID = projectId, DocumentGuid = documentGuid }, + commandType: CommandType.StoredProcedure); + return rows.ToList(); + } + + public async Task CreateRuntimeCharacterSuggestionsAsync(int userId, WordCompanionRuntimeCharacterSuggestionsRequest request) + { + using var connection = connectionFactory.CreateConnection(); + return await connection.QuerySingleOrDefaultAsync( + "dbo.WordCompanion_Runtime_CharacterSuggestions_Create", + new + { + UserID = userId, + request.DocumentGuid, + request.SceneId, + CharacterIds = ToCsv(request.CharacterIds) + }, + commandType: CommandType.StoredProcedure); + } + public async Task AnalyseManuscriptAsync(int userId, WordCompanionManuscriptAnalyseRequest request) { using var connection = connectionFactory.CreateConnection(); diff --git a/PlotLine/Models/WordCompanionApiModels.cs b/PlotLine/Models/WordCompanionApiModels.cs index f1912b4..e3e63a5 100644 --- a/PlotLine/Models/WordCompanionApiModels.cs +++ b/PlotLine/Models/WordCompanionApiModels.cs @@ -228,6 +228,35 @@ public sealed class WordCompanionRuntimeSceneWordCountRequest public int WordCount { get; set; } } +public sealed class WordCompanionRuntimeCharacterAliasDto +{ + public int CharacterId { get; init; } + public string Name { get; init; } = string.Empty; + public string MatchText { get; init; } = string.Empty; + public bool IsDisplayName { get; init; } +} + +public sealed class WordCompanionRuntimeCharacterAliasResponse +{ + public int ProjectId { get; init; } + public IReadOnlyList Characters { get; init; } = []; +} + +public sealed class WordCompanionRuntimeCharacterSuggestionsRequest +{ + public Guid DocumentGuid { get; set; } + public int SceneId { get; set; } + public IReadOnlyList CharacterIds { get; set; } = []; +} + +public sealed class WordCompanionRuntimeCharacterSuggestionsResponse +{ + public int SceneId { get; init; } + public int CreatedCount { get; init; } + public int SkippedCount { get; init; } + public string Message { get; init; } = "No new character suggestions."; +} + public sealed class WordCompanionManuscriptDocumentDto { public int ManuscriptDocumentId { get; init; } diff --git a/PlotLine/Services/WordCompanionService.cs b/PlotLine/Services/WordCompanionService.cs index fb61474..a05a734 100644 --- a/PlotLine/Services/WordCompanionService.cs +++ b/PlotLine/Services/WordCompanionService.cs @@ -20,6 +20,8 @@ public interface IWordCompanionService Task UpdateSceneLinksAsync(int sceneId, WordCompanionUpdateSceneLinksRequest request); Task UpdateWordCountAsync(int sceneId, WordCompanionUpdateWordCountRequest request); Task UpdateRuntimeSceneWordCountAsync(WordCompanionRuntimeSceneWordCountRequest request); + Task ListRuntimeCharacterAliasesAsync(int projectId, Guid documentGuid); + Task CreateRuntimeCharacterSuggestionsAsync(WordCompanionRuntimeCharacterSuggestionsRequest request); Task GetRuntimeBookAsync(int bookId, Guid documentGuid); Task GetManuscriptForBookAsync(int bookId); Task LinkManuscriptAsync(WordCompanionManuscriptLinkRequest request); @@ -234,6 +236,36 @@ public sealed class WordCompanionService( : repository.UpdateRuntimeSceneWordCountAsync(RequireUserId(), request); } + public async Task ListRuntimeCharacterAliasesAsync(int projectId, Guid documentGuid) + { + if (projectId <= 0 || documentGuid == Guid.Empty) + { + return null; + } + + var aliases = await repository.ListRuntimeCharacterAliasesAsync(RequireUserId(), projectId, documentGuid); + return new WordCompanionRuntimeCharacterAliasResponse + { + ProjectId = projectId, + Characters = aliases + }; + } + + public Task CreateRuntimeCharacterSuggestionsAsync(WordCompanionRuntimeCharacterSuggestionsRequest request) + { + request.CharacterIds = request.CharacterIds + .Where(id => id > 0) + .Distinct() + .Take(CharacterDiscoverySuggestionLimit) + .ToList(); + + return request.DocumentGuid == Guid.Empty + || request.SceneId <= 0 + || request.CharacterIds.Count == 0 + ? Task.FromResult(null) + : repository.CreateRuntimeCharacterSuggestionsAsync(RequireUserId(), request); + } + public async Task GetRuntimeBookAsync(int bookId, Guid documentGuid) { if (bookId <= 0 || documentGuid == Guid.Empty) diff --git a/PlotLine/Sql/098_Phase16H_WordCompanionCharacterSuggestions.sql b/PlotLine/Sql/098_Phase16H_WordCompanionCharacterSuggestions.sql new file mode 100644 index 0000000..dc028a6 --- /dev/null +++ b/PlotLine/Sql/098_Phase16H_WordCompanionCharacterSuggestions.sql @@ -0,0 +1,185 @@ +IF OBJECT_ID(N'dbo.SceneCharacterSuggestions', N'U') IS NULL +BEGIN + CREATE TABLE dbo.SceneCharacterSuggestions + ( + SceneCharacterSuggestionID int IDENTITY(1,1) NOT NULL CONSTRAINT PK_SceneCharacterSuggestions PRIMARY KEY, + SceneID int NOT NULL, + CharacterID int NOT NULL, + SuggestionSource nvarchar(50) NOT NULL CONSTRAINT DF_SceneCharacterSuggestions_Source DEFAULT (N'Word Companion'), + DetectedUtc datetime2 NOT NULL CONSTRAINT DF_SceneCharacterSuggestions_DetectedUtc DEFAULT SYSUTCDATETIME(), + Status nvarchar(20) NOT NULL CONSTRAINT DF_SceneCharacterSuggestions_Status DEFAULT (N'Pending'), + Confidence nvarchar(20) NOT NULL CONSTRAINT DF_SceneCharacterSuggestions_Confidence DEFAULT (N'High'), + Reason nvarchar(200) NULL, + CreatedByUserID int NOT NULL, + ReviewedByUserID int NULL, + ReviewedUtc datetime2 NULL, + CONSTRAINT FK_SceneCharacterSuggestions_Scenes FOREIGN KEY (SceneID) REFERENCES dbo.Scenes(SceneID), + CONSTRAINT FK_SceneCharacterSuggestions_Characters FOREIGN KEY (CharacterID) REFERENCES dbo.Characters(CharacterID), + CONSTRAINT FK_SceneCharacterSuggestions_CreatedByUser FOREIGN KEY (CreatedByUserID) REFERENCES dbo.AppUser(UserID), + CONSTRAINT FK_SceneCharacterSuggestions_ReviewedByUser FOREIGN KEY (ReviewedByUserID) REFERENCES dbo.AppUser(UserID), + CONSTRAINT CK_SceneCharacterSuggestions_Status CHECK (Status IN (N'Pending', N'Accepted', N'Rejected', N'Dismissed')), + CONSTRAINT CK_SceneCharacterSuggestions_Confidence CHECK (Confidence IN (N'High', N'Medium', N'Low')) + ); +END; +GO + +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'UX_SceneCharacterSuggestions_Pending' AND object_id = OBJECT_ID(N'dbo.SceneCharacterSuggestions')) + CREATE UNIQUE INDEX UX_SceneCharacterSuggestions_Pending ON dbo.SceneCharacterSuggestions(SceneID, CharacterID) WHERE Status = N'Pending'; +GO + +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_SceneCharacterSuggestions_SceneStatus' AND object_id = OBJECT_ID(N'dbo.SceneCharacterSuggestions')) + CREATE INDEX IX_SceneCharacterSuggestions_SceneStatus ON dbo.SceneCharacterSuggestions(SceneID, Status, CharacterID); +GO + +CREATE OR ALTER PROCEDURE dbo.WordCompanion_Runtime_CharacterAlias_List + @UserID int, + @ProjectID int, + @DocumentGuid uniqueidentifier +AS +BEGIN + SET NOCOUNT ON; + + IF @DocumentGuid IS NULL + OR @DocumentGuid = '00000000-0000-0000-0000-000000000000' + OR @ProjectID <= 0 + RETURN; + + IF NOT EXISTS + ( + SELECT 1 + FROM dbo.ManuscriptDocuments md + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = md.ProjectID + INNER JOIN dbo.Projects p ON p.ProjectID = md.ProjectID + WHERE md.DocumentGuid = @DocumentGuid + AND md.ProjectID = @ProjectID + AND md.IsActive = 1 + AND p.IsArchived = 0 + AND pua.UserID = @UserID + AND pua.IsActive = 1 + ) + RETURN; + + SELECT c.CharacterID AS CharacterId, + c.CharacterName AS Name, + c.CharacterName AS MatchText, + CAST(1 AS bit) AS IsDisplayName + FROM dbo.Characters c + WHERE c.ProjectID = @ProjectID + AND c.IsArchived = 0 + AND NULLIF(LTRIM(RTRIM(c.CharacterName)), N'') IS NOT NULL + + UNION ALL + + SELECT c.CharacterID AS CharacterId, + c.CharacterName AS Name, + ca.Alias AS MatchText, + CAST(0 AS bit) AS IsDisplayName + FROM dbo.Characters c + INNER JOIN dbo.CharacterAliases ca ON ca.CharacterID = c.CharacterID + WHERE c.ProjectID = @ProjectID + AND c.IsArchived = 0 + AND NULLIF(LTRIM(RTRIM(ca.Alias)), N'') IS NOT NULL + ORDER BY Name, CharacterId, IsDisplayName DESC, MatchText; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.WordCompanion_Runtime_CharacterSuggestions_Create + @UserID int, + @DocumentGuid uniqueidentifier, + @SceneID int, + @CharacterIds nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + + IF @DocumentGuid IS NULL + OR @DocumentGuid = '00000000-0000-0000-0000-000000000000' + OR @SceneID <= 0 + RETURN; + + DECLARE @ProjectID int; + DECLARE @ManuscriptDocumentID int; + + SELECT @ProjectID = b.ProjectID, + @ManuscriptDocumentID = md.ManuscriptDocumentID + FROM dbo.Scenes s + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + INNER JOIN dbo.Projects p ON p.ProjectID = b.ProjectID + INNER JOIN dbo.ManuscriptDocuments md ON md.BookID = b.BookID + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = b.ProjectID + WHERE s.SceneID = @SceneID + AND s.IsArchived = 0 + AND c.IsArchived = 0 + AND b.IsArchived = 0 + AND p.IsArchived = 0 + AND md.DocumentGuid = @DocumentGuid + AND md.IsActive = 1 + AND s.IsLinkedToManuscript = 1 + AND s.ManuscriptDocumentID = md.ManuscriptDocumentID + AND pua.UserID = @UserID + AND pua.IsActive = 1; + + IF @ProjectID IS NULL + RETURN; + + DECLARE @Requested table (CharacterID int NOT NULL PRIMARY KEY); + + INSERT @Requested (CharacterID) + SELECT DISTINCT TRY_CONVERT(int, LTRIM(RTRIM(value))) + FROM STRING_SPLIT(COALESCE(@CharacterIds, N''), N',') + WHERE TRY_CONVERT(int, LTRIM(RTRIM(value))) IS NOT NULL + AND TRY_CONVERT(int, LTRIM(RTRIM(value))) > 0; + + IF NOT EXISTS (SELECT 1 FROM @Requested) + BEGIN + SELECT @SceneID AS SceneId, + 0 AS CreatedCount, + 0 AS SkippedCount, + N'No character suggestions detected.' AS Message; + RETURN; + END; + + IF EXISTS + ( + SELECT 1 + FROM @Requested requested + WHERE NOT EXISTS + ( + SELECT 1 + FROM dbo.Characters ch + WHERE ch.CharacterID = requested.CharacterID + AND ch.ProjectID = @ProjectID + AND ch.IsArchived = 0 + ) + ) + RETURN; + + DECLARE @Inserted table (CharacterID int NOT NULL PRIMARY KEY); + + INSERT dbo.SceneCharacterSuggestions + (SceneID, CharacterID, SuggestionSource, Status, Confidence, Reason, CreatedByUserID) + OUTPUT inserted.CharacterID INTO @Inserted + SELECT @SceneID, + requested.CharacterID, + N'Word Companion', + N'Pending', + N'High', + N'Detected in manuscript text', + @UserID + FROM @Requested requested + WHERE NOT EXISTS + (SELECT 1 FROM dbo.SceneCharacters sc WHERE sc.SceneID = @SceneID AND sc.CharacterID = requested.CharacterID) + AND NOT EXISTS + (SELECT 1 FROM dbo.SceneCharacterSuggestions suggestion WHERE suggestion.SceneID = @SceneID AND suggestion.CharacterID = requested.CharacterID AND suggestion.Status = N'Pending'); + + SELECT @SceneID AS SceneId, + (SELECT COUNT(*) FROM @Inserted) AS CreatedCount, + (SELECT COUNT(*) FROM @Requested) - (SELECT COUNT(*) FROM @Inserted) AS SkippedCount, + CASE + WHEN (SELECT COUNT(*) FROM @Inserted) = 1 THEN N'1 character suggestion detected.' + WHEN (SELECT COUNT(*) FROM @Inserted) > 1 THEN CONCAT((SELECT COUNT(*) FROM @Inserted), N' character suggestions detected.') + ELSE N'No new character suggestions.' + END AS Message; +END; +GO diff --git a/PlotLine/wwwroot/js/word-companion-host.js b/PlotLine/wwwroot/js/word-companion-host.js index dae0585..b1eb968 100644 --- a/PlotLine/wwwroot/js/word-companion-host.js +++ b/PlotLine/wwwroot/js/word-companion-host.js @@ -207,6 +207,14 @@ let sceneWordCountSyncPending = false; let lastSyncedSceneId = null; let lastSyncedWordCount = null; + let characterSuggestionTimer = null; + let characterSuggestionInFlight = false; + let characterSuggestionPending = false; + let characterAliasCacheProjectId = null; + let characterAliasCacheDocumentGuid = ""; + let characterAliasCache = []; + let lastSuggestedSceneId = null; + let lastSuggestedCharacterSignature = ""; let lastLinkedSceneTitle = ""; let lastLinkedChapterTitle = ""; let runtimeLastDebugAt = 0; @@ -481,6 +489,7 @@ sceneContextStale = !!isStale; if (sceneContextStale) { clearPendingSceneWordCountSync(); + clearPendingCharacterSuggestionDetection(); } setText(sceneTrackingStatus, sceneContextStale ? "Stale" : sceneTrackingMode); updateSceneActionButtons(); @@ -499,6 +508,7 @@ } if (!resolvedSceneId) { clearPendingSceneWordCountSync(); + clearPendingCharacterSuggestionDetection(); } updateSceneActionButtons(); setSyncStatus(sceneContextStale @@ -565,6 +575,7 @@ documentStructureCache = null; plotDirectorStructureCache = null; plotDirectorStructureBookId = null; + resetRuntimeCharacterAliasCache(); setRuntimeBookContext(null); }; @@ -919,6 +930,7 @@ setResolvedScene(sceneId, chapterId, resolutionMethod); renderCompanionData(companionData); scheduleSceneWordCountSync(); + scheduleCharacterSuggestionDetection(); }; const setText = (element, value) => { @@ -2220,6 +2232,36 @@ }); }; + const readCachedCurrentSceneText = async () => { + const scene = documentStructureCache?.currentScene; + if (!scene || !Number.isInteger(scene.startParagraphIndex) || !Number.isInteger(scene.endParagraphIndex)) { + return ""; + } + + 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"); + }); + }; + const refreshDocumentStructure = async () => { setDocumentMessage(""); @@ -2911,6 +2953,7 @@ setDocumentMessage("Reading manuscript position..."); try { clearPlotDirectorStructureCache(); + await loadRuntimeCharacterAliases(true); await getBookStructureChapters(book.bookId); const structure = await window.Word.run(async (context) => await readRuntimeDocumentStructure(context, !!book.usesExplicitScenes)); renderOutline(structure); @@ -3804,6 +3847,149 @@ }, delayMs); }; + const clearPendingCharacterSuggestionDetection = () => { + if (characterSuggestionTimer) { + window.clearTimeout(characterSuggestionTimer); + characterSuggestionTimer = null; + } + }; + + const resetRuntimeCharacterAliasCache = () => { + characterAliasCacheProjectId = null; + characterAliasCacheDocumentGuid = ""; + characterAliasCache = []; + lastSuggestedSceneId = null; + lastSuggestedCharacterSignature = ""; + clearPendingCharacterSuggestionDetection(); + }; + + const loadRuntimeCharacterAliases = async (force = false) => { + const project = selectedProject(); + const documentGuid = currentDocumentGuid(); + if (!project || !documentGuid) { + characterAliasCache = []; + return []; + } + + if (!force + && characterAliasCacheProjectId === project.projectId + && characterAliasCacheDocumentGuid === documentGuid + && characterAliasCache.length > 0) { + return characterAliasCache; + } + + const response = await fetchJson(`/api/word-companion/runtime/characters?projectId=${encodeURIComponent(project.projectId)}&documentGuid=${encodeURIComponent(documentGuid)}`); + characterAliasCacheProjectId = project.projectId; + characterAliasCacheDocumentGuid = documentGuid; + characterAliasCache = Array.isArray(response?.characters) ? response.characters : []; + runtimeDebug("Character alias cache refreshed."); + return characterAliasCache; + }; + + const escapeRegex = (value) => String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + + const hasWholeWordMatch = (text, matchText) => { + const normalized = String(matchText || "").trim(); + if (!normalized) { + return false; + } + + const pattern = escapeRegex(normalized).replace(/\s+/g, "\\s+"); + return new RegExp(`(^|[^\\p{L}\\p{N}_])${pattern}(?=$|[^\\p{L}\\p{N}_])`, "iu").test(text); + }; + + const detectCharactersInSceneText = (sceneText, aliases) => { + if (!sceneText || !Array.isArray(aliases) || aliases.length === 0) { + return []; + } + + const detected = new Map(); + for (const item of aliases) { + const characterId = Number.parseInt(item.characterId || "", 10); + if (!Number.isInteger(characterId) || characterId <= 0 || detected.has(characterId)) { + continue; + } + + if (hasWholeWordMatch(sceneText, item.matchText)) { + detected.set(characterId, item.name || item.matchText || "Character"); + } + } + + return [...detected.entries()].map(([characterId, name]) => ({ characterId, name })); + }; + + const finishCharacterSuggestionDetection = () => { + characterSuggestionInFlight = false; + if (characterSuggestionPending) { + characterSuggestionPending = false; + scheduleCharacterSuggestionDetection(1500); + } + }; + + const detectAndSubmitCharacterSuggestions = async () => { + characterSuggestionTimer = null; + if (!resolvedSceneId || sceneContextStale || !currentDocumentGuid()) { + return; + } + + if (characterSuggestionInFlight) { + characterSuggestionPending = true; + runtimeDebug("Character suggestion detection deferred; detection already running."); + return; + } + + characterSuggestionInFlight = true; + characterSuggestionPending = false; + + try { + const [sceneText, aliases] = await Promise.all([ + readCachedCurrentSceneText(), + loadRuntimeCharacterAliases() + ]); + const detected = detectCharactersInSceneText(sceneText, aliases); + const characterIds = detected.map((item) => item.characterId); + const signature = characterIds.slice().sort((left, right) => left - right).join(","); + if (!signature || (lastSuggestedSceneId === resolvedSceneId && lastSuggestedCharacterSignature === signature)) { + runtimeDebug("Character suggestions skipped."); + return; + } + + const response = await postJson("/api/word-companion/runtime/character-suggestions", { + documentGuid: currentDocumentGuid(), + sceneId: resolvedSceneId, + characterIds + }); + + lastSuggestedSceneId = resolvedSceneId; + lastSuggestedCharacterSignature = signature; + if ((response?.createdCount || 0) > 0) { + const names = detected.slice(0, 3).map((item) => item.name).join(", "); + const suffix = detected.length > 3 ? ` +${detected.length - 3}` : ""; + setDocumentMessage(names ? `Characters detected: ${names}${suffix}` : response.message); + } + runtimeDebug(response?.message || "Character suggestions submitted."); + } catch (error) { + console.error("Unable to detect character suggestions.", error); + setDiagnostics({ lastError: errorText(error) }); + } finally { + finishCharacterSuggestionDetection(); + } + }; + + const scheduleCharacterSuggestionDetection = (delayMs = 2500) => { + clearPendingCharacterSuggestionDetection(); + if (!resolvedSceneId || sceneContextStale || characterSuggestionInFlight) { + if (characterSuggestionInFlight) { + characterSuggestionPending = true; + } + return; + } + + characterSuggestionTimer = window.setTimeout(() => { + void detectAndSubmitCharacterSuggestions(); + }, delayMs); + }; + const refreshPlotDirectorChapter = async () => { const project = selectedProject(); const book = selectedBook(); @@ -4131,6 +4317,7 @@ setSceneContextStale(false); setSceneTrackingState("Current scene updated"); scheduleSceneWordCountSync(); + scheduleCharacterSuggestionDetection(); return; } @@ -4143,6 +4330,7 @@ setSceneTrackingState("Current scene updated"); setDocumentMessage("Current scene updated."); scheduleSceneWordCountSync(); + scheduleCharacterSuggestionDetection(); } catch (error) { console.error("Unable to refresh current scene from Word selection.", error); setDiagnostics({ lastError: errorText(error) }); @@ -4169,6 +4357,7 @@ runtimeSelectionDirty = true; runtimeLastActivityAt = Date.now(); clearPendingSceneWordCountSync(); + clearPendingCharacterSuggestionDetection(); runtimeDebug(`${reason} changed.`); if (isAutoRefreshingScene) { @@ -4258,6 +4447,7 @@ setRefreshCurrentSceneBusy(true); setSceneTrackingState("Updating..."); try { + await loadRuntimeCharacterAliases(true); const scanned = await refreshDocumentStructure(); if (!scanned) { return; diff --git a/PlotLine/wwwroot/js/word-companion-host.min.js b/PlotLine/wwwroot/js/word-companion-host.min.js index 355ed85..f93f375 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"]),d=document.querySelector(".word-companion-shell"),s=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]"),f=document.querySelector("[data-first-run-scan]"),g=document.querySelector("[data-first-run-cancel]"),S=document.querySelector("[data-first-run-status]"),C=document.querySelector("[data-first-run-summary]"),b=document.querySelector("[data-first-run-character-section]"),I=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]"),E=document.querySelector("[data-first-run-skip-characters]"),N=document.querySelector("[data-first-run-continue]"),L=document.querySelector("[data-first-run-import-actions]"),q=document.querySelector("[data-first-run-import]"),P=document.querySelector("[data-first-run-import-cancel]"),D=document.querySelector("[data-first-run-replace-dialog]"),A=document.querySelector("[data-first-run-replace-confirm]"),T=document.querySelector("[data-first-run-replace-cancel]"),$=document.querySelector("[data-office-status]"),W=document.querySelector("[data-connection-status]"),j=document.querySelector("[data-summary-connection]"),R=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]"),z=document.querySelector("[data-scene-tracking-status]"),K=document.querySelector("[data-document-message]"),Q=document.querySelector("[data-sync-note]"),X=document.querySelector("[data-document-outline]"),Z=document.querySelector("[data-analyse-manuscript-structure]"),_=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]"),de=document.querySelector("[data-attach-plotdirector-ids]"),se=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]"),fe=document.querySelector("[data-runtime-last-sync]"),ge=document.querySelector("[data-sync-scene-progress]"),Se=document.querySelector("[data-sync-word-count]"),Ce=document.querySelector("[data-sync-plotdirector-count]"),be=document.querySelector("[data-sync-last-synced]"),Ie=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]"),Ee=document.querySelector("[data-character-chips]"),Ne=document.querySelector("[data-asset-chips]"),Le=(document.querySelector("[data-location-chips]"),document.querySelector("[data-primary-location-select]")),qe=document.querySelector("[data-save-scene-links]"),Pe=document.querySelector("[data-scene-links-status]"),De=document.querySelector("[data-links-editing-scene]"),Ae=document.querySelector("[data-chapter-create-link]"),Te=document.querySelector("[data-chapter-create-link-chapter]"),$e=document.querySelector("[data-create-plotdirector-chapter]"),We=document.querySelector("[data-link-existing-chapter]"),je=document.querySelector("[data-chapter-create-link-status]"),Re=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]"),ze=document.querySelector("[data-link-dialog-status]"),Ke=document.querySelector("[data-create-scene-dialog]"),Qe=document.querySelector("[data-create-dialog-scene]"),Xe=document.querySelector("[data-create-dialog-chapter]"),Ze=document.querySelector("[data-create-dialog-confirm]"),_e=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]"),dt=document.querySelector("[data-create-chapter-dialog-book]"),st=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]"),ft=document.querySelector("[data-resolve-book-id]"),gt=document.querySelector("[data-resolve-book-title]"),St=document.querySelector("[data-resolve-detected-chapter]"),Ct=document.querySelector("[data-resolve-detected-scene]"),bt=document.querySelector("[data-resolve-request-chapter]"),It=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]"),Et=document.querySelector("[data-run-diagnostics]"),Nt=document.querySelector("[data-diagnostic-host]"),Lt=document.querySelector("[data-diagnostic-platform]"),qt=document.querySelector("[data-diagnostic-ready]"),Pt=document.querySelector("[data-diagnostic-word-api]"),Dt=document.querySelector("[data-diagnostic-last-scan]"),At=document.querySelector("[data-diagnostic-last-error]"),Tt=document.querySelector("[data-diagnostic-anchor-type]"),$t=document.querySelector("[data-diagnostic-stored-scene-id]"),Wt=document.querySelector("[data-diagnostic-stored-chapter-id]"),jt=document.querySelector("[data-diagnostic-resolution-method]"),Rt=document.querySelector("[data-diagnostic-paragraphs]"),Ut=document.querySelector("[data-diagnostic-heading1]"),Mt=document.querySelector("[data-diagnostic-heading2]"),Ot="true"===d?.dataset.authenticated;let Ht=[],Bt=[],Gt=!1,Ft=!1,Vt="Unknown",Jt="Unknown",Yt="",zt="",Kt=null,Qt=null,Xt=null,Zt=null,_t=null,en=null,tn="",nn="Title Match",rn=!1,an=[],on=null,cn=null,dn=[],sn=null,ln=null,un=null,pn=null,hn=null,mn=null,yn=null,wn=null,fn=null,gn=null,Sn=[],Cn=!1,bn=!1,In=0,kn=!1,vn=!1,xn=!1,En=null,Nn="Manual",Ln=!1,qn=null,Pn=!1,Dn=0,An=!1;const Tn=1200;let $n=!1,Wn=!1,jn=null,Rn=!1,Un=!1,Mn=null,On=null,Hn="",Bn="",Gn=0,Fn={characters:[],assets:[],locations:[],primaryLocationId:null};const Vn=e=>{const t=Date.now();t-Gn<1e3||(Gn=t,console.debug(`[Word Companion Runtime] ${e}`))},Jn=e=>{$&&($.textContent=e)},Yn=(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)},zn=()=>{const e=(e=>{try{return window.localStorage.getItem(e)||""}catch{return""}})(n);Yn(i.has(e)?e:"scene",!1)},Kn=e=>{W&&(W.textContent=e),j&&(j.textContent=e)},Qn=e=>{H&&(H.textContent=e)},Xn=e=>{B&&(B.textContent=e)},Zn=e=>{K&&(K.textContent=e)},_n=e=>{re&&(re.textContent=e)},er=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("anchorType")&&Gr(Tt,fr(e.anchorType)),t("storedSceneId")&&Gr($t,fr(e.storedSceneId)),t("storedChapterId")&&Gr(Wt,fr(e.storedChapterId)),t("resolutionMethod")&&Gr(jt,fr(e.resolutionMethod))},tr=()=>{const e=_r(),t=Number.isInteger(_t)&&_t>0&&Zt===_t,n=!Number.isInteger(en)||en<=0||Xt===en,r=t&&n;Gr(ae,r?"Attached to PlotDirector":"Not attached"),Gr(oe,e?.bookId?String(e.bookId):"-"),Gr(ce,Number.isInteger(en)&&en>0?String(en):"-"),Gr(ie,Number.isInteger(_t)&&_t>0?String(_t):"-"),de&&(de.disabled=!_t||r&&!rn,de.textContent=Zt&&!r?"Reattach PlotDirector IDs":"Attach PlotDirector IDs"),er({anchorType:nn||"Title Match",storedSceneId:Zt,storedChapterId:Xt,resolutionMethod:tn})},nr=(e,t,n,r=null,a=null,o=null)=>{const c=e||"",i=t||"",d=Number.isInteger(n)?n:null,s=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&&zt===i&&Kt===d&&Qt===s&&Xt===l&&Zt===u;Yt=e||"",zt=t||"",Kt=Number.isInteger(n)?n:null,Qt=Number.isInteger(o)&&o>0?o:null,Xt=Number.isInteger(r)&&r>0?r:null,Zt=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):"-"),Gr(Se,Number.isInteger(n)?String(n):"-"),tr())},rr=()=>{jn&&(window.clearTimeout(jn),jn=null)},ar=(e,t)=>{e&&(e.hidden=t)},or=e=>{Gr(Ie,e)},cr=e=>{Gr(ee,e)},ir=(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)}cr(e),sr()},dr=(e=un)=>((e=un)=>Ea.flatMap(t=>Array.isArray(e?.[t.key])?e[t.key]:[]))(e).filter(e=>"couldLink"===e.category||"wouldCreateChapters"===e.category||"wouldCreateScenes"===e.category),sr=()=>{_&&(_.disabled=xn||0===dr().length)},lr=()=>{Z&&(Z.disabled=xn||!Zr()||!_r()),sr()},ur=()=>{De&&(De.textContent=_t?`Editing links for: ${Hn||zt||"Current scene"}`:"Link a PlotDirector scene first.")},pr=()=>{const e=Ln||!_t,t=e||!en||Rn;ge&&(ge.disabled=t),qe&&(qe.disabled=e),Le&&(Le.disabled=e);for(const t of[Ee,Ne])for(const n of t?[...t.querySelectorAll("input[type='checkbox']")]:[])n.disabled=e},hr=e=>{"Live"!==e&&"Manual"!==e||(Nn=e),Gr(z,e||Nn||"Manual")},mr=(e,t="")=>{Ln=!!e,Ln&&rr(),Gr(z,Ln?"Stale":Nn),pr(),t&&(Zn(t),Ir(t))},yr=(e,t=null,n="")=>{_t=Number.isInteger(e)&&e>0?e:null,en=Number.isInteger(t)&&t>0?t:null,tn=n||"",_t!==Mn&&(On=null),_t||rr(),pr(),or(Ln?"Refresh Current Scene before syncing.":_t?"Ready to sync.":"No resolved PlotDirector scene."),Ir(Ln?"Refresh Current Scene before saving.":_t?"Ready to save.":"Link a PlotDirector scene first."),ur(),tr()},wr=e=>{G&&(G.disabled=e,G.textContent=e?"Refreshing...":"Refresh Current Scene")},fr=e=>null==e||""===e?"-":String(e),gr=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"})}`},Sr=e=>{hn=e||null;const t=hn?.lastSyncUtc||hn?.manuscriptDocument?.lastSyncUtc;Gr(fe,gr(t)),Gr(be,gr(t))},Cr=()=>{mn=null,yn=null,wn=null,Sr(null)},br=()=>{yn=null,wn=null},Ir=e=>{Gr(Pe,e)},kr=e=>{Gr(Be,e)},vr=e=>{Gr(je,e)},xr=()=>!!_r()&&!!Yt&&!en,Er=()=>!!_r()&&!!zt&&Number.isInteger(en)&&en>0,Nr=()=>{ar(Ae,!0),vr(""),$e&&($e.disabled=!0,$e.textContent="Create Chapter in PlotDirector"),We&&(We.disabled=!0,We.textContent="Link to Existing Chapter")},Lr=(e="")=>{Gr(Te,fr(Yt)),ar(Ae,!1),vr(e);const t=xr();$e&&($e.disabled=!t,$e.textContent="Create Chapter in PlotDirector"),We&&(We.disabled=!t,We.textContent="Link to Existing Chapter")},qr=()=>{ar(Re,!0),kr(""),Oe&&(Oe.disabled=!0,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!0,He.textContent="Link to Existing Scene")},Pr=(e="")=>{Gr(Ue,fr(Yt)),Gr(Me,fr(zt)),ar(Re,!1),kr(e);const t=Er();Oe&&(Oe.disabled=!t,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!t,He.textContent="Link to Existing Scene")},Dr=e=>{_n(e),ar(se,!0),ar(ke,!0),ar(xe,!1),Nr(),qr(),tn="",Hn="",Bn="",nn=Zt?"SceneID Anchor":Xt?"ChapterID Anchor":"Title Match",rn=!1,Fn={characters:[],assets:[],locations:[],primaryLocationId:null},Tr(Ee,[],"character"),Tr(Ne,[],"asset"),$r([],null,!1),yr(null),Gr(Ce,"-"),Gr(le,"-"),Gr(ue,"-"),Gr(pe,"-"),Gr(he,"-"),Gr(me,"-"),Gr(we,"-"),ar(ye,!0),tr(),ur()},Ar=(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,Tr=(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(Ar(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)}},$r=(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(Ar(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},Wr=e=>String(e||"").trim().replace(/\s+/g," "),jr=(e,t)=>{const n=Wr(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 Wr(n.replace(r,""))||n},Rr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("projectId")&&Gr(yt,fr(e.projectId)),t("projectTitle")&&Gr(wt,fr(e.projectTitle)),t("bookId")&&Gr(ft,fr(e.bookId)),t("bookTitle")&&Gr(gt,fr(e.bookTitle)),t("detectedChapter")&&Gr(St,fr(e.detectedChapter)),t("detectedScene")&&Gr(Ct,fr(e.detectedScene)),t("requestChapter")&&Gr(bt,fr(e.requestChapter)),t("requestScene")&&Gr(It,fr(e.requestScene)),t("result")&&Gr(kt,fr(e.result)),t("chapterId")&&Gr(vt,fr(e.chapterId)),t("sceneId")&&Gr(xt,fr(e.sceneId))},Ur=async e=>{if(wn===e&&Array.isArray(yn?.chapters))return yn.chapters;const t=await Ka(`/api/word-companion/books/${e}/structure`);return wn=e,yn=t||null,Array.isArray(t?.chapters)?t.chapters:[]},Mr=async e=>{const t=await Ka(`/api/word-companion/books/${e}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},Or=e=>{if(Number.isInteger(en)&&en>0){const t=e.find(e=>e.chapterId===en);if(t)return t}const t=jr(Yt,"chapter").toLocaleLowerCase();return t&&e.find(e=>jr(e.title,"chapter").toLocaleLowerCase()===t)||null},Hr=async()=>{const e=_r();return e?Or(await Ur(e.bookId)):null},Br=async(e,t,n,r,a)=>{const o=await Ka(`/api/word-companion/scenes/${t}/companion`);try{o.revisionStatus=await(async(e,t)=>{const n=await Ka(`/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,mr(!1),_n("Linked to PlotDirector"),Zn(""),Nr(),qr(),yr(t,n,r),c=o,Hn=c?.sceneTitle||zt||"",Bn=c?.chapterTitle||Yt||"",Gr(le,fr(c?.sceneTitle)),Gr(ue,fr(c?.revisionStatus||c?.revisionStatusName||"Not provided")),Gr(pe,fr(c?.estimatedWords)),Gr(he,fr(c?.actualWords)),Gr(Ce,fr(c?.actualWords)),Gr(me,c?.blocked?"Blocked":"Not blocked"),c?.blockedReason?(Gr(we,c.blockedReason),ar(ye,!1)):(Gr(we,"-"),ar(ye,!0)),ve&&(ve.textContent=c?.writingBrief||"No writing brief has been added for this scene."),Fn={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},Tr(Ee,Fn.characters,"character",!!_t&&!Ln),Tr(Ne,Fn.assets,"asset",!!_t&&!Ln),$r(Fn.locations,Fn.primaryLocationId,!!_t&&!Ln),ur(),Ir(Ln?"Refresh Current Scene before saving.":_t?"Ready to save.":"No resolved PlotDirector scene."),ar(se,!1),ar(ke,!1),ar(xe,!1),yo()},Gr=(e,t)=>{if(e){const n=null==t?"":String(t);e.textContent!==n&&(e.textContent=n)}},Fr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("host")&&Gr(Nt,e.host),t("platform")&&Gr(Lt,e.platform),t("ready")&&Gr(qt,e.ready),t("wordApi")&&Gr(Pt,e.wordApi),t("lastScan")&&Gr(Dt,e.lastScan),t("lastError")&&Gr(At,e.lastError),t("paragraphs")&&Gr(Rt,e.paragraphs),t("heading1")&&Gr(Ut,e.heading1),t("heading2")&&Gr(Mt,e.heading2)},Vr=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)},Jr=async()=>{if(!window.Office||"function"!=typeof window.Office.onReady)return Gt=!1,Ft=!1,Vt="Unavailable",Jt="Unavailable",Fr({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,Fr({host:Vt,platform:Jt,ready:"Yes",wordApi:Ft?"Yes":"No"}),e},Yr=e=>{try{const t=window.localStorage.getItem(e),n=Number.parseInt(t||"",10);return Number.isInteger(n)&&n>0?n:null}catch{return null}},zr=(e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}},Kr=(e,t)=>{if(!e)return;e.innerHTML="";const n=document.createElement("option");n.value="",n.textContent=t,e.append(n),e.disabled=!0},Qr=(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},Xr=e=>{const t=String(e?.title||"").trim(),n=String(e?.subtitle||"").trim();return n?`${t}: ${n}`:t},Zr=()=>{const e=Number.parseInt(M?.value||"",10);return Ht.find(t=>t.projectId===e)||null},_r=()=>{const e=Number.parseInt(O?.value||"",10);return Bt.find(t=>t.bookId===e)||null},ea=()=>{const e=Number.parseInt(h?.value||"",10);return Ht.find(t=>t.projectId===e)||null},ta=()=>{const e=Number.parseInt(m?.value||"",10);return Bt.find(t=>t.bookId===e)||null},na=e=>Gr(S,e),ra=()=>{const e=ea(),t=ta(),n=bn&&Date.now()-In>=750;f&&(f.disabled=!e||!t||kn),w&&(w.disabled=!e||!String(y?.value||"").trim()||kn),q&&(q.disabled=!fn?.canImport||!gn||kn),x&&(x.disabled=!n||vn||0===ia().length)},aa=e=>{ar(p,!e),ar(s,e);for(const t of u)ar(t,!!e||"scene"!==t.dataset.tabPanel&&!t.classList.contains("is-active"));e||zn()},oa=()=>{if(!h)return;if(0===Ht.length)return void Kr(h,"No projects available.");Qr(h,"Choose a project",Ht,"projectId","title");const e=Number.parseInt(M?.value||"",10);Number.isInteger(e)&&e>0&&(h.value=String(e))},ca=(e="Select a Project and Book to begin.")=>{fn=null,gn=null,Sn=[],Cn=!1,bn=!1,In=0,ar(C,!0),ar(L,!0),ar(b,!0),ar(v,!0),C&&(C.innerHTML=""),k&&(k.innerHTML=""),Gr(I,""),na(e),ra()},ia=()=>k?[...k.querySelectorAll("input[type='checkbox']:checked")].map(e=>String(e.value||"").trim()).filter(Boolean):[],da=e=>{if(Sn=Array.isArray(e)?e:[],b&&k){if(k.innerHTML="",ar(b,!1),ar(v,!Cn||0===Sn.length),ar(x,!1),ar(E,!1),ar(N,!0),0===Sn.length)return Gr(I,"No likely major characters found."),void ra();Gr(I,`${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",ra);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)}ra()}},sa=()=>{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),d=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(d)&&d>0?d:1}},la=()=>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)),ua=()=>{const e=Zr(),t=_r();R&&(R.textContent=e?.title||"(Not connected)"),U&&(U.textContent=t?Xr(t):"(Not connected)"),Q&&(Q.textContent=t?"":"Select a PlotDirector book before refreshing."),lr()},pa=e=>String(e?.styleBuiltIn||e?.style||"").replace(/\s+/g,"").toLowerCase(),ha=(e,t)=>{const n=pa(e);return n===`heading${t}`||n.endsWith(`.heading${t}`)||n.includes(`heading${t}`)},ma=e=>String(e||"").trim().split(/\s+/).filter(Boolean).length,ya=(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},wa=e=>{try{return Array.isArray(e?.contentControls?.items)?e.contentControls.items:[]}catch(e){return console.warn("Word paragraph content controls were not available.",e),[]}},fa=(e,t)=>{const n=wa(e);for(const e of n){const n=ya(e.tag,t);if(n)return n}return null},ga=(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(ha(e,1))return r+=1,o={index:n.length+1,paragraphIndex:t,title:i,anchorId:fa(e,"PD-CHAPTER"),scenes:[]},n.push(o),void(c=null);if(ha(e,2)){if(a+=1,!o)return;return c={index:o.scenes.length+1,paragraphIndex:t,title:i,anchorId:fa(e,"PD-SCENE"),wordCount:0},void o.scenes.push(c)}c&&(c.wordCount+=ma(i))}});const i=t.find(e=>String(e.text||"").trim()),d=i?e.findIndex(e=>{return t=e,n=i,String(t?.text||"").trim()===String(n?.text||"").trim()&&pa(t)===pa(n);var t,n}):-1,s=d>=0&&n.filter(e=>e.paragraphIndex<=d).at(-1)||null,l=s&&d>=0&&s.scenes.filter(e=>e.paragraphIndex<=d).at(-1)||null;return{chapters:n,currentChapter:s,currentScene:l,paragraphCount:e.length,heading1Count:r,heading2Count:a}},Sa=new Set(["***","###"]),Ca=(e,t)=>{const n=String(e?.text||"").trim();return{index:t,text:n,styleBuiltIn:e?.styleBuiltIn||"",style:e?.style||"",wordCount:ma(n),chapterAnchorId:null,sceneAnchorId:null}},ba=(e,t)=>{e&&(e.endParagraphIndex=t)},Ia=(e,t)=>{e&&(e.endParagraphIndex=t,ba(e.scenes.at(-1),t))},ka=(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()&&pa(e)===pa(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&&(nr(t?.title,n?.title,n?.wordCount,t?.anchorId,n?.anchorId,t?.index),r)},xa=e=>{if(!X)return;if(X.innerHTML="",0===e.chapters.length){const e=document.createElement("p");return e.textContent="No chapters detected. Use Heading 1 for chapter titles.",void X.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.",X.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)}X.append(e)}},Ea=[{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"}],Na={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},La={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},qa=(e,t)=>jr(e,t).toLocaleLowerCase(),Pa=({category:e,action:t,type:n,wordTitle:r,match:a="",anchorStatus:o="None",matches:c=[],pdChapter:i=null,pdScene:d=null,wordChapter:s=null,wordScene:l=null,parentItem:u=null})=>({id:`${n}-${s?.index||0}-${l?.index||0}-${s?.paragraphIndex??l?.paragraphIndex??0}`,category:e,action:t,type:n,wordTitle:r,match:a,anchorStatus:o,matches:c,pdChapter:i,pdScene:d,wordChapter:s,wordScene:l,parentItem:u,result:"Pending",error:""}),Da=(e,t)=>{Array.isArray(e[t.category])&&e[t.category].push(t)},Aa=e=>Array.isArray(e?.scenes)?e.scenes:[],Ta=(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=Pa({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:e.title,match:`Chapter ${a.chapterId}: ${a.title}`,anchorStatus:r,pdChapter:a,wordChapter:e});return Da(n,t),t}const o=Pa({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:`${r} not found`,matches:[],pdChapter:null,wordChapter:e});return Da(n,o),o}const a=t.filter(t=>qa(t.title,"chapter")===qa(e.title,"chapter"));if(1===a.length){const t=Pa({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 Da(n,t),t}if(a.length>1){const t=Pa({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 Da(n,t),t}const o=Pa({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:e.title,anchorStatus:r,pdChapter:null,wordChapter:e});return Da(n,o),o},$a=(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=Aa(n).find(e=>e.sceneId===t);if(e)return{chapter:n,scene:e}}return null})(n,e.anchorId);return o?void Da(r,Pa({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 Da(r,Pa({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 Da(r,Pa({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 Da(r,Pa({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:a,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));const o=Aa(t.pdChapter).filter(t=>qa(t.title,"scene")===qa(e.title,"scene"));1!==o.length?o.length>1?Da(r,Pa({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})):Da(r,Pa({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:a,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:e,parentItem:t})):Da(r,Pa({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}))},Wa=e=>{const t=document.createElement("article");t.className="word-companion-preview-item";const n=document.createElement("strong");n.textContent=`${La[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: ${Na[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},ja=e=>{if(te){te.innerHTML="";for(const t of Ea){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(Wa(e));te.append(n)}sr()}},Ra=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)(ha(e,1)||ha(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=ga(t.items,n.items);return r.bodyParagraphs=t.items,r},Ua=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(Ca),r=[];let a=0,o=0,c=null,i=null,d=0;const s=(e,t=null,n=null)=>c?(ba(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&&(ha(e,1)?(Ia(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,s(e,"Scene 1",e.sceneAnchorId),d+=e.wordCount):c&&(t&&Sa.has(e.text)?(o+=1,s(e)):(c.wordCount+=e.wordCount,i&&(i.wordCount+=e.wordCount),d+=e.wordCount)));return Ia(c,n.length-1),{paragraphs:n,chapters:r,usesExplicitScenes:!!t,paragraphCount:n.length,heading1Count:a,heading2Count:o,documentWordCount:d,currentParagraphIndex:null,currentChapter:null,currentScene:null}})(n.items,t),o=ka(a,r.items);return mn=a,va(o),Vn("Cache rebuilt."),a},Ma=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&&!Sa.has(e)&&t!==o&&(r+=ma(e))}return e.wordCount=r,nr(mn.currentChapter?.title,e.title,r,mn.currentChapter?.anchorId,e.anchorId,mn.currentChapter?.index),r}):Kt},Oa=async()=>{if(Zn(""),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return nr(null,null,null),Zn("Word document access is unavailable."),Fr({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;F&&(F.disabled=!0,F.textContent="Scanning..."),Zn("Scanning document structure...");try{const e=await window.Word.run(async e=>{const t=_r();return t?await Ua(e,!!t.usesExplicitScenes):(mn=null,await Ra(e))});return mn||nr(e.currentChapter?.title,e.currentScene?.title,e.currentScene?.wordCount,e.currentChapter?.anchorId,e.currentScene?.anchorId,e.currentChapter?.index),Dr("Not detected"),xa(e),Zn(""),Fr({lastScan:"Success",lastError:"-",paragraphs:String(e.paragraphCount),heading1:String(e.heading1Count),heading2:String(e.heading2Count)}),!0}catch(e){const t=Vr(e);return console.error("Unable to scan the Word document.",e),nr(null,null,null),Zn(`Unable to scan the Word document: ${t}`),Fr({lastScan:"Failure",lastError:t}),!1}finally{F&&(F.disabled=!1,F.textContent="Refresh Document Structure")}},Ha=async()=>{const e=_r();if(!Zr()||!e)return cr("Select a project and book to analyse manuscript structure."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return cr("Word document access is unavailable."),Fr({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;Z&&(Z.disabled=!0,Z.textContent="Analysing..."),cr("Analysing manuscript structure...");try{const t=await window.Word.run(async e=>await Ra(e)),n=await Ka(`/api/word-companion/books/${e.bookId}/structure`);return nr(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),xa(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=Ta(t,r,n);for(const a of Aa(t))$a(a,e,r,n)}return n})(t,n),ja(un),cr("Preview generated. No changes have been applied."),Fr({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),cr("Unable to analyse manuscript structure."),Fr({lastScan:"Failure",lastError:Vr(e)}),!1}finally{Z&&(Z.textContent="Analyse Manuscript Structure",lr())}},Ba=e=>{En&&(En(e),En=null),ut?.close?ut.close():ut&&(ut.hidden=!0)},Ga=()=>{const e=((e=un)=>{const t=dr(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=>{En=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},Va=e=>Number.isInteger(e?.wordChapter?.index)&&e.wordChapter.index>0?10*e.wordChapter.index:null,Ja=e=>Number.isInteger(e?.wordScene?.index)&&e.wordScene.index>0?10*e.wordScene.index:null,Ya=async(e,t)=>{const n=await Qa(`/api/word-companion/books/${e}/chapters`,{title:Wr(t.wordTitle),sortOrder:Va(t)});if(!n?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");br(),t.pdChapter={chapterId:n.chapterId,title:n.title||t.wordTitle,sortOrder:n.sortOrder||Va(t)||0,scenes:[]},t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},za=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 Qa(`/api/word-companion/books/${e}/chapters/${n.chapterId}/scenes`,{sceneTitle:Wr(t.wordTitle),sortOrder:Ja(t)});if(!r?.sceneId)throw new Error("Scene creation did not return a scene ID.");br(),t.pdChapter=n,t.pdScene={sceneId:r.sceneId,title:t.wordTitle,sortOrder:Ja(t)||0},t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},Ka=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()},Qa=(e,t)=>Ka(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),Xa=async(e="")=>{bn=!1,In=0,Sn=[],k&&(k.innerHTML=""),ar(b,!0),aa(!1),na(""),ar(v,!0),e&&Zn(e);const t=await Za();e&&t&&Yt&&Zn(e)},Za=async()=>{const e=_r();if(!(e&&Gt&&Ft&&window.Word&&"function"==typeof window.Word.run))return!1;Zn("Reading manuscript position...");try{br(),await Ur(e.bookId);const t=await window.Word.run(async t=>await Ua(t,!!e.usesExplicitScenes));return xa(t),Fr({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),Yt?(zt?await fo():await wo(),mr(!1),hr("Live"),Zn(""),!0):(Dr("Not detected"),mr(!1),hr("Live"),Zn("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,hr("Manual"),Zn(`Unable to read manuscript position: ${Vr(e)}`),Fr({lastScan:"Failure",lastError:Vr(e)}),!1}},_a=e=>e?[...e.querySelectorAll("input[type='checkbox']:checked")].map(e=>Number.parseInt(e.value||"",10)).filter(e=>Number.isInteger(e)&&e>0):[],eo=()=>{const e=Number.parseInt(Le?.value||"",10);return Number.isInteger(e)&&e>0?e:null},to=(e,t,n,r)=>{const a=((e,t)=>wa(e).find(e=>ya(e.tag,t))||null)(e,r),o=a||e.getRange().insertContentControl();return o.title=t,o.tag=n,o.appearance="Hidden",o},no=async(e="PlotDirector IDs attached successfully.")=>{if(!_t||!en)return Zn("No resolved PlotDirector scene."),!1;if((Zt&&Zt!==_t||Xt&&Xt!==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 Zn("Word document access is unavailable."),!1;de&&(de.disabled=!0,de.textContent="Attaching...");try{return await window.Word.run(async e=>{const t=await Ra(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.");to(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),to(r,"PlotDirector Scene",`PD-SCENE-${_t}`,"PD-SCENE"),await e.sync()}),Xt=en,Zt=_t,rn=!1,nn="SceneID Anchor",tn="Anchor",Zn(e),Fr({lastError:"-"}),tr(),!0}catch(e){return console.error("Unable to attach PlotDirector IDs.",e),Zn("Unable to attach PlotDirector IDs."),Fr({lastError:Vr(e)}),tr(),!1}finally{de&&(de.textContent=Zt===_t?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",tr())}},ro=async e=>{if(!en)return vr("No resolved PlotDirector chapter."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return vr("Word document access is unavailable."),!1;try{return await window.Word.run(async e=>{const t=await Ra(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.");to(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),await e.sync()}),Xt=en,rn=!1,nn="ChapterID Anchor",tn="Chapter anchor",vr(e),Zn(e),Fr({lastError:"-"}),tr(),!0}catch(e){return console.error("Unable to attach PlotDirector chapter ID.",e),vr("Unable to attach PlotDirector chapter ID."),Fr({lastError:Vr(e)}),tr(),!1}},ao=async e=>{Nr(),await fo(),Zn(e),vr(e)},oo=e=>{ln&&(ln(e),ln=null),ct?.close?ct.close():ct&&(ct.hidden=!0)},co=()=>{if(!nt)return;const e=Wr(tt?.value||"").toLocaleLowerCase(),t=dn.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(nt.innerHTML="",sn=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",()=>{sn=t,rt&&(rt.disabled=!1)});const a=document.createElement("span");a.textContent=e.title||"Untitled chapter",n.append(r,a),nt.append(n)}},io=()=>{et?.close?et.close():et&&(et.hidden=!0)},so=async(e,t,n)=>{const r=_r();if(!r)return kr("Select a PlotDirector book first."),!1;await Br(r.bookId,e,t,"Manual link","Title Match");return!!await no(n)&&(kr(n),qr(),!0)},lo=e=>{cn&&(cn(e),cn=null),Ke?.close?Ke.close():Ke&&(Ke.hidden=!0)},uo=()=>{if(!Ve)return;const e=Wr(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)}},po=()=>{Ge?.close?Ge.close():Ge&&(Ge.hidden=!0)},ho=()=>{Rn=!1,pr(),Un&&(Un=!1,yo(1e3))},mo=async(e={})=>{const t=e.source||"manual";if(!_t)return void or("No resolved PlotDirector scene.");if(!en)return void or("No resolved PlotDirector chapter.");if(Ln)return void or("Refresh Current Scene before syncing.");const n=_r(),r=pn?.documentGuid||sa()?.documentGuid||"";if(!n||!r)return void or("Bound manuscript metadata is unavailable.");if(Rn)return Un=!0,void Vn("Scene sync deferred; sync already running.");rr(),Rn=!0,Un=!1;let a=Kt;try{a=await Ma()}catch(e){return or("Sync failed"),Fr({lastError:Vr(e)}),Vn("Scene sync failed."),void ho()}if(!Number.isInteger(a)||a<0)return or("Sync failed"),Vn("Scene sync failed."),void ho();if(Mn===_t&&On===a)return or("Synced"),Vn("Sync skipped (count unchanged)."),void ho();Vn("Scene word count changed."),ge&&(ge.disabled=!0,ge.textContent="Syncing..."),or("Syncing..."),Vn(`Scene sync started (${t}).`);try{const e=await Qa("/api/word-companion/runtime/scene-word-count",{documentGuid:r,bookId:n.bookId,chapterId:en,sceneId:_t,wordCount:a}),t=e?.actualWords??a,o=new Date;Mn=_t,On=t,Gr(Ce,fr(t)),Gr(he,fr(t)),Gr(be,gr(o)),Gr(fe,gr(o)),or("Synced"),Vn("Scene sync succeeded.")}catch(e){or("Sync failed"),Fr({lastError:Vr(e)}),Vn("Scene sync failed.")}finally{ge&&(ge.textContent="Sync Current Scene"),ho()}},yo=(e=4e3)=>{rr(),_t&&en&&!Ln&&!Rn&&(jn=window.setTimeout(()=>{jn=null,mo({source:"automatic"})},e))},wo=async()=>{const e=Zr(),t=_r(),n=jr(Yt,"chapter");if(Rr({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Xr(t):void 0,detectedChapter:Yt,detectedScene:zt,requestChapter:n,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!t)return Dr("Not detected"),Zn("Select a PlotDirector book first."),!1;if(!Yt)return Dr("Not detected"),Zn("No chapter detected in Word. Use Heading 1 for chapters."),!1;Dr("Not detected");try{const e=await Mr(t.bookId),r=Xt?e.find(e=>e.chapterId===Xt):null,a=n.toLocaleLowerCase(),o=a?e.find(e=>jr(e.title,"chapter").toLocaleLowerCase()===a):null,c=r||o;return c?(Nr(),yr(null,c.chapterId,r?"Chapter anchor":"Chapter title"),nn=r?"ChapterID Anchor":"Title Match",_n("Chapter linked to PlotDirector"),Zn("No scene detected in Word. Use Heading 2 for scenes."),Rr({result:"Chapter matched",chapterId:c.chapterId,sceneId:null}),!0):(yr(null),_n("Chapter not found in PlotDirector."),Zn("Chapter not found in PlotDirector."),Rr({result:"Chapter not matched",chapterId:null,sceneId:null}),Lr("Chapter not found in PlotDirector."),!1)}catch(e){return Dr("Not found in PlotDirector"),Fr({lastError:Vr(e)}),Zn("Unable to load PlotDirector chapter data."),!1}},fo=async()=>{const e=Zr(),t=_r(),n=jr(Yt,"chapter"),r=jr(zt,"scene");if(Rr({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Xr(t):void 0,detectedChapter:Yt,detectedScene:zt,requestChapter:n,requestScene:r,result:"Not run",chapterId:null,sceneId:null}),er({anchorType:Zt?"SceneID Anchor":Xt?"ChapterID Anchor":"Title Match",storedSceneId:Zt,storedChapterId:Xt,resolutionMethod:"-"}),!t)return Dr("Not detected"),Zn("Select a PlotDirector book first."),Rr({result:"Error"}),!1;if(!Yt||!zt)return Dr("Not detected"),Zn("No scene detected in Word. Use Heading 2 for scenes."),Rr({result:"Error"}),!1;ne&&(ne.disabled=!0,ne.textContent="Refreshing...");const a=()=>{ne&&(ne.disabled=!1,ne.textContent="Refresh PlotDirector Scene")};Dr("Not detected"),Zn("Resolving PlotDirector scene...");try{if(Zt){const e=await(async(e,t)=>{const n=await Ka(`/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===Zt);if(e)return Rr({result:"Matched",chapterId:e.chapter.chapterId,sceneId:e.scene.sceneId}),await Br(t.bookId,e.scene.sceneId,e.chapter.chapterId,"Anchor","SceneID Anchor"),!0;rn=!0,nn="SceneID Anchor",_n("Not found in PlotDirector"),Zn("Stored PlotDirector ID is invalid."),Rr({result:"Error",chapterId:Xt,sceneId:Zt}),er({anchorType:"SceneID Anchor",storedSceneId:Zt,storedChapterId:Xt,resolutionMethod:"Anchor"})}if(Xt){const e=(await Ur(t.bookId)).find(e=>e.chapterId===Xt),n=e?(Array.isArray(e.scenes)?e.scenes:[]).find(e=>jr(e.title,"scene").toLocaleLowerCase()===r.toLocaleLowerCase()):null;if(n)return Rr({result:"Matched",chapterId:e.chapterId,sceneId:n.sceneId}),await Br(t.bookId,n.sceneId,e.chapterId,"Anchor","ChapterID Anchor"),!0;e&&!Zt?(nn="ChapterID Anchor",yr(null,Xt,"Chapter anchor"),Rr({result:"Chapter matched",chapterId:Xt,sceneId:null})):Zt||(nn="ChapterID Anchor",Rr({result:"Chapter anchor not found",chapterId:Xt,sceneId:null}))}const e=await Qa(`/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 Dr("Not found in PlotDirector"),rn=t,c&&(yr(null,o,o===r?"Chapter anchor":"Chapter title"),_n("Scene not found in PlotDirector.")),Zn(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."),Rr({result:"Not matched",chapterId:c?o:e?.chapterId,sceneId:e?.sceneId}),t||(c?(Nr(),Pr("Scene not found in PlotDirector.")):(qr(),Lr("Chapter not found in PlotDirector."))),a(),!1}const o=rn;return Rr({result:o?"Matched by title fallback":"Matched",chapterId:e.chapterId,sceneId:e.sceneId}),await Br(t.bookId,e.sceneId,e.chapterId,o?"Title fallback":"Title","Title Match"),o&&(rn=!0,Zn("Stored PlotDirector ID is invalid."),tr()),!0}catch(e){const t=rn;return Fr({lastError:Vr(e)}),Dr("Not found in PlotDirector"),rn=t,Zn(t?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),Rr({result:"Error"}),!1}finally{a()}},go=async()=>{if(qn=null,Wn)return An=!0,void Vn("Runtime update deferred; update already running.");if(!Ot||!_r())return Pn=!1,void Vn("Runtime update skipped.");if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Pn=!1,hr("Manual"),void Zn("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");if(!mn)return Pn=!1,hr("Manual"),void Zn("Document structure is not cached yet. Use Refresh Current Scene.");const e=Date.now()-Dn;if(Pn&&eawait(async e=>{const t=e.document.getSelection().paragraphs;return t.load("text,styleBuiltIn,style"),await e.sync(),t.items})(e)),t=ka(mn,e),n=va(t);if(await Ma(),!n)return mr(!1),hr("Current scene updated"),void yo();zt?await fo():await wo(),mr(!1),hr("Current scene updated"),Zn("Current scene updated."),yo()}catch(e){console.error("Unable to refresh current scene from Word selection.",e),Fr({lastError:Vr(e)}),mr(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving.")}finally{Wn=!1,(An||Pn)&&(An=!1,So(Tn))}},So=(e=1200)=>{qn&&window.clearTimeout(qn),qn=window.setTimeout(go,Math.max(0,e)),hr("Waiting for typing to pause"),Vn("Runtime update scheduled.")},Co=()=>{((e="selection",t=1200)=>{if(Pn=!0,Dn=Date.now(),rr(),Vn(`${e} changed.`),Wn)return An=!0,void hr("Waiting for typing to pause");So(t)})("Selection")},bo=()=>{if($n&&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:Co}),$n=!1}catch(e){console.warn("Unable to remove Word selection tracking handler.",e)}},Io=async(e,n)=>{if(mn=null,br(),!e)return Bt=[],Kr(O,"Select a project first"),Kr(m,"Select a project first"),Xn(""),zr(t,null),ua(),Dr("Not detected"),void ir();Kr(O,"Loading books..."),Xn(""),Dr("Not detected"),ir("Select a book to analyse manuscript structure.");try{const r=await Ka(`/api/word-companion/projects/${e}/books`);if(Bt=Array.isArray(r.books)?r.books:[],0===Bt.length)return Kr(O,"No books available."),Kr(m,"No books available."),Xn("No books available."),zr(t,null),ua(),void ca("No books available.");Qr(O,"Choose a book",Bt.map(e=>({...e,displayTitle:Xr(e)})),"bookId","displayTitle");const a=Bt.find(e=>e.bookId===n);a&&O?(O.value=String(a.bookId),zr(t,a.bookId)):zr(t,null),((e=null)=>{if(!m)return;if(0===Bt.length)return void Kr(m,"No books available.");Qr(m,"Choose a book",Bt.map(e=>({...e,displayTitle:Xr(e)})),"bookId","displayTitle");const t=e||Number.parseInt(O?.value||"",10),n=Bt.find(e=>e.bookId===t);n&&(m.value=String(n.bookId)),ra()})(a?.bookId||n),ua(),Dr((_r(),"Not detected")),ir(_r()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),ca(ta()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{Bt=[],Kr(O,"Unable to load books."),Kr(m,"Unable to load books."),Xn("Unable to load books."),zr(t,null),ua(),Dr("Not detected"),ir("Unable to load books."),ca("Unable to load books.")}};for(const e of l)e.addEventListener("click",()=>Yn(e.dataset.tabButton));zn(),M?.addEventListener("change",async()=>{const n=Number.parseInt(M.value||"",10);Cr(),h&&Number.isInteger(n)&&n>0&&(h.value=String(n)),zr(e,Number.isInteger(n)&&n>0?n:null),zr(t,null),Dr("Not detected"),ir(),ca("Select a Book to begin."),await Io(n,null)}),O?.addEventListener("change",()=>{const e=Number.parseInt(O.value||"",10);Cr(),zr(t,Number.isInteger(e)&&e>0?e:null),m&&Number.isInteger(e)&&e>0&&(m.value=String(e)),ua(),Dr("Not detected"),ir(_r()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),ca(ta()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),h?.addEventListener("change",async()=>{const n=Number.parseInt(h.value||"",10);Cr(),M&&Number.isInteger(n)&&n>0&&(M.value=String(n)),zr(e,Number.isInteger(n)&&n>0?n:null),zr(t,null),ca("Select a Book to begin."),await Io(n,null)}),m?.addEventListener("change",()=>{const e=Number.parseInt(m.value||"",10);Cr(),O&&Number.isInteger(e)&&e>0&&(O.value=String(e)),zr(t,Number.isInteger(e)&&e>0?e:null),ua(),ca(ta()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),y?.addEventListener("input",ra),w?.addEventListener("click",async()=>{const e=ea(),t=String(y?.value||"").trim();if(e&&t){w.disabled=!0,na("Creating Book...");try{const n=await Qa(`/api/word-companion/projects/${e.projectId}/books`,{title:t});y&&(y.value=""),M&&(M.value=String(e.projectId)),await Io(e.projectId,n.bookId),m&&(m.value=String(n.bookId)),na("Ready to scan manuscript structure.")}catch(e){console.error("Unable to create Book from Word Companion.",e),na(`Unable to create Book: ${Vr(e)}`)}finally{ra()}}else ra()}),f?.addEventListener("click",async()=>{const e=ea(),t=ta();if(e&&t)if(Gt&&Ft&&window.Word&&"function"==typeof window.Word.run){f&&(f.disabled=!0,f.textContent="Scanning..."),na("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(["***","###"]),d=()=>{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 s=String(e.text||"").trim();if(!s)return;if(c.push(s),ha(e,1))return r={title:s,sortOrder:10*(n.length+1),wordCount:0,scenes:[]},n.push(r),a=d(),void(o+=ma(s));if(!r||!a)return;if(t&&i.has(s))return void(a=d());const l=ma(s);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)});gn=n,Cn=!1;const r=await Qa("/api/word-companion/manuscript/analyse",{projectId:e.projectId,bookId:t.bookId,documentGuid:la(),chapterCount:n.chapterCount,sceneCount:n.sceneCount,wordCount:n.wordCount});fn=r,(e=>{if(!C)return;C.innerHTML="";const t=document.createElement("strong");t.textContent="Manuscript Analysis",C.append(t);const n=document.createElement("dl"),r=[["Project",e.projectTitle],["Book",Xr({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)}C.append(n),ar(C,!1),ar(L,!1),na(e.message||"Preview generated."),ra()})(r);try{const t=await Qa("/api/word-companion/manuscript/discover-characters",{projectId:e.projectId,documentText:n.documentText||""});Sn=Array.isArray(t?.candidates)?t.candidates:[],ar(b,!0),ar(v,!0)}catch(e){console.error("Unable to discover character candidates.",e),Sn=[],ar(b,!0),ar(v,!0)}Fr({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(n.chapterCount),heading2:"-"})}catch(e){console.error("Unable to scan manuscript for first-run import.",e),ca(`Unable to scan manuscript: ${Vr(e)}`),Fr({lastScan:"Failure",lastError:Vr(e)})}finally{f&&(f.textContent="Scan Manuscript"),ra()}}else ca("Word document access is unavailable.");else ca("Select a Project and Book to begin.")}),q?.addEventListener("click",async()=>{const n=ea(),i=ta();if(!(n&&i&&gn&&fn?.canImport))return void ra();let d=!1;if(!fn.requiresReplaceConfirmation||(d=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),T?.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),T?.addEventListener("click",r),D?.addEventListener("cancel",a),D.showModal()}),d)){kn=!0,ra(),na("Importing manuscript structure...");try{const l=la(),u=await Qa("/api/word-companion/manuscript/import",{projectId:n.projectId,bookId:i.bookId,documentGuid:l,bindingVersion:1,replacePlanned:d,chapters:gn.chapters});if(!u.imported)return fn={...fn,canImport:!u.requiresReplaceConfirmation,requiresReplaceConfirmation:!!u.requiresReplaceConfirmation,message:u.message||fn.message},na(u.message||"Import was not completed."),void ra();const p=u.manuscriptDocument;await(s={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,s.documentGuid),n.set(a,String(s.bookId)),n.set(o,String(s.projectId)),n.set(c,String(s.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},zr(e,u.projectId),zr(t,u.bookId),M&&(M.value=String(u.projectId));const h=Sn;await Io(u.projectId,u.bookId),Kn("Connected"),Cn=!0,bn=h.length>0,In=bn?Date.now():0,Sn=h,h.length>0?(aa(!0),da(h),ar(L,!0),ar(v,!1),na(u.message||"Manuscript structure imported."),Zn(u.message||"Manuscript structure imported."),window.setTimeout(ra,750)):await Xa(u.message||"Manuscript structure imported.")}catch(e){console.error("Unable to import manuscript structure.",e),na(`Unable to import manuscript: ${Vr(e)}`)}finally{kn=!1,ra()}var s}else na("Import cancelled.")}),x?.addEventListener("click",async()=>{const e=ea()||Zr(),t=ia();if(!bn||Date.now()-In<750||!e||0===t.length)ra();else{vn=!0,ra(),Gr(I,"Creating selected characters...");try{const n=await Qa("/api/word-companion/manuscript/create-discovered-characters",{projectId:e.projectId,candidateNames:t});Zn(n.message||"Characters created."),Gr(I,`${n.createdCount||0} created, ${n.skippedCount||0} already existed.`),await Xa(n.message||"Characters created.")}catch(e){console.error("Unable to create discovered characters.",e),Gr(I,`Unable to create characters: ${Vr(e)}`)}finally{vn=!1,ra()}}}),E?.addEventListener("click",()=>Xa("Character creation skipped.")),N?.addEventListener("click",()=>Xa()),g?.addEventListener("click",()=>aa(!1)),P?.addEventListener("click",()=>ca("Import cancelled.")),F?.addEventListener("click",Oa),Z?.addEventListener("click",Ha),_?.addEventListener("click",async()=>{const e=_r();if(!e||0===dr().length||xn)return void sr();if(!await Ga())return;xn=!0,lr(),cr("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=dr().filter(e=>"couldLink"===e.category&&"Chapter"===e.type),r=dr().filter(e=>"wouldCreateChapters"===e.category),a=dr().filter(e=>"couldLink"===e.category&&"Scene"===e.type),o=dr().filter(e=>"wouldCreateScenes"===e.category),c=[];let i="";const d=(e,t)=>{c.push({item:e,counterName:t})},s=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 Ra(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.");to(a,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=e.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");to(a,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()})})(e),Fa(e,"Success"),t[n]+=1}catch(n){Fa(e,"Failed",Vr(n)),t.failed+=1}};try{for(const e of n)d(e,"linkedChapters");for(const n of r)try{await Ya(e.bookId,n),d(n,"createdChapters")}catch(e){Fa(n,"Failed",Vr(e)),t.failed+=1}for(const e of a)d(e,"linkedScenes");for(const n of o)try{await za(e.bookId,n),d(n,"createdScenes")}catch(e){Fa(n,"Failed",Vr(e)),t.failed+=1}for(const e of c)await s(e.item,e.counterName);for(const e of un.manualReview||[])Fa(e,"Skipped");ja(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),cr(i)}finally{xn=!1,lr(),i&&(br(),await Ha(),cr(`${i} Preview refreshed.`))}}),ht?.addEventListener("click",()=>Ba(!0)),mt?.addEventListener("click",()=>Ba(!1)),ut?.addEventListener("cancel",e=>{e.preventDefault(),Ba(!1)}),ne?.addEventListener("click",fo),G?.addEventListener("click",async()=>{if(!_r())return Zn("Select a PlotDirector book first."),void Dr("Not detected");qn&&(window.clearTimeout(qn),qn=null),Pn=!1,An=!1,wr(!0),hr("Updating...");try{if(!await Oa())return;if(mr(!1),!zt)return await wo(),void hr("Current scene updated");await fo(),hr("Current scene updated")}finally{wr(!1)}}),ge?.addEventListener("click",()=>mo({source:"manual"})),qe?.addEventListener("click",async()=>{if(_t)if(!Ln&&await(async()=>{if(!_t)return!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return mr(!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 Ra(e)),t=e.currentChapter?.title||"",n=e.currentScene?.title||"",r=e.currentScene?.anchorId||null,a=e.currentChapter?.anchorId||null,o=Number.isInteger(r)&&r===_t,c=Number.isInteger(a)&&a===en,i=jr(n,"scene").toLocaleLowerCase()===jr(Hn||zt,"scene").toLocaleLowerCase(),d=jr(t,"chapter").toLocaleLowerCase()===jr(Bn||Yt,"chapter").toLocaleLowerCase();return o||i&&(c||d)?(mr(!1),!0):(mr(!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),Fr({lastError:Vr(e)}),mr(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1}})()){qe&&(qe.disabled=!0,qe.textContent="Saving...");try{await(e=`/api/word-companion/scenes/${_t}/links`,t={characterIds:_a(Ee),assetIds:_a(Ne),locationIds:[],primaryLocationId:eo()},Ka(e,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})),(()=>{const e=new Set(_a(Ee)),t=new Set(_a(Ne));Fn={characters:Fn.characters.map(t=>({...t,linked:e.has(Number.parseInt(Ar(t,"character"),10))})),assets:Fn.assets.map(e=>({...e,linked:t.has(Number.parseInt(Ar(e,"asset"),10))})),locations:Fn.locations,primaryLocationId:eo()}})(),Ir("Scene links saved successfully."),Fr({lastError:"-"})}catch(e){Ir("Unable to save scene links."),Fr({lastError:Vr(e)})}finally{qe&&(qe.disabled=!_t||Ln,qe.textContent="Save Scene Links")}var e,t}else Ir("The Word cursor is now in a different scene. Refresh Current Scene before saving.");else Ir("Link a PlotDirector scene first.")}),de?.addEventListener("click",async()=>{await no()}),$e?.addEventListener("click",async()=>{const e=_r();if(!e||!Yt||en)return void Lr("Chapter not found in PlotDirector.");const t=Wr(Yt),n=await((e,t)=>(Gr(it,`"${e}"`),Gr(dt,`"${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,Xr(e)||"selected book");if(n){$e&&($e.disabled=!0,$e.textContent="Creating...");try{const n=Number.isInteger(Qt)&&Qt>0?10*Qt:null,r=await Qa(`/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.");br(),yr(null,r.chapterId,"Manual chapter link");if(!await ro("Chapter created and linked successfully."))return;await ao("Chapter created and linked successfully.")}catch(e){vr("Unable to create chapter."),Fr({lastError:Vr(e)})}finally{$e&&($e.disabled=!xr(),$e.textContent="Create Chapter in PlotDirector")}}}),We?.addEventListener("click",async()=>{const e=_r();if(e&&Yt&&!en){We&&(We.disabled=!0,We.textContent="Loading...");try{dn=await Mr(e.bookId),sn=null,tt&&(tt.value=""),Gr(ot,""),co(),et?.showModal?et.showModal():et&&(et.hidden=!1)}catch(e){vr("Unable to load chapters."),Fr({lastError:Vr(e)})}finally{We&&(We.disabled=!xr(),We.textContent="Link to Existing Chapter")}}else Lr("Chapter not found in PlotDirector.")}),tt?.addEventListener("input",co),rt?.addEventListener("click",async()=>{const e=dn.find(e=>e.chapterId===sn);if(e){rt&&(rt.disabled=!0,rt.textContent="Linking...");try{yr(null,e.chapterId,"Manual chapter link");if(!await ro("Chapter linked successfully."))return;io(),await ao("Chapter linked successfully.")}catch(e){Gr(ot,"Unable to link chapter."),vr("Unable to link chapter."),Fr({lastError:Vr(e)})}finally{rt&&(rt.disabled=!sn,rt.textContent="Link Chapter")}}else Gr(ot,"Select a chapter.")}),at?.addEventListener("click",io),st?.addEventListener("click",()=>oo(!0)),lt?.addEventListener("click",()=>oo(!1)),ct?.addEventListener("cancel",e=>{e.preventDefault(),oo(!1)}),Oe?.addEventListener("click",async()=>{const e=_r();if(!e||!zt)return void Pr("Scene not found in PlotDirector.");const t=jr(zt,"scene"),n=jr(Yt,"chapter"),r=await((e,t)=>(Gr(Qe,`"${e}"`),Gr(Xe,`"${t}"`),Ke?new Promise(e=>{cn=e,Ke.showModal?Ke.showModal():Ke.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 Hr();if(!n)return void Pr("This chapter does not exist in PlotDirector. Create or link the chapter first.");const r=await Qa(`/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.");br(),await so(r.sceneId,r.chapterId,"Scene created and linked successfully.")}catch(e){kr("Unable to create scene."),Fr({lastError:Vr(e)})}finally{Oe&&(Oe.disabled=!Er(),Oe.textContent="Create Scene in PlotDirector")}}}),He?.addEventListener("click",async()=>{const e=_r();if(e&&zt){He&&(He.disabled=!0,He.textContent="Loading...");try{const t=await Ur(e.bookId),n=Or(t);if(!n)return void Pr("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=""),Gr(ze,""),uo(),Ge?.showModal?Ge.showModal():Ge&&(Ge.hidden=!1)}catch(e){kr("Unable to load scenes."),Fr({lastError:Vr(e)})}finally{He&&(He.disabled=!Er(),He.textContent="Link to Existing Scene")}}else Pr("Scene not found in PlotDirector.")}),Fe?.addEventListener("input",uo),Je?.addEventListener("click",async()=>{const e=_r(),t=an.find(e=>e.sceneId===on);if(e&&t){Je&&(Je.disabled=!0,Je.textContent="Linking...");try{const e=await Hr();if(!e)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");po(),await so(t.sceneId,e.chapterId,"Scene linked successfully.")}catch(e){Gr(ze,"Unable to link scene."),kr("Unable to link scene."),Fr({lastError:Vr(e)})}finally{Je&&(Je.disabled=!on,Je.textContent="Link Scene")}}else Gr(ze,"Select a scene.")}),Ye?.addEventListener("click",po),Ze?.addEventListener("click",()=>lo(!0)),_e?.addEventListener("click",()=>lo(!1)),Ke?.addEventListener("cancel",e=>{e.preventDefault(),lo(!1)}),Et?.addEventListener("click",async()=>{Et&&(Et.disabled=!0,Et.textContent="Running...");try{if(await Jr(),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return void Fr({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});Fr({lastScan:"Success",lastError:"-",paragraphs:String(e)})}catch(e){console.error("Word Companion diagnostics failed.",e);const t=Vr(e);Fr({lastScan:"Failure",lastError:t}),Zn(`Unable to scan the Word document: ${t}`)}finally{Et&&(Et.disabled=!1,Et.textContent="Run Diagnostics")}});const ko=Ot?(async()=>{Kr(M,"Loading projects..."),Kr(O,"Select a project first"),Kr(h,"Loading projects..."),Kr(m,"Select a project first"),Qn(""),Xn("");try{const n=await Ka("/api/word-companion/projects");if(Ht=Array.isArray(n.projects)?n.projects:[],0===Ht.length)return Kr(M,"No projects available."),Kr(h,"No projects available."),Qn("No projects available."),zr(e,null),zr(t,null),ua(),void ca("No projects available.");Qr(M,"Choose a project",Ht,"projectId","title"),oa();const r=Yr(e),a=Ht.find(e=>e.projectId===r);a&&M?(M.value=String(a.projectId),h&&(h.value=String(a.projectId)),zr(e,a.projectId),await Io(a.projectId,Yr(t))):(zr(e,null),zr(t,null),ua(),ca("Select a Project and Book to begin."))}catch{Ht=[],Bt=[],Kr(M,"Unable to connect to PlotDirector."),Kr(O,"Select a project first"),Kr(h,"Unable to connect to PlotDirector."),Kr(m,"Select a project first"),Kn("Unable to connect to PlotDirector."),Qn("Unable to connect to PlotDirector."),zr(e,null),zr(t,null),ua(),ca("Unable to connect to PlotDirector.")}})():Promise.resolve();if(Ot||(Kr(M,"Please sign in to PlotDirector."),Kr(O,"Please sign in to PlotDirector."),Kr(h,"Please sign in to PlotDirector."),Kr(m,"Please sign in to PlotDirector."),ua()),!window.Office||"function"!=typeof window.Office.onReady)return Jn("Word Companion ready"),Zn("Word document access is unavailable."),hr("Manual"),void Fr({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"});Jr().then(async()=>{Jn("Word Companion ready"),await ko,await(async()=>{if(!Ot||!Ft)return void aa(!1);const n=sa();if(n)try{const r=await Ka(`/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,Sr(r),zr(e,r.projectId),zr(t,r.bookId),M&&(M.value=String(r.projectId)),await Io(r.projectId,r.bookId),aa(!1),Kn("Connected"),Xn("Bound manuscript detected."),void await Za()}catch{}pn=null,Cr(),oa(),ea()?await Io(ea().projectId,null):Kr(m,"Select a project first"),ca("Select a Project and Book to begin."),aa(!0)})(),Ft?(()=>{if(Ot){if(!window.Office?.context?.document||"function"!=typeof window.Office.context.document.addHandlerAsync||!window.Office?.EventType?.DocumentSelectionChanged)return hr("Manual"),void Zn("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");try{window.Office.context.document.addHandlerAsync(window.Office.EventType.DocumentSelectionChanged,Co,e=>{e?.status===window.Office.AsyncResultStatus.Succeeded?($n=!0,hr("Live")):(hr("Manual"),Zn("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))}),window.addEventListener("beforeunload",bo)}catch(e){console.warn("Unable to register Word selection tracking handler.",e),hr("Manual"),Zn("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}})():(Zn("Word document access is unavailable."),hr("Manual"))}).catch(e=>{console.error("Office readiness check failed.",e),Kn("Unable to connect to PlotDirector."),Jn("Word Companion unavailable"),Zn("Word document access is unavailable."),Fr({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",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]"),f=document.querySelector("[data-first-run-scan]"),g=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]"),E=document.querySelector("[data-first-run-skip-characters]"),N=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]"),T=document.querySelector("[data-first-run-replace-cancel]"),$=document.querySelector("[data-office-status]"),j=document.querySelector("[data-connection-status]"),W=document.querySelector("[data-summary-connection]"),R=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]"),fe=document.querySelector("[data-runtime-last-sync]"),ge=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]"),Ee=document.querySelector("[data-character-chips]"),Ne=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]"),Te=document.querySelector("[data-chapter-create-link-chapter]"),$e=document.querySelector("[data-create-plotdirector-chapter]"),je=document.querySelector("[data-link-existing-chapter]"),We=document.querySelector("[data-chapter-create-link-status]"),Re=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]"),ft=document.querySelector("[data-resolve-book-id]"),gt=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]"),Et=document.querySelector("[data-run-diagnostics]"),Nt=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]"),Tt=document.querySelector("[data-diagnostic-anchor-type]"),$t=document.querySelector("[data-diagnostic-stored-scene-id]"),jt=document.querySelector("[data-diagnostic-stored-chapter-id]"),Wt=document.querySelector("[data-diagnostic-resolution-method]"),Rt=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,fn=null,gn=null,Sn=[],In=!1,Cn=!1,bn=0,kn=!1,vn=!1,xn=!1,En=null,Nn="Manual",Ln=!1,Pn=null,qn=!1,Dn=0,An=!1;const Tn=1200;let $n=!1,jn=!1,Wn=null,Rn=!1,Un=!1,Mn=null,On=null,Hn=null,Bn=!1,Gn=!1,Fn=null,Vn="",Jn=[],Yn=null,_n="",zn="",Kn="",Qn=0,Xn={characters:[],assets:[],locations:[],primaryLocationId:null};const Zn=e=>{const t=Date.now();t-Qn<1e3||(Qn=t,console.debug(`[Word Companion Runtime] ${e}`))},er=e=>{$&&($.textContent=e)},tr=(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)},nr=()=>{const e=(e=>{try{return window.localStorage.getItem(e)||""}catch{return""}})(n);tr(i.has(e)?e:"scene",!1)},rr=e=>{j&&(j.textContent=e),W&&(W.textContent=e)},ar=e=>{H&&(H.textContent=e)},or=e=>{B&&(B.textContent=e)},cr=e=>{z&&(z.textContent=e)},ir=e=>{re&&(re.textContent=e)},sr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("anchorType")&&Qr(Tt,xr(e.anchorType)),t("storedSceneId")&&Qr($t,xr(e.storedSceneId)),t("storedChapterId")&&Qr(jt,xr(e.storedChapterId)),t("resolutionMethod")&&Qr(Wt,xr(e.resolutionMethod))},dr=()=>{const e=ia(),t=Number.isInteger(Zt)&&Zt>0&&Xt===Zt,n=!Number.isInteger(en)||en<=0||Qt===en,r=t&&n;Qr(ae,r?"Attached to PlotDirector":"Not attached"),Qr(oe,e?.bookId?String(e.bookId):"-"),Qr(ce,Number.isInteger(en)&&en>0?String(en):"-"),Qr(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})},lr=(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):"-"),Qr(Se,Number.isInteger(n)?String(n):"-"),dr())},ur=()=>{Wn&&(window.clearTimeout(Wn),Wn=null)},pr=(e,t)=>{e&&(e.hidden=t)},hr=e=>{Qr(be,e)},mr=e=>{Qr(ee,e)},yr=(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)}mr(e),fr()},wr=(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),fr=()=>{Z&&(Z.disabled=xn||0===wr().length)},gr=()=>{X&&(X.disabled=xn||!ca()||!ia()),fr()},Sr=()=>{De&&(De.textContent=Zt?`Editing links for: ${zn||_t||"Current scene"}`:"Link a PlotDirector scene first.")},Ir=()=>{const e=Ln||!Zt,t=e||!en||Rn;ge&&(ge.disabled=t),Pe&&(Pe.disabled=e),Le&&(Le.disabled=e);for(const t of[Ee,Ne])for(const n of t?[...t.querySelectorAll("input[type='checkbox']")]:[])n.disabled=e},Cr=e=>{"Live"!==e&&"Manual"!==e||(Nn=e),Qr(_,e||Nn||"Manual")},br=(e,t="")=>{Ln=!!e,Ln&&(ur(),Eo()),Qr(_,Ln?"Stale":Nn),Ir(),t&&(cr(t),qr(t))},kr=(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||(ur(),Eo()),Ir(),hr(Ln?"Refresh Current Scene before syncing.":Zt?"Ready to sync.":"No resolved PlotDirector scene."),qr(Ln?"Refresh Current Scene before saving.":Zt?"Ready to save.":"Link a PlotDirector scene first."),Sr(),dr()},vr=e=>{G&&(G.disabled=e,G.textContent=e?"Refreshing...":"Refresh Current Scene")},xr=e=>null==e||""===e?"-":String(e),Er=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"})}`},Nr=e=>{hn=e||null;const t=hn?.lastSyncUtc||hn?.manuscriptDocument?.lastSyncUtc;Qr(fe,Er(t)),Qr(Ce,Er(t))},Lr=()=>{mn=null,yn=null,wn=null,No(),Nr(null)},Pr=()=>{yn=null,wn=null},qr=e=>{Qr(qe,e)},Dr=e=>{Qr(Be,e)},Ar=e=>{Qr(We,e)},Tr=()=>!!ia()&&!!Yt&&!en,$r=()=>!!ia()&&!!_t&&Number.isInteger(en)&&en>0,jr=()=>{pr(Ae,!0),Ar(""),$e&&($e.disabled=!0,$e.textContent="Create Chapter in PlotDirector"),je&&(je.disabled=!0,je.textContent="Link to Existing Chapter")},Wr=(e="")=>{Qr(Te,xr(Yt)),pr(Ae,!1),Ar(e);const t=Tr();$e&&($e.disabled=!t,$e.textContent="Create Chapter in PlotDirector"),je&&(je.disabled=!t,je.textContent="Link to Existing Chapter")},Rr=()=>{pr(Re,!0),Dr(""),Oe&&(Oe.disabled=!0,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!0,He.textContent="Link to Existing Scene")},Ur=(e="")=>{Qr(Ue,xr(Yt)),Qr(Me,xr(_t)),pr(Re,!1),Dr(e);const t=$r();Oe&&(Oe.disabled=!t,Oe.textContent="Create Scene in PlotDirector"),He&&(He.disabled=!t,He.textContent="Link to Existing Scene")},Mr=e=>{ir(e),pr(de,!0),pr(ke,!0),pr(xe,!1),jr(),Rr(),tn="",zn="",Kn="",nn=Xt?"SceneID Anchor":Qt?"ChapterID Anchor":"Title Match",rn=!1,Xn={characters:[],assets:[],locations:[],primaryLocationId:null},Hr(Ee,[],"character"),Hr(Ne,[],"asset"),Br([],null,!1),kr(null),Qr(Ie,"-"),Qr(le,"-"),Qr(ue,"-"),Qr(pe,"-"),Qr(he,"-"),Qr(me,"-"),Qr(we,"-"),pr(ye,!0),dr(),Sr()},Or=(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,Hr=(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(Or(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)}},Br=(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(Or(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},Gr=e=>String(e||"").trim().replace(/\s+/g," "),Fr=(e,t)=>{const n=Gr(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 Gr(n.replace(r,""))||n},Vr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("projectId")&&Qr(yt,xr(e.projectId)),t("projectTitle")&&Qr(wt,xr(e.projectTitle)),t("bookId")&&Qr(ft,xr(e.bookId)),t("bookTitle")&&Qr(gt,xr(e.bookTitle)),t("detectedChapter")&&Qr(St,xr(e.detectedChapter)),t("detectedScene")&&Qr(It,xr(e.detectedScene)),t("requestChapter")&&Qr(Ct,xr(e.requestChapter)),t("requestScene")&&Qr(bt,xr(e.requestScene)),t("result")&&Qr(kt,xr(e.result)),t("chapterId")&&Qr(vt,xr(e.chapterId)),t("sceneId")&&Qr(xt,xr(e.sceneId))},Jr=async e=>{if(wn===e&&Array.isArray(yn?.chapters))return yn.chapters;const t=await oo(`/api/word-companion/books/${e}/structure`);return wn=e,yn=t||null,Array.isArray(t?.chapters)?t.chapters:[]},Yr=async e=>{const t=await oo(`/api/word-companion/books/${e}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},_r=e=>{if(Number.isInteger(en)&&en>0){const t=e.find(e=>e.chapterId===en);if(t)return t}const t=Fr(Yt,"chapter").toLocaleLowerCase();return t&&e.find(e=>Fr(e.title,"chapter").toLocaleLowerCase()===t)||null},zr=async()=>{const e=ia();return e?_r(await Jr(e.bookId)):null},Kr=async(e,t,n,r,a)=>{const o=await oo(`/api/word-companion/scenes/${t}/companion`);try{o.revisionStatus=await(async(e,t)=>{const n=await oo(`/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,br(!1),ir("Linked to PlotDirector"),cr(""),jr(),Rr(),kr(t,n,r),c=o,zn=c?.sceneTitle||_t||"",Kn=c?.chapterTitle||Yt||"",Qr(le,xr(c?.sceneTitle)),Qr(ue,xr(c?.revisionStatus||c?.revisionStatusName||"Not provided")),Qr(pe,xr(c?.estimatedWords)),Qr(he,xr(c?.actualWords)),Qr(Ie,xr(c?.actualWords)),Qr(me,c?.blocked?"Blocked":"Not blocked"),c?.blockedReason?(Qr(we,c.blockedReason),pr(ye,!1)):(Qr(we,"-"),pr(ye,!0)),ve&&(ve.textContent=c?.writingBrief||"No writing brief has been added for this scene."),Xn={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},Hr(Ee,Xn.characters,"character",!!Zt&&!Ln),Hr(Ne,Xn.assets,"asset",!!Zt&&!Ln),Br(Xn.locations,Xn.primaryLocationId,!!Zt&&!Ln),Sr(),qr(Ln?"Refresh Current Scene before saving.":Zt?"Ready to save.":"No resolved PlotDirector scene."),pr(de,!1),pr(ke,!1),pr(xe,!1),xo(),Do()},Qr=(e,t)=>{if(e){const n=null==t?"":String(t);e.textContent!==n&&(e.textContent=n)}},Xr=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("host")&&Qr(Nt,e.host),t("platform")&&Qr(Lt,e.platform),t("ready")&&Qr(Pt,e.ready),t("wordApi")&&Qr(qt,e.wordApi),t("lastScan")&&Qr(Dt,e.lastScan),t("lastError")&&Qr(At,e.lastError),t("paragraphs")&&Qr(Rt,e.paragraphs),t("heading1")&&Qr(Ut,e.heading1),t("heading2")&&Qr(Mt,e.heading2)},Zr=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)},ea=async()=>{if(!window.Office||"function"!=typeof window.Office.onReady)return Gt=!1,Ft=!1,Vt="Unavailable",Jt="Unavailable",Xr({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,Xr({host:Vt,platform:Jt,ready:"Yes",wordApi:Ft?"Yes":"No"}),e},ta=e=>{try{const t=window.localStorage.getItem(e),n=Number.parseInt(t||"",10);return Number.isInteger(n)&&n>0?n:null}catch{return null}},na=(e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}},ra=(e,t)=>{if(!e)return;e.innerHTML="";const n=document.createElement("option");n.value="",n.textContent=t,e.append(n),e.disabled=!0},aa=(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},oa=e=>{const t=String(e?.title||"").trim(),n=String(e?.subtitle||"").trim();return n?`${t}: ${n}`:t},ca=()=>{const e=Number.parseInt(M?.value||"",10);return Ht.find(t=>t.projectId===e)||null},ia=()=>{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},da=()=>{const e=Number.parseInt(m?.value||"",10);return Bt.find(t=>t.bookId===e)||null},la=e=>Qr(S,e),ua=()=>{const e=sa(),t=da(),n=Cn&&Date.now()-bn>=750;f&&(f.disabled=!e||!t||kn),w&&(w.disabled=!e||!String(y?.value||"").trim()||kn),P&&(P.disabled=!fn?.canImport||!gn||kn),x&&(x.disabled=!n||vn||0===ya().length)},pa=e=>{pr(p,!e),pr(d,e);for(const t of u)pr(t,!!e||"scene"!==t.dataset.tabPanel&&!t.classList.contains("is-active"));e||nr()},ha=()=>{if(!h)return;if(0===Ht.length)return void ra(h,"No projects available.");aa(h,"Choose a project",Ht,"projectId","title");const e=Number.parseInt(M?.value||"",10);Number.isInteger(e)&&e>0&&(h.value=String(e))},ma=(e="Select a Project and Book to begin.")=>{fn=null,gn=null,Sn=[],In=!1,Cn=!1,bn=0,pr(I,!0),pr(L,!0),pr(C,!0),pr(v,!0),I&&(I.innerHTML=""),k&&(k.innerHTML=""),Qr(b,""),la(e),ua()},ya=()=>k?[...k.querySelectorAll("input[type='checkbox']:checked")].map(e=>String(e.value||"").trim()).filter(Boolean):[],wa=e=>{if(Sn=Array.isArray(e)?e:[],C&&k){if(k.innerHTML="",pr(C,!1),pr(v,!In||0===Sn.length),pr(x,!1),pr(E,!1),pr(N,!0),0===Sn.length)return Qr(b,"No likely major characters found."),void ua();Qr(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",ua);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)}ua()}},fa=()=>{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}},ga=()=>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)),Sa=()=>pn?.documentGuid||fa()?.documentGuid||"",Ia=()=>{const e=ca(),t=ia();R&&(R.textContent=e?.title||"(Not connected)"),U&&(U.textContent=t?oa(t):"(Not connected)"),K&&(K.textContent=t?"":"Select a PlotDirector book before refreshing."),gr()},Ca=e=>String(e?.styleBuiltIn||e?.style||"").replace(/\s+/g,"").toLowerCase(),ba=(e,t)=>{const n=Ca(e);return n===`heading${t}`||n.endsWith(`.heading${t}`)||n.includes(`heading${t}`)},ka=e=>String(e||"").trim().split(/\s+/).filter(Boolean).length,va=(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},xa=e=>{try{return Array.isArray(e?.contentControls?.items)?e.contentControls.items:[]}catch(e){return console.warn("Word paragraph content controls were not available.",e),[]}},Ea=(e,t)=>{const n=xa(e);for(const e of n){const n=va(e.tag,t);if(n)return n}return null},Na=(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(ba(e,1))return r+=1,o={index:n.length+1,paragraphIndex:t,title:i,anchorId:Ea(e,"PD-CHAPTER"),scenes:[]},n.push(o),void(c=null);if(ba(e,2)){if(a+=1,!o)return;return c={index:o.scenes.length+1,paragraphIndex:t,title:i,anchorId:Ea(e,"PD-SCENE"),wordCount:0},void o.scenes.push(c)}c&&(c.wordCount+=ka(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()&&Ca(t)===Ca(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}},La=new Set(["***","###"]),Pa=(e,t)=>{const n=String(e?.text||"").trim();return{index:t,text:n,styleBuiltIn:e?.styleBuiltIn||"",style:e?.style||"",wordCount:ka(n),chapterAnchorId:null,sceneAnchorId:null}},qa=(e,t)=>{e&&(e.endParagraphIndex=t)},Da=(e,t)=>{e&&(e.endParagraphIndex=t,qa(e.scenes.at(-1),t))},Aa=(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()&&Ca(e)===Ca(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&&(lr(t?.title,n?.title,n?.wordCount,t?.anchorId,n?.anchorId,t?.index),r)},$a=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"}],Wa={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},Ra={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},Ua=(e,t)=>Fr(e,t).toLocaleLowerCase(),Ma=({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:""}),Oa=(e,t)=>{Array.isArray(e[t.category])&&e[t.category].push(t)},Ha=e=>Array.isArray(e?.scenes)?e.scenes:[],Ba=(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=Ma({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:e.title,match:`Chapter ${a.chapterId}: ${a.title}`,anchorStatus:r,pdChapter:a,wordChapter:e});return Oa(n,t),t}const o=Ma({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:`${r} not found`,matches:[],pdChapter:null,wordChapter:e});return Oa(n,o),o}const a=t.filter(t=>Ua(t.title,"chapter")===Ua(e.title,"chapter"));if(1===a.length){const t=Ma({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 Oa(n,t),t}if(a.length>1){const t=Ma({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 Oa(n,t),t}const o=Ma({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:e.title,anchorStatus:r,pdChapter:null,wordChapter:e});return Oa(n,o),o},Ga=(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=Ha(n).find(e=>e.sceneId===t);if(e)return{chapter:n,scene:e}}return null})(n,e.anchorId);return o?void Oa(r,Ma({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 Oa(r,Ma({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 Oa(r,Ma({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 Oa(r,Ma({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:a,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));const o=Ha(t.pdChapter).filter(t=>Ua(t.title,"scene")===Ua(e.title,"scene"));1!==o.length?o.length>1?Oa(r,Ma({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})):Oa(r,Ma({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:a,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:e,parentItem:t})):Oa(r,Ma({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}))},Fa=e=>{const t=document.createElement("article");t.className="word-companion-preview-item";const n=document.createElement("strong");n.textContent=`${Ra[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: ${Wa[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},Va=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(Fa(e));te.append(n)}fr()}},Ja=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)(ba(e,1)||ba(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=Na(t.items,n.items);return r.bodyParagraphs=t.items,r},Ya=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(Pa),r=[];let a=0,o=0,c=null,i=null,s=0;const d=(e,t=null,n=null)=>c?(qa(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&&(ba(e,1)?(Da(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&&La.has(e.text)?(o+=1,d(e)):(c.wordCount+=e.wordCount,i&&(i.wordCount+=e.wordCount),s+=e.wordCount)));return Da(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=Aa(a,r.items);return mn=a,Ta(o),Zn("Cache rebuilt."),a},_a=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&&!La.has(e)&&t!==o&&(r+=ka(e))}return e.wordCount=r,lr(mn.currentChapter?.title,e.title,r,mn.currentChapter?.anchorId,e.anchorId,mn.currentChapter?.index),r}):zt},za=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&&!La.has(e)&&t!==o&&r.push(e)}return r.join("\n")}):""},Ka=async()=>{if(cr(""),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return lr(null,null,null),cr("Word document access is unavailable."),Xr({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;F&&(F.disabled=!0,F.textContent="Scanning..."),cr("Scanning document structure...");try{const e=await window.Word.run(async e=>{const t=ia();return t?await Ya(e,!!t.usesExplicitScenes):(mn=null,await Ja(e))});return mn||lr(e.currentChapter?.title,e.currentScene?.title,e.currentScene?.wordCount,e.currentChapter?.anchorId,e.currentScene?.anchorId,e.currentChapter?.index),Mr("Not detected"),$a(e),cr(""),Xr({lastScan:"Success",lastError:"-",paragraphs:String(e.paragraphCount),heading1:String(e.heading1Count),heading2:String(e.heading2Count)}),!0}catch(e){const t=Zr(e);return console.error("Unable to scan the Word document.",e),lr(null,null,null),cr(`Unable to scan the Word document: ${t}`),Xr({lastScan:"Failure",lastError:t}),!1}finally{F&&(F.disabled=!1,F.textContent="Refresh Document Structure")}},Qa=async()=>{const e=ia();if(!ca()||!e)return mr("Select a project and book to analyse manuscript structure."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return mr("Word document access is unavailable."),Xr({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;X&&(X.disabled=!0,X.textContent="Analysing..."),mr("Analysing manuscript structure...");try{const t=await window.Word.run(async e=>await Ja(e)),n=await oo(`/api/word-companion/books/${e.bookId}/structure`);return lr(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),$a(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=Ba(t,r,n);for(const a of Ha(t))Ga(a,e,r,n)}return n})(t,n),Va(un),mr("Preview generated. No changes have been applied."),Xr({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),mr("Unable to analyse manuscript structure."),Xr({lastScan:"Failure",lastError:Zr(e)}),!1}finally{X&&(X.textContent="Analyse Manuscript Structure",gr())}},Xa=e=>{En&&(En(e),En=null),ut?.close?ut.close():ut&&(ut.hidden=!0)},Za=()=>{const e=((e=un)=>{const t=wr(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=>{En=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.`))},eo=(e,t,n="")=>{e.result=t,e.error=n},to=e=>Number.isInteger(e?.wordChapter?.index)&&e.wordChapter.index>0?10*e.wordChapter.index:null,no=e=>Number.isInteger(e?.wordScene?.index)&&e.wordScene.index>0?10*e.wordScene.index:null,ro=async(e,t)=>{const n=await co(`/api/word-companion/books/${e}/chapters`,{title:Gr(t.wordTitle),sortOrder:to(t)});if(!n?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");Pr(),t.pdChapter={chapterId:n.chapterId,title:n.title||t.wordTitle,sortOrder:n.sortOrder||to(t)||0,scenes:[]},t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},ao=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 co(`/api/word-companion/books/${e}/chapters/${n.chapterId}/scenes`,{sceneTitle:Gr(t.wordTitle),sortOrder:no(t)});if(!r?.sceneId)throw new Error("Scene creation did not return a scene ID.");Pr(),t.pdChapter=n,t.pdScene={sceneId:r.sceneId,title:t.wordTitle,sortOrder:no(t)||0},t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},oo=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()},co=(e,t)=>oo(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),io=async(e="")=>{Cn=!1,bn=0,Sn=[],k&&(k.innerHTML=""),pr(C,!0),pa(!1),la(""),pr(v,!0),e&&cr(e);const t=await so();e&&t&&Yt&&cr(e)},so=async()=>{const e=ia();if(!(e&&Gt&&Ft&&window.Word&&"function"==typeof window.Word.run))return!1;cr("Reading manuscript position...");try{Pr(),await Lo(!0),await Jr(e.bookId);const t=await window.Word.run(async t=>await Ya(t,!!e.usesExplicitScenes));return $a(t),Xr({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),Yt?(_t?await To():await Ao(),br(!1),Cr("Live"),cr(""),!0):(Mr("Not detected"),br(!1),Cr("Live"),cr("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,Cr("Manual"),cr(`Unable to read manuscript position: ${Zr(e)}`),Xr({lastScan:"Failure",lastError:Zr(e)}),!1}},lo=e=>e?[...e.querySelectorAll("input[type='checkbox']:checked")].map(e=>Number.parseInt(e.value||"",10)).filter(e=>Number.isInteger(e)&&e>0):[],uo=()=>{const e=Number.parseInt(Le?.value||"",10);return Number.isInteger(e)&&e>0?e:null},po=(e,t,n,r)=>{const a=((e,t)=>xa(e).find(e=>va(e.tag,t))||null)(e,r),o=a||e.getRange().insertContentControl();return o.title=t,o.tag=n,o.appearance="Hidden",o},ho=async(e="PlotDirector IDs attached successfully.")=>{if(!Zt||!en)return cr("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 cr("Word document access is unavailable."),!1;se&&(se.disabled=!0,se.textContent="Attaching...");try{return await window.Word.run(async e=>{const t=await Ja(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.");po(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),po(r,"PlotDirector Scene",`PD-SCENE-${Zt}`,"PD-SCENE"),await e.sync()}),Qt=en,Xt=Zt,rn=!1,nn="SceneID Anchor",tn="Anchor",cr(e),Xr({lastError:"-"}),dr(),!0}catch(e){return console.error("Unable to attach PlotDirector IDs.",e),cr("Unable to attach PlotDirector IDs."),Xr({lastError:Zr(e)}),dr(),!1}finally{se&&(se.textContent=Xt===Zt?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",dr())}},mo=async e=>{if(!en)return Ar("No resolved PlotDirector chapter."),!1;if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return Ar("Word document access is unavailable."),!1;try{return await window.Word.run(async e=>{const t=await Ja(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.");po(n,"PlotDirector Chapter",`PD-CHAPTER-${en}`,"PD-CHAPTER"),await e.sync()}),Qt=en,rn=!1,nn="ChapterID Anchor",tn="Chapter anchor",Ar(e),cr(e),Xr({lastError:"-"}),dr(),!0}catch(e){return console.error("Unable to attach PlotDirector chapter ID.",e),Ar("Unable to attach PlotDirector chapter ID."),Xr({lastError:Zr(e)}),dr(),!1}},yo=async e=>{jr(),await To(),cr(e),Ar(e)},wo=e=>{ln&&(ln(e),ln=null),ct?.close?ct.close():ct&&(ct.hidden=!0)},fo=()=>{if(!nt)return;const e=Gr(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)}},go=()=>{et?.close?et.close():et&&(et.hidden=!0)},So=async(e,t,n)=>{const r=ia();if(!r)return Dr("Select a PlotDirector book first."),!1;await Kr(r.bookId,e,t,"Manual link","Title Match");return!!await ho(n)&&(Dr(n),Rr(),!0)},Io=e=>{cn&&(cn(e),cn=null),ze?.close?ze.close():ze&&(ze.hidden=!0)},Co=()=>{if(!Ve)return;const e=Gr(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)}},bo=()=>{Ge?.close?Ge.close():Ge&&(Ge.hidden=!0)},ko=()=>{Rn=!1,Ir(),Un&&(Un=!1,xo(1e3))},vo=async(e={})=>{const t=e.source||"manual";if(!Zt)return void hr("No resolved PlotDirector scene.");if(!en)return void hr("No resolved PlotDirector chapter.");if(Ln)return void hr("Refresh Current Scene before syncing.");const n=ia(),r=Sa();if(!n||!r)return void hr("Bound manuscript metadata is unavailable.");if(Rn)return Un=!0,void Zn("Scene sync deferred; sync already running.");ur(),Rn=!0,Un=!1;let a=zt;try{a=await _a()}catch(e){return hr("Sync failed"),Xr({lastError:Zr(e)}),Zn("Scene sync failed."),void ko()}if(!Number.isInteger(a)||a<0)return hr("Sync failed"),Zn("Scene sync failed."),void ko();if(Mn===Zt&&On===a)return hr("Synced"),Zn("Sync skipped (count unchanged)."),void ko();Zn("Scene word count changed."),ge&&(ge.disabled=!0,ge.textContent="Syncing..."),hr("Syncing..."),Zn(`Scene sync started (${t}).`);try{const e=await co("/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,Qr(Ie,xr(t)),Qr(he,xr(t)),Qr(Ce,Er(o)),Qr(fe,Er(o)),hr("Synced"),Zn("Scene sync succeeded.")}catch(e){hr("Sync failed"),Xr({lastError:Zr(e)}),Zn("Scene sync failed.")}finally{ge&&(ge.textContent="Sync Current Scene"),ko()}},xo=(e=4e3)=>{ur(),Zt&&en&&!Ln&&!Rn&&(Wn=window.setTimeout(()=>{Wn=null,vo({source:"automatic"})},e))},Eo=()=>{Hn&&(window.clearTimeout(Hn),Hn=null)},No=()=>{Fn=null,Vn="",Jn=[],Yn=null,_n="",Eo()},Lo=async(e=!1)=>{const t=ca(),n=Sa();if(!t||!n)return Jn=[],[];if(!e&&Fn===t.projectId&&Vn===n&&Jn.length>0)return Jn;const r=await oo(`/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:[],Zn("Character alias cache refreshed."),Jn},Po=(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)},qo=async()=>{if(Hn=null,Zt&&!Ln&&Sa()){if(Bn)return Gn=!0,void Zn("Character suggestion detection deferred; detection already running.");Bn=!0,Gn=!1;try{const[e,t]=await Promise.all([za(),Lo()]),n=((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)||Po(e,r.matchText)&&n.set(t,r.name||r.matchText||"Character")}return[...n.entries()].map(([e,t])=>({characterId:e,name:t}))})(e,t),r=n.map(e=>e.characterId),a=r.slice().sort((e,t)=>e-t).join(",");if(!a||Yn===Zt&&_n===a)return void Zn("Character suggestions skipped.");const o=await co("/api/word-companion/runtime/character-suggestions",{documentGuid:Sa(),sceneId:Zt,characterIds:r});if(Yn=Zt,_n=a,(o?.createdCount||0)>0){const e=n.slice(0,3).map(e=>e.name).join(", "),t=n.length>3?" +"+(n.length-3):"";cr(e?`Characters detected: ${e}${t}`:o.message)}Zn(o?.message||"Character suggestions submitted.")}catch(e){console.error("Unable to detect character suggestions.",e),Xr({lastError:Zr(e)})}finally{Bn=!1,Gn&&(Gn=!1,Do(1500))}}},Do=(e=2500)=>{Eo(),!Zt||Ln||Bn?Bn&&(Gn=!0):Hn=window.setTimeout(()=>{qo()},e)},Ao=async()=>{const e=ca(),t=ia(),n=Fr(Yt,"chapter");if(Vr({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?oa(t):void 0,detectedChapter:Yt,detectedScene:_t,requestChapter:n,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!t)return Mr("Not detected"),cr("Select a PlotDirector book first."),!1;if(!Yt)return Mr("Not detected"),cr("No chapter detected in Word. Use Heading 1 for chapters."),!1;Mr("Not detected");try{const e=await Yr(t.bookId),r=Qt?e.find(e=>e.chapterId===Qt):null,a=n.toLocaleLowerCase(),o=a?e.find(e=>Fr(e.title,"chapter").toLocaleLowerCase()===a):null,c=r||o;return c?(jr(),kr(null,c.chapterId,r?"Chapter anchor":"Chapter title"),nn=r?"ChapterID Anchor":"Title Match",ir("Chapter linked to PlotDirector"),cr("No scene detected in Word. Use Heading 2 for scenes."),Vr({result:"Chapter matched",chapterId:c.chapterId,sceneId:null}),!0):(kr(null),ir("Chapter not found in PlotDirector."),cr("Chapter not found in PlotDirector."),Vr({result:"Chapter not matched",chapterId:null,sceneId:null}),Wr("Chapter not found in PlotDirector."),!1)}catch(e){return Mr("Not found in PlotDirector"),Xr({lastError:Zr(e)}),cr("Unable to load PlotDirector chapter data."),!1}},To=async()=>{const e=ca(),t=ia(),n=Fr(Yt,"chapter"),r=Fr(_t,"scene");if(Vr({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?oa(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 Mr("Not detected"),cr("Select a PlotDirector book first."),Vr({result:"Error"}),!1;if(!Yt||!_t)return Mr("Not detected"),cr("No scene detected in Word. Use Heading 2 for scenes."),Vr({result:"Error"}),!1;ne&&(ne.disabled=!0,ne.textContent="Refreshing...");const a=()=>{ne&&(ne.disabled=!1,ne.textContent="Refresh PlotDirector Scene")};Mr("Not detected"),cr("Resolving PlotDirector scene...");try{if(Xt){const e=await(async(e,t)=>{const n=await oo(`/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 Vr({result:"Matched",chapterId:e.chapter.chapterId,sceneId:e.scene.sceneId}),await Kr(t.bookId,e.scene.sceneId,e.chapter.chapterId,"Anchor","SceneID Anchor"),!0;rn=!0,nn="SceneID Anchor",ir("Not found in PlotDirector"),cr("Stored PlotDirector ID is invalid."),Vr({result:"Error",chapterId:Qt,sceneId:Xt}),sr({anchorType:"SceneID Anchor",storedSceneId:Xt,storedChapterId:Qt,resolutionMethod:"Anchor"})}if(Qt){const e=(await Jr(t.bookId)).find(e=>e.chapterId===Qt),n=e?(Array.isArray(e.scenes)?e.scenes:[]).find(e=>Fr(e.title,"scene").toLocaleLowerCase()===r.toLocaleLowerCase()):null;if(n)return Vr({result:"Matched",chapterId:e.chapterId,sceneId:n.sceneId}),await Kr(t.bookId,n.sceneId,e.chapterId,"Anchor","ChapterID Anchor"),!0;e&&!Xt?(nn="ChapterID Anchor",kr(null,Qt,"Chapter anchor"),Vr({result:"Chapter matched",chapterId:Qt,sceneId:null})):Xt||(nn="ChapterID Anchor",Vr({result:"Chapter anchor not found",chapterId:Qt,sceneId:null}))}const e=await co(`/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 Mr("Not found in PlotDirector"),rn=t,c&&(kr(null,o,o===r?"Chapter anchor":"Chapter title"),ir("Scene not found in PlotDirector.")),cr(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."),Vr({result:"Not matched",chapterId:c?o:e?.chapterId,sceneId:e?.sceneId}),t||(c?(jr(),Ur("Scene not found in PlotDirector.")):(Rr(),Wr("Chapter not found in PlotDirector."))),a(),!1}const o=rn;return Vr({result:o?"Matched by title fallback":"Matched",chapterId:e.chapterId,sceneId:e.sceneId}),await Kr(t.bookId,e.sceneId,e.chapterId,o?"Title fallback":"Title","Title Match"),o&&(rn=!0,cr("Stored PlotDirector ID is invalid."),dr()),!0}catch(e){const t=rn;return Xr({lastError:Zr(e)}),Mr("Not found in PlotDirector"),rn=t,cr(t?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),Vr({result:"Error"}),!1}finally{a()}},$o=async()=>{if(Pn=null,jn)return An=!0,void Zn("Runtime update deferred; update already running.");if(!Ot||!ia())return qn=!1,void Zn("Runtime update skipped.");if(!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return qn=!1,Cr("Manual"),void cr("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");if(!mn)return qn=!1,Cr("Manual"),void cr("Document structure is not cached yet. Use Refresh Current Scene.");const e=Date.now()-Dn;if(qn&&eawait(async e=>{const t=e.document.getSelection().paragraphs;return t.load("text,styleBuiltIn,style"),await e.sync(),t.items})(e)),t=Aa(mn,e),n=Ta(t);if(await _a(),!n)return br(!1),Cr("Current scene updated"),xo(),void Do();_t?await To():await Ao(),br(!1),Cr("Current scene updated"),cr("Current scene updated."),xo(),Do()}catch(e){console.error("Unable to refresh current scene from Word selection.",e),Xr({lastError:Zr(e)}),br(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving.")}finally{jn=!1,(An||qn)&&(An=!1,jo(Tn))}},jo=(e=1200)=>{Pn&&window.clearTimeout(Pn),Pn=window.setTimeout($o,Math.max(0,e)),Cr("Waiting for typing to pause"),Zn("Runtime update scheduled.")},Wo=()=>{((e="selection",t=1200)=>{if(qn=!0,Dn=Date.now(),ur(),Eo(),Zn(`${e} changed.`),jn)return An=!0,void Cr("Waiting for typing to pause");jo(t)})("Selection")},Ro=()=>{if($n&&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:Wo}),$n=!1}catch(e){console.warn("Unable to remove Word selection tracking handler.",e)}},Uo=async(e,n)=>{if(mn=null,Pr(),!e)return Bt=[],ra(O,"Select a project first"),ra(m,"Select a project first"),or(""),na(t,null),Ia(),Mr("Not detected"),void yr();ra(O,"Loading books..."),or(""),Mr("Not detected"),yr("Select a book to analyse manuscript structure.");try{const r=await oo(`/api/word-companion/projects/${e}/books`);if(Bt=Array.isArray(r.books)?r.books:[],0===Bt.length)return ra(O,"No books available."),ra(m,"No books available."),or("No books available."),na(t,null),Ia(),void ma("No books available.");aa(O,"Choose a book",Bt.map(e=>({...e,displayTitle:oa(e)})),"bookId","displayTitle");const a=Bt.find(e=>e.bookId===n);a&&O?(O.value=String(a.bookId),na(t,a.bookId)):na(t,null),((e=null)=>{if(!m)return;if(0===Bt.length)return void ra(m,"No books available.");aa(m,"Choose a book",Bt.map(e=>({...e,displayTitle:oa(e)})),"bookId","displayTitle");const t=e||Number.parseInt(O?.value||"",10),n=Bt.find(e=>e.bookId===t);n&&(m.value=String(n.bookId)),ua()})(a?.bookId||n),Ia(),Mr((ia(),"Not detected")),yr(ia()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),ma(da()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{Bt=[],ra(O,"Unable to load books."),ra(m,"Unable to load books."),or("Unable to load books."),na(t,null),Ia(),Mr("Not detected"),yr("Unable to load books."),ma("Unable to load books.")}};for(const e of l)e.addEventListener("click",()=>tr(e.dataset.tabButton));nr(),M?.addEventListener("change",async()=>{const n=Number.parseInt(M.value||"",10);Lr(),h&&Number.isInteger(n)&&n>0&&(h.value=String(n)),na(e,Number.isInteger(n)&&n>0?n:null),na(t,null),Mr("Not detected"),yr(),ma("Select a Book to begin."),await Uo(n,null)}),O?.addEventListener("change",()=>{const e=Number.parseInt(O.value||"",10);Lr(),na(t,Number.isInteger(e)&&e>0?e:null),m&&Number.isInteger(e)&&e>0&&(m.value=String(e)),Ia(),Mr("Not detected"),yr(ia()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),ma(da()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),h?.addEventListener("change",async()=>{const n=Number.parseInt(h.value||"",10);Lr(),M&&Number.isInteger(n)&&n>0&&(M.value=String(n)),na(e,Number.isInteger(n)&&n>0?n:null),na(t,null),ma("Select a Book to begin."),await Uo(n,null)}),m?.addEventListener("change",()=>{const e=Number.parseInt(m.value||"",10);Lr(),O&&Number.isInteger(e)&&e>0&&(O.value=String(e)),na(t,Number.isInteger(e)&&e>0?e:null),Ia(),ma(da()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),y?.addEventListener("input",ua),w?.addEventListener("click",async()=>{const e=sa(),t=String(y?.value||"").trim();if(e&&t){w.disabled=!0,la("Creating Book...");try{const n=await co(`/api/word-companion/projects/${e.projectId}/books`,{title:t});y&&(y.value=""),M&&(M.value=String(e.projectId)),await Uo(e.projectId,n.bookId),m&&(m.value=String(n.bookId)),la("Ready to scan manuscript structure.")}catch(e){console.error("Unable to create Book from Word Companion.",e),la(`Unable to create Book: ${Zr(e)}`)}finally{ua()}}else ua()}),f?.addEventListener("click",async()=>{const e=sa(),t=da();if(e&&t)if(Gt&&Ft&&window.Word&&"function"==typeof window.Word.run){f&&(f.disabled=!0,f.textContent="Scanning..."),la("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),ba(e,1))return r={title:d,sortOrder:10*(n.length+1),wordCount:0,scenes:[]},n.push(r),a=s(),void(o+=ka(d));if(!r||!a)return;if(t&&i.has(d))return void(a=s());const l=ka(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)});gn=n,In=!1;const r=await co("/api/word-companion/manuscript/analyse",{projectId:e.projectId,bookId:t.bookId,documentGuid:ga(),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",oa({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),pr(I,!1),pr(L,!1),la(e.message||"Preview generated."),ua()})(r);try{const t=await co("/api/word-companion/manuscript/discover-characters",{projectId:e.projectId,documentText:n.documentText||""});Sn=Array.isArray(t?.candidates)?t.candidates:[],pr(C,!0),pr(v,!0)}catch(e){console.error("Unable to discover character candidates.",e),Sn=[],pr(C,!0),pr(v,!0)}Xr({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(n.chapterCount),heading2:"-"})}catch(e){console.error("Unable to scan manuscript for first-run import.",e),ma(`Unable to scan manuscript: ${Zr(e)}`),Xr({lastScan:"Failure",lastError:Zr(e)})}finally{f&&(f.textContent="Scan Manuscript"),ua()}}else ma("Word document access is unavailable.");else ma("Select a Project and Book to begin.")}),P?.addEventListener("click",async()=>{const n=sa(),i=da();if(!(n&&i&&gn&&fn?.canImport))return void ua();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),T?.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),T?.addEventListener("click",r),D?.addEventListener("cancel",a),D.showModal()}),s)){kn=!0,ua(),la("Importing manuscript structure...");try{const l=ga(),u=await co("/api/word-companion/manuscript/import",{projectId:n.projectId,bookId:i.bookId,documentGuid:l,bindingVersion:1,replacePlanned:s,chapters:gn.chapters});if(!u.imported)return fn={...fn,canImport:!u.requiresReplaceConfirmation,requiresReplaceConfirmation:!!u.requiresReplaceConfirmation,message:u.message||fn.message},la(u.message||"Import was not completed."),void ua();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},na(e,u.projectId),na(t,u.bookId),M&&(M.value=String(u.projectId));const h=Sn;await Uo(u.projectId,u.bookId),rr("Connected"),In=!0,Cn=h.length>0,bn=Cn?Date.now():0,Sn=h,h.length>0?(pa(!0),wa(h),pr(L,!0),pr(v,!1),la(u.message||"Manuscript structure imported."),cr(u.message||"Manuscript structure imported."),window.setTimeout(ua,750)):await io(u.message||"Manuscript structure imported.")}catch(e){console.error("Unable to import manuscript structure.",e),la(`Unable to import manuscript: ${Zr(e)}`)}finally{kn=!1,ua()}var d}else la("Import cancelled.")}),x?.addEventListener("click",async()=>{const e=sa()||ca(),t=ya();if(!Cn||Date.now()-bn<750||!e||0===t.length)ua();else{vn=!0,ua(),Qr(b,"Creating selected characters...");try{const n=await co("/api/word-companion/manuscript/create-discovered-characters",{projectId:e.projectId,candidateNames:t});cr(n.message||"Characters created."),Qr(b,`${n.createdCount||0} created, ${n.skippedCount||0} already existed.`),await io(n.message||"Characters created.")}catch(e){console.error("Unable to create discovered characters.",e),Qr(b,`Unable to create characters: ${Zr(e)}`)}finally{vn=!1,ua()}}}),E?.addEventListener("click",()=>io("Character creation skipped.")),N?.addEventListener("click",()=>io()),g?.addEventListener("click",()=>pa(!1)),q?.addEventListener("click",()=>ma("Import cancelled.")),F?.addEventListener("click",Ka),X?.addEventListener("click",Qa),Z?.addEventListener("click",async()=>{const e=ia();if(!e||0===wr().length||xn)return void fr();if(!await Za())return;xn=!0,gr(),mr("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=wr().filter(e=>"couldLink"===e.category&&"Chapter"===e.type),r=wr().filter(e=>"wouldCreateChapters"===e.category),a=wr().filter(e=>"couldLink"===e.category&&"Scene"===e.type),o=wr().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 Ja(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.");po(a,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=e.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");po(a,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()})})(e),eo(e,"Success"),t[n]+=1}catch(n){eo(e,"Failed",Zr(n)),t.failed+=1}};try{for(const e of n)s(e,"linkedChapters");for(const n of r)try{await ro(e.bookId,n),s(n,"createdChapters")}catch(e){eo(n,"Failed",Zr(e)),t.failed+=1}for(const e of a)s(e,"linkedScenes");for(const n of o)try{await ao(e.bookId,n),s(n,"createdScenes")}catch(e){eo(n,"Failed",Zr(e)),t.failed+=1}for(const e of c)await d(e.item,e.counterName);for(const e of un.manualReview||[])eo(e,"Skipped");Va(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),mr(i)}finally{xn=!1,gr(),i&&(Pr(),await Qa(),mr(`${i} Preview refreshed.`))}}),ht?.addEventListener("click",()=>Xa(!0)),mt?.addEventListener("click",()=>Xa(!1)),ut?.addEventListener("cancel",e=>{e.preventDefault(),Xa(!1)}),ne?.addEventListener("click",To),G?.addEventListener("click",async()=>{if(!ia())return cr("Select a PlotDirector book first."),void Mr("Not detected");Pn&&(window.clearTimeout(Pn),Pn=null),qn=!1,An=!1,vr(!0),Cr("Updating...");try{await Lo(!0);if(!await Ka())return;if(br(!1),!_t)return await Ao(),void Cr("Current scene updated");await To(),Cr("Current scene updated")}finally{vr(!1)}}),ge?.addEventListener("click",()=>vo({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 br(!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 Ja(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=Fr(n,"scene").toLocaleLowerCase()===Fr(zn||_t,"scene").toLocaleLowerCase(),s=Fr(t,"chapter").toLocaleLowerCase()===Fr(Kn||Yt,"chapter").toLocaleLowerCase();return o||i&&(c||s)?(br(!1),!0):(br(!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),Xr({lastError:Zr(e)}),br(!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:lo(Ee),assetIds:lo(Ne),locationIds:[],primaryLocationId:uo()},oo(e,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})),(()=>{const e=new Set(lo(Ee)),t=new Set(lo(Ne));Xn={characters:Xn.characters.map(t=>({...t,linked:e.has(Number.parseInt(Or(t,"character"),10))})),assets:Xn.assets.map(e=>({...e,linked:t.has(Number.parseInt(Or(e,"asset"),10))})),locations:Xn.locations,primaryLocationId:uo()}})(),qr("Scene links saved successfully."),Xr({lastError:"-"})}catch(e){qr("Unable to save scene links."),Xr({lastError:Zr(e)})}finally{Pe&&(Pe.disabled=!Zt||Ln,Pe.textContent="Save Scene Links")}var e,t}else qr("The Word cursor is now in a different scene. Refresh Current Scene before saving.");else qr("Link a PlotDirector scene first.")}),se?.addEventListener("click",async()=>{await ho()}),$e?.addEventListener("click",async()=>{const e=ia();if(!e||!Yt||en)return void Wr("Chapter not found in PlotDirector.");const t=Gr(Yt),n=await((e,t)=>(Qr(it,`"${e}"`),Qr(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,oa(e)||"selected book");if(n){$e&&($e.disabled=!0,$e.textContent="Creating...");try{const n=Number.isInteger(Kt)&&Kt>0?10*Kt:null,r=await co(`/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.");Pr(),kr(null,r.chapterId,"Manual chapter link");if(!await mo("Chapter created and linked successfully."))return;await yo("Chapter created and linked successfully.")}catch(e){Ar("Unable to create chapter."),Xr({lastError:Zr(e)})}finally{$e&&($e.disabled=!Tr(),$e.textContent="Create Chapter in PlotDirector")}}}),je?.addEventListener("click",async()=>{const e=ia();if(e&&Yt&&!en){je&&(je.disabled=!0,je.textContent="Loading...");try{sn=await Yr(e.bookId),dn=null,tt&&(tt.value=""),Qr(ot,""),fo(),et?.showModal?et.showModal():et&&(et.hidden=!1)}catch(e){Ar("Unable to load chapters."),Xr({lastError:Zr(e)})}finally{je&&(je.disabled=!Tr(),je.textContent="Link to Existing Chapter")}}else Wr("Chapter not found in PlotDirector.")}),tt?.addEventListener("input",fo),rt?.addEventListener("click",async()=>{const e=sn.find(e=>e.chapterId===dn);if(e){rt&&(rt.disabled=!0,rt.textContent="Linking...");try{kr(null,e.chapterId,"Manual chapter link");if(!await mo("Chapter linked successfully."))return;go(),await yo("Chapter linked successfully.")}catch(e){Qr(ot,"Unable to link chapter."),Ar("Unable to link chapter."),Xr({lastError:Zr(e)})}finally{rt&&(rt.disabled=!dn,rt.textContent="Link Chapter")}}else Qr(ot,"Select a chapter.")}),at?.addEventListener("click",go),dt?.addEventListener("click",()=>wo(!0)),lt?.addEventListener("click",()=>wo(!1)),ct?.addEventListener("cancel",e=>{e.preventDefault(),wo(!1)}),Oe?.addEventListener("click",async()=>{const e=ia();if(!e||!_t)return void Ur("Scene not found in PlotDirector.");const t=Fr(_t,"scene"),n=Fr(Yt,"chapter"),r=await((e,t)=>(Qr(Ke,`"${e}"`),Qr(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 zr();if(!n)return void Ur("This chapter does not exist in PlotDirector. Create or link the chapter first.");const r=await co(`/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.");Pr(),await So(r.sceneId,r.chapterId,"Scene created and linked successfully.")}catch(e){Dr("Unable to create scene."),Xr({lastError:Zr(e)})}finally{Oe&&(Oe.disabled=!$r(),Oe.textContent="Create Scene in PlotDirector")}}}),He?.addEventListener("click",async()=>{const e=ia();if(e&&_t){He&&(He.disabled=!0,He.textContent="Loading...");try{const t=await Jr(e.bookId),n=_r(t);if(!n)return void Ur("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=""),Qr(_e,""),Co(),Ge?.showModal?Ge.showModal():Ge&&(Ge.hidden=!1)}catch(e){Dr("Unable to load scenes."),Xr({lastError:Zr(e)})}finally{He&&(He.disabled=!$r(),He.textContent="Link to Existing Scene")}}else Ur("Scene not found in PlotDirector.")}),Fe?.addEventListener("input",Co),Je?.addEventListener("click",async()=>{const e=ia(),t=an.find(e=>e.sceneId===on);if(e&&t){Je&&(Je.disabled=!0,Je.textContent="Linking...");try{const e=await zr();if(!e)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");bo(),await So(t.sceneId,e.chapterId,"Scene linked successfully.")}catch(e){Qr(_e,"Unable to link scene."),Dr("Unable to link scene."),Xr({lastError:Zr(e)})}finally{Je&&(Je.disabled=!on,Je.textContent="Link Scene")}}else Qr(_e,"Select a scene.")}),Ye?.addEventListener("click",bo),Xe?.addEventListener("click",()=>Io(!0)),Ze?.addEventListener("click",()=>Io(!1)),ze?.addEventListener("cancel",e=>{e.preventDefault(),Io(!1)}),Et?.addEventListener("click",async()=>{Et&&(Et.disabled=!0,Et.textContent="Running...");try{if(await ea(),!Gt||!Ft||!window.Word||"function"!=typeof window.Word.run)return void Xr({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});Xr({lastScan:"Success",lastError:"-",paragraphs:String(e)})}catch(e){console.error("Word Companion diagnostics failed.",e);const t=Zr(e);Xr({lastScan:"Failure",lastError:t}),cr(`Unable to scan the Word document: ${t}`)}finally{Et&&(Et.disabled=!1,Et.textContent="Run Diagnostics")}});const Mo=Ot?(async()=>{ra(M,"Loading projects..."),ra(O,"Select a project first"),ra(h,"Loading projects..."),ra(m,"Select a project first"),ar(""),or("");try{const n=await oo("/api/word-companion/projects");if(Ht=Array.isArray(n.projects)?n.projects:[],0===Ht.length)return ra(M,"No projects available."),ra(h,"No projects available."),ar("No projects available."),na(e,null),na(t,null),Ia(),void ma("No projects available.");aa(M,"Choose a project",Ht,"projectId","title"),ha();const r=ta(e),a=Ht.find(e=>e.projectId===r);a&&M?(M.value=String(a.projectId),h&&(h.value=String(a.projectId)),na(e,a.projectId),await Uo(a.projectId,ta(t))):(na(e,null),na(t,null),Ia(),ma("Select a Project and Book to begin."))}catch{Ht=[],Bt=[],ra(M,"Unable to connect to PlotDirector."),ra(O,"Select a project first"),ra(h,"Unable to connect to PlotDirector."),ra(m,"Select a project first"),rr("Unable to connect to PlotDirector."),ar("Unable to connect to PlotDirector."),na(e,null),na(t,null),Ia(),ma("Unable to connect to PlotDirector.")}})():Promise.resolve();if(Ot||(ra(M,"Please sign in to PlotDirector."),ra(O,"Please sign in to PlotDirector."),ra(h,"Please sign in to PlotDirector."),ra(m,"Please sign in to PlotDirector."),Ia()),!window.Office||"function"!=typeof window.Office.onReady)return er("Word Companion ready"),cr("Word document access is unavailable."),Cr("Manual"),void Xr({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"});ea().then(async()=>{er("Word Companion ready"),await Mo,await(async()=>{if(!Ot||!Ft)return void pa(!1);const n=fa();if(n)try{const r=await oo(`/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,Nr(r),na(e,r.projectId),na(t,r.bookId),M&&(M.value=String(r.projectId)),await Uo(r.projectId,r.bookId),pa(!1),rr("Connected"),or("Bound manuscript detected."),void await so()}catch{}pn=null,Lr(),ha(),sa()?await Uo(sa().projectId,null):ra(m,"Select a project first"),ma("Select a Project and Book to begin."),pa(!0)})(),Ft?(()=>{if(Ot){if(!window.Office?.context?.document||"function"!=typeof window.Office.context.document.addHandlerAsync||!window.Office?.EventType?.DocumentSelectionChanged)return Cr("Manual"),void cr("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");try{window.Office.context.document.addHandlerAsync(window.Office.EventType.DocumentSelectionChanged,Wo,e=>{e?.status===window.Office.AsyncResultStatus.Succeeded?($n=!0,Cr("Live")):(Cr("Manual"),cr("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))}),window.addEventListener("beforeunload",Ro)}catch(e){console.warn("Unable to register Word selection tracking handler.",e),Cr("Manual"),cr("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}})():(cr("Word document access is unavailable."),Cr("Manual"))}).catch(e=>{console.error("Office readiness check failed.",e),rr("Unable to connect to PlotDirector."),er("Word Companion unavailable"),cr("Word document access is unavailable."),Xr({ready:"No",wordApi:"No",lastScan:"Failure"})})})(); \ No newline at end of file