File size: 25,561 Bytes
e280ef7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50cc26e
 
e280ef7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50cc26e
 
e280ef7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// ─────────────────────────────────────────────
// DOM REFS
// ─────────────────────────────────────────────
const $ = (id) => document.getElementById(id);

const els = {
  repoInput:      $('repoInput'),
  analyseBtn:     $('analyseBtn'),
  landingPage:    $('landingPage'),
  processingPage: $('processingPage'),
  chatPage:       $('chatPage'),
  stepsContainer: $('stepsContainer'),
  procSubtitle:   $('procSubtitle'),
  footer:         $('footer'),
  chatInput:      $('chatInput'),
  sendBtn:        $('sendBtn'),
  chatMessages:   $('chatMessages'),
  warningBanner:  $('warningBanner'),
  dismissWarning: $('dismissWarning'),
  statusDot:      $('statusDot'),
  statusLabel:    $('statusLabel'),
};

let IS_BIG_REPO   = false;
let activeStepBox = null;
let hadError      = false;
let hadWarning    = false;

// ─────────────────────────────────────────────
// MARKED.JS SETUP
// ─────────────────────────────────────────────
if (typeof marked !== 'undefined') {
  marked.setOptions({ breaks: true, gfm: true });
}

// ─────────────────────────────────────────────
// UTILITIES
// ─────────────────────────────────────────────
const delay = (ms) => new Promise((r) => setTimeout(r, ms));

function setStatus(mode, label) {
  els.statusDot.className   = 'status-dot ' + mode;
  els.statusLabel.textContent = label;
}

function showPage(pageEl) {
  ['landingPage', 'processingPage', 'chatPage'].forEach((id) => {
    $(id).classList.remove('active');
  });
  pageEl.classList.add('active');
}

function formatTime(d) {
  return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

// ─────────────────────────────────────────────
// AUTO-GROW TEXTAREA
// ─────────────────────────────────────────────
els.chatInput.addEventListener('input', () => {
  els.chatInput.style.height = 'auto';
  els.chatInput.style.height = Math.min(els.chatInput.scrollHeight, 160) + 'px';
});

// ─────────────────────────────────────────────
// COLLAPSE A COMPLETED STEP BOX
// ─────────────────────────────────────────────
function collapseBox(box, status) {
  return new Promise((resolve) => {
    // Lock height at current value so we can animate down
    const currentH = box.offsetHeight;
    box.style.height = currentH + 'px';
    box.style.overflow = 'hidden';

    // Badge text
    const badge = document.createElement('span');
    badge.className = 'step-collapsed-badge';
    badge.textContent = status === 'ERROR' ? 'Β· Error' : status === 'WARNING' ? 'Β· Warning' : 'Β· Done';
    box.querySelector('.step-title').appendChild(badge);

    // Hide sub-items right away so they don't flash during resize
    const subItems = box.querySelector('.sub-items');
    if (subItems) subItems.style.opacity = '0';

    // Animate to collapsed height next frame
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        box.style.height = '46px';
        box.style.paddingTop = '0';
        box.style.paddingBottom = '0';
      });
    });

    box.addEventListener('transitionend', function handler(e) {
      if (e.propertyName !== 'height') return;
      box.removeEventListener('transitionend', handler);
      // Reveal the badge now that height is settled
      const b = box.querySelector('.step-collapsed-badge');
      if (b) b.classList.add('visible');
      resolve();
    });
  });
}

// ─────────────────────────────────────────────
// LANDING β†’ PROCESSING
// ─────────────────────────────────────────────
els.analyseBtn.addEventListener('click', startAnalysis);
els.repoInput.addEventListener('keydown', (e) => {
  if (e.key === 'Enter') startAnalysis();
});

// Welcome chip clicks
document.querySelectorAll('.welcome-chip').forEach((chip) => {
  chip.addEventListener('click', () => {
    els.chatInput.value = chip.textContent;
    els.chatInput.focus();
  });
});

function startAnalysis() {
  const repoUrl = els.repoInput.value.trim();
  if (!repoUrl) return;

  setStatus('active', 'analysing');
  showPage(els.processingPage);
  els.stepsContainer.innerHTML = '';
  activeStepBox = null;
  IS_BIG_REPO   = false;
  hadError      = false;
  hadWarning    = false;

  connectToBackend(repoUrl);
}

