File size: 13,019 Bytes
9d2d895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import { Panel } from './Panel';
import { createLazyClient, getRpcBaseUrl } from '@/services/rpc-client';
import { premiumFetch } from '@/services/premium-fetch';
import { h, replaceChildren, setTrustedHtml, trustedHtml } from '@/utils/dom-utils';
import { yieldToMain } from '@/utils/after-paint';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import type { NewsItem, DeductContextDetail } from '@/types';
import { buildNewsContext } from '@/utils/news-context';
import { getActiveFrameworkForPanel } from '@/services/analysis-framework-store';
import { hasPremiumAccess } from '@/services/panel-gating';
import { FrameworkSelector } from './FrameworkSelector';
import { extractDeductionProbability } from './deduction-probability';
import { IntelligenceServiceClient } from '@/services/generated-rpc-clients';

// deduct-situation + list-market-implications are premium-gated.
const getIntelligenceClient = createLazyClient(() => new IntelligenceServiceClient(getRpcBaseUrl(), { fetch: premiumFetch }));

const COOLDOWN_MS = 5_000;

export class DeductionPanel extends Panel {
    private formEl: HTMLFormElement;
    private inputEl: HTMLTextAreaElement;
    private geoInputEl: HTMLInputElement;
    private resultContainer: HTMLElement;
    private submitBtn: HTMLButtonElement;
    private isSubmitting = false;
    private getLatestNews?: () => NewsItem[];
    private contextHandler: EventListener;
    private fwSelector: FrameworkSelector;

    constructor(getLatestNews?: () => NewsItem[]) {
        super({
            id: 'deduction',
            title: 'Deduct Situation',
            infoTooltip: 'Use AI intelligence to deduct the timeline and impact of a hypothetical or current event.',
        });

        this.getLatestNews = getLatestNews;

        this.inputEl = h('textarea', {
            className: 'deduction-input',
            placeholder: 'E.g., What will possibly happen in the next 24 hours in Middle East?',
            required: true,
            rows: 3,
        }) as HTMLTextAreaElement;

        this.geoInputEl = h('input', {
            className: 'deduction-geo-input',
            type: 'text',
            placeholder: 'Geographic or situation context (optional)...',
        }) as HTMLInputElement;

        this.submitBtn = h('button', {
            className: 'deduction-submit-btn',
            type: 'submit',
        }, 'Analyze') as HTMLButtonElement;

        const formRow = h('div', { className: 'deduction-form-row' },
            this.geoInputEl,
            this.submitBtn,
        );

        this.formEl = h('form', { className: 'deduction-form' },
            this.inputEl,
            formRow,
        ) as HTMLFormElement;

        this.formEl.addEventListener('submit', this.handleSubmit.bind(this));

        this.resultContainer = h('div', { className: 'deduction-result' });

        const container = h('div', { className: 'deduction-panel-content' },
            this.formEl,
            this.resultContainer
        );

        replaceChildren(this.content, container);

        /* Styles moved to panels.css (PERF-012) */

        this.contextHandler = ((e: CustomEvent<DeductContextDetail>) => {
            const { query, geoContext, autoSubmit } = e.detail;

            if (query) {
                this.inputEl.value = query;
            }
            if (geoContext) {
                this.geoInputEl.value = geoContext;
            }

            this.show();

            this.element.animate([
                { backgroundColor: 'var(--overlay-heavy, rgba(255,255,255,.2))' },
                { backgroundColor: 'transparent' }
            ], { duration: 800, easing: 'ease-out' });

            if (autoSubmit && this.inputEl.value && !this.submitBtn.disabled) {
                this.formEl.requestSubmit();
            }
        }) as EventListener;
        document.addEventListener('wm:deduct-context', this.contextHandler);

        this.fwSelector = new FrameworkSelector({ panelId: 'deduction', isPremium: hasPremiumAccess(), panel: this });
        this.header.appendChild(this.fwSelector.el);
    }

    public override destroy(): void {
        document.removeEventListener('wm:deduct-context', this.contextHandler);
        this.fwSelector.destroy();
        super.destroy();
    }

