diff --git a/PlotLine/Services/WordCompanionService.cs b/PlotLine/Services/WordCompanionService.cs index b769c79..5f4ecd5 100644 --- a/PlotLine/Services/WordCompanionService.cs +++ b/PlotLine/Services/WordCompanionService.cs @@ -51,7 +51,7 @@ public sealed class WordCompanionService( "Don", "Won", "Could", "Would", "Should", "Do", "Does", "Had", "Has", "Was", "Were", "Is", "Am", "Right", "Really", "Now", "Look", "Listen", "Sorry", "Thanks", "Fine", "Great", "Sure", "Course", "Thing", "Things", "Everyone", "Everything", "Anything", "Someone", "Nobody", "People", - "Still", "Err", "Er", "Erm", "Alright", "Allright", "Alrite" + "Still", "Err", "Er", "Erm", "Alright", "Allright", "Alrite", "New", "Somewhere", "Coke" }; private static readonly HashSet CharacterDiscoveryTemporalWords = new(StringComparer.OrdinalIgnoreCase) { diff --git a/PlotLine/wwwroot/css/word-companion.css b/PlotLine/wwwroot/css/word-companion.css index c37f1c7..7d4a802 100644 --- a/PlotLine/wwwroot/css/word-companion.css +++ b/PlotLine/wwwroot/css/word-companion.css @@ -408,39 +408,59 @@ body { .word-companion-character-candidates { display: grid; - gap: 5px; - max-height: 190px; + align-content: start; + gap: 7px; + grid-auto-rows: max-content; + max-height: min(260px, 42vh); overflow-y: auto; + overflow-x: hidden; + padding-right: 2px; } -.word-companion-character-candidate { - display: grid; - grid-template-columns: auto 1fr auto; - align-items: center; - gap: 7px; - min-height: 31px; +.word-companion-section .word-companion-character-candidate { + display: flex; + align-items: flex-start; + gap: 9px; + min-height: 42px; border: 1px solid rgba(111, 75, 45, 0.18); border-radius: 6px; - padding: 5px 7px; + padding: 7px 8px; background: #fffdf8; } .word-companion-character-candidate input { + flex: 0 0 auto; width: 16px; height: 16px; - margin: 0; + margin: 2px 0 0; accent-color: var(--companion-accent); } -.word-companion-character-candidate strong { - font-size: 0.9rem; +.word-companion-section .word-companion-character-candidate-text { + display: grid; + gap: 2px; + min-width: 0; + color: var(--companion-ink); + font-size: inherit; + font-weight: inherit; + overflow-wrap: anywhere; + text-transform: none; } -.word-companion-character-candidate em { +.word-companion-section .word-companion-character-candidate strong { + color: var(--companion-ink); + font-size: 0.92rem; + line-height: 1.2; + text-transform: none; +} + +.word-companion-section .word-companion-character-candidate em { color: var(--companion-muted); - font-size: 0.78rem; + font-size: 0.76rem; font-style: normal; - font-weight: 800; + font-weight: 700; + line-height: 1.25; + text-transform: none; } .word-companion-connection .word-companion-message { diff --git a/PlotLine/wwwroot/css/word-companion.min.css b/PlotLine/wwwroot/css/word-companion.min.css index f9cf188..66d1831 100644 --- a/PlotLine/wwwroot/css/word-companion.min.css +++ b/PlotLine/wwwroot/css/word-companion.min.css @@ -1 +1 @@ -:root{--companion-ink:#2d241d;--companion-muted:#7b7168;--companion-paper:#f8f1e6;--companion-panel:#fffaf2;--companion-line:#e1d3bf;--companion-accent:#6f4b2d;--companion-accent-dark:#4a321f;--companion-gold:#b68a46;--companion-soft:#f3eadc;--companion-soft-strong:#ead9c1}*{box-sizing:border-box}[hidden]{display:none!important}body{margin:0;min-width:280px;color:var(--companion-ink);background:var(--companion-paper);font-family:"Segoe UI",system-ui,-apple-system,BlinkMacSystemFont,sans-serif}.word-companion-login-body{min-width:280px}.word-companion-login-shell{display:grid;align-content:start;gap:12px;width:100%;max-width:420px;padding:14px 12px}.word-companion-login-header{display:grid;gap:2px;border-bottom:1px solid var(--companion-line);padding-bottom:9px}.word-companion-login-header h1{margin:0;color:var(--companion-accent-dark);font-size:1.22rem;line-height:1.1}.word-companion-login-header p{margin:0;color:var(--companion-muted);font-size:.82rem;font-weight:800;text-transform:uppercase}.word-companion-login-card,.word-companion-login-alert{border:1px solid var(--companion-line);border-radius:10px;background:var(--companion-panel);box-shadow:0 2px 8px rgba(74,50,31,.08)}.word-companion-login-card{padding:14px}.word-companion-login-alert{padding:10px;color:var(--companion-accent-dark);font-size:.86rem}.word-companion-login-form{display:grid;gap:10px}.word-companion-login-form div{display:grid;gap:4px}.word-companion-login-form label{color:var(--companion-muted);font-size:.74rem;font-weight:800;text-transform:uppercase}.word-companion-login-form input[type="email"],.word-companion-login-form input[type="password"],.word-companion-login-form input:not([type]){width:100%;min-height:34px;border:1px solid var(--companion-line);border-radius:6px;padding:7px 8px;background:#fffdf8;color:var(--companion-ink);font:inherit}.word-companion-login-form span{color:#8f3528;font-size:.76rem}.word-companion-login-check{display:flex!important;align-items:center;gap:7px;color:var(--companion-ink)!important;font-size:.84rem!important;font-weight:600!important;text-transform:none!important}.word-companion-login-check input{width:16px;height:16px;margin:0;accent-color:var(--companion-accent)}.word-companion-login-form button{min-height:36px;border:1px solid var(--companion-accent);border-radius:8px;background:linear-gradient(180deg,#7b5432 0%,var(--companion-accent-dark) 100%);color:#fff9ef;font:inherit;font-size:.9rem;font-weight:800}.word-companion-login-links{display:grid;gap:6px;border-top:1px solid var(--companion-line);padding-top:9px}.word-companion-login-links a{color:var(--companion-accent-dark);font-size:.84rem;font-weight:700;text-decoration:none}.word-companion-login-validation:empty{display:none}.word-companion-shell{display:grid;align-content:start;gap:9px;width:100%;max-width:420px;padding:10px 11px}.word-companion-header{display:flex;align-items:center;justify-content:space-between;gap:10px;border-bottom:1px solid var(--companion-line);padding-bottom:7px}.word-companion-eyebrow{margin:0;color:var(--companion-accent-dark);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.word-companion-header h1{margin:0;font-size:1.12rem;line-height:1.1;color:var(--companion-accent-dark)}.word-companion-status,.word-companion-user,.word-companion-message,.word-companion-footer{margin:0;color:var(--companion-muted);font-size:.82rem}.word-companion-status{color:var(--companion-accent-dark);font-weight:700}.word-companion-sign-in{display:inline-flex;align-items:center;justify-content:center;width:fit-content;border:1px solid var(--companion-accent);border-radius:6px;padding:6px 10px;background:var(--companion-accent);color:#fff;font-size:.88rem;font-weight:700;text-decoration:none}.word-companion-signed-out{display:grid;gap:12px;border:1px solid var(--companion-line);border-radius:10px;padding:16px;background:var(--companion-panel);box-shadow:0 2px 8px rgba(74,50,31,.08)}.word-companion-signed-out p{margin:0;color:var(--companion-ink);font-size:.94rem;line-height:1.35}.word-companion-signed-out ul{display:grid;gap:5px;margin:0;padding-left:18px;color:var(--companion-muted);font-size:.88rem}.word-companion-sign-in-primary{width:100%;min-height:36px;border-radius:8px;font-size:.9rem}.word-companion-tabs{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:3px;border:1px solid var(--companion-line);border-radius:9px;padding:3px;background:#fff7eb;box-shadow:inset 0 1px 0 rgba(255,255,255,.75)}.word-companion-tabs button{min-width:0;height:28px;min-height:28px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--companion-muted);font:inherit;font-size:.68rem;font-weight:700;line-height:1;padding:0 4px;white-space:nowrap}.word-companion-tabs button.is-active{border-color:rgba(111,75,45,.3);background:var(--companion-soft-strong);color:var(--companion-accent-dark);font-weight:900;box-shadow:none}.word-companion-tab-panel{display:grid;align-content:start;gap:8px}.word-companion-section{display:grid;gap:7px;border:1px solid var(--companion-line);border-radius:8px;padding:9px;background:var(--companion-panel);box-shadow:0 1px 2px rgba(74,50,31,.05)}.word-companion-section span,.word-companion-section label,.word-companion-summary span{color:var(--companion-muted);font-size:.76rem;font-weight:800;text-transform:uppercase}.word-companion-section label{display:block}.word-companion-section select,.word-companion-section input[type="text"]{width:100%;min-height:34px;border:1px solid var(--companion-line);border-radius:6px;padding:6px 8px;background:#fffdf8;color:var(--companion-ink);font:inherit}.word-companion-connection{grid-template-columns:1fr;gap:9px}.word-companion-first-run{gap:10px}.word-companion-inline-create{display:grid;gap:5px}.word-companion-inline-create>div{display:grid;grid-template-columns:1fr auto;gap:6px}.word-companion-inline-create button{min-height:34px;border:1px solid var(--companion-accent);border-radius:6px;padding:6px 9px;background:var(--companion-accent);color:#fff9ef;font:inherit;font-size:.8rem;font-weight:800}.word-companion-inline-create button:disabled{border-color:var(--companion-line);background:var(--companion-soft);color:var(--companion-muted)}.word-companion-import-summary{display:grid;gap:7px;border-top:1px solid var(--companion-line);padding-top:9px}.word-companion-import-summary dl{display:grid;grid-template-columns:1fr auto;gap:5px 10px;margin:0}.word-companion-import-summary dt{color:var(--companion-muted);font-size:.76rem;font-weight:800;text-transform:uppercase}.word-companion-import-summary dd{margin:0;color:var(--companion-ink);font-weight:800;text-align:right}.word-companion-character-discovery{display:grid;gap:8px;border-top:1px solid var(--companion-line);padding-top:9px}.word-companion-character-candidates{display:grid;gap:5px;max-height:190px;overflow-y:auto}.word-companion-character-candidate{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:7px;min-height:31px;border:1px solid rgba(111,75,45,.18);border-radius:6px;padding:5px 7px;background:#fffdf8}.word-companion-character-candidate input{width:16px;height:16px;margin:0;accent-color:var(--companion-accent)}.word-companion-character-candidate strong{font-size:.9rem}.word-companion-character-candidate em{color:var(--companion-muted);font-size:.78rem;font-style:normal;font-weight:800}.word-companion-connection .word-companion-message{grid-column:auto}.word-companion-section select:disabled{background:var(--companion-soft);color:var(--companion-muted)}.word-companion-section-header{display:flex;align-items:center;justify-content:space-between;gap:7px}.word-companion-header-actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:5px}.word-companion-section-header button{min-height:28px;border:1px solid var(--companion-accent);border-radius:6px;padding:4px 7px;background:var(--companion-accent);color:#fff9ef;font:inherit;font-size:.74rem;font-weight:700}.word-companion-actions button:disabled,.word-companion-section-header button:disabled{border-color:var(--companion-line);background:var(--companion-soft);color:var(--companion-muted)}.word-companion-actions{display:grid;grid-template-columns:1fr 1fr;gap:7px}.word-companion-actions button{min-height:31px;border:1px solid var(--companion-accent);border-radius:6px;padding:6px 8px;background:#fffdf8;color:var(--companion-accent-dark);font:inherit;font-size:.8rem;font-weight:800}.word-companion-actions .word-companion-primary-action{background:linear-gradient(180deg,#7b5432 0%,var(--companion-accent-dark) 100%);color:#fff9ef}.word-companion-link-groups .word-companion-section-header button,.word-companion-structure-preview .word-companion-section-header button{min-height:27px;padding:4px 7px;font-size:.72rem}.word-companion-actions button:disabled{border-color:var(--companion-line);background:var(--companion-soft);color:var(--companion-muted)}.word-companion-current-scene>button{min-height:34px;border:1px solid var(--companion-line);border-radius:6px;padding:6px 8px;background:#fff;color:var(--companion-accent-dark);font:inherit;font-size:.84rem;font-weight:800}.word-companion-current-scene>button:disabled{background:var(--companion-soft);color:var(--companion-muted)}.word-companion-message:empty{display:none}.word-companion-section strong{min-width:0;font-size:.96rem;overflow-wrap:anywhere}.word-companion-scene-card,.word-companion-structure-grid,.word-companion-metrics{display:grid;gap:8px}.word-companion-scene-card{border:1px solid rgba(111,75,45,.2);border-radius:8px;padding:10px;background:var(--companion-soft)}.word-companion-scene-summary{gap:8px}.word-companion-title-row strong{color:var(--companion-accent-dark);font-size:1rem;line-height:1.25}.word-companion-badges{display:flex;flex-wrap:wrap;gap:6px}.word-companion-badge{display:inline-flex;align-items:center;gap:4px;width:fit-content;min-height:24px;border:1px solid rgba(111,75,45,.24);border-radius:999px;padding:3px 8px;background:#fffaf2;color:var(--companion-accent-dark)!important;font-size:.74rem!important;font-weight:800!important;text-transform:none!important}.word-companion-badge strong{color:var(--companion-accent-dark);font-size:inherit}.word-companion-link-context{margin:-2px 0 2px;border:1px solid rgba(111,75,45,.16);border-radius:6px;padding:7px 8px;background:var(--companion-soft);color:var(--companion-accent-dark);font-size:.82rem;font-weight:700}.word-companion-scene-card div,.word-companion-sync-meta div,.word-companion-structure-grid div,.word-companion-diagnostics-grid div,.word-companion-metrics div{display:grid;gap:2px}.word-companion-metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:7px}.word-companion-metrics div{border:1px solid rgba(111,75,45,.16);border-radius:6px;padding:7px;background:#fffdf8}.word-companion-metrics strong{color:var(--companion-accent-dark);font-size:.91rem}.word-companion-sync-meta{display:grid;gap:8px;grid-template-columns:1fr 1fr}.word-companion-diagnostics-grid{display:grid;gap:8px;grid-template-columns:1fr 1fr}.word-companion-diagnostics-grid strong{font-size:.88rem}.word-companion-resolve-diagnostics,.word-companion-scene-details,.word-companion-link-groups{display:grid;gap:7px}.word-companion-resolve-diagnostics div,.word-companion-scene-details div,.word-companion-link-groups div{display:grid;gap:3px}.word-companion-resolve-diagnostics{padding-top:4px;grid-template-columns:repeat(2,minmax(0,1fr));gap:5px 7px}.word-companion-resolve-diagnostics div{min-width:0;border-bottom:1px solid rgba(225,211,191,.6);padding-bottom:4px}.word-companion-resolve-diagnostics strong{color:var(--companion-ink);font-size:.8rem;line-height:1.25}.word-companion-resolve-diagnostics span{font-size:.68rem;letter-spacing:.01em}.word-companion-progress-sync{display:grid;gap:8px;border-top:1px solid var(--companion-line);padding-top:8px}.word-companion-progress-grid{display:grid;gap:8px}.word-companion-progress-grid div{display:grid;gap:3px}.word-companion-progress-grid strong{font-size:.88rem}.word-companion-brief{display:grid;gap:5px}.word-companion-brief p{margin:0;border:1px solid var(--companion-line);border-radius:6px;padding:9px;background:var(--companion-soft);color:var(--companion-ink);font-size:.9rem;line-height:1.35;white-space:pre-wrap}.word-companion-check-list{display:grid;gap:4px}.word-companion-check-item{display:grid;grid-template-columns:auto 1fr;align-items:center;gap:7px;min-height:29px;border:1px solid rgba(111,75,45,.18);border-radius:6px;padding:5px 7px;background:#fffdf8;color:var(--companion-ink);font-size:.9rem}.word-companion-check-item input{width:16px;height:16px;margin:0;accent-color:var(--companion-accent)}.word-companion-check-item span{color:var(--companion-ink);font-size:.9rem;font-weight:600;text-transform:none}.word-companion-check-item:has(input:disabled){background:var(--companion-soft);color:var(--companion-muted)}.word-companion-create-link{border-color:rgba(182,138,70,.45);background:#fff8ec}.word-companion-structure-preview{border-color:rgba(182,138,70,.35)}.word-companion-preview-groups,.word-companion-preview-group,.word-companion-preview-item{display:grid;gap:6px}.word-companion-preview-group{border-top:1px solid var(--companion-line);padding-top:7px}.word-companion-preview-group:first-child{border-top:0;padding-top:0}.word-companion-preview-item{border:1px solid rgba(111,75,45,.16);border-radius:6px;padding:7px;background:#fffdf8}.word-companion-preview-item span,.word-companion-preview-matches li{color:var(--companion-ink);font-size:.86rem;font-weight:500;text-transform:none}.word-companion-preview-matches{display:grid;gap:3px}.word-companion-preview-matches ul{display:grid;gap:3px;margin:0;padding-left:18px}.word-companion-apply-summary ul{display:grid;gap:4px;margin:0;padding-left:18px}.word-companion-apply-summary li{color:var(--companion-ink);font-size:.9rem}.word-companion-dialog{width:min(360px,calc(100vw - 24px));border:1px solid var(--companion-line);border-radius:8px;padding:12px;background:var(--companion-panel);color:var(--companion-ink);font-family:"Segoe UI",system-ui,-apple-system,BlinkMacSystemFont,sans-serif}.word-companion-dialog::backdrop{background:rgba(30,37,43,.28)}.word-companion-dialog form{display:grid;gap:8px}.word-companion-dialog strong{min-width:0;overflow-wrap:anywhere}.word-companion-dialog-copy{margin:0;color:var(--companion-muted);font-size:.9rem}.word-companion-dialog-actions{display:grid;grid-template-columns:1fr 1fr;gap:8px}.word-companion-dialog input[type="search"]{width:100%;min-height:36px;border:1px solid var(--companion-line);border-radius:6px;padding:6px 8px;background:#fffdf8;color:var(--companion-ink);font:inherit}.word-companion-dialog button{min-height:32px;border:1px solid var(--companion-accent);border-radius:6px;padding:5px 9px;background:var(--companion-accent);color:#fff9ef;font:inherit;font-size:.82rem;font-weight:700}.word-companion-dialog button:disabled{border-color:var(--companion-line);background:var(--companion-soft);color:var(--companion-muted)}.word-companion-scene-options{display:grid;gap:5px;max-height:220px;overflow-y:auto}.word-companion-scene-option{display:grid;grid-template-columns:auto 1fr;align-items:center;gap:7px;min-height:32px;border:1px solid rgba(111,75,45,.18);border-radius:6px;padding:5px 7px;background:#fffdf8;color:var(--companion-ink);font-size:.9rem}.word-companion-scene-option input{width:16px;height:16px;margin:0;accent-color:var(--companion-accent)}.word-companion-empty-list{margin:0;color:var(--companion-muted);font-size:.88rem}.word-companion-outline{display:grid;gap:7px;padding-top:4px}.word-companion-outline p{margin:0;color:var(--companion-muted);font-size:.9rem}.word-companion-outline-chapter{display:grid;gap:4px}.word-companion-outline-chapter ul{display:grid;gap:3px;margin:0;padding-left:18px}.word-companion-outline-chapter li{color:var(--companion-ink);font-size:.9rem}.word-companion-summary{display:grid;gap:8px;border:1px solid rgba(111,75,45,.18);border-radius:8px;padding:12px;background:var(--companion-soft)}.word-companion-summary div{display:grid;gap:2px}.word-companion-summary strong{min-width:0;font-size:.92rem;overflow-wrap:anywhere}.word-companion-collapsible{gap:8px;background:#fff8ec}.word-companion-collapsible:not([open])>:not(summary){display:none!important}.word-companion-collapsible summary{cursor:pointer;color:var(--companion-ink);font-size:.92rem;font-weight:800;list-style-position:outside}.word-companion-collapsible[open] summary{padding-bottom:6px;border-bottom:1px solid var(--companion-line)}.word-companion-collapsible .word-companion-section-header{padding-top:4px}.word-companion-footer{border-top:1px solid var(--companion-line);padding-top:7px;font-size:.76rem}@media(min-width:390px){.word-companion-connection{grid-template-columns:1fr 1fr}}@media(max-width:340px){.word-companion-tabs{grid-template-columns:repeat(2,minmax(0,1fr))}.word-companion-metrics,.word-companion-resolve-diagnostics{grid-template-columns:1fr}.word-companion-actions{grid-template-columns:1fr}} \ No newline at end of file +:root{--companion-ink:#2d241d;--companion-muted:#7b7168;--companion-paper:#f8f1e6;--companion-panel:#fffaf2;--companion-line:#e1d3bf;--companion-accent:#6f4b2d;--companion-accent-dark:#4a321f;--companion-gold:#b68a46;--companion-soft:#f3eadc;--companion-soft-strong:#ead9c1}*{box-sizing:border-box}[hidden]{display:none!important}body{margin:0;min-width:280px;color:var(--companion-ink);background:var(--companion-paper);font-family:"Segoe UI",system-ui,-apple-system,BlinkMacSystemFont,sans-serif}.word-companion-login-body{min-width:280px}.word-companion-login-shell{display:grid;align-content:start;gap:12px;width:100%;max-width:420px;padding:14px 12px}.word-companion-login-header{display:grid;gap:2px;border-bottom:1px solid var(--companion-line);padding-bottom:9px}.word-companion-login-header h1{margin:0;color:var(--companion-accent-dark);font-size:1.22rem;line-height:1.1}.word-companion-login-header p{margin:0;color:var(--companion-muted);font-size:.82rem;font-weight:800;text-transform:uppercase}.word-companion-login-alert,.word-companion-login-card{border:1px solid var(--companion-line);border-radius:10px;background:var(--companion-panel);box-shadow:0 2px 8px rgba(74,50,31,.08)}.word-companion-login-card{padding:14px}.word-companion-login-alert{padding:10px;color:var(--companion-accent-dark);font-size:.86rem}.word-companion-login-form{display:grid;gap:10px}.word-companion-login-form div{display:grid;gap:4px}.word-companion-login-form label{color:var(--companion-muted);font-size:.74rem;font-weight:800;text-transform:uppercase}.word-companion-login-form input:not([type]),.word-companion-login-form input[type=email],.word-companion-login-form input[type=password]{width:100%;min-height:34px;border:1px solid var(--companion-line);border-radius:6px;padding:7px 8px;background:#fffdf8;color:var(--companion-ink);font:inherit}.word-companion-login-form span{color:#8f3528;font-size:.76rem}.word-companion-login-check{display:flex!important;align-items:center;gap:7px;color:var(--companion-ink)!important;font-size:.84rem!important;font-weight:600!important;text-transform:none!important}.word-companion-login-check input{width:16px;height:16px;margin:0;accent-color:var(--companion-accent)}.word-companion-login-form button{min-height:36px;border:1px solid var(--companion-accent);border-radius:8px;background:linear-gradient(180deg,#7b5432 0,var(--companion-accent-dark) 100%);color:#fff9ef;font:inherit;font-size:.9rem;font-weight:800}.word-companion-login-links{display:grid;gap:6px;border-top:1px solid var(--companion-line);padding-top:9px}.word-companion-login-links a{color:var(--companion-accent-dark);font-size:.84rem;font-weight:700;text-decoration:none}.word-companion-login-validation:empty{display:none}.word-companion-shell{display:grid;align-content:start;gap:9px;width:100%;max-width:420px;padding:10px 11px}.word-companion-header{display:flex;align-items:center;justify-content:space-between;gap:10px;border-bottom:1px solid var(--companion-line);padding-bottom:7px}.word-companion-eyebrow{margin:0;color:var(--companion-accent-dark);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.word-companion-header h1{margin:0;font-size:1.12rem;line-height:1.1;color:var(--companion-accent-dark)}.word-companion-footer,.word-companion-message,.word-companion-status,.word-companion-user{margin:0;color:var(--companion-muted);font-size:.82rem}.word-companion-status{color:var(--companion-accent-dark);font-weight:700}.word-companion-sign-in{display:inline-flex;align-items:center;justify-content:center;width:fit-content;border:1px solid var(--companion-accent);border-radius:6px;padding:6px 10px;background:var(--companion-accent);color:#fff;font-size:.88rem;font-weight:700;text-decoration:none}.word-companion-signed-out{display:grid;gap:12px;border:1px solid var(--companion-line);border-radius:10px;padding:16px;background:var(--companion-panel);box-shadow:0 2px 8px rgba(74,50,31,.08)}.word-companion-signed-out p{margin:0;color:var(--companion-ink);font-size:.94rem;line-height:1.35}.word-companion-signed-out ul{display:grid;gap:5px;margin:0;padding-left:18px;color:var(--companion-muted);font-size:.88rem}.word-companion-sign-in-primary{width:100%;min-height:36px;border-radius:8px;font-size:.9rem}.word-companion-tabs{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:3px;border:1px solid var(--companion-line);border-radius:9px;padding:3px;background:#fff7eb;box-shadow:inset 0 1px 0 rgba(255,255,255,.75)}.word-companion-tabs button{min-width:0;height:28px;min-height:28px;border:1px solid transparent;border-radius:7px;background:0 0;color:var(--companion-muted);font:inherit;font-size:.68rem;font-weight:700;line-height:1;padding:0 4px;white-space:nowrap}.word-companion-tabs button.is-active{border-color:rgba(111,75,45,.3);background:var(--companion-soft-strong);color:var(--companion-accent-dark);font-weight:900;box-shadow:none}.word-companion-tab-panel{display:grid;align-content:start;gap:8px}.word-companion-section{display:grid;gap:7px;border:1px solid var(--companion-line);border-radius:8px;padding:9px;background:var(--companion-panel);box-shadow:0 1px 2px rgba(74,50,31,.05)}.word-companion-section label,.word-companion-section span,.word-companion-summary span{color:var(--companion-muted);font-size:.76rem;font-weight:800;text-transform:uppercase}.word-companion-section label{display:block}.word-companion-section input[type=text],.word-companion-section select{width:100%;min-height:34px;border:1px solid var(--companion-line);border-radius:6px;padding:6px 8px;background:#fffdf8;color:var(--companion-ink);font:inherit}.word-companion-connection{grid-template-columns:1fr;gap:9px}.word-companion-first-run{gap:10px}.word-companion-inline-create{display:grid;gap:5px}.word-companion-inline-create>div{display:grid;grid-template-columns:1fr auto;gap:6px}.word-companion-inline-create button{min-height:34px;border:1px solid var(--companion-accent);border-radius:6px;padding:6px 9px;background:var(--companion-accent);color:#fff9ef;font:inherit;font-size:.8rem;font-weight:800}.word-companion-inline-create button:disabled{border-color:var(--companion-line);background:var(--companion-soft);color:var(--companion-muted)}.word-companion-import-summary{display:grid;gap:7px;border-top:1px solid var(--companion-line);padding-top:9px}.word-companion-import-summary dl{display:grid;grid-template-columns:1fr auto;gap:5px 10px;margin:0}.word-companion-import-summary dt{color:var(--companion-muted);font-size:.76rem;font-weight:800;text-transform:uppercase}.word-companion-import-summary dd{margin:0;color:var(--companion-ink);font-weight:800;text-align:right}.word-companion-character-discovery{display:grid;gap:8px;border-top:1px solid var(--companion-line);padding-top:9px}.word-companion-character-candidates{display:grid;align-content:start;gap:7px;grid-auto-rows:max-content;max-height:min(260px,42vh);overflow-y:auto;overflow-x:hidden;padding-right:2px}.word-companion-section .word-companion-character-candidate{display:flex;align-items:flex-start;gap:9px;min-height:42px;border:1px solid rgba(111,75,45,.18);border-radius:6px;padding:7px 8px;background:#fffdf8}.word-companion-character-candidate input{flex:0 0 auto;width:16px;height:16px;margin:2px 0 0;accent-color:var(--companion-accent)}.word-companion-section .word-companion-character-candidate-text{display:grid;gap:2px;min-width:0;color:var(--companion-ink);font-size:inherit;font-weight:inherit;overflow-wrap:anywhere;text-transform:none}.word-companion-section .word-companion-character-candidate strong{color:var(--companion-ink);font-size:.92rem;line-height:1.2;text-transform:none}.word-companion-section .word-companion-character-candidate em{color:var(--companion-muted);font-size:.76rem;font-style:normal;font-weight:700;line-height:1.25;text-transform:none}.word-companion-connection .word-companion-message{grid-column:auto}.word-companion-section select:disabled{background:var(--companion-soft);color:var(--companion-muted)}.word-companion-section-header{display:flex;align-items:center;justify-content:space-between;gap:7px}.word-companion-header-actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:5px}.word-companion-section-header button{min-height:28px;border:1px solid var(--companion-accent);border-radius:6px;padding:4px 7px;background:var(--companion-accent);color:#fff9ef;font:inherit;font-size:.74rem;font-weight:700}.word-companion-actions button:disabled,.word-companion-section-header button:disabled{border-color:var(--companion-line);background:var(--companion-soft);color:var(--companion-muted)}.word-companion-actions{display:grid;grid-template-columns:1fr 1fr;gap:7px}.word-companion-actions button{min-height:31px;border:1px solid var(--companion-accent);border-radius:6px;padding:6px 8px;background:#fffdf8;color:var(--companion-accent-dark);font:inherit;font-size:.8rem;font-weight:800}.word-companion-actions .word-companion-primary-action{background:linear-gradient(180deg,#7b5432 0,var(--companion-accent-dark) 100%);color:#fff9ef}.word-companion-link-groups .word-companion-section-header button,.word-companion-structure-preview .word-companion-section-header button{min-height:27px;padding:4px 7px;font-size:.72rem}.word-companion-actions button:disabled{border-color:var(--companion-line);background:var(--companion-soft);color:var(--companion-muted)}.word-companion-current-scene>button{min-height:34px;border:1px solid var(--companion-line);border-radius:6px;padding:6px 8px;background:#fff;color:var(--companion-accent-dark);font:inherit;font-size:.84rem;font-weight:800}.word-companion-current-scene>button:disabled{background:var(--companion-soft);color:var(--companion-muted)}.word-companion-message:empty{display:none}.word-companion-section strong{min-width:0;font-size:.96rem;overflow-wrap:anywhere}.word-companion-metrics,.word-companion-scene-card,.word-companion-structure-grid{display:grid;gap:8px}.word-companion-scene-card{border:1px solid rgba(111,75,45,.2);border-radius:8px;padding:10px;background:var(--companion-soft)}.word-companion-scene-summary{gap:8px}.word-companion-title-row strong{color:var(--companion-accent-dark);font-size:1rem;line-height:1.25}.word-companion-badges{display:flex;flex-wrap:wrap;gap:6px}.word-companion-badge{display:inline-flex;align-items:center;gap:4px;width:fit-content;min-height:24px;border:1px solid rgba(111,75,45,.24);border-radius:999px;padding:3px 8px;background:#fffaf2;color:var(--companion-accent-dark)!important;font-size:.74rem!important;font-weight:800!important;text-transform:none!important}.word-companion-badge strong{color:var(--companion-accent-dark);font-size:inherit}.word-companion-link-context{margin:-2px 0 2px;border:1px solid rgba(111,75,45,.16);border-radius:6px;padding:7px 8px;background:var(--companion-soft);color:var(--companion-accent-dark);font-size:.82rem;font-weight:700}.word-companion-diagnostics-grid div,.word-companion-metrics div,.word-companion-scene-card div,.word-companion-structure-grid div,.word-companion-sync-meta div{display:grid;gap:2px}.word-companion-metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:7px}.word-companion-metrics div{border:1px solid rgba(111,75,45,.16);border-radius:6px;padding:7px;background:#fffdf8}.word-companion-metrics strong{color:var(--companion-accent-dark);font-size:.91rem}.word-companion-sync-meta{display:grid;gap:8px;grid-template-columns:1fr 1fr}.word-companion-diagnostics-grid{display:grid;gap:8px;grid-template-columns:1fr 1fr}.word-companion-diagnostics-grid strong{font-size:.88rem}.word-companion-link-groups,.word-companion-resolve-diagnostics,.word-companion-scene-details{display:grid;gap:7px}.word-companion-link-groups div,.word-companion-resolve-diagnostics div,.word-companion-scene-details div{display:grid;gap:3px}.word-companion-resolve-diagnostics{padding-top:4px;grid-template-columns:repeat(2,minmax(0,1fr));gap:5px 7px}.word-companion-resolve-diagnostics div{min-width:0;border-bottom:1px solid rgba(225,211,191,.6);padding-bottom:4px}.word-companion-resolve-diagnostics strong{color:var(--companion-ink);font-size:.8rem;line-height:1.25}.word-companion-resolve-diagnostics span{font-size:.68rem;letter-spacing:.01em}.word-companion-progress-sync{display:grid;gap:8px;border-top:1px solid var(--companion-line);padding-top:8px}.word-companion-progress-grid{display:grid;gap:8px}.word-companion-progress-grid div{display:grid;gap:3px}.word-companion-progress-grid strong{font-size:.88rem}.word-companion-brief{display:grid;gap:5px}.word-companion-brief p{margin:0;border:1px solid var(--companion-line);border-radius:6px;padding:9px;background:var(--companion-soft);color:var(--companion-ink);font-size:.9rem;line-height:1.35;white-space:pre-wrap}.word-companion-check-list{display:grid;gap:4px}.word-companion-check-item{display:grid;grid-template-columns:auto 1fr;align-items:center;gap:7px;min-height:29px;border:1px solid rgba(111,75,45,.18);border-radius:6px;padding:5px 7px;background:#fffdf8;color:var(--companion-ink);font-size:.9rem}.word-companion-check-item input{width:16px;height:16px;margin:0;accent-color:var(--companion-accent)}.word-companion-check-item span{color:var(--companion-ink);font-size:.9rem;font-weight:600;text-transform:none}.word-companion-check-item:has(input:disabled){background:var(--companion-soft);color:var(--companion-muted)}.word-companion-create-link{border-color:rgba(182,138,70,.45);background:#fff8ec}.word-companion-structure-preview{border-color:rgba(182,138,70,.35)}.word-companion-preview-group,.word-companion-preview-groups,.word-companion-preview-item{display:grid;gap:6px}.word-companion-preview-group{border-top:1px solid var(--companion-line);padding-top:7px}.word-companion-preview-group:first-child{border-top:0;padding-top:0}.word-companion-preview-item{border:1px solid rgba(111,75,45,.16);border-radius:6px;padding:7px;background:#fffdf8}.word-companion-preview-item span,.word-companion-preview-matches li{color:var(--companion-ink);font-size:.86rem;font-weight:500;text-transform:none}.word-companion-preview-matches{display:grid;gap:3px}.word-companion-preview-matches ul{display:grid;gap:3px;margin:0;padding-left:18px}.word-companion-apply-summary ul{display:grid;gap:4px;margin:0;padding-left:18px}.word-companion-apply-summary li{color:var(--companion-ink);font-size:.9rem}.word-companion-dialog{width:min(360px,calc(100vw - 24px));border:1px solid var(--companion-line);border-radius:8px;padding:12px;background:var(--companion-panel);color:var(--companion-ink);font-family:"Segoe UI",system-ui,-apple-system,BlinkMacSystemFont,sans-serif}.word-companion-dialog::backdrop{background:rgba(30,37,43,.28)}.word-companion-dialog form{display:grid;gap:8px}.word-companion-dialog strong{min-width:0;overflow-wrap:anywhere}.word-companion-dialog-copy{margin:0;color:var(--companion-muted);font-size:.9rem}.word-companion-dialog-actions{display:grid;grid-template-columns:1fr 1fr;gap:8px}.word-companion-dialog input[type=search]{width:100%;min-height:36px;border:1px solid var(--companion-line);border-radius:6px;padding:6px 8px;background:#fffdf8;color:var(--companion-ink);font:inherit}.word-companion-dialog button{min-height:32px;border:1px solid var(--companion-accent);border-radius:6px;padding:5px 9px;background:var(--companion-accent);color:#fff9ef;font:inherit;font-size:.82rem;font-weight:700}.word-companion-dialog button:disabled{border-color:var(--companion-line);background:var(--companion-soft);color:var(--companion-muted)}.word-companion-scene-options{display:grid;gap:5px;max-height:220px;overflow-y:auto}.word-companion-scene-option{display:grid;grid-template-columns:auto 1fr;align-items:center;gap:7px;min-height:32px;border:1px solid rgba(111,75,45,.18);border-radius:6px;padding:5px 7px;background:#fffdf8;color:var(--companion-ink);font-size:.9rem}.word-companion-scene-option input{width:16px;height:16px;margin:0;accent-color:var(--companion-accent)}.word-companion-empty-list{margin:0;color:var(--companion-muted);font-size:.88rem}.word-companion-outline{display:grid;gap:7px;padding-top:4px}.word-companion-outline p{margin:0;color:var(--companion-muted);font-size:.9rem}.word-companion-outline-chapter{display:grid;gap:4px}.word-companion-outline-chapter ul{display:grid;gap:3px;margin:0;padding-left:18px}.word-companion-outline-chapter li{color:var(--companion-ink);font-size:.9rem}.word-companion-summary{display:grid;gap:8px;border:1px solid rgba(111,75,45,.18);border-radius:8px;padding:12px;background:var(--companion-soft)}.word-companion-summary div{display:grid;gap:2px}.word-companion-summary strong{min-width:0;font-size:.92rem;overflow-wrap:anywhere}.word-companion-collapsible{gap:8px;background:#fff8ec}.word-companion-collapsible:not([open])>:not(summary){display:none!important}.word-companion-collapsible summary{cursor:pointer;color:var(--companion-ink);font-size:.92rem;font-weight:800;list-style-position:outside}.word-companion-collapsible[open] summary{padding-bottom:6px;border-bottom:1px solid var(--companion-line)}.word-companion-collapsible .word-companion-section-header{padding-top:4px}.word-companion-footer{border-top:1px solid var(--companion-line);padding-top:7px;font-size:.76rem}@media (min-width:390px){.word-companion-connection{grid-template-columns:1fr 1fr}}@media (max-width:340px){.word-companion-tabs{grid-template-columns:repeat(2,minmax(0,1fr))}.word-companion-metrics,.word-companion-resolve-diagnostics{grid-template-columns:1fr}.word-companion-actions{grid-template-columns:1fr}} \ No newline at end of file diff --git a/PlotLine/wwwroot/js/word-companion-host.js b/PlotLine/wwwroot/js/word-companion-host.js index a566a1f..df2de88 100644 --- a/PlotLine/wwwroot/js/word-companion-host.js +++ b/PlotLine/wwwroot/js/word-companion-host.js @@ -1102,7 +1102,7 @@ const checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.value = candidate.text || ""; - checkbox.checked = String(candidate.confidence || "").toLowerCase() === "high"; + checkbox.checked = String(candidate.confidence || "").trim().toLowerCase() === "high"; checkbox.addEventListener("change", updateFirstRunButtons); const name = document.createElement("strong"); @@ -1111,10 +1111,14 @@ const mentions = document.createElement("em"); const reason = String(candidate.reason || "").trim(); mentions.textContent = reason - ? `${Number(candidate.mentionCount || 0).toLocaleString()} mentions, ${reason.toLowerCase()}` + ? `${Number(candidate.mentionCount || 0).toLocaleString()} mentions · ${reason}` : `${Number(candidate.mentionCount || 0).toLocaleString()} mentions`; - label.append(checkbox, name, mentions); + const text = document.createElement("span"); + text.className = "word-companion-character-candidate-text"; + text.append(name, mentions); + + label.append(checkbox, text); firstRunCharacterCandidates.append(label); } diff --git a/PlotLine/wwwroot/js/word-companion-host.min.js b/PlotLine/wwwroot/js/word-companion-host.min.js index 202de3a..6e18a1d 100644 --- a/PlotLine/wwwroot/js/word-companion-host.min.js +++ b/PlotLine/wwwroot/js/word-companion-host.min.js @@ -1,25 +1 @@ -(()=>{const f={projectId:"plotdirector.word.projectId",bookId:"plotdirector.word.bookId",activeTab:"plotdirector.word.activeTab"},pi={documentGuid:"plotdirector.word.documentGuid",bookId:"plotdirector.word.boundBookId",projectId:"plotdirector.word.boundProjectId",bindingVersion:"plotdirector.word.bindingVersion"},es=new Set(["scene","links","structure","diagnostics"]),fl=document.querySelector(".word-companion-shell"),el=document.querySelector(".word-companion-tabs"),le=[...document.querySelectorAll("[data-tab-button]")],os=[...document.querySelectorAll("[data-tab-panel]")],ol=document.querySelector("[data-first-run-wizard]"),tt=document.querySelector("[data-first-run-project-select]"),y=document.querySelector("[data-first-run-book-select]"),uu=document.querySelector("[data-first-run-new-book-title]"),uf=document.querySelector("[data-first-run-create-book]"),wi=document.querySelector("[data-first-run-scan]"),sl=document.querySelector("[data-first-run-cancel]"),hl=document.querySelector("[data-first-run-status]"),bi=document.querySelector("[data-first-run-summary]"),ae=document.querySelector("[data-first-run-character-section]"),ur=document.querySelector("[data-first-run-character-status]"),fr=document.querySelector("[data-first-run-character-candidates]"),ff=document.querySelector("[data-first-run-character-actions]"),ve=document.querySelector("[data-first-run-create-characters]"),cl=document.querySelector("[data-first-run-skip-characters]"),ye=document.querySelector("[data-first-run-import-actions]"),pe=document.querySelector("[data-first-run-import]"),ll=document.querySelector("[data-first-run-import-cancel]"),kr=document.querySelector("[data-first-run-replace-dialog]"),ss=document.querySelector("[data-first-run-replace-confirm]"),hs=document.querySelector("[data-first-run-replace-cancel]"),cs=document.querySelector("[data-office-status]"),ls=document.querySelector("[data-connection-status]"),as=document.querySelector("[data-summary-connection]"),vs=document.querySelector("[data-summary-project]"),ys=document.querySelector("[data-summary-book]"),v=document.querySelector("[data-project-select]"),g=document.querySelector("[data-book-select]"),ps=document.querySelector("[data-project-message]"),ws=document.querySelector("[data-book-message]"),ef=document.querySelector("[data-refresh-current-scene]"),er=document.querySelector("[data-refresh-document]"),bs=document.querySelector("[data-current-chapter]"),ks=document.querySelector("[data-current-scene]"),ds=document.querySelector("[data-current-word-count]"),gs=document.querySelector("[data-scene-tracking-status]"),nh=document.querySelector("[data-document-message]"),th=document.querySelector("[data-sync-note]"),fu=document.querySelector("[data-document-outline]"),ki=document.querySelector("[data-analyse-manuscript-structure]"),we=document.querySelector("[data-apply-structure-sync]"),al=document.querySelector("[data-structure-preview-status]"),dr=document.querySelector("[data-structure-preview-results]"),or=document.querySelector("[data-refresh-plotdirector-scene]"),ih=document.querySelector("[data-plotdirector-scene-status]"),vl=document.querySelector("[data-anchor-status]"),yl=document.querySelector("[data-anchor-book-id]"),pl=document.querySelector("[data-anchor-chapter-id]"),wl=document.querySelector("[data-anchor-scene-id]"),ui=document.querySelector("[data-attach-plotdirector-ids]"),rh=document.querySelector("[data-plotdirector-scene-details]"),uh=document.querySelector("[data-plotdirector-scene-title]"),fh=document.querySelector("[data-plotdirector-revision-status]"),eh=document.querySelector("[data-plotdirector-estimated-words]"),be=document.querySelector("[data-plotdirector-actual-words]"),oh=document.querySelector("[data-plotdirector-blocked-status]"),ke=document.querySelector("[data-plotdirector-blocked-reason-row]"),de=document.querySelector("[data-plotdirector-blocked-reason]"),fi=document.querySelector("[data-sync-scene-progress]"),bl=document.querySelector("[data-sync-word-count]"),ge=document.querySelector("[data-sync-plotdirector-count]"),kl=document.querySelector("[data-sync-last-synced]"),dl=document.querySelector("[data-sync-status]"),sh=document.querySelector("[data-writing-brief-block]"),hh=document.querySelector("[data-writing-brief]"),ch=document.querySelector("[data-plotdirector-link-groups]"),eu=document.querySelector("[data-character-chips]"),ou=document.querySelector("[data-asset-chips]"),pw=document.querySelector("[data-location-chips]"),di=document.querySelector("[data-primary-location-select]"),ei=document.querySelector("[data-save-scene-links]"),gl=document.querySelector("[data-scene-links-status]"),lh=document.querySelector("[data-links-editing-scene]"),ah=document.querySelector("[data-chapter-create-link]"),na=document.querySelector("[data-chapter-create-link-chapter]"),ft=document.querySelector("[data-create-plotdirector-chapter]"),et=document.querySelector("[data-link-existing-chapter]"),ta=document.querySelector("[data-chapter-create-link-status]"),vh=document.querySelector("[data-scene-create-link]"),ia=document.querySelector("[data-create-link-chapter]"),ra=document.querySelector("[data-create-link-scene]"),ot=document.querySelector("[data-create-plotdirector-scene]"),st=document.querySelector("[data-link-existing-scene]"),ua=document.querySelector("[data-create-link-status]"),gi=document.querySelector("[data-link-existing-dialog]"),sf=document.querySelector("[data-link-scene-search]"),hf=document.querySelector("[data-link-scene-options]"),wt=document.querySelector("[data-link-selected-scene]"),fa=document.querySelector("[data-link-dialog-cancel]"),no=document.querySelector("[data-link-dialog-status]"),oi=document.querySelector("[data-create-scene-dialog]"),ea=document.querySelector("[data-create-dialog-scene]"),oa=document.querySelector("[data-create-dialog-chapter]"),sa=document.querySelector("[data-create-dialog-confirm]"),ha=document.querySelector("[data-create-dialog-cancel]"),nr=document.querySelector("[data-link-existing-chapter-dialog]"),cf=document.querySelector("[data-link-chapter-search]"),lf=document.querySelector("[data-link-chapter-options]"),bt=document.querySelector("[data-link-selected-chapter]"),ca=document.querySelector("[data-link-chapter-dialog-cancel]"),to=document.querySelector("[data-link-chapter-dialog-status]"),si=document.querySelector("[data-create-chapter-dialog]"),la=document.querySelector("[data-create-chapter-dialog-chapter]"),aa=document.querySelector("[data-create-chapter-dialog-book]"),va=document.querySelector("[data-create-chapter-dialog-confirm]"),ya=document.querySelector("[data-create-chapter-dialog-cancel]"),hi=document.querySelector("[data-apply-structure-sync-dialog]"),io=document.querySelector("[data-apply-structure-sync-summary]"),pa=document.querySelector("[data-apply-structure-sync-confirm]"),wa=document.querySelector("[data-apply-structure-sync-cancel]"),ba=document.querySelector("[data-resolve-project-id]"),ka=document.querySelector("[data-resolve-project-title]"),da=document.querySelector("[data-resolve-book-id]"),ga=document.querySelector("[data-resolve-book-title]"),nv=document.querySelector("[data-resolve-detected-chapter]"),tv=document.querySelector("[data-resolve-detected-scene]"),iv=document.querySelector("[data-resolve-request-chapter]"),rv=document.querySelector("[data-resolve-request-scene]"),uv=document.querySelector("[data-resolve-result]"),fv=document.querySelector("[data-resolve-chapter-id]"),ev=document.querySelector("[data-resolve-scene-id]"),sr=document.querySelector("[data-run-diagnostics]"),ov=document.querySelector("[data-diagnostic-host]"),sv=document.querySelector("[data-diagnostic-platform]"),hv=document.querySelector("[data-diagnostic-ready]"),cv=document.querySelector("[data-diagnostic-word-api]"),lv=document.querySelector("[data-diagnostic-last-scan]"),av=document.querySelector("[data-diagnostic-last-error]"),vv=document.querySelector("[data-diagnostic-anchor-type]"),yv=document.querySelector("[data-diagnostic-stored-scene-id]"),pv=document.querySelector("[data-diagnostic-stored-chapter-id]"),wv=document.querySelector("[data-diagnostic-resolution-method]"),bv=document.querySelector("[data-diagnostic-paragraphs]"),kv=document.querySelector("[data-diagnostic-heading1]"),dv=document.querySelector("[data-diagnostic-heading2]"),su=fl?.dataset.authenticated==="true";let ci=[],ct=[],kt=!1,rt=!1,af="Unknown",vf="Unknown",p="",nt="",hu=null,yf=null,a=null,w=null,r=null,e=null,cu="",li="Title Match",lt=!1,ro=[],lu=null,pf=null,uo=[],au=null,wf=null,dt=null,vu=null,tr=null,yu=null,ir=[],bf=!1,pu=!1,fo=!1,wu=!1,kf=null,eo="Manual",ht=!1,oo=null,so=!1,ho=!1,df="",co="",gt={characters:[],assets:[],locations:[],primaryLocationId:null};const lo=n=>{cs&&(cs.textContent=n)},gv=n=>{try{return window.localStorage.getItem(n)||""}catch{return""}},ny=(n,t)=>{try{t?window.localStorage.setItem(n,String(t)):window.localStorage.removeItem(n)}catch{}},yh=(n,t=true)=>{const i=es.has(n)&&le.some(t=>t.dataset.tabButton===n)?n:"scene";for(const n of le){const t=n.dataset.tabButton===i;n.classList.toggle("is-active",t);n.setAttribute("aria-selected",t?"true":"false")}for(const n of os){const t=n.dataset.tabPanel===i;n.classList.toggle("is-active",t);n.hidden=!t}t&&ny(f.activeTab,i)},ph=()=>{const n=gv(f.activeTab);yh(es.has(n)?n:"scene",!1)},gf=n=>{ls&&(ls.textContent=n),as&&(as.textContent=n)},ao=n=>{ps&&(ps.textContent=n)},bu=n=>{ws&&(ws.textContent=n)},t=n=>{nh&&(nh.textContent=n)},gr=n=>{ih&&(ih.textContent=n)},vo=t=>{const i=n=>Object.prototype.hasOwnProperty.call(t,n);i("anchorType")&&n(vv,o(t.anchorType));i("storedSceneId")&&n(yv,o(t.storedSceneId));i("storedChapterId")&&n(pv,o(t.storedChapterId));i("resolutionMethod")&&n(wv,o(t.resolutionMethod))},ai=()=>{const i=l(),u=Number.isInteger(r)&&r>0&&w===r,f=!Number.isInteger(e)||e<=0||a===e,t=u&&f;n(vl,t?"Attached to PlotDirector":"Not attached");n(yl,i?.bookId?String(i.bookId):"-");n(pl,Number.isInteger(e)&&e>0?String(e):"-");n(wl,Number.isInteger(r)&&r>0?String(r):"-");ui&&(ui.disabled=!r||t&&!lt,ui.textContent=w&&!t?"Reattach PlotDirector IDs":"Attach PlotDirector IDs");vo({anchorType:li||"Title Match",storedSceneId:w,storedChapterId:a,resolutionMethod:cu})},ku=(t,i,r,u=null,f=null,e=null)=>{p=t||"",nt=i||"",hu=Number.isInteger(r)?r:null,yf=Number.isInteger(e)&&e>0?e:null,a=Number.isInteger(u)&&u>0?u:null,w=Number.isInteger(f)&&f>0?f:null,bs&&(bs.textContent=t||"Not detected"),ks&&(ks.textContent=i||"Not detected"),ds&&(ds.textContent=Number.isInteger(r)?String(r):"-"),n(bl,Number.isInteger(r)?String(r):"-"),ai()},u=(n,t)=>{n&&(n.hidden=t)},nu=t=>{n(dl,t)},vi=t=>{n(al,t)},tu=(n="Select a project and book to analyse manuscript structure.")=>{if(dt=null,dr){dr.innerHTML="";const n=document.createElement("p");n.textContent="No preview generated.";dr.append(n)}vi(n);ne()},ty=(n=dt)=>sc.flatMap(t=>Array.isArray(n?.[t.key])?n[t.key]:[]),hr=(n=dt)=>ty(n).filter(n=>n.category==="couldLink"||n.category==="wouldCreateChapters"||n.category==="wouldCreateScenes"),ne=()=>{we&&(we.disabled=wu||hr().length===0)},te=()=>{ki&&(ki.disabled=wu||!iu()||!l()),ne()},yo=()=>{lh&&(lh.textContent=r?`Editing links for: ${df||nt||"Current scene"}`:"Link a PlotDirector scene first.")},wh=()=>{const n=ht||!r;fi&&(fi.disabled=n);ei&&(ei.disabled=n);di&&(di.disabled=n);for(const t of[eu,ou])for(const i of t?[...t.querySelectorAll("input[type='checkbox']")]:[])i.disabled=n},ni=t=>{(t==="Live"||t==="Manual")&&(eo=t),n(gs,t||eo||"Manual")},yi=(i,r="")=>{ht=!!i,n(gs,ht?"Stale":eo),wh(),r&&(t(r),cr(r))},rr=(n,t=null,i="")=>{r=Number.isInteger(n)&&n>0?n:null,e=Number.isInteger(t)&&t>0?t:null,cu=i||"",wh(),nu(ht?"Refresh Current Scene before syncing.":r?"Ready to sync.":"No resolved PlotDirector scene."),cr(ht?"Refresh Current Scene before saving.":r?"Ready to save.":"Link a PlotDirector scene first."),yo(),ai()},bh=n=>{ef&&(ef.disabled=n,ef.textContent=n?"Refreshing...":"Refresh Current Scene")},o=n=>n===null||n===undefined||n===""?"-":String(n),cr=t=>{n(gl,t)},lr=t=>{n(ua,t)},ti=t=>{n(ta,t)},po=()=>!!l()&&!!p&&!e,wo=()=>!!l()&&!!nt&&Number.isInteger(e)&&e>0,du=()=>{u(ah,!0),ti(""),ft&&(ft.disabled=!0,ft.textContent="Create Chapter in PlotDirector"),et&&(et.disabled=!0,et.textContent="Link to Existing Chapter")},ie=(t="")=>{n(na,o(p));u(ah,!1);ti(t);const i=po();ft&&(ft.disabled=!i,ft.textContent="Create Chapter in PlotDirector");et&&(et.disabled=!i,et.textContent="Link to Existing Chapter")},re=()=>{u(vh,!0),lr(""),ot&&(ot.disabled=!0,ot.textContent="Create Scene in PlotDirector"),st&&(st.disabled=!0,st.textContent="Link to Existing Scene")},gu=(t="")=>{n(ia,o(p));n(ra,o(nt));u(vh,!1);lr(t);const i=wo();ot&&(ot.disabled=!i,ot.textContent="Create Scene in PlotDirector");st&&(st.disabled=!i,st.textContent="Link to Existing Scene")},k=t=>{gr(t),u(rh,!0),u(sh,!0),u(ch,!1),du(),re(),cu="",df="",co="",li=w?"SceneID Anchor":a?"ChapterID Anchor":"Title Match",lt=!1,gt={characters:[],assets:[],locations:[],primaryLocationId:null},fe(eu,[],"character"),fe(ou,[],"asset"),kh([],null,!1),rr(null),n(ge,"-"),n(uh,"-"),n(fh,"-"),n(eh,"-"),n(be,"-"),n(oh,"-"),n(de,"-"),u(ke,!0),ai(),yo()},ue=(n,t)=>t==="asset"?n?.assetId||n?.AssetId||n?.storyAssetId||n?.StoryAssetId||0:t==="location"?n?.locationId||n?.LocationId||0:n?.characterId||n?.CharacterId||0,fe=(n,t,i,r=false)=>{if(n){n.innerHTML="";const u=Array.isArray(t)?t:[];if(u.length===0){const t=document.createElement("p");t.className="word-companion-empty-list";t.textContent="None";n.append(t);return}for(const t of u){const f=Number.parseInt(ue(t,i),10);if(Number.isInteger(f)&&!(f<=0)){const e=document.createElement("label");e.className="word-companion-check-item";const u=document.createElement("input");u.type="checkbox";u.value=String(f);u.checked=!!t.linked;u.disabled=!r;const o=document.createElement("span");o.textContent=t.name||"Unnamed";e.append(u,o);n.append(e)}}}},kh=(n,t,i=false)=>{if(di){di.innerHTML="";const r=document.createElement("option");r.value="";r.textContent="None";di.append(r);const u=Number.parseInt(t||"",10);for(const t of Array.isArray(n)?n:[]){const n=Number.parseInt(ue(t,"location"),10);if(Number.isInteger(n)&&!(n<=0)){const i=document.createElement("option");i.value=String(n);i.textContent=t.name||"Unnamed";i.selected=n===u;di.append(i)}}di.disabled=!i}},iy=t=>{df=t?.sceneTitle||nt||"",co=t?.chapterTitle||p||"",n(uh,o(t?.sceneTitle)),n(fh,o(t?.revisionStatus||t?.revisionStatusName||"Not provided")),n(eh,o(t?.estimatedWords)),n(be,o(t?.actualWords)),n(ge,o(t?.actualWords)),n(oh,t?.blocked?"Blocked":"Not blocked"),t?.blockedReason?(n(de,t.blockedReason),u(ke,!1)):(n(de,"-"),u(ke,!0)),hh&&(hh.textContent=t?.writingBrief||"No writing brief has been added for this scene."),gt={characters:Array.isArray(t?.characters)?t.characters:[],assets:Array.isArray(t?.assets)?t.assets:[],locations:Array.isArray(t?.locations)?t.locations:[],primaryLocationId:t?.primaryLocationId??null},fe(eu,gt.characters,"character",!!r&&!ht),fe(ou,gt.assets,"asset",!!r&&!ht),kh(gt.locations,gt.primaryLocationId,!!r&&!ht),yo(),cr(ht?"Refresh Current Scene before saving.":r?"Ready to save.":"No resolved PlotDirector scene."),u(rh,!1),u(sh,!1),u(ch,!1)},ar=n=>String(n||"").trim().replace(/\s+/g," "),b=(n,t)=>{const i=ar(n);if(!i)return"";const r=t==="scene"?"scene":"chapter",u=new RegExp(`^${r}\\s+${"(?:\\d+|[ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)"}\\s*(?::|-|\\u2013|\\u2014)\\s*`,"i"),f=ar(i.replace(u,""));return f||i},ut=t=>{const i=n=>Object.prototype.hasOwnProperty.call(t,n);i("projectId")&&n(ba,o(t.projectId));i("projectTitle")&&n(ka,o(t.projectTitle));i("bookId")&&n(da,o(t.bookId));i("bookTitle")&&n(ga,o(t.bookTitle));i("detectedChapter")&&n(nv,o(t.detectedChapter));i("detectedScene")&&n(tv,o(t.detectedScene));i("requestChapter")&&n(iv,o(t.requestChapter));i("requestScene")&&n(rv,o(t.requestScene));i("result")&&n(uv,o(t.result));i("chapterId")&&n(fv,o(t.chapterId));i("sceneId")&&n(ev,o(t.sceneId))},ry=async(n,t)=>{const i=await pt(`/api/word-companion/books/${n}/structure`),r=Array.isArray(i?.chapters)?i.chapters:[];for(const n of r){const r=Array.isArray(n.scenes)?n.scenes:[],i=r.find(n=>n.sceneId===t);if(i)return i.revisionStatus||""}return""},uy=async(n,t)=>{const i=await pt(`/api/word-companion/books/${n}/structure`),r=Array.isArray(i?.chapters)?i.chapters:[];for(const n of r){const i=Array.isArray(n.scenes)?n.scenes:[];for(const r of i)if(t(n,r))return{chapter:n,scene:r}}return null},bo=async n=>{const t=await pt(`/api/word-companion/books/${n}/structure`);return Array.isArray(t?.chapters)?t.chapters:[]},dh=async n=>{const t=await pt(`/api/word-companion/books/${n}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},gh=n=>{if(Number.isInteger(e)&&e>0){const t=n.find(n=>n.chapterId===e);if(t)return t}const t=b(p,"chapter").toLocaleLowerCase();return t?n.find(n=>b(n.title,"chapter").toLocaleLowerCase()===t)||null:null},nc=async()=>{const n=l();return n?gh(await bo(n.bookId)):null},ee=async(n,i,r,u,f)=>{const e=await pt(`/api/word-companion/scenes/${i}/companion`);try{e.revisionStatus=await ry(n,i)}catch{e.revisionStatus=""}li=f||"Title Match";lt=!1;yi(!1);gr("Linked to PlotDirector");t("");du();re();rr(i,r,u);iy(e)},n=(n,t)=>{n&&(n.textContent=t)},i=t=>{const i=n=>Object.prototype.hasOwnProperty.call(t,n);i("host")&&n(ov,t.host);i("platform")&&n(sv,t.platform);i("ready")&&n(hv,t.ready);i("wordApi")&&n(cv,t.wordApi);i("lastScan")&&n(lv,t.lastScan);i("lastError")&&n(av,t.lastError);i("paragraphs")&&n(bv,t.paragraphs);i("heading1")&&n(kv,t.heading1);i("heading2")&&n(dv,t.heading2)},s=n=>{const t=[];return n?.name&&t.push(n.name),n?.code&&n.code!==n.name&&t.push(n.code),n?.message&&t.push(n.message),n?.debugInfo?.errorLocation&&t.push(`Location: ${n.debugInfo.errorLocation}`),t.length>0?t.join(": "):String(n)},tc=async()=>{if(!window.Office||typeof window.Office.onReady!="function")return kt=!1,rt=!1,af="Unavailable",vf="Unavailable",i({host:af,platform:vf,ready:"No",wordApi:"No"}),null;const n=await window.Office.onReady();return kt=!0,af=n?.host||"Unknown",vf=n?.platform||"Unknown",rt=!!window.Word&&!!window.Office.HostType&&n?.host===window.Office.HostType.Word,i({host:af,platform:vf,ready:"Yes",wordApi:rt?"Yes":"No"}),n},ic=n=>{try{const i=window.localStorage.getItem(n),t=Number.parseInt(i||"",10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},c=(n,t)=>{try{t?window.localStorage.setItem(n,String(t)):window.localStorage.removeItem(n)}catch{}},h=(n,t)=>{if(n){n.innerHTML="";const i=document.createElement("option");i.value="";i.textContent=t;n.append(i);n.disabled=!0}},oe=(n,t,i,r,u)=>{if(n){n.innerHTML="";const f=document.createElement("option");f.value="";f.textContent=t;n.append(f);for(const t of i){const i=document.createElement("option");i.value=String(t[r]);i.textContent=t[u];n.append(i)}n.disabled=i.length===0}},vr=n=>{const t=String(n?.title||"").trim(),i=String(n?.subtitle||"").trim();return i?`${t}: ${i}`:t},iu=()=>{const n=Number.parseInt(v?.value||"",10);return ci.find(t=>t.projectId===n)||null},l=()=>{const n=Number.parseInt(g?.value||"",10);return ct.find(t=>t.bookId===n)||null},yr=()=>{const n=Number.parseInt(tt?.value||"",10);return ci.find(t=>t.projectId===n)||null},ru=()=>{const n=Number.parseInt(y?.value||"",10);return ct.find(t=>t.bookId===n)||null},at=t=>n(hl,t),d=()=>{const n=yr(),t=ru();wi&&(wi.disabled=!n||!t||pu);uf&&(uf.disabled=!n||!String(uu?.value||"").trim()||pu);pe&&(pe.disabled=!tr?.canImport||!yu||pu);ve&&(ve.disabled=fo||uc().length===0)},pr=n=>{u(ol,!n);u(el,n);for(const t of os)u(t,n?!0:t.dataset.tabPanel!=="scene"&&!t.classList.contains("is-active"));n||ph()},rc=()=>{if(tt){if(ci.length===0){h(tt,"No projects available.");return}oe(tt,"Choose a project",ci,"projectId","title");const n=Number.parseInt(v?.value||"",10);Number.isInteger(n)&&n>0&&(tt.value=String(n))}},fy=(n=null)=>{if(y){if(ct.length===0){h(y,"No books available.");return}oe(y,"Choose a book",ct.map(n=>({...n,displayTitle:vr(n)})),"bookId","displayTitle");const i=n||Number.parseInt(g?.value||"",10),t=ct.find(n=>n.bookId===i);t&&(y.value=String(t.bookId));d()}},it=(t="Select a Project and Book to begin.")=>{tr=null,yu=null,ir=[],bf=!1,u(bi,!0),u(ye,!0),u(ae,!0),u(ff,!0),bi&&(bi.innerHTML=""),fr&&(fr.innerHTML=""),n(ur,""),at(t),d()},uc=()=>fr?[...fr.querySelectorAll("input[type='checkbox']:checked")].map(n=>String(n.value||"").trim()).filter(Boolean):[],ko=t=>{if(ir=Array.isArray(t)?t:[],ae&&fr){if(fr.innerHTML="",u(ae,!1),u(ff,!bf||ir.length===0),ir.length===0){n(ur,"No likely major characters found.");d();return}n(ur,`${ir.length} likely major characters found.`);for(const n of ir){const i=document.createElement("label");i.className="word-companion-character-candidate";const t=document.createElement("input");t.type="checkbox";t.value=n.text||"";t.checked=String(n.confidence||"").toLowerCase()==="high";t.addEventListener("change",d);const r=document.createElement("strong");r.textContent=n.text||"";const u=document.createElement("em"),f=String(n.reason||"").trim();u.textContent=f?`${Number(n.mentionCount||0).toLocaleString()} mentions, ${f.toLowerCase()}`:`${Number(n.mentionCount||0).toLocaleString()} mentions`;i.append(t,r,u);fr.append(i)}d()}},ey=n=>{if(bi){bi.innerHTML="";const t=document.createElement("strong");t.textContent="Manuscript Analysis";bi.append(t);const i=document.createElement("dl"),r=[["Project",n.projectTitle],["Book",vr({title:n.bookTitle,subtitle:n.bookSubtitle})],["Chapters",Number(n.chapterCount||0).toLocaleString()],["Scenes",Number(n.sceneCount||0).toLocaleString()],["Words",Number(n.wordCount||0).toLocaleString()]];for(const[n,t]of r){const r=document.createElement("dt");r.textContent=n;const u=document.createElement("dd");u.textContent=t||"-";i.append(r,u)}bi.append(i);u(bi,!1);u(ye,!1);at(n.message||"Preview generated.");d()}},oy=()=>{const n=window.Office?.context?.document?.settings;if(!n)return null;const u=String(n.get(pi.documentGuid)||"").trim(),t=Number.parseInt(n.get(pi.bookId)||"",10),i=Number.parseInt(n.get(pi.projectId)||"",10),r=Number.parseInt(n.get(pi.bindingVersion)||"",10);return!u||!Number.isInteger(t)||t<=0||!Number.isInteger(i)||i<=0?null:{documentGuid:u,bookId:t,projectId:i,bindingVersion:Number.isInteger(r)&&r>0?r:1}},sy=n=>new Promise((t,i)=>{const r=window.Office?.context?.document?.settings;if(!r){i(new Error("Word document settings are unavailable."));return}r.set(pi.documentGuid,n.documentGuid);r.set(pi.bookId,String(n.bookId));r.set(pi.projectId,String(n.projectId));r.set(pi.bindingVersion,String(n.bindingVersion||1));r.saveAsync(n=>{n.status===window.Office.AsyncResultStatus.Succeeded?t():i(n.error||new Error("Unable to save Word document metadata."))})}),fc=()=>vu?.documentGuid?vu.documentGuid:window.crypto?.randomUUID?window.crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(Number(n)^Math.random()*16>>Number(n)/4).toString(16)),ii=()=>{const t=iu(),n=l();vs&&(vs.textContent=t?.title||"(Not connected)");ys&&(ys.textContent=n?vr(n):"(Not connected)");th&&(th.textContent=n?"":"Select a PlotDirector book before refreshing.");te()},go=n=>{const t=n?.styleBuiltIn||n?.style||"";return String(t).replace(/\s+/g,"").toLowerCase()},nf=(n,t)=>{const i=go(n);return i===`heading${t}`||i.endsWith(`.heading${t}`)||i.includes(`heading${t}`)},ns=n=>{const t=String(n||"").trim().split(/\s+/).filter(Boolean);return t.length},hy=(n,t)=>String(n?.text||"").trim()===String(t?.text||"").trim()&&go(n)===go(t),ec=(n,t)=>{const r=String(n||"").match(new RegExp(`^${t}-(\\d+)$`,"i"));if(!r)return null;const i=Number.parseInt(r[1],10);return Number.isInteger(i)&&i>0?i:null},oc=(n,t)=>{const i=Array.isArray(n?.contentControls?.items)?n.contentControls.items:[];for(const n of i){const i=ec(n.tag,t);if(i)return i}return null},cy=(n,t)=>{const u=[];let o=0,s=0,i=null,r=null;n.forEach((n,t)=>{const f=String(n.text||"").trim();if(f){if(nf(n,1)){o+=1;i={index:u.length+1,paragraphIndex:t,title:f,anchorId:oc(n,"PD-CHAPTER"),scenes:[]};u.push(i);r=null;return}if(nf(n,2)){if(s+=1,!i)return;r={index:i.scenes.length+1,paragraphIndex:t,title:f,anchorId:oc(n,"PD-SCENE"),wordCount:0};i.scenes.push(r);return}r&&(r.wordCount+=ns(f))}});const h=t.find(n=>String(n.text||"").trim()),f=h?n.findIndex(n=>hy(n,h)):-1,e=f>=0?u.filter(n=>n.paragraphIndex<=f).at(-1)||null:null,c=e&&f>=0?e.scenes.filter(n=>n.paragraphIndex<=f).at(-1)||null:null;return{chapters:u,currentChapter:e,currentScene:c,paragraphCount:n.length,heading1Count:o,heading2Count:s}},ly=(n,t)=>{const r=[];let i=null,u=null,f=0;const e=[],s=new Set(["***","###"]),o=()=>{if(!i)return null;const n={title:`Scene ${i.scenes.length+1}`,sortOrder:(i.scenes.length+1)*10,wordCount:0};return i.scenes.push(n),n};return n.forEach(n=>{const h=String(n.text||"").trim();if(h){if(e.push(h),nf(n,1)){i={title:h,sortOrder:(r.length+1)*10,wordCount:0,scenes:[]};r.push(i);u=o();f+=ns(h);return}if(i&&u){if(t&&s.has(h)){u=o();return}const c=ns(h);i.wordCount+=c;u.wordCount+=c;f+=c}}}),{chapters:r,chapterCount:r.length,sceneCount:r.reduce((n,t)=>n+t.scenes.length,0),wordCount:f,documentText:e.join("\n")}},ts=n=>{if(fu){if(fu.innerHTML="",n.chapters.length===0){const n=document.createElement("p");n.textContent="No chapters detected. Use Heading 1 for chapter titles.";fu.append(n);return}const t=n.chapters.some(n=>n.scenes.length>0);if(!t){const n=document.createElement("p");n.textContent="No scenes detected. Use Heading 2 for scene titles.";fu.append(n)}for(const t of n.chapters){const n=document.createElement("div");n.className="word-companion-outline-chapter";const i=document.createElement("strong");if(i.textContent=t.title,n.append(i),t.scenes.length>0){const i=document.createElement("ul");for(const n of t.scenes){const t=document.createElement("li");t.textContent=n.title;i.append(t)}n.append(i)}fu.append(n)}}},sc=[{key:"alreadyLinked",title:"Already Linked"},{key:"couldLink",title:"Could Link"},{key:"wouldCreateChapters",title:"Would Create Chapters"},{key:"wouldCreateScenes",title:"Would Create Scenes"},{key:"manualReview",title:"Manual Review Required"}],ay={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},vy={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},se=(n,t)=>b(n,t).toLocaleLowerCase(),vt=({category:i,action:n,type:s,wordTitle:l,match:r="",anchorStatus:t="None",matches:u=[],pdChapter:e=null,pdScene:o=null,wordChapter:h=null,wordScene:c=null,parentItem:f=null})=>({id:`${s}-${h?.index||0}-${c?.index||0}-${h?.paragraphIndex??c?.paragraphIndex??0}`,category:i,action:n,type:s,wordTitle:l,match:r,anchorStatus:t,matches:u,pdChapter:e,pdScene:o,wordChapter:h,wordScene:c,parentItem:f,result:"Pending",error:""}),yt=(n,t)=>{Array.isArray(n[t.category])&&n[t.category].push(t)},is=n=>Array.isArray(n?.scenes)?n.scenes:[],yy=(n,t)=>{for(const i of n){const n=is(i).find(n=>n.sceneId===t);if(n)return{chapter:i,scene:n}}return null},py=(n,t,i)=>{const u=n.anchorId?`PD-CHAPTER-${n.anchorId}`:"None";if(n.anchorId){const r=t.find(t=>t.chapterId===n.anchorId);if(r){const t=vt({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:n.title,match:`Chapter ${r.chapterId}: ${r.title}`,anchorStatus:u,pdChapter:r,wordChapter:n});return yt(i,t),t}const f=vt({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:n.title,anchorStatus:`${u} not found`,matches:[],pdChapter:null,wordChapter:n});return yt(i,f),f}const r=t.filter(t=>se(t.title,"chapter")===se(n.title,"chapter"));if(r.length===1){const t=vt({category:"couldLink",action:"couldLink",type:"Chapter",wordTitle:n.title,match:`Chapter ${r[0].chapterId}: ${r[0].title}`,anchorStatus:u,pdChapter:r[0],wordChapter:n});return yt(i,t),t}if(r.length>1){const t=vt({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:n.title,anchorStatus:u,matches:r.map(n=>`Chapter ${n.chapterId}: ${n.title}`),pdChapter:null,wordChapter:n});return yt(i,t),t}const f=vt({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:n.title,anchorStatus:u,pdChapter:null,wordChapter:n});return yt(i,f),f},wy=(n,t,i,r)=>{const u=n.anchorId?`PD-SCENE-${n.anchorId}`:"None";if(n.anchorId){const f=yy(i,n.anchorId);if(f){yt(r,vt({category:"alreadyLinked",action:"alreadyLinked",type:"Scene",wordTitle:n.title,match:`Scene ${f.scene.sceneId}: ${f.scene.title}`,anchorStatus:u,pdChapter:f.chapter,pdScene:f.scene,wordChapter:t?.wordChapter,wordScene:n,parentItem:t}));return}yt(r,vt({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:n.title,anchorStatus:`${u} not found`,wordChapter:t?.wordChapter,wordScene:n,parentItem:t}));return}if(!t?.pdChapter&&t?.category==="manualReview"){yt(r,vt({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:n.title,anchorStatus:u,matches:["Parent chapter requires manual review."],wordChapter:t?.wordChapter,wordScene:n,parentItem:t}));return}if(!t?.pdChapter){yt(r,vt({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:n.title,anchorStatus:u,wordChapter:t?.wordChapter,wordScene:n,parentItem:t}));return}const f=is(t.pdChapter).filter(t=>se(t.title,"scene")===se(n.title,"scene"));if(f.length===1){yt(r,vt({category:"couldLink",action:"couldLink",type:"Scene",wordTitle:n.title,match:`Scene ${f[0].sceneId}: ${f[0].title}`,anchorStatus:u,pdChapter:t.pdChapter,pdScene:f[0],wordChapter:t.wordChapter,wordScene:n,parentItem:t}));return}if(f.length>1){yt(r,vt({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:n.title,anchorStatus:u,matches:f.map(n=>`Scene ${n.sceneId}: ${n.title}`),wordChapter:t.wordChapter,wordScene:n,parentItem:t}));return}yt(r,vt({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:n.title,anchorStatus:u,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:n,parentItem:t}))},by=(n,t)=>{const i={alreadyLinked:[],couldLink:[],wouldCreateChapters:[],wouldCreateScenes:[],manualReview:[]},r=Array.isArray(t?.chapters)?t.chapters:[];for(const t of Array.isArray(n?.chapters)?n.chapters:[]){const n=py(t,r,i);for(const u of is(t))wy(u,n,r,i)}return i},ky=n=>{const t=document.createElement("article");t.className="word-companion-preview-item";const i=document.createElement("strong");i.textContent=`${vy[n.action]||""} ${n.type}: ${n.wordTitle}`;t.append(i);const r=document.createElement("span");if(r.textContent=`Anchor: ${n.anchorStatus||"None"}`,t.append(r),n.match){const i=document.createElement("span");i.textContent=`Match: ${n.match}`;t.append(i)}if(Array.isArray(n.matches)&&n.matches.length>0){const i=document.createElement("div");i.className="word-companion-preview-matches";const r=document.createElement("span");r.textContent="Matches:";i.append(r);const u=document.createElement("ul");for(const t of n.matches){const n=document.createElement("li");n.textContent=t;u.append(n)}i.append(u);t.append(i)}const u=document.createElement("span");if(u.textContent=`Action: ${ay[n.action]||n.action}`,t.append(u),n.result&&n.result!=="Pending"){const i=document.createElement("span");i.textContent=n.error?`Result: ${n.result} - ${n.error}`:`Result: ${n.result}`;t.append(i)}return t},hc=n=>{if(dr){dr.innerHTML="";for(const t of sc){const i=document.createElement("section");i.className="word-companion-preview-group";const r=document.createElement("strong");r.textContent=t.title;i.append(r);const u=Array.isArray(n?.[t.key])?n[t.key]:[];if(u.length===0){const n=document.createElement("p");n.className="word-companion-empty-list";n.textContent="None";i.append(n)}else for(const n of u)i.append(ky(n));dr.append(i)}ne()}},wr=async n=>{const t=n.document.body.paragraphs,i=n.document.getSelection().paragraphs;t.load("text,styleBuiltIn,style");i.load("text,styleBuiltIn,style");await n.sync();for(const n of t.items)(nf(n,1)||nf(n,2))&&n.contentControls.load("items/tag,title");await n.sync();const r=cy(t.items,i.items);return r.bodyParagraphs=t.items,r},cc=async()=>{if(t(""),!kt||!rt||!window.Word||typeof window.Word.run!="function")return ku(null,null,null),t("Word document access is unavailable."),i({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;er&&(er.disabled=!0,er.textContent="Scanning...");t("Scanning document structure...");try{const n=await window.Word.run(async n=>await wr(n));return ku(n.currentChapter?.title,n.currentScene?.title,n.currentScene?.wordCount,n.currentChapter?.anchorId,n.currentScene?.anchorId,n.currentChapter?.index),k("Not detected"),ts(n),t(""),i({lastScan:"Success",lastError:"-",paragraphs:String(n.paragraphCount),heading1:String(n.heading1Count),heading2:String(n.heading2Count)}),!0}catch(n){const r=s(n);return console.error("Unable to scan the Word document.",n),ku(null,null,null),t(`Unable to scan the Word document: ${r}`),i({lastScan:"Failure",lastError:r}),!1}finally{er&&(er.disabled=!1,er.textContent="Refresh Document Structure")}},lc=async()=>{const n=l();if(!iu()||!n)return vi("Select a project and book to analyse manuscript structure."),!1;if(!kt||!rt||!window.Word||typeof window.Word.run!="function")return vi("Word document access is unavailable."),i({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;ki&&(ki.disabled=!0,ki.textContent="Analysing...");vi("Analysing manuscript structure...");try{const t=await window.Word.run(async n=>await wr(n)),r=await pt(`/api/word-companion/books/${n.bookId}/structure`);return ku(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),ts(t),dt=by(t,r),hc(dt),vi("Preview generated. No changes have been applied."),i({lastScan:"Success",lastError:"-",paragraphs:String(t.paragraphCount),heading1:String(t.heading1Count),heading2:String(t.heading2Count)}),!0}catch(t){return console.error("Unable to analyse manuscript structure.",t),vi("Unable to analyse manuscript structure."),i({lastScan:"Failure",lastError:s(t)}),!1}finally{ki&&(ki.textContent="Analyse Manuscript Structure",te())}},dy=(n=dt)=>{const t=hr(n),i=t.filter(n=>n.category==="couldLink"&&n.type==="Chapter").length,r=t.filter(n=>n.category==="couldLink"&&n.type==="Scene").length,u=t.filter(n=>n.category==="wouldCreateChapters").length,f=t.filter(n=>n.category==="wouldCreateScenes").length,e=Array.isArray(n?.manualReview)?n.manualReview.length:0;return{linkChapters:i,linkScenes:r,createChapters:u,createScenes:f,manualReview:e}},gy=n=>{if(io){io.innerHTML="";const i=[`Link ${n.linkChapters+n.linkScenes} chapters/scenes`,`Create ${n.createChapters} chapters`,`Create ${n.createScenes} scenes`],t=document.createElement("ul");for(const n of i){const i=document.createElement("li");i.textContent=n;t.append(i)}io.append(t)}},rs=n=>{kf&&(kf(n),kf=null),hi?.close?hi.close():hi&&(hi.hidden=!0)},np=()=>{const n=dy();return(gy(n),!hi)?Promise.resolve(window.confirm(`Apply Structure Sync? - -This will: - -- Link ${n.linkChapters+n.linkScenes} chapters/scenes -- Create ${n.createChapters} chapters -- Create ${n.createScenes} scenes - -Manual review items will be skipped.`)):new Promise(n=>{kf=n,hi.showModal?hi.showModal():hi.hidden=!1})},tf=(n,t,i="")=>{n.result=t,n.error=i},ac=n=>Number.isInteger(n?.wordChapter?.index)&&n.wordChapter.index>0?n.wordChapter.index*10:null,vc=n=>Number.isInteger(n?.wordScene?.index)&&n.wordScene.index>0?n.wordScene.index*10:null,tp=async(n,t)=>{const i=await ri(`/api/word-companion/books/${n}/chapters`,{title:ar(t.wordTitle),sortOrder:ac(t)});if(!i?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");t.pdChapter={chapterId:i.chapterId,title:i.title||t.wordTitle,sortOrder:i.sortOrder||ac(t)||0,scenes:[]};t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},ip=async(n,t)=>{const i=t.pdChapter||t.parentItem?.pdChapter;if(!i?.chapterId)throw new Error("Scene parent chapter is not available.");const r=await ri(`/api/word-companion/books/${n}/chapters/${i.chapterId}/scenes`,{sceneTitle:ar(t.wordTitle),sortOrder:vc(t)});if(!r?.sceneId)throw new Error("Scene creation did not return a scene ID.");t.pdChapter=i;t.pdScene={sceneId:r.sceneId,title:t.wordTitle,sortOrder:vc(t)||0};t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},rp=async n=>{if(!kt||!rt||!window.Word||typeof window.Word.run!="function")throw new Error("Word document access is unavailable.");await window.Word.run(async t=>{const u=await wr(t),r=n.type==="Chapter"?n.wordChapter:n.wordScene,i=Number.isInteger(r?.paragraphIndex)?u.bodyParagraphs[r.paragraphIndex]:null;if(!i)throw new Error("Unable to locate the Word heading.");if(n.type==="Chapter"){const t=n.pdChapter?.chapterId;if(!t)throw new Error("Chapter ID is not available.");rf(i,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=n.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");rf(i,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()})},up=n=>`Structure Sync Complete. Created: ${n.createdChapters} Chapters, ${n.createdScenes} Scenes. Linked: ${n.linkedChapters} Chapters, ${n.linkedScenes} Scenes. Skipped: ${n.skipped} Manual Review items. Failed: ${n.failed} Items.`,fp=async()=>{const r=l();if(!r||hr().length===0||wu){ne();return}const f=await np();if(f){wu=!0;te();vi("Applying structure sync...");const n={createdChapters:0,createdScenes:0,linkedChapters:0,linkedScenes:0,skipped:Array.isArray(dt?.manualReview)?dt.manualReview.length:0,failed:0},e=hr().filter(n=>n.category==="couldLink"&&n.type==="Chapter"),o=hr().filter(n=>n.category==="wouldCreateChapters"),h=hr().filter(n=>n.category==="couldLink"&&n.type==="Scene"),c=hr().filter(n=>n.category==="wouldCreateScenes"),u=[];let t="";const i=(n,t)=>{u.push({item:n,counterName:t})},a=async(t,i)=>{try{await rp(t);tf(t,"Success");n[i]+=1}catch(r){tf(t,"Failed",s(r));n.failed+=1}};try{for(const n of e)i(n,"linkedChapters");for(const t of o)try{await tp(r.bookId,t);i(t,"createdChapters")}catch(u){tf(t,"Failed",s(u));n.failed+=1}for(const n of h)i(n,"linkedScenes");for(const t of c)try{await ip(r.bookId,t);i(t,"createdScenes")}catch(u){tf(t,"Failed",s(u));n.failed+=1}for(const n of u)await a(n.item,n.counterName);for(const n of dt.manualReview||[])tf(n,"Skipped");hc(dt);t=up(n);vi(t)}finally{wu=!1;te();t&&(await lc(),vi(`${t} Preview refreshed.`))}}},ep=async()=>{sr&&(sr.disabled=!0,sr.textContent="Running...");try{if(await tc(),!kt||!rt||!window.Word||typeof window.Word.run!="function"){i({lastScan:"Failure",lastError:"Word document access is unavailable.",paragraphs:"-",heading1:"-",heading2:"-"});return}const n=await window.Word.run(async n=>{const t=n.document.body.paragraphs;return t.load("items"),await n.sync(),t.items.length});i({lastScan:"Success",lastError:"-",paragraphs:String(n)})}catch(n){console.error("Word Companion diagnostics failed.",n);const r=s(n);i({lastScan:"Failure",lastError:r});t(`Unable to scan the Word document: ${r}`)}finally{sr&&(sr.disabled=!1,sr.textContent="Run Diagnostics")}},pt=async(n,t={})=>{const i=await window.fetch(n,{credentials:"same-origin",...t,headers:{Accept:"application/json",...(t.headers||{})}});if(!i.ok)throw new Error(`Request failed: ${i.status}`);return await i.json()},ri=(n,t)=>pt(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),op=async()=>{const t=yr(),r=ru();if(!t||!r){it("Select a Project and Book to begin.");return}if(!kt||!rt||!window.Word||typeof window.Word.run!="function"){it("Word document access is unavailable.");return}wi&&(wi.disabled=!0,wi.textContent="Scanning...");at("Scanning manuscript structure...");try{const u=await window.Word.run(async n=>{const t=n.document.body.paragraphs;return t.load("text,styleBuiltIn,style"),await n.sync(),ly(t.items,!!r.usesExplicitScenes)});yu=u;bf=!1;const f=await ri("/api/word-companion/manuscript/analyse",{projectId:t.projectId,bookId:r.bookId,documentGuid:fc(),chapterCount:u.chapterCount,sceneCount:u.sceneCount,wordCount:u.wordCount});tr=f;ey(f);try{const n=await ri("/api/word-companion/manuscript/discover-characters",{projectId:t.projectId,documentText:u.documentText||""});ko(n?.candidates||[])}catch(e){console.error("Unable to discover character candidates.",e);ko([]);n(ur,"Character discovery is unavailable.")}i({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(u.chapterCount),heading2:"-"})}catch(u){console.error("Unable to scan manuscript for first-run import.",u);it(`Unable to scan manuscript: ${s(u)}`);i({lastScan:"Failure",lastError:s(u)})}finally{wi&&(wi.textContent="Scan Manuscript");d()}},sp=()=>new Promise(n=>{if(!kr||typeof kr.showModal!="function"){n(window.confirm("This Book already contains planned chapters and scenes.\n\nImporting this manuscript will replace the planned structure.\n\nContinue?"));return}const t=t=>{ss?.removeEventListener("click",i),hs?.removeEventListener("click",r),kr?.removeEventListener("cancel",u),kr?.close(),n(t)},i=()=>t(!0),r=()=>t(!1),u=n=>{n.preventDefault(),t(!1)};ss?.addEventListener("click",i);hs?.addEventListener("click",r);kr?.addEventListener("cancel",u);kr.showModal()}),hp=async()=>{const i=yr(),r=ru();if(!i||!r||!yu||!tr?.canImport){d();return}let n=!1;if(tr.requiresReplaceConfirmation&&(n=await sp(),!n)){at("Import cancelled.");return}pu=!0;d();at("Importing manuscript structure...");try{const s=fc(),e=await ri("/api/word-companion/manuscript/import",{projectId:i.projectId,bookId:r.bookId,documentGuid:s,bindingVersion:1,replacePlanned:n,chapters:yu.chapters});if(!e.imported){tr={...tr,canImport:!e.requiresReplaceConfirmation,requiresReplaceConfirmation:!!e.requiresReplaceConfirmation,message:e.message||tr.message};at(e.message||"Import was not completed.");d();return}const o=e.manuscriptDocument;await sy({documentGuid:o?.documentGuid||s,bookId:e.bookId,projectId:e.projectId,bindingVersion:o?.bindingVersion||1});vu={documentGuid:o?.documentGuid||s,bookId:e.bookId,projectId:e.projectId,bindingVersion:o?.bindingVersion||1};c(f.projectId,e.projectId);c(f.bookId,e.bookId);v&&(v.value=String(e.projectId));const h=ir;await br(e.projectId,e.bookId);gf("Connected");bf=!0;ir=h;h.length>0?(pr(!0),ko(h),u(ye,!0),u(ff,!1),at(e.message||"Manuscript structure imported."),t(e.message||"Manuscript structure imported.")):(pr(!1),t(e.message||"Manuscript structure imported."))}catch(e){console.error("Unable to import manuscript structure.",e);at(`Unable to import manuscript: ${s(e)}`)}finally{pu=!1;d()}},yc=()=>{pr(!1),at(""),u(ff,!0)},cp=async()=>{const i=yr()||iu(),r=uc();if(!i||r.length===0){d();return}fo=!0;d();n(ur,"Creating selected characters...");try{const u=await ri("/api/word-companion/manuscript/create-discovered-characters",{projectId:i.projectId,candidateNames:r});t(u.message||"Characters created.");n(ur,`${u.createdCount||0} created, ${u.skippedCount||0} already existed.`);yc()}catch(u){console.error("Unable to create discovered characters.",u);n(ur,`Unable to create characters: ${s(u)}`)}finally{fo=!1;d()}},lp=async()=>{if(!su||!rt){pr(!1);return}const n=oy();if(n)try{const i=await pt(`/api/word-companion/manuscript/book/${n.bookId}`),t=i?.manuscriptDocument;if(t&&String(t.documentGuid).toLowerCase()===n.documentGuid.toLowerCase()){vu=n;c(f.projectId,n.projectId);c(f.bookId,n.bookId);v&&(v.value=String(n.projectId));await br(n.projectId,n.bookId);pr(!1);gf("Connected");return}}catch{}vu=null;rc();yr()?await br(yr().projectId,null):h(y,"Select a project first");it("Select a Project and Book to begin.");pr(!0)},ap=(n,t)=>pt(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),vp=(n,t)=>pt(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),he=n=>n?[...n.querySelectorAll("input[type='checkbox']:checked")].map(n=>Number.parseInt(n.value||"",10)).filter(n=>Number.isInteger(n)&&n>0):[],pc=()=>{const n=Number.parseInt(di?.value||"",10);return Number.isInteger(n)&&n>0?n:null},yp=()=>{const n=new Set(he(eu)),t=new Set(he(ou));gt={characters:gt.characters.map(t=>({...t,linked:n.has(Number.parseInt(ue(t,"character"),10))})),assets:gt.assets.map(n=>({...n,linked:t.has(Number.parseInt(ue(n,"asset"),10))})),locations:gt.locations,primaryLocationId:pc()}},pp=async()=>{if(!r)return!1;if(!kt||!rt||!window.Word||typeof window.Word.run!="function")return yi(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1;try{const n=await window.Word.run(async n=>await wr(n)),u=n.currentChapter?.title||"",f=n.currentScene?.title||"",t=n.currentScene?.anchorId||null,i=n.currentChapter?.anchorId||null,o=Number.isInteger(t)&&t===r,s=Number.isInteger(i)&&i===e,h=b(f,"scene").toLocaleLowerCase()===b(df||nt,"scene").toLocaleLowerCase(),c=b(u,"chapter").toLocaleLowerCase()===b(co||p,"chapter").toLocaleLowerCase(),l=o||h&&(s||c);return l?(yi(!1),!0):(yi(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1)}catch(n){return console.error("Unable to verify current Word scene before saving.",n),i({lastError:s(n)}),yi(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1}},wp=async()=>{if(!r){cr("Link a PlotDirector scene first.");return}if(ht||!await pp()){cr("The Word cursor is now in a different scene. Refresh Current Scene before saving.");return}ei&&(ei.disabled=!0,ei.textContent="Saving...");try{await vp(`/api/word-companion/scenes/${r}/links`,{characterIds:he(eu),assetIds:he(ou),locationIds:[],primaryLocationId:pc()});yp();cr("Scene links saved successfully.");i({lastError:"-"})}catch(n){cr("Unable to save scene links.");i({lastError:s(n)})}finally{ei&&(ei.disabled=!r||ht,ei.textContent="Save Scene Links")}},bp=(n,t)=>{const i=Array.isArray(n?.contentControls?.items)?n.contentControls.items:[];return i.find(n=>ec(n.tag,t))||null},rf=(n,t,i,r)=>{const f=bp(n,r),u=f||n.getRange().insertContentControl();return u.title=t,u.tag=i,u.appearance="Hidden",u},wc=async(n="PlotDirector IDs attached successfully.")=>{if(!r||!e)return t("No resolved PlotDirector scene."),!1;const f=w&&w!==r||a&&a!==e;if(f&&!window.confirm("This scene is already linked. Replace the existing PlotDirector link?"))return!1;if(!kt||!rt||!window.Word||typeof window.Word.run!="function")return t("Word document access is unavailable."),!1;ui&&(ui.disabled=!0,ui.textContent="Attaching...");try{return await window.Word.run(async n=>{const t=await wr(n);if(!t.currentChapter||!t.currentScene)throw new Error("No scene detected in Word. Use Heading 2 for scenes.");const i=t.bodyParagraphs[t.currentChapter.paragraphIndex],u=t.bodyParagraphs[t.currentScene.paragraphIndex];if(!i||!u)throw new Error("Unable to locate the current Word headings.");rf(i,"PlotDirector Chapter",`PD-CHAPTER-${e}`,"PD-CHAPTER");rf(u,"PlotDirector Scene",`PD-SCENE-${r}`,"PD-SCENE");await n.sync()}),a=e,w=r,lt=!1,li="SceneID Anchor",cu="Anchor",t(n),i({lastError:"-"}),ai(),!0}catch(u){return console.error("Unable to attach PlotDirector IDs.",u),t("Unable to attach PlotDirector IDs."),i({lastError:s(u)}),ai(),!1}finally{ui&&(ui.textContent=w===r?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",ai())}},bc=async n=>{if(!e)return ti("No resolved PlotDirector chapter."),!1;if(!kt||!rt||!window.Word||typeof window.Word.run!="function")return ti("Word document access is unavailable."),!1;try{return await window.Word.run(async n=>{const t=await wr(n);if(!t.currentChapter)throw new Error("No chapter detected in Word. Use Heading 1 for chapters.");const i=t.bodyParagraphs[t.currentChapter.paragraphIndex];if(!i)throw new Error("Unable to locate the current Word chapter heading.");rf(i,"PlotDirector Chapter",`PD-CHAPTER-${e}`,"PD-CHAPTER");await n.sync()}),a=e,lt=!1,li="ChapterID Anchor",cu="Chapter anchor",ti(n),t(n),i({lastError:"-"}),ai(),!0}catch(r){return console.error("Unable to attach PlotDirector chapter ID.",r),ti("Unable to attach PlotDirector chapter ID."),i({lastError:s(r)}),ai(),!1}},kp=async()=>{await wc()},kc=async n=>{du(),await ce(),t(n),ti(n)},us=n=>{wf&&(wf(n),wf=null),si?.close?si.close():si&&(si.hidden=!0)},dp=(t,i)=>(n(la,`"${t}"`),n(aa,`"${i}"`),!si)?Promise.resolve(window.confirm(`Create PlotDirector chapter: - -"${t}" - -in book: - -"${i}" - -?`)):new Promise(n=>{wf=n,si.showModal?si.showModal():si.hidden=!1}),gp=async()=>{const n=l();if(!n||!p||e){ie("Chapter not found in PlotDirector.");return}const t=ar(p),r=await dp(t,vr(n)||"selected book");if(r){ft&&(ft.disabled=!0,ft.textContent="Creating...");try{const r=Number.isInteger(yf)&&yf>0?yf*10:null,i=await ri(`/api/word-companion/books/${n.bookId}/chapters`,{title:t,sortOrder:r});if(!i?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");rr(null,i.chapterId,"Manual chapter link");const u=await bc("Chapter created and linked successfully.");if(!u)return;await kc("Chapter created and linked successfully.")}catch(u){ti("Unable to create chapter.");i({lastError:s(u)})}finally{ft&&(ft.disabled=!po(),ft.textContent="Create Chapter in PlotDirector")}}},dc=()=>{if(lf){const n=ar(cf?.value||"").toLocaleLowerCase(),t=uo.filter(t=>!n||String(t.title||"").toLocaleLowerCase().includes(n));if(lf.innerHTML="",au=null,bt&&(bt.disabled=!0),t.length===0){const n=document.createElement("p");n.className="word-companion-empty-list";n.textContent="No chapters found.";lf.append(n);return}for(const n of t){const i=Number.parseInt(n.chapterId||"",10);if(Number.isInteger(i)&&!(i<=0)){const r=document.createElement("label");r.className="word-companion-scene-option";const t=document.createElement("input");t.type="radio";t.name="word-companion-link-chapter";t.value=String(i);t.addEventListener("change",()=>{au=i,bt&&(bt.disabled=!1)});const u=document.createElement("span");u.textContent=n.title||"Untitled chapter";r.append(t,u);lf.append(r)}}}},nw=async()=>{const t=l();if(!t||!p||e){ie("Chapter not found in PlotDirector.");return}et&&(et.disabled=!0,et.textContent="Loading...");try{uo=await dh(t.bookId);au=null;cf&&(cf.value="");n(to,"");dc();nr?.showModal?nr.showModal():nr&&(nr.hidden=!1)}catch(r){ti("Unable to load chapters.");i({lastError:s(r)})}finally{et&&(et.disabled=!po(),et.textContent="Link to Existing Chapter")}},gc=()=>{nr?.close?nr.close():nr&&(nr.hidden=!0)},tw=async()=>{const t=uo.find(n=>n.chapterId===au);if(!t){n(to,"Select a chapter.");return}bt&&(bt.disabled=!0,bt.textContent="Linking...");try{rr(null,t.chapterId,"Manual chapter link");const n=await bc("Chapter linked successfully.");if(!n)return;gc();await kc("Chapter linked successfully.")}catch(r){n(to,"Unable to link chapter.");ti("Unable to link chapter.");i({lastError:s(r)})}finally{bt&&(bt.disabled=!au,bt.textContent="Link Chapter")}},nl=async(n,t,i)=>{const r=l();if(!r)return lr("Select a PlotDirector book first."),!1;await ee(r.bookId,n,t,"Manual link","Title Match");const u=await wc(i);return u?(lr(i),re(),!0):!1},fs=n=>{pf&&(pf(n),pf=null),oi?.close?oi.close():oi&&(oi.hidden=!0)},iw=(t,i)=>(n(ea,`"${t}"`),n(oa,`"${i}"`),!oi)?Promise.resolve(window.confirm(`Create PlotDirector scene: - -"${t}" - -within chapter: - -"${i}" - -?`)):new Promise(n=>{pf=n,oi.showModal?oi.showModal():oi.hidden=!1}),rw=async()=>{const n=l();if(!n||!nt){gu("Scene not found in PlotDirector.");return}const t=b(nt,"scene"),r=b(p,"chapter"),u=await iw(t,r);if(u){ot&&(ot.disabled=!0,ot.textContent="Creating...");try{const r=await nc();if(!r){gu("This chapter does not exist in PlotDirector. Create or link the chapter first.");return}const i=await ri(`/api/word-companion/books/${n.bookId}/chapters/${r.chapterId}/scenes`,{sceneTitle:t});if(!i?.sceneId||!i?.chapterId)throw new Error("Scene creation did not return a scene ID.");await nl(i.sceneId,i.chapterId,"Scene created and linked successfully.")}catch(f){lr("Unable to create scene.");i({lastError:s(f)})}finally{ot&&(ot.disabled=!wo(),ot.textContent="Create Scene in PlotDirector")}}},tl=()=>{if(hf){const n=ar(sf?.value||"").toLocaleLowerCase(),t=ro.filter(t=>!n||String(t.title||"").toLocaleLowerCase().includes(n));if(hf.innerHTML="",lu=null,wt&&(wt.disabled=!0),t.length===0){const n=document.createElement("p");n.className="word-companion-empty-list";n.textContent="No scenes found.";hf.append(n);return}for(const n of t){const i=Number.parseInt(n.sceneId||"",10);if(Number.isInteger(i)&&!(i<=0)){const r=document.createElement("label");r.className="word-companion-scene-option";const t=document.createElement("input");t.type="radio";t.name="word-companion-link-scene";t.value=String(i);t.addEventListener("change",()=>{lu=i,wt&&(wt.disabled=!1)});const u=document.createElement("span");u.textContent=n.title||"Untitled scene";r.append(t,u);hf.append(r)}}}},uw=async()=>{const t=l();if(!t||!nt){gu("Scene not found in PlotDirector.");return}st&&(st.disabled=!0,st.textContent="Loading...");try{const r=await bo(t.bookId),i=gh(r);if(!i){gu("This chapter does not exist in PlotDirector. Create or link the chapter first.");return}ro=Array.isArray(i.scenes)?i.scenes:[];lu=null;sf&&(sf.value="");n(no,"");tl();gi?.showModal?gi.showModal():gi&&(gi.hidden=!1)}catch(r){lr("Unable to load scenes.");i({lastError:s(r)})}finally{st&&(st.disabled=!wo(),st.textContent="Link to Existing Scene")}},il=()=>{gi?.close?gi.close():gi&&(gi.hidden=!0)},fw=async()=>{const r=l(),t=ro.find(n=>n.sceneId===lu);if(!r||!t){n(no,"Select a scene.");return}wt&&(wt.disabled=!0,wt.textContent="Linking...");try{const n=await nc();if(!n)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");il();await nl(t.sceneId,n.chapterId,"Scene linked successfully.")}catch(u){n(no,"Unable to link scene.");lr("Unable to link scene.");i({lastError:s(u)})}finally{wt&&(wt.disabled=!lu,wt.textContent="Link Scene")}},ew=async()=>{if(!r){nu("No resolved PlotDirector scene.");return}if(ht){nu("Refresh Current Scene before syncing.");return}if(!Number.isInteger(hu)){nu("Unable to sync progress.");return}fi&&(fi.disabled=!0,fi.textContent="Syncing...");const t=(new Date).toISOString();try{const i=await ap(`/api/word-companion/scenes/${r}/word-count`,{actualWordCount:hu,lastWorkedOn:t});n(ge,o(i?.actualWords??hu));n(be,o(i?.actualWords??hu));n(kl,(new Date).toLocaleString());nu("Progress synced successfully.")}catch{nu("Unable to sync progress.")}finally{fi&&(fi.disabled=!r||ht,fi.textContent="Sync Progress")}},rl=async()=>{const r=iu(),n=l(),u=b(p,"chapter");if(ut({projectId:r?.projectId,projectTitle:r?.title,bookId:n?.bookId,bookTitle:n?vr(n):undefined,detectedChapter:p,detectedScene:nt,requestChapter:u,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!n)return k("Not detected"),t("Select a PlotDirector book first."),!1;if(!p)return k("Not detected"),t("No chapter detected in Word. Use Heading 1 for chapters."),!1;k("Not detected");try{const f=await dh(n.bookId),i=a?f.find(n=>n.chapterId===a):null,e=u.toLocaleLowerCase(),o=e?f.find(n=>b(n.title,"chapter").toLocaleLowerCase()===e):null,r=i||o;return r?(du(),rr(null,r.chapterId,i?"Chapter anchor":"Chapter title"),li=i?"ChapterID Anchor":"Title Match",gr("Chapter linked to PlotDirector"),t("No scene detected in Word. Use Heading 2 for scenes."),ut({result:"Chapter matched",chapterId:r.chapterId,sceneId:null}),!0):(rr(null),gr("Chapter not found in PlotDirector."),t("Chapter not found in PlotDirector."),ut({result:"Chapter not matched",chapterId:null,sceneId:null}),ie("Chapter not found in PlotDirector."),!1)}catch(f){return k("Not found in PlotDirector"),i({lastError:s(f)}),t("Unable to load PlotDirector chapter data."),!1}},ce=async()=>{const u=iu(),n=l(),f=b(p,"chapter"),r=b(nt,"scene");if(ut({projectId:u?.projectId,projectTitle:u?.title,bookId:n?.bookId,bookTitle:n?vr(n):undefined,detectedChapter:p,detectedScene:nt,requestChapter:f,requestScene:r,result:"Not run",chapterId:null,sceneId:null}),vo({anchorType:w?"SceneID Anchor":a?"ChapterID Anchor":"Title Match",storedSceneId:w,storedChapterId:a,resolutionMethod:"-"}),!n)return k("Not detected"),t("Select a PlotDirector book first."),ut({result:"Error"}),!1;if(!p||!nt)return k("Not detected"),t("No scene detected in Word. Use Heading 2 for scenes."),ut({result:"Error"}),!1;or&&(or.disabled=!0,or.textContent="Refreshing...");const o=()=>{or&&(or.disabled=!1,or.textContent="Refresh PlotDirector Scene")};k("Not detected");t("Resolving PlotDirector scene...");try{if(w){const i=await uy(n.bookId,(n,t)=>t.sceneId===w);if(i)return ut({result:"Matched",chapterId:i.chapter.chapterId,sceneId:i.scene.sceneId}),await ee(n.bookId,i.scene.sceneId,i.chapter.chapterId,"Anchor","SceneID Anchor"),!0;lt=!0;li="SceneID Anchor";gr("Not found in PlotDirector");t("Stored PlotDirector ID is invalid.");ut({result:"Error",chapterId:a,sceneId:w});vo({anchorType:"SceneID Anchor",storedSceneId:w,storedChapterId:a,resolutionMethod:"Anchor"})}if(a){const u=await bo(n.bookId),t=u.find(n=>n.chapterId===a),i=t?(Array.isArray(t.scenes)?t.scenes:[]).find(n=>b(n.title,"scene").toLocaleLowerCase()===r.toLocaleLowerCase()):null;if(i)return ut({result:"Matched",chapterId:t.chapterId,sceneId:i.sceneId}),await ee(n.bookId,i.sceneId,t.chapterId,"Anchor","ChapterID Anchor"),!0;t&&!w?(li="ChapterID Anchor",rr(null,a,"Chapter anchor"),ut({result:"Chapter matched",chapterId:a,sceneId:null})):w||(li="ChapterID Anchor",ut({result:"Chapter anchor not found",chapterId:a,sceneId:null}))}const i=await ri(`/api/word-companion/books/${n.bookId}/resolve-scene`,{chapterTitle:f,sceneTitle:r});if(!i?.matched||!i.sceneId){const u=lt,f=Number.parseInt(i?.chapterId||"",10),s=Number.isInteger(e)&&e>0?e:null,n=Number.isInteger(f)&&f>0?f:s,r=!!i?.chapterMatched||!!n;return k("Not found in PlotDirector"),lt=u,r&&(rr(null,n,n===s?"Chapter anchor":"Chapter title"),gr("Scene not found in PlotDirector.")),t(u?"Stored PlotDirector ID is invalid.":r?"Scene not found in PlotDirector.":"This chapter does not exist in PlotDirector. Create or link the chapter first."),ut({result:"Not matched",chapterId:r?n:i?.chapterId,sceneId:i?.sceneId}),u||(r?(du(),gu("Scene not found in PlotDirector.")):(re(),ie("Chapter not found in PlotDirector."))),o(),!1}const u=lt;return ut({result:u?"Matched by title fallback":"Matched",chapterId:i.chapterId,sceneId:i.sceneId}),await ee(n.bookId,i.sceneId,i.chapterId,u?"Title fallback":"Title","Title Match"),u&&(lt=!0,t("Stored PlotDirector ID is invalid."),ai()),!0}catch(h){const n=lt;return i({lastError:s(h)}),k("Not found in PlotDirector"),lt=n,t(n?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),ut({result:"Error"}),!1}finally{o()}},ow=n=>{const t=n.currentChapter?.title||"",i=n.currentScene?.title||"",r=n.currentChapter?.anchorId||null,u=n.currentScene?.anchorId||null;return b(t,"chapter")!==b(p,"chapter")||b(i,"scene")!==b(nt,"scene")||r!==a||u!==w},sw=async()=>{if(!ho&&su&&l()){if(!kt||!rt||!window.Word||typeof window.Word.run!="function"){ni("Manual");t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");return}ho=!0;ni("Refreshing");t("Updating current scene...");try{const n=await window.Word.run(async n=>await wr(n)),r=ow(n);if(ku(n.currentChapter?.title,n.currentScene?.title,n.currentScene?.wordCount,n.currentChapter?.anchorId,n.currentScene?.anchorId,n.currentChapter?.index),ts(n),i({lastScan:"Success",lastError:"-",paragraphs:String(n.paragraphCount),heading1:String(n.heading1Count),heading2:String(n.heading2Count)}),!r){yi(!1);ni("Live");t("Current scene updated.");return}nt?await ce():await rl();yi(!1);ni("Live");t("Current scene updated.")}catch(n){console.error("Unable to refresh current scene from Word selection.",n);i({lastScan:"Failure",lastError:s(n)});yi(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving.")}finally{ho=!1}}},hw=()=>{oo&&window.clearTimeout(oo),oo=window.setTimeout(sw,850)},ul=()=>{hw()},cw=()=>{if(so&&window.Office?.context?.document&&typeof window.Office.context.document.removeHandlerAsync=="function"&&window.Office?.EventType?.DocumentSelectionChanged)try{window.Office.context.document.removeHandlerAsync(window.Office.EventType.DocumentSelectionChanged,{handler:ul});so=!1}catch(n){console.warn("Unable to remove Word selection tracking handler.",n)}},lw=()=>{if(su){if(!window.Office?.context?.document||typeof window.Office.context.document.addHandlerAsync!="function"||!window.Office?.EventType?.DocumentSelectionChanged){ni("Manual");t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");return}try{window.Office.context.document.addHandlerAsync(window.Office.EventType.DocumentSelectionChanged,ul,n=>{n?.status===window.Office.AsyncResultStatus.Succeeded?(so=!0,ni("Live")):(ni("Manual"),t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))});window.addEventListener("beforeunload",cw)}catch(n){console.warn("Unable to register Word selection tracking handler.",n);ni("Manual");t("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}},aw=async()=>{if(!l()){t("Select a PlotDirector book first.");k("Not detected");return}bh(!0);try{const n=await cc();if(!n)return;if(yi(!1),!nt){await rl();return}await ce()}finally{bh(!1)}},br=async(n,t)=>{if(!n){ct=[];h(g,"Select a project first");h(y,"Select a project first");bu("");c(f.bookId,null);ii();k("Not detected");tu();return}h(g,"Loading books...");bu("");k("Not detected");tu("Select a book to analyse manuscript structure.");try{const r=await pt(`/api/word-companion/projects/${n}/books`);if(ct=Array.isArray(r.books)?r.books:[],ct.length===0){h(g,"No books available.");h(y,"No books available.");bu("No books available.");c(f.bookId,null);ii();it("No books available.");return}oe(g,"Choose a book",ct.map(n=>({...n,displayTitle:vr(n)})),"bookId","displayTitle");const i=ct.find(n=>n.bookId===t);i&&g?(g.value=String(i.bookId),c(f.bookId,i.bookId)):c(f.bookId,null);fy(i?.bookId||t);ii();k(l()?"Not detected":"Not detected");tu(l()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure.");it(ru()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{ct=[];h(g,"Unable to load books.");h(y,"Unable to load books.");bu("Unable to load books.");c(f.bookId,null);ii();k("Not detected");tu("Unable to load books.");it("Unable to load books.")}},vw=async()=>{h(v,"Loading projects...");h(g,"Select a project first");h(tt,"Loading projects...");h(y,"Select a project first");ao("");bu("");try{const t=await pt("/api/word-companion/projects");if(ci=Array.isArray(t.projects)?t.projects:[],ci.length===0){h(v,"No projects available.");h(tt,"No projects available.");ao("No projects available.");c(f.projectId,null);c(f.bookId,null);ii();it("No projects available.");return}oe(v,"Choose a project",ci,"projectId","title");rc();const i=ic(f.projectId),n=ci.find(n=>n.projectId===i);n&&v?(v.value=String(n.projectId),tt&&(tt.value=String(n.projectId)),c(f.projectId,n.projectId),await br(n.projectId,ic(f.bookId))):(c(f.projectId,null),c(f.bookId,null),ii(),it("Select a Project and Book to begin."))}catch{ci=[];ct=[];h(v,"Unable to connect to PlotDirector.");h(g,"Select a project first");h(tt,"Unable to connect to PlotDirector.");h(y,"Select a project first");gf("Unable to connect to PlotDirector.");ao("Unable to connect to PlotDirector.");c(f.projectId,null);c(f.bookId,null);ii();it("Unable to connect to PlotDirector.")}};for(const n of le)n.addEventListener("click",()=>yh(n.dataset.tabButton));ph();v?.addEventListener("change",async()=>{const n=Number.parseInt(v.value||"",10);tt&&Number.isInteger(n)&&n>0&&(tt.value=String(n));c(f.projectId,Number.isInteger(n)&&n>0?n:null);c(f.bookId,null);k("Not detected");tu();it("Select a Book to begin.");await br(n,null)});g?.addEventListener("change",()=>{const n=Number.parseInt(g.value||"",10);c(f.bookId,Number.isInteger(n)&&n>0?n:null);y&&Number.isInteger(n)&&n>0&&(y.value=String(n));ii();k("Not detected");tu(l()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure.");it(ru()?"Ready to scan manuscript structure.":"Select a Book to begin.")});tt?.addEventListener("change",async()=>{const n=Number.parseInt(tt.value||"",10);v&&Number.isInteger(n)&&n>0&&(v.value=String(n));c(f.projectId,Number.isInteger(n)&&n>0?n:null);c(f.bookId,null);it("Select a Book to begin.");await br(n,null)});y?.addEventListener("change",()=>{const n=Number.parseInt(y.value||"",10);g&&Number.isInteger(n)&&n>0&&(g.value=String(n));c(f.bookId,Number.isInteger(n)&&n>0?n:null);ii();it(ru()?"Ready to scan manuscript structure.":"Select a Book to begin.")});uu?.addEventListener("input",d);uf?.addEventListener("click",async()=>{const n=yr(),t=String(uu?.value||"").trim();if(!n||!t){d();return}uf.disabled=!0;at("Creating Book...");try{const i=await ri(`/api/word-companion/projects/${n.projectId}/books`,{title:t});uu&&(uu.value="");v&&(v.value=String(n.projectId));await br(n.projectId,i.bookId);y&&(y.value=String(i.bookId));at("Ready to scan manuscript structure.")}catch(i){console.error("Unable to create Book from Word Companion.",i);at(`Unable to create Book: ${s(i)}`)}finally{d()}});wi?.addEventListener("click",op);pe?.addEventListener("click",hp);ve?.addEventListener("click",cp);cl?.addEventListener("click",yc);sl?.addEventListener("click",()=>pr(!1));ll?.addEventListener("click",()=>it("Import cancelled."));er?.addEventListener("click",cc);ki?.addEventListener("click",lc);we?.addEventListener("click",fp);pa?.addEventListener("click",()=>rs(!0));wa?.addEventListener("click",()=>rs(!1));hi?.addEventListener("cancel",n=>{n.preventDefault(),rs(!1)});or?.addEventListener("click",ce);ef?.addEventListener("click",aw);fi?.addEventListener("click",ew);ei?.addEventListener("click",wp);ui?.addEventListener("click",kp);ft?.addEventListener("click",gp);et?.addEventListener("click",nw);cf?.addEventListener("input",dc);bt?.addEventListener("click",tw);ca?.addEventListener("click",gc);va?.addEventListener("click",()=>us(!0));ya?.addEventListener("click",()=>us(!1));si?.addEventListener("cancel",n=>{n.preventDefault(),us(!1)});ot?.addEventListener("click",rw);st?.addEventListener("click",uw);sf?.addEventListener("input",tl);wt?.addEventListener("click",fw);fa?.addEventListener("click",il);sa?.addEventListener("click",()=>fs(!0));ha?.addEventListener("click",()=>fs(!1));oi?.addEventListener("cancel",n=>{n.preventDefault(),fs(!1)});sr?.addEventListener("click",ep);const yw=su?vw():Promise.resolve();if(su||(h(v,"Please sign in to PlotDirector."),h(g,"Please sign in to PlotDirector."),h(tt,"Please sign in to PlotDirector."),h(y,"Please sign in to PlotDirector."),ii()),!window.Office||typeof window.Office.onReady!="function"){lo("Word Companion ready");t("Word document access is unavailable.");ni("Manual");i({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"});return}tc().then(async()=>{lo("Word Companion ready"),await yw,await lp(),rt?lw():(t("Word document access is unavailable."),ni("Manual"))}).catch(n=>{console.error("Office readiness check failed.",n),gf("Unable to connect to PlotDirector."),lo("Word Companion unavailable"),t("Word document access is unavailable."),i({ready:"No",wordApi:"No",lastScan:"Failure"})})})(); \ No newline at end of file +(()=>{const e="plotdirector.word.projectId",t="plotdirector.word.bookId",r="plotdirector.word.activeTab",n="plotdirector.word.documentGuid",o="plotdirector.word.boundBookId",a="plotdirector.word.boundProjectId",c="plotdirector.word.bindingVersion",i=new Set(["scene","links","structure","diagnostics"]),s=document.querySelector(".word-companion-shell"),d=document.querySelector(".word-companion-tabs"),l=[...document.querySelectorAll("[data-tab-button]")],u=[...document.querySelectorAll("[data-tab-panel]")],p=document.querySelector("[data-first-run-wizard]"),h=document.querySelector("[data-first-run-project-select]"),m=document.querySelector("[data-first-run-book-select]"),y=document.querySelector("[data-first-run-new-book-title]"),f=document.querySelector("[data-first-run-create-book]"),w=document.querySelector("[data-first-run-scan]"),S=document.querySelector("[data-first-run-cancel]"),g=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]"),E=document.querySelector("[data-first-run-create-characters]"),L=document.querySelector("[data-first-run-skip-characters]"),N=document.querySelector("[data-first-run-import-actions]"),q=document.querySelector("[data-first-run-import]"),x=document.querySelector("[data-first-run-import-cancel]"),P=document.querySelector("[data-first-run-replace-dialog]"),D=document.querySelector("[data-first-run-replace-confirm]"),A=document.querySelector("[data-first-run-replace-cancel]"),T=document.querySelector("[data-office-status]"),$=document.querySelector("[data-connection-status]"),j=document.querySelector("[data-summary-connection]"),R=document.querySelector("[data-summary-project]"),W=document.querySelector("[data-summary-book]"),U=document.querySelector("[data-project-select]"),M=document.querySelector("[data-book-select]"),O=document.querySelector("[data-project-message]"),H=document.querySelector("[data-book-message]"),B=document.querySelector("[data-refresh-current-scene]"),F=document.querySelector("[data-refresh-document]"),G=document.querySelector("[data-current-chapter]"),V=document.querySelector("[data-current-scene]"),J=document.querySelector("[data-current-word-count]"),Y=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]"),_=document.querySelector("[data-structure-preview-status]"),ee=document.querySelector("[data-structure-preview-results]"),te=document.querySelector("[data-refresh-plotdirector-scene]"),re=document.querySelector("[data-plotdirector-scene-status]"),ne=document.querySelector("[data-anchor-status]"),oe=document.querySelector("[data-anchor-book-id]"),ae=document.querySelector("[data-anchor-chapter-id]"),ce=document.querySelector("[data-anchor-scene-id]"),ie=document.querySelector("[data-attach-plotdirector-ids]"),se=document.querySelector("[data-plotdirector-scene-details]"),de=document.querySelector("[data-plotdirector-scene-title]"),le=document.querySelector("[data-plotdirector-revision-status]"),ue=document.querySelector("[data-plotdirector-estimated-words]"),pe=document.querySelector("[data-plotdirector-actual-words]"),he=document.querySelector("[data-plotdirector-blocked-status]"),me=document.querySelector("[data-plotdirector-blocked-reason-row]"),ye=document.querySelector("[data-plotdirector-blocked-reason]"),fe=document.querySelector("[data-sync-scene-progress]"),we=document.querySelector("[data-sync-word-count]"),Se=document.querySelector("[data-sync-plotdirector-count]"),ge=document.querySelector("[data-sync-last-synced]"),Ce=document.querySelector("[data-sync-status]"),be=document.querySelector("[data-writing-brief-block]"),Ie=document.querySelector("[data-writing-brief]"),ke=document.querySelector("[data-plotdirector-link-groups]"),ve=document.querySelector("[data-character-chips]"),Ee=document.querySelector("[data-asset-chips]"),Le=(document.querySelector("[data-location-chips]"),document.querySelector("[data-primary-location-select]")),Ne=document.querySelector("[data-save-scene-links]"),qe=document.querySelector("[data-scene-links-status]"),xe=document.querySelector("[data-links-editing-scene]"),Pe=document.querySelector("[data-chapter-create-link]"),De=document.querySelector("[data-chapter-create-link-chapter]"),Ae=document.querySelector("[data-create-plotdirector-chapter]"),Te=document.querySelector("[data-link-existing-chapter]"),$e=document.querySelector("[data-chapter-create-link-status]"),je=document.querySelector("[data-scene-create-link]"),Re=document.querySelector("[data-create-link-chapter]"),We=document.querySelector("[data-create-link-scene]"),Ue=document.querySelector("[data-create-plotdirector-scene]"),Me=document.querySelector("[data-link-existing-scene]"),Oe=document.querySelector("[data-create-link-status]"),He=document.querySelector("[data-link-existing-dialog]"),Be=document.querySelector("[data-link-scene-search]"),Fe=document.querySelector("[data-link-scene-options]"),Ge=document.querySelector("[data-link-selected-scene]"),Ve=document.querySelector("[data-link-dialog-cancel]"),Je=document.querySelector("[data-link-dialog-status]"),Ye=document.querySelector("[data-create-scene-dialog]"),ze=document.querySelector("[data-create-dialog-scene]"),Ke=document.querySelector("[data-create-dialog-chapter]"),Qe=document.querySelector("[data-create-dialog-confirm]"),Xe=document.querySelector("[data-create-dialog-cancel]"),Ze=document.querySelector("[data-link-existing-chapter-dialog]"),_e=document.querySelector("[data-link-chapter-search]"),et=document.querySelector("[data-link-chapter-options]"),tt=document.querySelector("[data-link-selected-chapter]"),rt=document.querySelector("[data-link-chapter-dialog-cancel]"),nt=document.querySelector("[data-link-chapter-dialog-status]"),ot=document.querySelector("[data-create-chapter-dialog]"),at=document.querySelector("[data-create-chapter-dialog-chapter]"),ct=document.querySelector("[data-create-chapter-dialog-book]"),it=document.querySelector("[data-create-chapter-dialog-confirm]"),st=document.querySelector("[data-create-chapter-dialog-cancel]"),dt=document.querySelector("[data-apply-structure-sync-dialog]"),lt=document.querySelector("[data-apply-structure-sync-summary]"),ut=document.querySelector("[data-apply-structure-sync-confirm]"),pt=document.querySelector("[data-apply-structure-sync-cancel]"),ht=document.querySelector("[data-resolve-project-id]"),mt=document.querySelector("[data-resolve-project-title]"),yt=document.querySelector("[data-resolve-book-id]"),ft=document.querySelector("[data-resolve-book-title]"),wt=document.querySelector("[data-resolve-detected-chapter]"),St=document.querySelector("[data-resolve-detected-scene]"),gt=document.querySelector("[data-resolve-request-chapter]"),Ct=document.querySelector("[data-resolve-request-scene]"),bt=document.querySelector("[data-resolve-result]"),It=document.querySelector("[data-resolve-chapter-id]"),kt=document.querySelector("[data-resolve-scene-id]"),vt=document.querySelector("[data-run-diagnostics]"),Et=document.querySelector("[data-diagnostic-host]"),Lt=document.querySelector("[data-diagnostic-platform]"),Nt=document.querySelector("[data-diagnostic-ready]"),qt=document.querySelector("[data-diagnostic-word-api]"),xt=document.querySelector("[data-diagnostic-last-scan]"),Pt=document.querySelector("[data-diagnostic-last-error]"),Dt=document.querySelector("[data-diagnostic-anchor-type]"),At=document.querySelector("[data-diagnostic-stored-scene-id]"),Tt=document.querySelector("[data-diagnostic-stored-chapter-id]"),$t=document.querySelector("[data-diagnostic-resolution-method]"),jt=document.querySelector("[data-diagnostic-paragraphs]"),Rt=document.querySelector("[data-diagnostic-heading1]"),Wt=document.querySelector("[data-diagnostic-heading2]"),Ut="true"===s?.dataset.authenticated;let Mt=[],Ot=[],Ht=!1,Bt=!1,Ft="Unknown",Gt="Unknown",Vt="",Jt="",Yt=null,zt=null,Kt=null,Qt=null,Xt=null,Zt=null,_t="",er="Title Match",tr=!1,rr=[],nr=null,or=null,ar=[],cr=null,ir=null,sr=null,dr=null,lr=null,ur=null,pr=[],hr=!1,mr=!1,yr=!1,fr=!1,wr=null,Sr="Manual",gr=!1,Cr=null,br=!1,Ir=!1,kr="",vr="",Er={characters:[],assets:[],locations:[],primaryLocationId:null};const Lr=e=>{T&&(T.textContent=e)},Nr=(e,t=!0)=>{const n=i.has(e)&&l.some(t=>t.dataset.tabButton===e)?e:"scene";for(const e of l){const t=e.dataset.tabButton===n;e.classList.toggle("is-active",t),e.setAttribute("aria-selected",t?"true":"false")}for(const e of u){const t=e.dataset.tabPanel===n;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{}})(r,n)},qr=()=>{const e=(e=>{try{return window.localStorage.getItem(e)||""}catch{return""}})(r);Nr(i.has(e)?e:"scene",!1)},xr=e=>{$&&($.textContent=e),j&&(j.textContent=e)},Pr=e=>{O&&(O.textContent=e)},Dr=e=>{H&&(H.textContent=e)},Ar=e=>{z&&(z.textContent=e)},Tr=e=>{re&&(re.textContent=e)},$r=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("anchorType")&&gn(Dt,Qr(e.anchorType)),t("storedSceneId")&&gn(At,Qr(e.storedSceneId)),t("storedChapterId")&&gn(Tt,Qr(e.storedChapterId)),t("resolutionMethod")&&gn($t,Qr(e.resolutionMethod))},jr=()=>{const e=xn(),t=Number.isInteger(Xt)&&Xt>0&&Qt===Xt,r=!Number.isInteger(Zt)||Zt<=0||Kt===Zt,n=t&&r;gn(ne,n?"Attached to PlotDirector":"Not attached"),gn(oe,e?.bookId?String(e.bookId):"-"),gn(ae,Number.isInteger(Zt)&&Zt>0?String(Zt):"-"),gn(ce,Number.isInteger(Xt)&&Xt>0?String(Xt):"-"),ie&&(ie.disabled=!Xt||n&&!tr,ie.textContent=Qt&&!n?"Reattach PlotDirector IDs":"Attach PlotDirector IDs"),$r({anchorType:er||"Title Match",storedSceneId:Qt,storedChapterId:Kt,resolutionMethod:_t})},Rr=(e,t,r,n=null,o=null,a=null)=>{Vt=e||"",Jt=t||"",Yt=Number.isInteger(r)?r:null,zt=Number.isInteger(a)&&a>0?a:null,Kt=Number.isInteger(n)&&n>0?n:null,Qt=Number.isInteger(o)&&o>0?o:null,G&&(G.textContent=e||"Not detected"),V&&(V.textContent=t||"Not detected"),J&&(J.textContent=Number.isInteger(r)?String(r):"-"),gn(we,Number.isInteger(r)?String(r):"-"),jr()},Wr=(e,t)=>{e&&(e.hidden=t)},Ur=e=>{gn(Ce,e)},Mr=e=>{gn(_,e)},Or=(e="Select a project and book to analyse manuscript structure.")=>{if(sr=null,ee){ee.innerHTML="";const e=document.createElement("p");e.textContent="No preview generated.",ee.append(e)}Mr(e),Br()},Hr=(e=sr)=>((e=sr)=>zn.flatMap(t=>Array.isArray(e?.[t.key])?e[t.key]:[]))(e).filter(e=>"couldLink"===e.category||"wouldCreateChapters"===e.category||"wouldCreateScenes"===e.category),Br=()=>{Z&&(Z.disabled=fr||0===Hr().length)},Fr=()=>{X&&(X.disabled=fr||!qn()||!xn()),Br()},Gr=()=>{xe&&(xe.textContent=Xt?`Editing links for: ${kr||Jt||"Current scene"}`:"Link a PlotDirector scene first.")},Vr=()=>{const e=gr||!Xt;fe&&(fe.disabled=e),Ne&&(Ne.disabled=e),Le&&(Le.disabled=e);for(const t of[ve,Ee])for(const r of t?[...t.querySelectorAll("input[type='checkbox']")]:[])r.disabled=e},Jr=e=>{"Live"!==e&&"Manual"!==e||(Sr=e),gn(Y,e||Sr||"Manual")},Yr=(e,t="")=>{gr=!!e,gn(Y,gr?"Stale":Sr),Vr(),t&&(Ar(t),Xr(t))},zr=(e,t=null,r="")=>{Xt=Number.isInteger(e)&&e>0?e:null,Zt=Number.isInteger(t)&&t>0?t:null,_t=r||"",Vr(),Ur(gr?"Refresh Current Scene before syncing.":Xt?"Ready to sync.":"No resolved PlotDirector scene."),Xr(gr?"Refresh Current Scene before saving.":Xt?"Ready to save.":"Link a PlotDirector scene first."),Gr(),jr()},Kr=e=>{B&&(B.disabled=e,B.textContent=e?"Refreshing...":"Refresh Current Scene")},Qr=e=>null==e||""===e?"-":String(e),Xr=e=>{gn(qe,e)},Zr=e=>{gn(Oe,e)},_r=e=>{gn($e,e)},en=()=>!!xn()&&!!Vt&&!Zt,tn=()=>!!xn()&&!!Jt&&Number.isInteger(Zt)&&Zt>0,rn=()=>{Wr(Pe,!0),_r(""),Ae&&(Ae.disabled=!0,Ae.textContent="Create Chapter in PlotDirector"),Te&&(Te.disabled=!0,Te.textContent="Link to Existing Chapter")},nn=(e="")=>{gn(De,Qr(Vt)),Wr(Pe,!1),_r(e);const t=en();Ae&&(Ae.disabled=!t,Ae.textContent="Create Chapter in PlotDirector"),Te&&(Te.disabled=!t,Te.textContent="Link to Existing Chapter")},on=()=>{Wr(je,!0),Zr(""),Ue&&(Ue.disabled=!0,Ue.textContent="Create Scene in PlotDirector"),Me&&(Me.disabled=!0,Me.textContent="Link to Existing Scene")},an=(e="")=>{gn(Re,Qr(Vt)),gn(We,Qr(Jt)),Wr(je,!1),Zr(e);const t=tn();Ue&&(Ue.disabled=!t,Ue.textContent="Create Scene in PlotDirector"),Me&&(Me.disabled=!t,Me.textContent="Link to Existing Scene")},cn=e=>{Tr(e),Wr(se,!0),Wr(be,!0),Wr(ke,!1),rn(),on(),_t="",kr="",vr="",er=Qt?"SceneID Anchor":Kt?"ChapterID Anchor":"Title Match",tr=!1,Er={characters:[],assets:[],locations:[],primaryLocationId:null},dn(ve,[],"character"),dn(Ee,[],"asset"),ln([],null,!1),zr(null),gn(Se,"-"),gn(de,"-"),gn(le,"-"),gn(ue,"-"),gn(pe,"-"),gn(he,"-"),gn(ye,"-"),Wr(me,!0),jr(),Gr()},sn=(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,dn=(e,t,r,n=!1)=>{if(!e)return;e.innerHTML="";const o=Array.isArray(t)?t:[];if(0===o.length){const t=document.createElement("p");return t.className="word-companion-empty-list",t.textContent="None",void e.append(t)}for(const t of o){const o=Number.parseInt(sn(t,r),10);if(!Number.isInteger(o)||o<=0)continue;const a=document.createElement("label");a.className="word-companion-check-item";const c=document.createElement("input");c.type="checkbox",c.value=String(o),c.checked=!!t.linked,c.disabled=!n;const i=document.createElement("span");i.textContent=t.name||"Unnamed",a.append(c,i),e.append(a)}},ln=(e,t,r=!1)=>{if(!Le)return;Le.innerHTML="";const n=document.createElement("option");n.value="",n.textContent="None",Le.append(n);const o=Number.parseInt(t||"",10);for(const t of Array.isArray(e)?e:[]){const e=Number.parseInt(sn(t,"location"),10);if(!Number.isInteger(e)||e<=0)continue;const r=document.createElement("option");r.value=String(e),r.textContent=t.name||"Unnamed",r.selected=e===o,Le.append(r)}Le.disabled=!r},un=e=>String(e||"").trim().replace(/\s+/g," "),pn=(e,t)=>{const r=un(e);if(!r)return"";const n=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 un(r.replace(n,""))||r},hn=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("projectId")&&gn(ht,Qr(e.projectId)),t("projectTitle")&&gn(mt,Qr(e.projectTitle)),t("bookId")&&gn(yt,Qr(e.bookId)),t("bookTitle")&&gn(ft,Qr(e.bookTitle)),t("detectedChapter")&&gn(wt,Qr(e.detectedChapter)),t("detectedScene")&&gn(St,Qr(e.detectedScene)),t("requestChapter")&&gn(gt,Qr(e.requestChapter)),t("requestScene")&&gn(Ct,Qr(e.requestScene)),t("result")&&gn(bt,Qr(e.result)),t("chapterId")&&gn(It,Qr(e.chapterId)),t("sceneId")&&gn(kt,Qr(e.sceneId))},mn=async e=>{const t=await fo(`/api/word-companion/books/${e}/structure`);return Array.isArray(t?.chapters)?t.chapters:[]},yn=async e=>{const t=await fo(`/api/word-companion/books/${e}/chapters`);return Array.isArray(t?.chapters)?t.chapters:[]},fn=e=>{if(Number.isInteger(Zt)&&Zt>0){const t=e.find(e=>e.chapterId===Zt);if(t)return t}const t=pn(Vt,"chapter").toLocaleLowerCase();return t&&e.find(e=>pn(e.title,"chapter").toLocaleLowerCase()===t)||null},wn=async()=>{const e=xn();return e?fn(await mn(e.bookId)):null},Sn=async(e,t,r,n,o)=>{const a=await fo(`/api/word-companion/scenes/${t}/companion`);try{a.revisionStatus=await(async(e,t)=>{const r=await fo(`/api/word-companion/books/${e}/structure`),n=Array.isArray(r?.chapters)?r.chapters:[];for(const e of n){const r=(Array.isArray(e.scenes)?e.scenes:[]).find(e=>e.sceneId===t);if(r)return r.revisionStatus||""}return""})(e,t)}catch{a.revisionStatus=""}var c;er=o||"Title Match",tr=!1,Yr(!1),Tr("Linked to PlotDirector"),Ar(""),rn(),on(),zr(t,r,n),c=a,kr=c?.sceneTitle||Jt||"",vr=c?.chapterTitle||Vt||"",gn(de,Qr(c?.sceneTitle)),gn(le,Qr(c?.revisionStatus||c?.revisionStatusName||"Not provided")),gn(ue,Qr(c?.estimatedWords)),gn(pe,Qr(c?.actualWords)),gn(Se,Qr(c?.actualWords)),gn(he,c?.blocked?"Blocked":"Not blocked"),c?.blockedReason?(gn(ye,c.blockedReason),Wr(me,!1)):(gn(ye,"-"),Wr(me,!0)),Ie&&(Ie.textContent=c?.writingBrief||"No writing brief has been added for this scene."),Er={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},dn(ve,Er.characters,"character",!!Xt&&!gr),dn(Ee,Er.assets,"asset",!!Xt&&!gr),ln(Er.locations,Er.primaryLocationId,!!Xt&&!gr),Gr(),Xr(gr?"Refresh Current Scene before saving.":Xt?"Ready to save.":"No resolved PlotDirector scene."),Wr(se,!1),Wr(be,!1),Wr(ke,!1)},gn=(e,t)=>{e&&(e.textContent=t)},Cn=e=>{const t=t=>Object.prototype.hasOwnProperty.call(e,t);t("host")&&gn(Et,e.host),t("platform")&&gn(Lt,e.platform),t("ready")&&gn(Nt,e.ready),t("wordApi")&&gn(qt,e.wordApi),t("lastScan")&&gn(xt,e.lastScan),t("lastError")&&gn(Pt,e.lastError),t("paragraphs")&&gn(jt,e.paragraphs),t("heading1")&&gn(Rt,e.heading1),t("heading2")&&gn(Wt,e.heading2)},bn=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)},In=async()=>{if(!window.Office||"function"!=typeof window.Office.onReady)return Ht=!1,Bt=!1,Ft="Unavailable",Gt="Unavailable",Cn({host:Ft,platform:Gt,ready:"No",wordApi:"No"}),null;const e=await window.Office.onReady();return Ht=!0,Ft=e?.host||"Unknown",Gt=e?.platform||"Unknown",Bt=!!window.Word&&!!window.Office.HostType&&e?.host===window.Office.HostType.Word,Cn({host:Ft,platform:Gt,ready:"Yes",wordApi:Bt?"Yes":"No"}),e},kn=e=>{try{const t=window.localStorage.getItem(e),r=Number.parseInt(t||"",10);return Number.isInteger(r)&&r>0?r:null}catch{return null}},vn=(e,t)=>{try{t?window.localStorage.setItem(e,String(t)):window.localStorage.removeItem(e)}catch{}},En=(e,t)=>{if(!e)return;e.innerHTML="";const r=document.createElement("option");r.value="",r.textContent=t,e.append(r),e.disabled=!0},Ln=(e,t,r,n,o)=>{if(!e)return;e.innerHTML="";const a=document.createElement("option");a.value="",a.textContent=t,e.append(a);for(const t of r){const r=document.createElement("option");r.value=String(t[n]),r.textContent=t[o],e.append(r)}e.disabled=0===r.length},Nn=e=>{const t=String(e?.title||"").trim(),r=String(e?.subtitle||"").trim();return r?`${t}: ${r}`:t},qn=()=>{const e=Number.parseInt(U?.value||"",10);return Mt.find(t=>t.projectId===e)||null},xn=()=>{const e=Number.parseInt(M?.value||"",10);return Ot.find(t=>t.bookId===e)||null},Pn=()=>{const e=Number.parseInt(h?.value||"",10);return Mt.find(t=>t.projectId===e)||null},Dn=()=>{const e=Number.parseInt(m?.value||"",10);return Ot.find(t=>t.bookId===e)||null},An=e=>gn(g,e),Tn=()=>{const e=Pn(),t=Dn();w&&(w.disabled=!e||!t||mr),f&&(f.disabled=!e||!String(y?.value||"").trim()||mr),q&&(q.disabled=!lr?.canImport||!ur||mr),E&&(E.disabled=yr||0===Wn().length)},$n=e=>{Wr(p,!e),Wr(d,e);for(const t of u)Wr(t,!!e||"scene"!==t.dataset.tabPanel&&!t.classList.contains("is-active"));e||qr()},jn=()=>{if(!h)return;if(0===Mt.length)return void En(h,"No projects available.");Ln(h,"Choose a project",Mt,"projectId","title");const e=Number.parseInt(U?.value||"",10);Number.isInteger(e)&&e>0&&(h.value=String(e))},Rn=(e="Select a Project and Book to begin.")=>{lr=null,ur=null,pr=[],hr=!1,Wr(C,!0),Wr(N,!0),Wr(b,!0),Wr(v,!0),C&&(C.innerHTML=""),k&&(k.innerHTML=""),gn(I,""),An(e),Tn()},Wn=()=>k?[...k.querySelectorAll("input[type='checkbox']:checked")].map(e=>String(e.value||"").trim()).filter(Boolean):[],Un=e=>{if(pr=Array.isArray(e)?e:[],b&&k){if(k.innerHTML="",Wr(b,!1),Wr(v,!hr||0===pr.length),0===pr.length)return gn(I,"No likely major characters found."),void Tn();gn(I,`${pr.length} likely major characters found.`);for(const e of pr){const t=document.createElement("label");t.className="word-companion-character-candidate";const r=document.createElement("input");r.type="checkbox",r.value=e.text||"",r.checked="high"===String(e.confidence||"").trim().toLowerCase(),r.addEventListener("change",Tn);const n=document.createElement("strong");n.textContent=e.text||"";const o=document.createElement("em"),a=String(e.reason||"").trim();o.textContent=a?`${Number(e.mentionCount||0).toLocaleString()} mentions · ${a}`:`${Number(e.mentionCount||0).toLocaleString()} mentions`;const c=document.createElement("span");c.className="word-companion-character-candidate-text",c.append(n,o),t.append(r,c),k.append(t)}Tn()}},Mn=()=>dr?.documentGuid?dr.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)),On=()=>{const e=qn(),t=xn();R&&(R.textContent=e?.title||"(Not connected)"),W&&(W.textContent=t?Nn(t):"(Not connected)"),K&&(K.textContent=t?"":"Select a PlotDirector book before refreshing."),Fr()},Hn=e=>String(e?.styleBuiltIn||e?.style||"").replace(/\s+/g,"").toLowerCase(),Bn=(e,t)=>{const r=Hn(e);return r===`heading${t}`||r.endsWith(`.heading${t}`)||r.includes(`heading${t}`)},Fn=e=>String(e||"").trim().split(/\s+/).filter(Boolean).length,Gn=(e,t)=>{const r=String(e||"").match(new RegExp(`^${t}-(\\d+)$`,"i"));if(!r)return null;const n=Number.parseInt(r[1],10);return Number.isInteger(n)&&n>0?n:null},Vn=(e,t)=>{const r=Array.isArray(e?.contentControls?.items)?e.contentControls.items:[];for(const e of r){const r=Gn(e.tag,t);if(r)return r}return null},Jn=(e,t)=>{const r=[];let n=0,o=0,a=null,c=null;e.forEach((e,t)=>{const i=String(e.text||"").trim();if(i){if(Bn(e,1))return n+=1,a={index:r.length+1,paragraphIndex:t,title:i,anchorId:Vn(e,"PD-CHAPTER"),scenes:[]},r.push(a),void(c=null);if(Bn(e,2)){if(o+=1,!a)return;return c={index:a.scenes.length+1,paragraphIndex:t,title:i,anchorId:Vn(e,"PD-SCENE"),wordCount:0},void a.scenes.push(c)}c&&(c.wordCount+=Fn(i))}});const i=t.find(e=>String(e.text||"").trim()),s=i?e.findIndex(e=>{return t=e,r=i,String(t?.text||"").trim()===String(r?.text||"").trim()&&Hn(t)===Hn(r);var t,r}):-1,d=s>=0&&r.filter(e=>e.paragraphIndex<=s).at(-1)||null,l=d&&s>=0&&d.scenes.filter(e=>e.paragraphIndex<=s).at(-1)||null;return{chapters:r,currentChapter:d,currentScene:l,paragraphCount:e.length,heading1Count:n,heading2Count:o}},Yn=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 r=document.createElement("strong");if(r.textContent=t.title,e.append(r),t.scenes.length>0){const r=document.createElement("ul");for(const e of t.scenes){const t=document.createElement("li");t.textContent=e.title,r.append(t)}e.append(r)}Q.append(e)}},zn=[{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"}],Kn={alreadyLinked:"Already Linked",couldLink:"Could Link",wouldCreateChapter:"Would Create Chapter",wouldCreateScene:"Would Create Scene",manualReview:"Manual Review Required"},Qn={alreadyLinked:"✓",couldLink:"~",wouldCreateChapter:"+",wouldCreateScene:"+",manualReview:"?"},Xn=(e,t)=>pn(e,t).toLocaleLowerCase(),Zn=({category:e,action:t,type:r,wordTitle:n,match:o="",anchorStatus:a="None",matches:c=[],pdChapter:i=null,pdScene:s=null,wordChapter:d=null,wordScene:l=null,parentItem:u=null})=>({id:`${r}-${d?.index||0}-${l?.index||0}-${d?.paragraphIndex??l?.paragraphIndex??0}`,category:e,action:t,type:r,wordTitle:n,match:o,anchorStatus:a,matches:c,pdChapter:i,pdScene:s,wordChapter:d,wordScene:l,parentItem:u,result:"Pending",error:""}),_n=(e,t)=>{Array.isArray(e[t.category])&&e[t.category].push(t)},eo=e=>Array.isArray(e?.scenes)?e.scenes:[],to=(e,t,r)=>{const n=e.anchorId?`PD-CHAPTER-${e.anchorId}`:"None";if(e.anchorId){const o=t.find(t=>t.chapterId===e.anchorId);if(o){const t=Zn({category:"alreadyLinked",action:"alreadyLinked",type:"Chapter",wordTitle:e.title,match:`Chapter ${o.chapterId}: ${o.title}`,anchorStatus:n,pdChapter:o,wordChapter:e});return _n(r,t),t}const a=Zn({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:`${n} not found`,matches:[],pdChapter:null,wordChapter:e});return _n(r,a),a}const o=t.filter(t=>Xn(t.title,"chapter")===Xn(e.title,"chapter"));if(1===o.length){const t=Zn({category:"couldLink",action:"couldLink",type:"Chapter",wordTitle:e.title,match:`Chapter ${o[0].chapterId}: ${o[0].title}`,anchorStatus:n,pdChapter:o[0],wordChapter:e});return _n(r,t),t}if(o.length>1){const t=Zn({category:"manualReview",action:"manualReview",type:"Chapter",wordTitle:e.title,anchorStatus:n,matches:o.map(e=>`Chapter ${e.chapterId}: ${e.title}`),pdChapter:null,wordChapter:e});return _n(r,t),t}const a=Zn({category:"wouldCreateChapters",action:"wouldCreateChapter",type:"Chapter",wordTitle:e.title,anchorStatus:n,pdChapter:null,wordChapter:e});return _n(r,a),a},ro=(e,t,r,n)=>{const o=e.anchorId?`PD-SCENE-${e.anchorId}`:"None";if(e.anchorId){const a=((e,t)=>{for(const r of e){const e=eo(r).find(e=>e.sceneId===t);if(e)return{chapter:r,scene:e}}return null})(r,e.anchorId);return a?void _n(n,Zn({category:"alreadyLinked",action:"alreadyLinked",type:"Scene",wordTitle:e.title,match:`Scene ${a.scene.sceneId}: ${a.scene.title}`,anchorStatus:o,pdChapter:a.chapter,pdScene:a.scene,wordChapter:t?.wordChapter,wordScene:e,parentItem:t})):void _n(n,Zn({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:`${o} not found`,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}))}if(!t?.pdChapter&&"manualReview"===t?.category)return void _n(n,Zn({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:o,matches:["Parent chapter requires manual review."],wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));if(!t?.pdChapter)return void _n(n,Zn({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:o,wordChapter:t?.wordChapter,wordScene:e,parentItem:t}));const a=eo(t.pdChapter).filter(t=>Xn(t.title,"scene")===Xn(e.title,"scene"));1!==a.length?a.length>1?_n(n,Zn({category:"manualReview",action:"manualReview",type:"Scene",wordTitle:e.title,anchorStatus:o,matches:a.map(e=>`Scene ${e.sceneId}: ${e.title}`),wordChapter:t.wordChapter,wordScene:e,parentItem:t})):_n(n,Zn({category:"wouldCreateScenes",action:"wouldCreateScene",type:"Scene",wordTitle:e.title,anchorStatus:o,pdChapter:t.pdChapter,wordChapter:t.wordChapter,wordScene:e,parentItem:t})):_n(n,Zn({category:"couldLink",action:"couldLink",type:"Scene",wordTitle:e.title,match:`Scene ${a[0].sceneId}: ${a[0].title}`,anchorStatus:o,pdChapter:t.pdChapter,pdScene:a[0],wordChapter:t.wordChapter,wordScene:e,parentItem:t}))},no=e=>{const t=document.createElement("article");t.className="word-companion-preview-item";const r=document.createElement("strong");r.textContent=`${Qn[e.action]||""} ${e.type}: ${e.wordTitle}`,t.append(r);const n=document.createElement("span");if(n.textContent=`Anchor: ${e.anchorStatus||"None"}`,t.append(n),e.match){const r=document.createElement("span");r.textContent=`Match: ${e.match}`,t.append(r)}if(Array.isArray(e.matches)&&e.matches.length>0){const r=document.createElement("div");r.className="word-companion-preview-matches";const n=document.createElement("span");n.textContent="Matches:",r.append(n);const o=document.createElement("ul");for(const t of e.matches){const e=document.createElement("li");e.textContent=t,o.append(e)}r.append(o),t.append(r)}const o=document.createElement("span");if(o.textContent=`Action: ${Kn[e.action]||e.action}`,t.append(o),e.result&&"Pending"!==e.result){const r=document.createElement("span");r.textContent=e.error?`Result: ${e.result} - ${e.error}`:`Result: ${e.result}`,t.append(r)}return t},oo=e=>{if(ee){ee.innerHTML="";for(const t of zn){const r=document.createElement("section");r.className="word-companion-preview-group";const n=document.createElement("strong");n.textContent=t.title,r.append(n);const o=Array.isArray(e?.[t.key])?e[t.key]:[];if(0===o.length){const e=document.createElement("p");e.className="word-companion-empty-list",e.textContent="None",r.append(e)}else for(const e of o)r.append(no(e));ee.append(r)}Br()}},ao=async e=>{const t=e.document.body.paragraphs,r=e.document.getSelection().paragraphs;t.load("text,styleBuiltIn,style"),r.load("text,styleBuiltIn,style"),await e.sync();for(const e of t.items)(Bn(e,1)||Bn(e,2))&&e.contentControls.load("items/tag,title");await e.sync();const n=Jn(t.items,r.items);return n.bodyParagraphs=t.items,n},co=async()=>{if(Ar(""),!Ht||!Bt||!window.Word||"function"!=typeof window.Word.run)return Rr(null,null,null),Ar("Word document access is unavailable."),Cn({lastScan:"Failure",lastError:"Word document access is unavailable."}),!1;F&&(F.disabled=!0,F.textContent="Scanning..."),Ar("Scanning document structure...");try{const e=await window.Word.run(async e=>await ao(e));return Rr(e.currentChapter?.title,e.currentScene?.title,e.currentScene?.wordCount,e.currentChapter?.anchorId,e.currentScene?.anchorId,e.currentChapter?.index),cn("Not detected"),Yn(e),Ar(""),Cn({lastScan:"Success",lastError:"-",paragraphs:String(e.paragraphCount),heading1:String(e.heading1Count),heading2:String(e.heading2Count)}),!0}catch(e){const t=bn(e);return console.error("Unable to scan the Word document.",e),Rr(null,null,null),Ar(`Unable to scan the Word document: ${t}`),Cn({lastScan:"Failure",lastError:t}),!1}finally{F&&(F.disabled=!1,F.textContent="Refresh Document Structure")}},io=async()=>{const e=xn();if(!qn()||!e)return Mr("Select a project and book to analyse manuscript structure."),!1;if(!Ht||!Bt||!window.Word||"function"!=typeof window.Word.run)return Mr("Word document access is unavailable."),Cn({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 ao(e)),r=await fo(`/api/word-companion/books/${e.bookId}/structure`);return Rr(t.currentChapter?.title,t.currentScene?.title,t.currentScene?.wordCount,t.currentChapter?.anchorId,t.currentScene?.anchorId,t.currentChapter?.index),Yn(t),sr=((e,t)=>{const r={alreadyLinked:[],couldLink:[],wouldCreateChapters:[],wouldCreateScenes:[],manualReview:[]},n=Array.isArray(t?.chapters)?t.chapters:[];for(const t of Array.isArray(e?.chapters)?e.chapters:[]){const e=to(t,n,r);for(const o of eo(t))ro(o,e,n,r)}return r})(t,r),oo(sr),Mr("Preview generated. No changes have been applied."),Cn({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."),Cn({lastScan:"Failure",lastError:bn(e)}),!1}finally{X&&(X.textContent="Analyse Manuscript Structure",Fr())}},so=e=>{wr&&(wr(e),wr=null),dt?.close?dt.close():dt&&(dt.hidden=!0)},lo=()=>{const e=((e=sr)=>{const t=Hr(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(!lt)return;lt.innerHTML="";const t=[`Link ${e.linkChapters+e.linkScenes} chapters/scenes`,`Create ${e.createChapters} chapters`,`Create ${e.createScenes} scenes`],r=document.createElement("ul");for(const e of t){const t=document.createElement("li");t.textContent=e,r.append(t)}lt.append(r)})(e),dt?new Promise(e=>{wr=e,dt.showModal?dt.showModal():dt.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.`))},uo=(e,t,r="")=>{e.result=t,e.error=r},po=e=>Number.isInteger(e?.wordChapter?.index)&&e.wordChapter.index>0?10*e.wordChapter.index:null,ho=e=>Number.isInteger(e?.wordScene?.index)&&e.wordScene.index>0?10*e.wordScene.index:null,mo=async(e,t)=>{const r=await wo(`/api/word-companion/books/${e}/chapters`,{title:un(t.wordTitle),sortOrder:po(t)});if(!r?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");t.pdChapter={chapterId:r.chapterId,title:r.title||t.wordTitle,sortOrder:r.sortOrder||po(t)||0,scenes:[]},t.match=`Chapter ${t.pdChapter.chapterId}: ${t.pdChapter.title}`},yo=async(e,t)=>{const r=t.pdChapter||t.parentItem?.pdChapter;if(!r?.chapterId)throw new Error("Scene parent chapter is not available.");const n=await wo(`/api/word-companion/books/${e}/chapters/${r.chapterId}/scenes`,{sceneTitle:un(t.wordTitle),sortOrder:ho(t)});if(!n?.sceneId)throw new Error("Scene creation did not return a scene ID.");t.pdChapter=r,t.pdScene={sceneId:n.sceneId,title:t.wordTitle,sortOrder:ho(t)||0},t.match=`Scene ${t.pdScene.sceneId}: ${t.pdScene.title}`},fo=async(e,t={})=>{const r=await window.fetch(e,{credentials:"same-origin",...t,headers:{Accept:"application/json",...t.headers||{}}});if(!r.ok)throw new Error(`Request failed: ${r.status}`);return await r.json()},wo=(e,t)=>fo(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),So=()=>{$n(!1),An(""),Wr(v,!0)},go=async()=>{if(!Ut||!Bt)return void $n(!1);const r=(()=>{const e=window.Office?.context?.document?.settings;if(!e)return null;const t=String(e.get(n)||"").trim(),r=Number.parseInt(e.get(o)||"",10),i=Number.parseInt(e.get(a)||"",10),s=Number.parseInt(e.get(c)||"",10);return!t||!Number.isInteger(r)||r<=0||!Number.isInteger(i)||i<=0?null:{documentGuid:t,bookId:r,projectId:i,bindingVersion:Number.isInteger(s)&&s>0?s:1}})();if(r)try{const n=await fo(`/api/word-companion/manuscript/book/${r.bookId}`),o=n?.manuscriptDocument;if(o&&String(o.documentGuid).toLowerCase()===r.documentGuid.toLowerCase())return dr=r,vn(e,r.projectId),vn(t,r.bookId),U&&(U.value=String(r.projectId)),await Uo(r.projectId,r.bookId),$n(!1),void xr("Connected")}catch{}dr=null,jn(),Pn()?await Uo(Pn().projectId,null):En(m,"Select a project first"),Rn("Select a Project and Book to begin."),$n(!0)},Co=e=>e?[...e.querySelectorAll("input[type='checkbox']:checked")].map(e=>Number.parseInt(e.value||"",10)).filter(e=>Number.isInteger(e)&&e>0):[],bo=()=>{const e=Number.parseInt(Le?.value||"",10);return Number.isInteger(e)&&e>0?e:null},Io=(e,t,r,n)=>{const o=((e,t)=>(Array.isArray(e?.contentControls?.items)?e.contentControls.items:[]).find(e=>Gn(e.tag,t))||null)(e,n),a=o||e.getRange().insertContentControl();return a.title=t,a.tag=r,a.appearance="Hidden",a},ko=async(e="PlotDirector IDs attached successfully.")=>{if(!Xt||!Zt)return Ar("No resolved PlotDirector scene."),!1;if((Qt&&Qt!==Xt||Kt&&Kt!==Zt)&&!window.confirm("This scene is already linked. Replace the existing PlotDirector link?"))return!1;if(!Ht||!Bt||!window.Word||"function"!=typeof window.Word.run)return Ar("Word document access is unavailable."),!1;ie&&(ie.disabled=!0,ie.textContent="Attaching...");try{return await window.Word.run(async e=>{const t=await ao(e);if(!t.currentChapter||!t.currentScene)throw new Error("No scene detected in Word. Use Heading 2 for scenes.");const r=t.bodyParagraphs[t.currentChapter.paragraphIndex],n=t.bodyParagraphs[t.currentScene.paragraphIndex];if(!r||!n)throw new Error("Unable to locate the current Word headings.");Io(r,"PlotDirector Chapter",`PD-CHAPTER-${Zt}`,"PD-CHAPTER"),Io(n,"PlotDirector Scene",`PD-SCENE-${Xt}`,"PD-SCENE"),await e.sync()}),Kt=Zt,Qt=Xt,tr=!1,er="SceneID Anchor",_t="Anchor",Ar(e),Cn({lastError:"-"}),jr(),!0}catch(e){return console.error("Unable to attach PlotDirector IDs.",e),Ar("Unable to attach PlotDirector IDs."),Cn({lastError:bn(e)}),jr(),!1}finally{ie&&(ie.textContent=Qt===Xt?"Attach PlotDirector IDs":"Reattach PlotDirector IDs",jr())}},vo=async e=>{if(!Zt)return _r("No resolved PlotDirector chapter."),!1;if(!Ht||!Bt||!window.Word||"function"!=typeof window.Word.run)return _r("Word document access is unavailable."),!1;try{return await window.Word.run(async e=>{const t=await ao(e);if(!t.currentChapter)throw new Error("No chapter detected in Word. Use Heading 1 for chapters.");const r=t.bodyParagraphs[t.currentChapter.paragraphIndex];if(!r)throw new Error("Unable to locate the current Word chapter heading.");Io(r,"PlotDirector Chapter",`PD-CHAPTER-${Zt}`,"PD-CHAPTER"),await e.sync()}),Kt=Zt,tr=!1,er="ChapterID Anchor",_t="Chapter anchor",_r(e),Ar(e),Cn({lastError:"-"}),jr(),!0}catch(e){return console.error("Unable to attach PlotDirector chapter ID.",e),_r("Unable to attach PlotDirector chapter ID."),Cn({lastError:bn(e)}),jr(),!1}},Eo=async e=>{rn(),await $o(),Ar(e),_r(e)},Lo=e=>{ir&&(ir(e),ir=null),ot?.close?ot.close():ot&&(ot.hidden=!0)},No=()=>{if(!et)return;const e=un(_e?.value||"").toLocaleLowerCase(),t=ar.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(et.innerHTML="",cr=null,tt&&(tt.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No chapters found.",void et.append(e)}for(const e of t){const t=Number.parseInt(e.chapterId||"",10);if(!Number.isInteger(t)||t<=0)continue;const r=document.createElement("label");r.className="word-companion-scene-option";const n=document.createElement("input");n.type="radio",n.name="word-companion-link-chapter",n.value=String(t),n.addEventListener("change",()=>{cr=t,tt&&(tt.disabled=!1)});const o=document.createElement("span");o.textContent=e.title||"Untitled chapter",r.append(n,o),et.append(r)}},qo=()=>{Ze?.close?Ze.close():Ze&&(Ze.hidden=!0)},xo=async(e,t,r)=>{const n=xn();if(!n)return Zr("Select a PlotDirector book first."),!1;await Sn(n.bookId,e,t,"Manual link","Title Match");return!!await ko(r)&&(Zr(r),on(),!0)},Po=e=>{or&&(or(e),or=null),Ye?.close?Ye.close():Ye&&(Ye.hidden=!0)},Do=()=>{if(!Fe)return;const e=un(Be?.value||"").toLocaleLowerCase(),t=rr.filter(t=>!e||String(t.title||"").toLocaleLowerCase().includes(e));if(Fe.innerHTML="",nr=null,Ge&&(Ge.disabled=!0),0===t.length){const e=document.createElement("p");return e.className="word-companion-empty-list",e.textContent="No scenes found.",void Fe.append(e)}for(const e of t){const t=Number.parseInt(e.sceneId||"",10);if(!Number.isInteger(t)||t<=0)continue;const r=document.createElement("label");r.className="word-companion-scene-option";const n=document.createElement("input");n.type="radio",n.name="word-companion-link-scene",n.value=String(t),n.addEventListener("change",()=>{nr=t,Ge&&(Ge.disabled=!1)});const o=document.createElement("span");o.textContent=e.title||"Untitled scene",r.append(n,o),Fe.append(r)}},Ao=()=>{He?.close?He.close():He&&(He.hidden=!0)},To=async()=>{const e=qn(),t=xn(),r=pn(Vt,"chapter");if(hn({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Nn(t):void 0,detectedChapter:Vt,detectedScene:Jt,requestChapter:r,requestScene:"",result:"Not run",chapterId:null,sceneId:null}),!t)return cn("Not detected"),Ar("Select a PlotDirector book first."),!1;if(!Vt)return cn("Not detected"),Ar("No chapter detected in Word. Use Heading 1 for chapters."),!1;cn("Not detected");try{const e=await yn(t.bookId),n=Kt?e.find(e=>e.chapterId===Kt):null,o=r.toLocaleLowerCase(),a=o?e.find(e=>pn(e.title,"chapter").toLocaleLowerCase()===o):null,c=n||a;return c?(rn(),zr(null,c.chapterId,n?"Chapter anchor":"Chapter title"),er=n?"ChapterID Anchor":"Title Match",Tr("Chapter linked to PlotDirector"),Ar("No scene detected in Word. Use Heading 2 for scenes."),hn({result:"Chapter matched",chapterId:c.chapterId,sceneId:null}),!0):(zr(null),Tr("Chapter not found in PlotDirector."),Ar("Chapter not found in PlotDirector."),hn({result:"Chapter not matched",chapterId:null,sceneId:null}),nn("Chapter not found in PlotDirector."),!1)}catch(e){return cn("Not found in PlotDirector"),Cn({lastError:bn(e)}),Ar("Unable to load PlotDirector chapter data."),!1}},$o=async()=>{const e=qn(),t=xn(),r=pn(Vt,"chapter"),n=pn(Jt,"scene");if(hn({projectId:e?.projectId,projectTitle:e?.title,bookId:t?.bookId,bookTitle:t?Nn(t):void 0,detectedChapter:Vt,detectedScene:Jt,requestChapter:r,requestScene:n,result:"Not run",chapterId:null,sceneId:null}),$r({anchorType:Qt?"SceneID Anchor":Kt?"ChapterID Anchor":"Title Match",storedSceneId:Qt,storedChapterId:Kt,resolutionMethod:"-"}),!t)return cn("Not detected"),Ar("Select a PlotDirector book first."),hn({result:"Error"}),!1;if(!Vt||!Jt)return cn("Not detected"),Ar("No scene detected in Word. Use Heading 2 for scenes."),hn({result:"Error"}),!1;te&&(te.disabled=!0,te.textContent="Refreshing...");const o=()=>{te&&(te.disabled=!1,te.textContent="Refresh PlotDirector Scene")};cn("Not detected"),Ar("Resolving PlotDirector scene...");try{if(Qt){const e=await(async(e,t)=>{const r=await fo(`/api/word-companion/books/${e}/structure`),n=Array.isArray(r?.chapters)?r.chapters:[];for(const e of n){const r=Array.isArray(e.scenes)?e.scenes:[];for(const n of r)if(t(e,n))return{chapter:e,scene:n}}return null})(t.bookId,(e,t)=>t.sceneId===Qt);if(e)return hn({result:"Matched",chapterId:e.chapter.chapterId,sceneId:e.scene.sceneId}),await Sn(t.bookId,e.scene.sceneId,e.chapter.chapterId,"Anchor","SceneID Anchor"),!0;tr=!0,er="SceneID Anchor",Tr("Not found in PlotDirector"),Ar("Stored PlotDirector ID is invalid."),hn({result:"Error",chapterId:Kt,sceneId:Qt}),$r({anchorType:"SceneID Anchor",storedSceneId:Qt,storedChapterId:Kt,resolutionMethod:"Anchor"})}if(Kt){const e=(await mn(t.bookId)).find(e=>e.chapterId===Kt),r=e?(Array.isArray(e.scenes)?e.scenes:[]).find(e=>pn(e.title,"scene").toLocaleLowerCase()===n.toLocaleLowerCase()):null;if(r)return hn({result:"Matched",chapterId:e.chapterId,sceneId:r.sceneId}),await Sn(t.bookId,r.sceneId,e.chapterId,"Anchor","ChapterID Anchor"),!0;e&&!Qt?(er="ChapterID Anchor",zr(null,Kt,"Chapter anchor"),hn({result:"Chapter matched",chapterId:Kt,sceneId:null})):Qt||(er="ChapterID Anchor",hn({result:"Chapter anchor not found",chapterId:Kt,sceneId:null}))}const e=await wo(`/api/word-companion/books/${t.bookId}/resolve-scene`,{chapterTitle:r,sceneTitle:n});if(!e?.matched||!e.sceneId){const t=tr,r=Number.parseInt(e?.chapterId||"",10),n=Number.isInteger(Zt)&&Zt>0?Zt:null,a=Number.isInteger(r)&&r>0?r:n,c=!!e?.chapterMatched||!!a;return cn("Not found in PlotDirector"),tr=t,c&&(zr(null,a,a===n?"Chapter anchor":"Chapter title"),Tr("Scene not found in PlotDirector.")),Ar(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."),hn({result:"Not matched",chapterId:c?a:e?.chapterId,sceneId:e?.sceneId}),t||(c?(rn(),an("Scene not found in PlotDirector.")):(on(),nn("Chapter not found in PlotDirector."))),o(),!1}const a=tr;return hn({result:a?"Matched by title fallback":"Matched",chapterId:e.chapterId,sceneId:e.sceneId}),await Sn(t.bookId,e.sceneId,e.chapterId,a?"Title fallback":"Title","Title Match"),a&&(tr=!0,Ar("Stored PlotDirector ID is invalid."),jr()),!0}catch(e){const t=tr;return Cn({lastError:bn(e)}),cn("Not found in PlotDirector"),tr=t,Ar(t?"Stored PlotDirector ID is invalid.":"Unable to load PlotDirector scene data."),hn({result:"Error"}),!1}finally{o()}},jo=async()=>{if(!Ir&&Ut&&xn()){if(!Ht||!Bt||!window.Word||"function"!=typeof window.Word.run)return Jr("Manual"),void Ar("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");Ir=!0,Jr("Refreshing"),Ar("Updating current scene...");try{const e=await window.Word.run(async e=>await ao(e)),t=(e=>{const t=e.currentChapter?.title||"",r=e.currentScene?.title||"",n=e.currentChapter?.anchorId||null,o=e.currentScene?.anchorId||null;return pn(t,"chapter")!==pn(Vt,"chapter")||pn(r,"scene")!==pn(Jt,"scene")||n!==Kt||o!==Qt})(e);if(Rr(e.currentChapter?.title,e.currentScene?.title,e.currentScene?.wordCount,e.currentChapter?.anchorId,e.currentScene?.anchorId,e.currentChapter?.index),Yn(e),Cn({lastScan:"Success",lastError:"-",paragraphs:String(e.paragraphCount),heading1:String(e.heading1Count),heading2:String(e.heading2Count)}),!t)return Yr(!1),Jr("Live"),void Ar("Current scene updated.");Jt?await $o():await To(),Yr(!1),Jr("Live"),Ar("Current scene updated.")}catch(e){console.error("Unable to refresh current scene from Word selection.",e),Cn({lastScan:"Failure",lastError:bn(e)}),Yr(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving.")}finally{Ir=!1}}},Ro=()=>{Cr&&window.clearTimeout(Cr),Cr=window.setTimeout(jo,850)},Wo=()=>{if(br&&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:Ro}),br=!1}catch(e){console.warn("Unable to remove Word selection tracking handler.",e)}},Uo=async(e,r)=>{if(!e)return Ot=[],En(M,"Select a project first"),En(m,"Select a project first"),Dr(""),vn(t,null),On(),cn("Not detected"),void Or();En(M,"Loading books..."),Dr(""),cn("Not detected"),Or("Select a book to analyse manuscript structure.");try{const n=await fo(`/api/word-companion/projects/${e}/books`);if(Ot=Array.isArray(n.books)?n.books:[],0===Ot.length)return En(M,"No books available."),En(m,"No books available."),Dr("No books available."),vn(t,null),On(),void Rn("No books available.");Ln(M,"Choose a book",Ot.map(e=>({...e,displayTitle:Nn(e)})),"bookId","displayTitle");const o=Ot.find(e=>e.bookId===r);o&&M?(M.value=String(o.bookId),vn(t,o.bookId)):vn(t,null),((e=null)=>{if(!m)return;if(0===Ot.length)return void En(m,"No books available.");Ln(m,"Choose a book",Ot.map(e=>({...e,displayTitle:Nn(e)})),"bookId","displayTitle");const t=e||Number.parseInt(M?.value||"",10),r=Ot.find(e=>e.bookId===t);r&&(m.value=String(r.bookId)),Tn()})(o?.bookId||r),On(),cn((xn(),"Not detected")),Or(xn()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),Rn(Dn()?"Ready to scan manuscript structure.":"Select a Book to begin.")}catch{Ot=[],En(M,"Unable to load books."),En(m,"Unable to load books."),Dr("Unable to load books."),vn(t,null),On(),cn("Not detected"),Or("Unable to load books."),Rn("Unable to load books.")}};for(const e of l)e.addEventListener("click",()=>Nr(e.dataset.tabButton));qr(),U?.addEventListener("change",async()=>{const r=Number.parseInt(U.value||"",10);h&&Number.isInteger(r)&&r>0&&(h.value=String(r)),vn(e,Number.isInteger(r)&&r>0?r:null),vn(t,null),cn("Not detected"),Or(),Rn("Select a Book to begin."),await Uo(r,null)}),M?.addEventListener("change",()=>{const e=Number.parseInt(M.value||"",10);vn(t,Number.isInteger(e)&&e>0?e:null),m&&Number.isInteger(e)&&e>0&&(m.value=String(e)),On(),cn("Not detected"),Or(xn()?"Ready to analyse manuscript structure.":"Select a book to analyse manuscript structure."),Rn(Dn()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),h?.addEventListener("change",async()=>{const r=Number.parseInt(h.value||"",10);U&&Number.isInteger(r)&&r>0&&(U.value=String(r)),vn(e,Number.isInteger(r)&&r>0?r:null),vn(t,null),Rn("Select a Book to begin."),await Uo(r,null)}),m?.addEventListener("change",()=>{const e=Number.parseInt(m.value||"",10);M&&Number.isInteger(e)&&e>0&&(M.value=String(e)),vn(t,Number.isInteger(e)&&e>0?e:null),On(),Rn(Dn()?"Ready to scan manuscript structure.":"Select a Book to begin.")}),y?.addEventListener("input",Tn),f?.addEventListener("click",async()=>{const e=Pn(),t=String(y?.value||"").trim();if(e&&t){f.disabled=!0,An("Creating Book...");try{const r=await wo(`/api/word-companion/projects/${e.projectId}/books`,{title:t});y&&(y.value=""),U&&(U.value=String(e.projectId)),await Uo(e.projectId,r.bookId),m&&(m.value=String(r.bookId)),An("Ready to scan manuscript structure.")}catch(e){console.error("Unable to create Book from Word Companion.",e),An(`Unable to create Book: ${bn(e)}`)}finally{Tn()}}else Tn()}),w?.addEventListener("click",async()=>{const e=Pn(),t=Dn();if(e&&t)if(Ht&&Bt&&window.Word&&"function"==typeof window.Word.run){w&&(w.disabled=!0,w.textContent="Scanning..."),An("Scanning manuscript structure...");try{const r=await window.Word.run(async e=>{const r=e.document.body.paragraphs;return r.load("text,styleBuiltIn,style"),await e.sync(),((e,t)=>{const r=[];let n=null,o=null,a=0;const c=[],i=new Set(["***","###"]),s=()=>{if(!n)return null;const e={title:`Scene ${n.scenes.length+1}`,sortOrder:10*(n.scenes.length+1),wordCount:0};return n.scenes.push(e),e};return e.forEach(e=>{const d=String(e.text||"").trim();if(!d)return;if(c.push(d),Bn(e,1))return n={title:d,sortOrder:10*(r.length+1),wordCount:0,scenes:[]},r.push(n),o=s(),void(a+=Fn(d));if(!n||!o)return;if(t&&i.has(d))return void(o=s());const l=Fn(d);n.wordCount+=l,o.wordCount+=l,a+=l}),{chapters:r,chapterCount:r.length,sceneCount:r.reduce((e,t)=>e+t.scenes.length,0),wordCount:a,documentText:c.join("\n")}})(r.items,!!t.usesExplicitScenes)});ur=r,hr=!1;const n=await wo("/api/word-companion/manuscript/analyse",{projectId:e.projectId,bookId:t.bookId,documentGuid:Mn(),chapterCount:r.chapterCount,sceneCount:r.sceneCount,wordCount:r.wordCount});lr=n,(e=>{if(!C)return;C.innerHTML="";const t=document.createElement("strong");t.textContent="Manuscript Analysis",C.append(t);const r=document.createElement("dl"),n=[["Project",e.projectTitle],["Book",Nn({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 n){const n=document.createElement("dt");n.textContent=e;const o=document.createElement("dd");o.textContent=t||"-",r.append(n,o)}C.append(r),Wr(C,!1),Wr(N,!1),An(e.message||"Preview generated."),Tn()})(n);try{const t=await wo("/api/word-companion/manuscript/discover-characters",{projectId:e.projectId,documentText:r.documentText||""});Un(t?.candidates||[])}catch(e){console.error("Unable to discover character candidates.",e),Un([]),gn(I,"Character discovery is unavailable.")}Cn({lastScan:"Success",lastError:"-",paragraphs:"-",heading1:String(r.chapterCount),heading2:"-"})}catch(e){console.error("Unable to scan manuscript for first-run import.",e),Rn(`Unable to scan manuscript: ${bn(e)}`),Cn({lastScan:"Failure",lastError:bn(e)})}finally{w&&(w.textContent="Scan Manuscript"),Tn()}}else Rn("Word document access is unavailable.");else Rn("Select a Project and Book to begin.")}),q?.addEventListener("click",async()=>{const r=Pn(),i=Dn();if(!(r&&i&&ur&&lr?.canImport))return void Tn();let s=!1;if(!lr.requiresReplaceConfirmation||(s=await new Promise(e=>{if(!P||"function"!=typeof P.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=>{D?.removeEventListener("click",r),A?.removeEventListener("click",n),P?.removeEventListener("cancel",o),P?.close(),e(t)},r=()=>t(!0),n=()=>t(!1),o=e=>{e.preventDefault(),t(!1)};D?.addEventListener("click",r),A?.addEventListener("click",n),P?.addEventListener("cancel",o),P.showModal()}),s)){mr=!0,Tn(),An("Importing manuscript structure...");try{const l=Mn(),u=await wo("/api/word-companion/manuscript/import",{projectId:r.projectId,bookId:i.bookId,documentGuid:l,bindingVersion:1,replacePlanned:s,chapters:ur.chapters});if(!u.imported)return lr={...lr,canImport:!u.requiresReplaceConfirmation,requiresReplaceConfirmation:!!u.requiresReplaceConfirmation,message:u.message||lr.message},An(u.message||"Import was not completed."),void Tn();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 r=window.Office?.context?.document?.settings;r?(r.set(n,d.documentGuid),r.set(o,String(d.bookId)),r.set(a,String(d.projectId)),r.set(c,String(d.bindingVersion||1)),r.saveAsync(r=>{r.status===window.Office.AsyncResultStatus.Succeeded?e():t(r.error||new Error("Unable to save Word document metadata."))})):t(new Error("Word document settings are unavailable."))})),dr={documentGuid:p?.documentGuid||l,bookId:u.bookId,projectId:u.projectId,bindingVersion:p?.bindingVersion||1},vn(e,u.projectId),vn(t,u.bookId),U&&(U.value=String(u.projectId));const h=pr;await Uo(u.projectId,u.bookId),xr("Connected"),hr=!0,pr=h,h.length>0?($n(!0),Un(h),Wr(N,!0),Wr(v,!1),An(u.message||"Manuscript structure imported."),Ar(u.message||"Manuscript structure imported.")):($n(!1),Ar(u.message||"Manuscript structure imported."))}catch(e){console.error("Unable to import manuscript structure.",e),An(`Unable to import manuscript: ${bn(e)}`)}finally{mr=!1,Tn()}var d}else An("Import cancelled.")}),E?.addEventListener("click",async()=>{const e=Pn()||qn(),t=Wn();if(e&&0!==t.length){yr=!0,Tn(),gn(I,"Creating selected characters...");try{const r=await wo("/api/word-companion/manuscript/create-discovered-characters",{projectId:e.projectId,candidateNames:t});Ar(r.message||"Characters created."),gn(I,`${r.createdCount||0} created, ${r.skippedCount||0} already existed.`),So()}catch(e){console.error("Unable to create discovered characters.",e),gn(I,`Unable to create characters: ${bn(e)}`)}finally{yr=!1,Tn()}}else Tn()}),L?.addEventListener("click",So),S?.addEventListener("click",()=>$n(!1)),x?.addEventListener("click",()=>Rn("Import cancelled.")),F?.addEventListener("click",co),X?.addEventListener("click",io),Z?.addEventListener("click",async()=>{const e=xn();if(!e||0===Hr().length||fr)return void Br();if(!await lo())return;fr=!0,Fr(),Mr("Applying structure sync...");const t={createdChapters:0,createdScenes:0,linkedChapters:0,linkedScenes:0,skipped:Array.isArray(sr?.manualReview)?sr.manualReview.length:0,failed:0},r=Hr().filter(e=>"couldLink"===e.category&&"Chapter"===e.type),n=Hr().filter(e=>"wouldCreateChapters"===e.category),o=Hr().filter(e=>"couldLink"===e.category&&"Scene"===e.type),a=Hr().filter(e=>"wouldCreateScenes"===e.category),c=[];let i="";const s=(e,t)=>{c.push({item:e,counterName:t})},d=async(e,r)=>{try{await(async e=>{if(!Ht||!Bt||!window.Word||"function"!=typeof window.Word.run)throw new Error("Word document access is unavailable.");await window.Word.run(async t=>{const r=await ao(t),n="Chapter"===e.type?e.wordChapter:e.wordScene,o=Number.isInteger(n?.paragraphIndex)?r.bodyParagraphs[n.paragraphIndex]:null;if(!o)throw new Error("Unable to locate the Word heading.");if("Chapter"===e.type){const t=e.pdChapter?.chapterId;if(!t)throw new Error("Chapter ID is not available.");Io(o,"PlotDirector Chapter",`PD-CHAPTER-${t}`,"PD-CHAPTER")}else{const t=e.pdScene?.sceneId;if(!t)throw new Error("Scene ID is not available.");Io(o,"PlotDirector Scene",`PD-SCENE-${t}`,"PD-SCENE")}await t.sync()})})(e),uo(e,"Success"),t[r]+=1}catch(r){uo(e,"Failed",bn(r)),t.failed+=1}};try{for(const e of r)s(e,"linkedChapters");for(const r of n)try{await mo(e.bookId,r),s(r,"createdChapters")}catch(e){uo(r,"Failed",bn(e)),t.failed+=1}for(const e of o)s(e,"linkedScenes");for(const r of a)try{await yo(e.bookId,r),s(r,"createdScenes")}catch(e){uo(r,"Failed",bn(e)),t.failed+=1}for(const e of c)await d(e.item,e.counterName);for(const e of sr.manualReview||[])uo(e,"Skipped");oo(sr),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{fr=!1,Fr(),i&&(await io(),Mr(`${i} Preview refreshed.`))}}),ut?.addEventListener("click",()=>so(!0)),pt?.addEventListener("click",()=>so(!1)),dt?.addEventListener("cancel",e=>{e.preventDefault(),so(!1)}),te?.addEventListener("click",$o),B?.addEventListener("click",async()=>{if(!xn())return Ar("Select a PlotDirector book first."),void cn("Not detected");Kr(!0);try{if(!await co())return;if(Yr(!1),!Jt)return void await To();await $o()}finally{Kr(!1)}}),fe?.addEventListener("click",async()=>{if(!Xt)return void Ur("No resolved PlotDirector scene.");if(gr)return void Ur("Refresh Current Scene before syncing.");if(!Number.isInteger(Yt))return void Ur("Unable to sync progress.");fe&&(fe.disabled=!0,fe.textContent="Syncing...");const e=(new Date).toISOString();try{const n=await(t=`/api/word-companion/scenes/${Xt}/word-count`,r={actualWordCount:Yt,lastWorkedOn:e},fo(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}));gn(Se,Qr(n?.actualWords??Yt)),gn(pe,Qr(n?.actualWords??Yt)),gn(ge,(new Date).toLocaleString()),Ur("Progress synced successfully.")}catch{Ur("Unable to sync progress.")}finally{fe&&(fe.disabled=!Xt||gr,fe.textContent="Sync Progress")}var t,r}),Ne?.addEventListener("click",async()=>{if(Xt)if(!gr&&await(async()=>{if(!Xt)return!1;if(!Ht||!Bt||!window.Word||"function"!=typeof window.Word.run)return Yr(!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 ao(e)),t=e.currentChapter?.title||"",r=e.currentScene?.title||"",n=e.currentScene?.anchorId||null,o=e.currentChapter?.anchorId||null,a=Number.isInteger(n)&&n===Xt,c=Number.isInteger(o)&&o===Zt,i=pn(r,"scene").toLocaleLowerCase()===pn(kr||Jt,"scene").toLocaleLowerCase(),s=pn(t,"chapter").toLocaleLowerCase()===pn(vr||Vt,"chapter").toLocaleLowerCase();return a||i&&(c||s)?(Yr(!1),!0):(Yr(!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),Cn({lastError:bn(e)}),Yr(!0,"The Word cursor is now in a different scene. Refresh Current Scene before saving."),!1}})()){Ne&&(Ne.disabled=!0,Ne.textContent="Saving...");try{await(e=`/api/word-companion/scenes/${Xt}/links`,t={characterIds:Co(ve),assetIds:Co(Ee),locationIds:[],primaryLocationId:bo()},fo(e,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})),(()=>{const e=new Set(Co(ve)),t=new Set(Co(Ee));Er={characters:Er.characters.map(t=>({...t,linked:e.has(Number.parseInt(sn(t,"character"),10))})),assets:Er.assets.map(e=>({...e,linked:t.has(Number.parseInt(sn(e,"asset"),10))})),locations:Er.locations,primaryLocationId:bo()}})(),Xr("Scene links saved successfully."),Cn({lastError:"-"})}catch(e){Xr("Unable to save scene links."),Cn({lastError:bn(e)})}finally{Ne&&(Ne.disabled=!Xt||gr,Ne.textContent="Save Scene Links")}var e,t}else Xr("The Word cursor is now in a different scene. Refresh Current Scene before saving.");else Xr("Link a PlotDirector scene first.")}),ie?.addEventListener("click",async()=>{await ko()}),Ae?.addEventListener("click",async()=>{const e=xn();if(!e||!Vt||Zt)return void nn("Chapter not found in PlotDirector.");const t=un(Vt),r=await((e,t)=>(gn(at,`"${e}"`),gn(ct,`"${t}"`),ot?new Promise(e=>{ir=e,ot.showModal?ot.showModal():ot.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector chapter:\n\n"${e}"\n\nin book:\n\n"${t}"\n\n?`))))(t,Nn(e)||"selected book");if(r){Ae&&(Ae.disabled=!0,Ae.textContent="Creating...");try{const r=Number.isInteger(zt)&&zt>0?10*zt:null,n=await wo(`/api/word-companion/books/${e.bookId}/chapters`,{title:t,sortOrder:r});if(!n?.chapterId)throw new Error("Chapter creation did not return a chapter ID.");zr(null,n.chapterId,"Manual chapter link");if(!await vo("Chapter created and linked successfully."))return;await Eo("Chapter created and linked successfully.")}catch(e){_r("Unable to create chapter."),Cn({lastError:bn(e)})}finally{Ae&&(Ae.disabled=!en(),Ae.textContent="Create Chapter in PlotDirector")}}}),Te?.addEventListener("click",async()=>{const e=xn();if(e&&Vt&&!Zt){Te&&(Te.disabled=!0,Te.textContent="Loading...");try{ar=await yn(e.bookId),cr=null,_e&&(_e.value=""),gn(nt,""),No(),Ze?.showModal?Ze.showModal():Ze&&(Ze.hidden=!1)}catch(e){_r("Unable to load chapters."),Cn({lastError:bn(e)})}finally{Te&&(Te.disabled=!en(),Te.textContent="Link to Existing Chapter")}}else nn("Chapter not found in PlotDirector.")}),_e?.addEventListener("input",No),tt?.addEventListener("click",async()=>{const e=ar.find(e=>e.chapterId===cr);if(e){tt&&(tt.disabled=!0,tt.textContent="Linking...");try{zr(null,e.chapterId,"Manual chapter link");if(!await vo("Chapter linked successfully."))return;qo(),await Eo("Chapter linked successfully.")}catch(e){gn(nt,"Unable to link chapter."),_r("Unable to link chapter."),Cn({lastError:bn(e)})}finally{tt&&(tt.disabled=!cr,tt.textContent="Link Chapter")}}else gn(nt,"Select a chapter.")}),rt?.addEventListener("click",qo),it?.addEventListener("click",()=>Lo(!0)),st?.addEventListener("click",()=>Lo(!1)),ot?.addEventListener("cancel",e=>{e.preventDefault(),Lo(!1)}),Ue?.addEventListener("click",async()=>{const e=xn();if(!e||!Jt)return void an("Scene not found in PlotDirector.");const t=pn(Jt,"scene"),r=pn(Vt,"chapter"),n=await((e,t)=>(gn(ze,`"${e}"`),gn(Ke,`"${t}"`),Ye?new Promise(e=>{or=e,Ye.showModal?Ye.showModal():Ye.hidden=!1}):Promise.resolve(window.confirm(`Create PlotDirector scene:\n\n"${e}"\n\nwithin chapter:\n\n"${t}"\n\n?`))))(t,r);if(n){Ue&&(Ue.disabled=!0,Ue.textContent="Creating...");try{const r=await wn();if(!r)return void an("This chapter does not exist in PlotDirector. Create or link the chapter first.");const n=await wo(`/api/word-companion/books/${e.bookId}/chapters/${r.chapterId}/scenes`,{sceneTitle:t});if(!n?.sceneId||!n?.chapterId)throw new Error("Scene creation did not return a scene ID.");await xo(n.sceneId,n.chapterId,"Scene created and linked successfully.")}catch(e){Zr("Unable to create scene."),Cn({lastError:bn(e)})}finally{Ue&&(Ue.disabled=!tn(),Ue.textContent="Create Scene in PlotDirector")}}}),Me?.addEventListener("click",async()=>{const e=xn();if(e&&Jt){Me&&(Me.disabled=!0,Me.textContent="Loading...");try{const t=await mn(e.bookId),r=fn(t);if(!r)return void an("This chapter does not exist in PlotDirector. Create or link the chapter first.");rr=Array.isArray(r.scenes)?r.scenes:[],nr=null,Be&&(Be.value=""),gn(Je,""),Do(),He?.showModal?He.showModal():He&&(He.hidden=!1)}catch(e){Zr("Unable to load scenes."),Cn({lastError:bn(e)})}finally{Me&&(Me.disabled=!tn(),Me.textContent="Link to Existing Scene")}}else an("Scene not found in PlotDirector.")}),Be?.addEventListener("input",Do),Ge?.addEventListener("click",async()=>{const e=xn(),t=rr.find(e=>e.sceneId===nr);if(e&&t){Ge&&(Ge.disabled=!0,Ge.textContent="Linking...");try{const e=await wn();if(!e)throw new Error("This chapter does not exist in PlotDirector. Create or link the chapter first.");Ao(),await xo(t.sceneId,e.chapterId,"Scene linked successfully.")}catch(e){gn(Je,"Unable to link scene."),Zr("Unable to link scene."),Cn({lastError:bn(e)})}finally{Ge&&(Ge.disabled=!nr,Ge.textContent="Link Scene")}}else gn(Je,"Select a scene.")}),Ve?.addEventListener("click",Ao),Qe?.addEventListener("click",()=>Po(!0)),Xe?.addEventListener("click",()=>Po(!1)),Ye?.addEventListener("cancel",e=>{e.preventDefault(),Po(!1)}),vt?.addEventListener("click",async()=>{vt&&(vt.disabled=!0,vt.textContent="Running...");try{if(await In(),!Ht||!Bt||!window.Word||"function"!=typeof window.Word.run)return void Cn({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});Cn({lastScan:"Success",lastError:"-",paragraphs:String(e)})}catch(e){console.error("Word Companion diagnostics failed.",e);const t=bn(e);Cn({lastScan:"Failure",lastError:t}),Ar(`Unable to scan the Word document: ${t}`)}finally{vt&&(vt.disabled=!1,vt.textContent="Run Diagnostics")}});const Mo=Ut?(async()=>{En(U,"Loading projects..."),En(M,"Select a project first"),En(h,"Loading projects..."),En(m,"Select a project first"),Pr(""),Dr("");try{const r=await fo("/api/word-companion/projects");if(Mt=Array.isArray(r.projects)?r.projects:[],0===Mt.length)return En(U,"No projects available."),En(h,"No projects available."),Pr("No projects available."),vn(e,null),vn(t,null),On(),void Rn("No projects available.");Ln(U,"Choose a project",Mt,"projectId","title"),jn();const n=kn(e),o=Mt.find(e=>e.projectId===n);o&&U?(U.value=String(o.projectId),h&&(h.value=String(o.projectId)),vn(e,o.projectId),await Uo(o.projectId,kn(t))):(vn(e,null),vn(t,null),On(),Rn("Select a Project and Book to begin."))}catch{Mt=[],Ot=[],En(U,"Unable to connect to PlotDirector."),En(M,"Select a project first"),En(h,"Unable to connect to PlotDirector."),En(m,"Select a project first"),xr("Unable to connect to PlotDirector."),Pr("Unable to connect to PlotDirector."),vn(e,null),vn(t,null),On(),Rn("Unable to connect to PlotDirector.")}})():Promise.resolve();if(Ut||(En(U,"Please sign in to PlotDirector."),En(M,"Please sign in to PlotDirector."),En(h,"Please sign in to PlotDirector."),En(m,"Please sign in to PlotDirector."),On()),!window.Office||"function"!=typeof window.Office.onReady)return Lr("Word Companion ready"),Ar("Word document access is unavailable."),Jr("Manual"),void Cn({host:"Unavailable",platform:"Unavailable",ready:"No",wordApi:"No"});In().then(async()=>{Lr("Word Companion ready"),await Mo,await go(),Bt?(()=>{if(Ut){if(!window.Office?.context?.document||"function"!=typeof window.Office.context.document.addHandlerAsync||!window.Office?.EventType?.DocumentSelectionChanged)return Jr("Manual"),void Ar("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.");try{window.Office.context.document.addHandlerAsync(window.Office.EventType.DocumentSelectionChanged,Ro,e=>{e?.status===window.Office.AsyncResultStatus.Succeeded?(br=!0,Jr("Live")):(Jr("Manual"),Ar("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene."))}),window.addEventListener("beforeunload",Wo)}catch(e){console.warn("Unable to register Word selection tracking handler.",e),Jr("Manual"),Ar("Automatic scene tracking is unavailable in this Word version. Use Refresh Current Scene.")}}})():(Ar("Word document access is unavailable."),Jr("Manual"))}).catch(e=>{console.error("Office readiness check failed.",e),xr("Unable to connect to PlotDirector."),Lr("Word Companion unavailable"),Ar("Word document access is unavailable."),Cn({ready:"No",wordApi:"No",lastScan:"Failure"})})})(); \ No newline at end of file