// ─────────────────────────────────────────────
// BACKEND: INIT-REPO STREAM
// ─────────────────────────────────────────────
async function connectToBackend(repoUrl) {
  try {
   //const response = await fetch('http://localhost:8000/init-repo', {
    const response = await fetch('/init-repo', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body:    JSON.stringify({ url: repoUrl }),
    });

    if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);

    const reader  = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer    = '';

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n\n');
      buffer = lines.pop();

      for (const event of lines) {
        if (!event.trim()) continue;
        const dataLine = event.split('\n')[0];
        if (!dataLine.startsWith('data: ')) continue;
        try {
          const data = JSON.parse(dataLine.slice(6).trim());
          await processBackendEvent(data);
        } catch (e) {
          console.error('Parse error:', e);
        }
      }
    }
  } catch (error) {
    console.error('Fetch error:', error);

    if (activeStepBox) {
      await finishActiveBox(activeStepBox, 'ERROR');
    } else {
      const errorBox = createNewStepBox(`Error: ${error.message}`);
      await finishActiveBox(errorBox, 'ERROR');
    }

    showProcessingAction('error');
  }
}

async function processBackendEvent(data) {
  const { status, task } = data;

  if (status === 'FINISHED') {
    if (activeStepBox) await finishActiveBox(activeStepBox, 'SUCCESS');

    if (hadError) {
      showProcessingAction('error');
    } else if (hadWarning) {
      showProcessingAction('warning');
    } else {
      await delay(700);
      setStatus('chat', 'ready');
      transitionToChat();
    }
    return;
  }

  if (status === 'START') {
    if (activeStepBox) await finishActiveBox(activeStepBox, 'SUCCESS');
    activeStepBox = createNewStepBox(task);
    if (els.procSubtitle) els.procSubtitle.textContent = task;
  }

  if (status === 'WARNING' && task && task.includes('Repo is large')) {
    IS_BIG_REPO = true;
  }

  if (status === 'WARNING') hadWarning = true;
  if (status === 'ERROR')   hadError   = true;

  if (status === 'SUCCESS' || status === 'WARNING' || status === 'ERROR') {
    if (activeStepBox) {
      const titleText = activeStepBox.querySelector('.title-text');
      if (titleText) titleText.textContent = task;
      await finishActiveBox(activeStepBox, status);
      activeStepBox = null;
    } else {
      const box = createNewStepBox(task);
      await finishActiveBox(box, status);
    }
  }
}

// ─────────────────────────────────────────────
// PROCESSING ACTION BUTTON (error / warning gate)
// ─────────────────────────────────────────────
function showProcessingAction(type) {
  // Remove any existing action card
  const existing = els.stepsContainer.querySelector('.proc-action-card');
  if (existing) existing.remove();

  const card = document.createElement('div');
  card.className = `proc-action-card ${type === 'error' ? 'proc-action-error' : 'proc-action-warning'}`;

  if (type === 'error') {
    card.innerHTML = `
      <div class="proc-action-icon">βœ•</div>
      <div class="proc-action-body">
        <p class="proc-action-title">Analysis failed</p>
        <p class="proc-action-desc">An error occurred while analysing this repository. Please check the URL and try again.</p>
        <button class="proc-action-btn proc-btn-error" id="procBackBtn">← Try a Different Repo</button>
      </div>`;
  } else {
    card.innerHTML = `
      <div class="proc-action-icon">⚠</div>
      <div class="proc-action-body">
        <p class="proc-action-title">Analysis complete with warnings</p>
        <p class="proc-action-desc">Some steps raised warnings. Results may be partial, but you can still explore the repository.</p>
        <button class="proc-action-btn proc-btn-warning" id="procContinueBtn">Continue to Chat β†’</button>
      </div>`;
  }

  els.stepsContainer.appendChild(card);
  card.scrollIntoView({ behavior: 'smooth', block: 'nearest' });

  if (type === 'error') {
    document.getElementById('procBackBtn').addEventListener('click', () => {
      showPage(els.landingPage);
      setStatus('', 'idle');
    });
  } else {
    document.getElementById('procContinueBtn').addEventListener('click', () => {
      setStatus('chat', 'ready');
      transitionToChat();
    });
  }
}