    /** Post-process parsed markdown HTML into visually structured sections. */
    private reformatResult(container: HTMLElement): void {
        const SECTIONS = [
            { re: /^bottom\s+line/i,       cls: 'ds-verdict',   label: 'Bottom Line' },
            { re: /^what\s+we\s+know/i,    cls: 'ds-evidence',  label: 'What We Know' },
            { re: /^most\s+likely\s+path/i, cls: 'ds-primary',  label: 'Most Likely Path' },
            { re: /^alternative\s+path/i,  cls: 'ds-alt',       label: 'Alternative Paths' },
            { re: /^confidence/i,          cls: 'ds-confidence', label: 'Confidence' },
        ] as const;

        // Collect top-level children; group by section boundary
        const nodes = Array.from(container.childNodes) as HTMLElement[];
        const groups: { cls: string; label: string; nodes: HTMLElement[] }[] = [];
        let current: { cls: string; label: string; nodes: HTMLElement[] } | null = null;

        for (const node of nodes) {
            const strongText = (node.querySelector?.('strong')?.textContent ?? node.textContent ?? '').trim();
            const match = SECTIONS.find(s => s.re.test(strongText));
            if (match) {
                current = { cls: match.cls, label: match.label, nodes: [] };
                groups.push(current);
            }
            if (current) current.nodes.push(node);
            else if (!match) groups.push({ cls: '', label: '', nodes: [node] }); // unsectioned
        }

        if (groups.every(g => !g.cls)) return; // nothing to restructure

        container.replaceChildren();
        for (const group of groups) {
            if (!group.cls) {
                group.nodes.forEach(n => container.appendChild(n));
                continue;
            }

            const section = document.createElement('div');
            section.className = group.cls;

            // Inject section label (remove the <strong> header from content)
            const labelEl = document.createElement('div');
            labelEl.className = 'ds-section-label';

            // For primary path, extract probability from heading text
            if (group.cls === 'ds-primary') {
                const headingNode = group.nodes[0];
                const fullText = headingNode?.textContent ?? '';
                const probability = extractDeductionProbability(fullText);
                const timeMatch = /\(([^)]+)\)/.exec(fullText);
                labelEl.textContent = group.label;
                if (timeMatch) {
                    const timeSpan = document.createElement('span');
                    timeSpan.style.cssText = 'font-size:10px;color:var(--text-dim);font-weight:400;text-transform:none;letter-spacing:0';
                    timeSpan.textContent = timeMatch[1] ?? '';
                    labelEl.appendChild(timeSpan);
                }
                if (probability) {
                    const badge = document.createElement('span');
                    badge.className = 'ds-prob-badge';
                    badge.textContent = probability.label;
                    badge.title = probability.isRange ? 'Rough probability range from the source' : 'Approximate probability from the source';
                    labelEl.appendChild(badge);
                }
            } else {
                labelEl.textContent = group.label;
            }
            section.appendChild(labelEl);

            // Add body nodes (skip first node which was the header paragraph)
            const bodyNodes = group.nodes.slice(1);
            if (bodyNodes.length === 0 && group.nodes[0]) {
                // Inline header: strip the strong header, keep the rest as body
                const clone = group.nodes[0].cloneNode(true) as HTMLElement;
                clone.querySelector('strong')?.remove();
                const bodyDiv = document.createElement('div');
                bodyDiv.className = group.cls === 'ds-primary' ? 'ds-primary-body' : '';
                setTrustedHtml(
                    bodyDiv,
                    trustedHtml(clone.innerHTML.replace(/^[\s:–—-]+/, ''), 'legacy direct innerHTML migration'),
                );
                section.appendChild(bodyDiv);
            } else {
                // For alt paths: inject probability badges into li items
                if (group.cls === 'ds-alt') {
                    bodyNodes.forEach(n => {
                        if (n.tagName === 'UL') {
                            n.querySelectorAll('li').forEach(li => {
                                const probability = extractDeductionProbability(li.textContent ?? '', { leadingOnly: true });
                                if (probability) {
                                    const badge = document.createElement('span');
                                    badge.className = 'ds-alt-prob';
                                    badge.textContent = probability.label;
                                    badge.title = probability.isRange ? 'Rough probability range from the source' : 'Approximate probability from the source';
                                    li.textContent = probability.remainder;
                                    li.insertBefore(badge, li.firstChild);
                                }
                            });
                        }
                        section.appendChild(n);
                    });
                } else {
                    bodyNodes.forEach(n => section.appendChild(n));
                }
            }

            container.appendChild(section);
        }
    }

    private async handleSubmit(e: Event) {
        e.preventDefault();
        if (this.isSubmitting) return;

        const query = this.inputEl.value.trim();
        if (!query) return;

        let geoContext = this.geoInputEl.value.trim();

        if (this.getLatestNews && !geoContext.includes('Recent News:')) {
            const newsCtx = buildNewsContext(this.getLatestNews);
            if (newsCtx) {
                geoContext = geoContext ? `${geoContext}\n\n${newsCtx}` : newsCtx;
            }
        }

        const fw = getActiveFrameworkForPanel('deduction');

        this.isSubmitting = true;
        this.submitBtn.disabled = true;

        this.resultContainer.className = 'deduction-result loading';
        setTrustedHtml(
            this.resultContainer,
            trustedHtml(
                '<div class="deduction-loading-dots"><span></span><span></span><span></span></div>Analyzing…',
                'legacy direct innerHTML migration',
            ),
        );

        try {
            const resp = await getIntelligenceClient().deductSituation({
                query,
                geoContext,
                framework: fw?.systemPromptAppend ?? '',
            });
            if (!this.element?.isConnected) return;

            this.resultContainer.className = 'deduction-result';
            if (resp.analysis) {
                const parsed = await marked.parse(resp.analysis);
                if (!this.element?.isConnected) return;
                // Yield so the response paint lands before the synchronous DOMPurify
                // pass (the heavy `sanitize` chunk) — breaks the post-response long
                // task instead of running parse+purify+innerHTML as one block (#4537).
                await yieldToMain();
                if (!this.element?.isConnected) return;
                const safe = DOMPurify.sanitize(parsed);
                setTrustedHtml(this.resultContainer, trustedHtml(safe, 'legacy direct innerHTML migration'));
                this.reformatResult(this.resultContainer);
            } else {
                this.resultContainer.textContent = resp.provider === 'error'
                    ? 'AI analysis temporarily unavailable. Please try again in a moment.'
                    : 'No analysis available for this query.';
            }
        } catch (err) {
            if (!this.element?.isConnected) return;
            console.error('[DeductionPanel] Error:', err);
            this.resultContainer.className = 'deduction-result error';
            this.resultContainer.textContent = 'An error occurred while analyzing the situation.';
        } finally {
            this.isSubmitting = false;
            if (this.element?.isConnected) {
                setTimeout(() => { this.submitBtn.disabled = false; }, COOLDOWN_MS);
            }
        }
    }
}