// ─────────────────────────────────────────────
// STEP BOX HELPERS
// ─────────────────────────────────────────────
function createNewStepBox(message) {
  const box = document.createElement('div');
  box.className = 'step-box';

  box.innerHTML = `
    <div class="step-title">
      <span class="step-icon-wrap">
        <span class="step-ring-spinner"></span>
      </span>
      <span class="title-text">${escapeHtml(message)}</span>
    </div>
    <div class="sub-items"></div>`;

  els.stepsContainer.appendChild(box);
  box.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  return box;
}

async function finishActiveBox(box, status) {
  // Swap spinner for status icon
  const iconWrap = box.querySelector('.step-icon-wrap');
  if (iconWrap) {
    const spinner = iconWrap.querySelector('.step-ring-spinner');
    if (spinner) spinner.remove();

    const icon = document.createElement('span');
    icon.className = 'step-status-icon';

    if (status === 'WARNING') {
      icon.textContent = '⚠';
      icon.classList.add('warn');
    } else if (status === 'ERROR') {
      icon.textContent = 'βœ•';
      icon.classList.add('err');
    } else {
      icon.textContent = 'βœ“';
      icon.classList.add('green');
    }

    iconWrap.appendChild(icon);
  }

  // Apply status colour class
  if (status === 'WARNING') {
    box.classList.add('warn-yellow');
  } else if (status === 'ERROR') {
    box.classList.add('err-red');
  } else {
    box.classList.add('done-green');
  }

  // Brief pause so the colour is visible, then animate collapsed
  await delay(320);
  await collapseBox(box, status);
}

// ─────────────────────────────────────────────
// PROCESSING β†’ CHAT
// ─────────────────────────────────────────────
function transitionToChat() {
  if (IS_BIG_REPO) els.warningBanner.classList.remove('hidden');

  showPage(els.chatPage);
  renderWelcome();
  els.footer.classList.remove('hidden');
  els.chatInput.focus();
}

els.dismissWarning.addEventListener('click', () => {
  els.warningBanner.classList.add('hidden');
});

// ─────────────────────────────────────────────
// WELCOME TO CHAT STATE
// ─────────────────────────────────────────────
function renderWelcome() {
  els.chatMessages.innerHTML = '';

  const welcome = document.createElement('div');
  welcome.className = 'chat-welcome';
  welcome.innerHTML = `
    <div class="welcome-icon">βŽ”</div>
    <div class="welcome-title">Where do you want to start?</div>
    <div class="welcome-sub">Ask anything about this repository</div>
    <div class="welcome-chips">
      <span class="welcome-chip">Give me an overview of this repo</span>
      <span class="welcome-chip">What are the main dependencies?</span>
      <span class="welcome-chip">How do I run this locally?</span>
      <span class="welcome-chip">What design patterns are used?</span>
    </div>`;

  els.chatMessages.appendChild(welcome);

  welcome.querySelectorAll('.welcome-chip').forEach((chip) => {
    chip.addEventListener('click', () => {
      els.chatInput.value = chip.dataset.q || chip.textContent;
      els.chatInput.focus();
      sendMessage();
    });
  });
}

// ─────────────────────────────────────────────
// CHAT: SEND
// ─────────────────────────────────────────────
els.sendBtn.addEventListener('click', sendMessage);
els.chatInput.addEventListener('keydown', (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
});

async function sendMessage() {
  const text = els.chatInput.value.trim();
  if (!text) return;

  // Remove welcome block if present
  const welcome = els.chatMessages.querySelector('.chat-welcome');
  if (welcome) welcome.remove();

  els.chatInput.value = '';
  els.chatInput.style.height = 'auto';

  // User bubble
  appendUserMessage(text);

  // Bot group container
  const botGroup = document.createElement('div');
  botGroup.className = 'msg-group bot';
  els.chatMessages.appendChild(botGroup);

  // Thinking UI (collapsible)
  let thinkingWrap  = null;
  let stepsInner    = null;
  let lastStepEl    = null;
  let stepCount     = 0;
  let finalBubble   = null;
  let fullMarkdown  = '';

  try {
    //const response = await fetch('http://localhost:8000/chat', {
    const response = await fetch('/chat', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body:    JSON.stringify({ message: text }),
    });

    if (!response.ok) throw new Error('Backend connection failed');

    const reader  = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer    = '';

    while (true) {
      const { value, done } = await reader.read();

      if (value) {
        buffer += decoder.decode(value, { stream: !done });
        const lines = buffer.split('\n\n');
        buffer = lines.pop();

        for (const event of lines) {
          if (!event.trim()) continue;
          const dataLine = event.split('\n')[0];
          if (!dataLine.startsWith('data: ')) continue;

          try {
            const data = JSON.parse(dataLine.slice(6).trim());

            if (data.type === 'tool' || data.type === 'thinking') {
              // Build thinking UI on first thought
              if (!thinkingWrap) {
                const ui = createThinkingUI(botGroup);
                thinkingWrap = ui.wrap;
                stepsInner   = ui.inner;
              }
              lastStepEl = addThinkingStep(stepsInner, data.text, lastStepEl);
              stepCount++;
              updateThinkingToggleLabel(thinkingWrap, stepCount, false);
            }

            else if (data.type === 'message') {
              // Mark last step done
              if (lastStepEl) lastStepEl.classList.add('done-step');

              // Finalise thinking toggle
              if (thinkingWrap) {
                updateThinkingToggleLabel(thinkingWrap, stepCount, true);
                closeThinkingPanel(thinkingWrap);
              }

              // Accumulate markdown text
              fullMarkdown += data.text;

              // Create or update the answer bubble
              if (!finalBubble) {
                finalBubble = createBotBubble(botGroup);
              }
              renderMarkdownToBubble(finalBubble, fullMarkdown);
              finalBubble.scrollIntoView({ behavior: 'smooth', block: 'end' });
            }

          } catch (e) {
            console.error('Parse error:', e);
          }
        }
      }

      if (done) break;
      console.log("End has come!!")
    }

    // Add copy-response button after streaming is done
    if (finalBubble && fullMarkdown) {
      const copyBtn = buildCopyResponseBtn(fullMarkdown, finalBubble);
      botGroup.appendChild(copyBtn);
    }

    // Add timestamp after response is complete
    const meta = document.createElement('div');
    meta.className = 'msg-meta';
    meta.textContent = 'WHATREPO Β· ' + formatTime(new Date());
    botGroup.appendChild(meta);

  } catch (error) {
    const errBubble = createBotBubble(botGroup);
    errBubble.innerHTML = `<span style="color:var(--red)">Error: ${escapeHtml(error.message)}</span>`;
  }
}

// ─────────────────────────────────────────────
// MARKDOWN RENDERING
// ─────────────────────────────────────────────
function renderMarkdownToBubble(bubble, mdText) {
  if (typeof marked === 'undefined') {
    // Fallback: plain text with line breaks
    bubble.textContent = mdText;
    return;
  }

  const html = marked.parse(mdText);
  bubble.innerHTML = html;

  // Post-process: wrap <pre> blocks with header + copy button
  bubble.querySelectorAll('pre').forEach((pre) => {
    if (pre.parentElement && pre.parentElement.classList.contains('code-block-wrap')) return; // already wrapped

    const codeEl = pre.querySelector('code');
    const rawLang = codeEl ? codeEl.className.replace(/^language-/, '').trim() : '';
    const lang = rawLang || 'code';

    const wrap = document.createElement('div');
    wrap.className = 'code-block-wrap';

    const header = document.createElement('div');
    header.className = 'code-block-header';

    const langLabel = document.createElement('span');
    langLabel.className = 'code-lang-label';
    langLabel.textContent = lang;

    const copyBtn = document.createElement('button');
    copyBtn.className = 'code-copy-btn';
    copyBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true"><rect x="5" y="5" width="9" height="9" rx="1.5" stroke="currentColor" stroke-width="1.5"/><path d="M3 11V3h8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg><span>Copy</span>`;

    copyBtn.addEventListener('click', () => {
      const content = codeEl ? codeEl.textContent : pre.textContent;
      navigator.clipboard.writeText(content).then(() => {
        copyBtn.querySelector('span').textContent = 'Copied!';
        setTimeout(() => { copyBtn.querySelector('span').textContent = 'Copy'; }, 1800);
      }).catch(() => {});
    });

    header.appendChild(langLabel);
    header.appendChild(copyBtn);

    pre.parentNode.insertBefore(wrap, pre);
    wrap.appendChild(header);
    wrap.appendChild(pre);
  });
}

function buildCopyResponseBtn(markdownText, bubble) {
  const btn = document.createElement('button');
  btn.className = 'msg-copy-btn';
  btn.innerHTML = `<svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true"><rect x="5" y="5" width="9" height="9" rx="1.5" stroke="currentColor" stroke-width="1.5"/><path d="M3 11V3h8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`;

  btn.addEventListener('click', () => {
    // Copy plain text from the rendered bubble
    navigator.clipboard.writeText(bubble.innerText).then(() => {
      btn.querySelector('span').textContent = 'Copied!';
      setTimeout(() => { btn.querySelector('span').textContent = 'Copy response'; }, 1800);
    }).catch(() => {});
  });

  return btn;
}

// ─────────────────────────────────────────────
// MESSAGE UI HELPERS
// ─────────────────────────────────────────────
function appendUserMessage(text) {
  const group = document.createElement('div');
  group.className = 'msg-group user';
  group.innerHTML = `
    <div class="msg-sender">You</div>
    <div class="msg-bubble user">${escapeHtml(text)}</div>
    <div class="msg-meta">${formatTime(new Date())}</div>`;
  els.chatMessages.appendChild(group);
  group.scrollIntoView({ behavior: 'smooth', block: 'end' });
}

function createBotBubble(container) {
  const bubble = document.createElement('div');
  bubble.className = 'msg-bubble bot';
  container.appendChild(bubble);
  return bubble;
}

// ─────────────────────────────────────────────
// THINKING UI β€” Collapsible (Gemini-style)
// ─────────────────────────────────────────────
function createThinkingUI(container) {
  const wrap = document.createElement('div');
  wrap.className = 'thinking-wrap';

  wrap.innerHTML = `
    <button class="thinking-toggle active open" aria-expanded="true">
      <span class="thinking-spinner">
        <svg width="12" height="12" viewBox="0 0 50 50">
          <circle cx="25" cy="25" r="20" fill="none" stroke="var(--accent)" stroke-width="5"
            stroke-dasharray="80 45" stroke-linecap="round"/>
        </svg>
      </span>
      <span class="thinking-label">Thinking…</span>
      <span class="thinking-chevron">β–Ύ</span>
    </button>
    <div class="thinking-steps-panel open">
      <div class="thinking-steps-inner"></div>
    </div>`;

  container.appendChild(wrap);

  // Toggle click
  const toggle = wrap.querySelector('.thinking-toggle');
  const panel  = wrap.querySelector('.thinking-steps-panel');

  toggle.addEventListener('click', () => {
    const isOpen = panel.classList.contains('open');
    panel.classList.toggle('open', !isOpen);
    toggle.classList.toggle('open', !isOpen);
    toggle.setAttribute('aria-expanded', String(!isOpen));
  });

  return {
    wrap,
    toggle,
    panel,
    inner: wrap.querySelector('.thinking-steps-inner'),
  };
}

function addThinkingStep(inner, text, previousStepEl) {
  // Mark previous as done
  if (previousStepEl) {
    previousStepEl.classList.remove('current');
    previousStepEl.classList.add('done-step');
  }

  const step = document.createElement('div');
  step.className = 'thinking-step current';

  // Preserve newlines from backend
  const formatted = escapeHtml(text).replace(/\n/g, '<br>');
  step.innerHTML = `<span class="thinking-step-dot"></span><span class="thinking-step-text">${formatted}</span>`;
  inner.appendChild(step);

  // Scroll the panel
  inner.scrollTop = inner.scrollHeight;

  return step;
}

function updateThinkingToggleLabel(wrap, count, isDone) {
  const label   = wrap.querySelector('.thinking-label');
  const spinner = wrap.querySelector('.thinking-spinner');
  const toggle  = wrap.querySelector('.thinking-toggle');

  if (isDone) {
    label.textContent = `Thought for ${count} step${count !== 1 ? 's' : ''}`;
    spinner.classList.add('done');
    spinner.innerHTML = `<svg width="12" height="12" viewBox="0 0 12 12"><circle cx="6" cy="6" r="4" fill="var(--green)"/></svg>`;
    toggle.classList.remove('active');
  } else {
    label.textContent = `Thinking… (${count} step${count !== 1 ? 's' : ''})`;
  }
}

function closeThinkingPanel(wrap) {
  const panel  = wrap.querySelector('.thinking-steps-panel');
  const toggle = wrap.querySelector('.thinking-toggle');
  // Auto-collapse once done so the focus is on the answer
  panel.classList.remove('open');
  toggle.classList.remove('open');
  toggle.setAttribute('aria-expanded', 'false');
}

// ─────────────────────────────────────────────
// ESCAPE
// ─────────────────────────────────────────────
function escapeHtml(str) {
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}