File size: 20,765 Bytes
a18b9a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat with Me</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display:ital@0;1&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  :root {
    --bg: #0d0d0f; --surface: #16161a; --border: rgba(255,255,255,0.08);
    --accent: #c8a96e; --text: #e8e4dc; --muted: rgba(232,228,220,0.45);
    --user-bg: #1e2533; --bot-bg: #1a1a1e; --radius: 18px;
    --font-head: 'DM Serif Display', Georgia, serif;
    --font-body: 'DM Sans', system-ui, sans-serif;
  }
  html, body { height: 100%; background: var(--bg); color: var(--text); font-family: var(--font-body); font-size: 16px; line-height: 1.6; }
  .shell { display: grid; grid-template-columns: 320px 1fr; grid-template-rows: 100vh; max-width: 1100px; margin: 0 auto; }
  .sidebar { border-right: 1px solid var(--border); display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 2.5rem 1.5rem; gap: 1.5rem; position: relative; overflow: hidden; }
  .sidebar::before { content: ''; position: absolute; inset: 0; background: radial-gradient(ellipse at 50% 40%, rgba(200,169,110,0.07) 0%, transparent 70%); pointer-events: none; }
  
  .avatar-wrap { position: relative; width: 220px; height: 290px; }
  
  .avatar-ring { position: absolute; inset: -6px; border-radius: 16px; border: 1.5px solid var(--accent); opacity: 0.3; animation: pulse-ring 2.8s ease-in-out infinite; }
  .avatar-ring.r2 { inset: -12px; opacity: 0.1; animation-delay: 0.6s; }
  @keyframes pulse-ring { 0%, 100% { transform: scale(1); opacity: 0.3; } 50% { transform: scale(1.03); opacity: 0.1; } }
  
  .avatar-img { 
    width: 220px; 
    height: 290px; 
    border-radius: 16px; 
    object-fit: cover; 
    object-position: center center; 
    border: 1.5px solid rgba(200, 169, 110, 0.4); 
    display: block; 
    background: var(--surface); 
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
  }
  
  .speaking-badge { display: none; align-items: center; gap: 6px; font-size: 12px; color: var(--accent); letter-spacing: 0.08em; text-transform: uppercase; font-weight: 500; }
  .speaking-badge.active { display: flex; }
  .speaking-dots { display: flex; gap: 3px; }
  .speaking-dots span { width: 4px; height: 4px; border-radius: 50%; background: var(--accent); animation: bounce-dot 1s ease-in-out infinite; }
  .speaking-dots span:nth-child(2) { animation-delay: 0.15s; }
  .speaking-dots span:nth-child(3) { animation-delay: 0.30s; }
  @keyframes bounce-dot { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-5px); } }
  .bot-name { font-family: var(--font-head); font-size: 1.6rem; color: var(--text); text-align: center; }
  .bot-tagline { font-size: 13px; color: var(--muted); text-align: center; max-width: 220px; line-height: 1.5; }
  .voice-toggle { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--muted); cursor: pointer; user-select: none; padding: 6px 12px; border: 1px solid var(--border); border-radius: 99px; transition: border-color 0.2s, color 0.2s; }
  .voice-toggle:hover { border-color: var(--accent); color: var(--accent); }
  .voice-toggle input { display: none; }
  .voice-toggle.on { border-color: var(--accent); color: var(--accent); }
  
  .delay-note { font-size: 12px; color: var(--muted); text-align: center; max-width: 200px; line-height: 1.4; font-style: italic; margin-top: -4px; }

  .chat-panel { display: flex; flex-direction: column; height: 100vh; }
  .chat-header { padding: 1.25rem 1.75rem; border-bottom: 1px solid var(--border); font-size: 13px; color: var(--muted); letter-spacing: 0.06em; text-transform: uppercase; flex-shrink: 0; }
  .messages { flex: 1; overflow-y: auto; padding: 1.75rem; display: flex; flex-direction: column; gap: 1rem; scroll-behavior: smooth; }
  .messages::-webkit-scrollbar { width: 4px; }
  .messages::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
  .msg { display: flex; flex-direction: column; max-width: 78%; gap: 4px; animation: msg-in 0.25s ease-out both; }
  @keyframes msg-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
  .msg.user { align-self: flex-end; align-items: flex-end; }
  .msg.bot  { align-self: flex-start; align-items: flex-start; }
  .bubble { padding: 0.75rem 1.1rem; border-radius: var(--radius); font-size: 15px; line-height: 1.65; }
  .msg.user .bubble { background: var(--user-bg); border-bottom-right-radius: 4px; border: 1px solid rgba(126,159,199,0.2); }
  .msg.bot  .bubble { background: var(--bot-bg); border-bottom-left-radius: 4px; border: 1px solid var(--border); }
  .msg-time { font-size: 11px; color: var(--muted); padding: 0 4px; }
  
  .replay-btn { font-size: 11px; color: var(--accent); background: none; border: 1px solid rgba(200, 169, 110, 0.3); border-radius: 99px; padding: 3px 10px; cursor: pointer; margin-top: 6px; width: fit-content; transition: background 0.15s, border-color 0.15s; display: none; align-items: center; gap: 4px; }
  .replay-btn.visible { display: flex; }
  .replay-btn:hover { background: rgba(200, 169, 110, 0.1); border-color: var(--accent); }

  .typing-bubble { background: var(--bot-bg); border: 1px solid var(--border); border-radius: var(--radius); border-bottom-left-radius: 4px; padding: 0.75rem 1.1rem; display: none; align-items: center; gap: 5px; width: fit-content; }
  .typing-bubble.visible { display: flex; }
  .typing-bubble span { width: 6px; height: 6px; border-radius: 50%; background: var(--muted); animation: bounce-dot 1s ease-in-out infinite; }
  .typing-bubble span:nth-child(2) { animation-delay: 0.15s; }
  .typing-bubble span:nth-child(3) { animation-delay: 0.30s; }
  .gen-voice { font-size: 12px; color: var(--muted); padding: 4px 8px; display: none; }
  .gen-voice.visible { display: block; }
  .input-bar { padding: 1.25rem 1.75rem; border-top: 1px solid var(--border); display: flex; gap: 10px; align-items: flex-end; flex-shrink: 0; background: var(--bg); }
  .input-wrap { flex: 1; background: var(--surface); border: 1px solid var(--border); border-radius: 14px; padding: 0.65rem 1rem; display: flex; align-items: flex-end; gap: 8px; transition: border-color 0.2s; }
  .input-wrap:focus-within { border-color: rgba(200,169,110,0.4); }
  #user-input { flex: 1; background: none; border: none; outline: none; color: var(--text); font-family: var(--font-body); font-size: 15px; resize: none; max-height: 120px; min-height: 24px; line-height: 1.5; }
  #user-input::placeholder { color: var(--muted); }
  .send-btn { width: 38px; height: 38px; border-radius: 10px; border: none; background: var(--accent); color: #0d0d0f; cursor: pointer; display: flex; align-items: center; justify-content: center; flex-shrink: 0; transition: opacity 0.15s, transform 0.1s; font-size: 18px; }
  .send-btn:hover { opacity: 0.85; }
  .send-btn:active { transform: scale(0.95); }
  .send-btn:disabled { opacity: 0.35; cursor: not-allowed; }
  @media (max-width: 660px) {
    .shell { grid-template-columns: 1fr; grid-template-rows: auto 1fr; height: 100vh; }
    .sidebar { flex-direction: row; border-right: none; border-bottom: 1px solid var(--border); padding: 1rem 1.25rem; gap: 1rem; justify-content: flex-start; }
    .avatar-wrap { width: 56px; height: 56px; flex-shrink: 0; }
    .avatar-img { width: 56px; height: 56px; border-radius: 8px; }
    .avatar-ring, .avatar-ring.r2 { display: none; }
    .bot-tagline, .voice-toggle, .speaking-badge, .delay-note { display: none !important; }
    .bot-name { font-size: 1.1rem; }
    .chat-panel { height: 0; min-height: 0; }
  }
</style>
</head>
<body>
<div class="shell">
  <aside class="sidebar">
    <div class="avatar-wrap">
      <div class="avatar-ring"></div>
      <div class="avatar-ring r2"></div>
      <img id="avatar-static" class="avatar-img" src="me.jpg"
           onerror="this.style.background='#2a2a30';this.src=''" alt="Avatar">
    </div>
    <div class="speaking-badge" id="speaking-badge">
      <div class="speaking-dots"><span></span><span></span><span></span></div>
      Speaking
    </div>
    <div>
      <h1 class="bot-name">Papa Jerry</h1>
      <p class="bot-tagline">Ask me anything — I'm here to help.</p>
    </div>
    <label class="voice-toggle on" id="voice-toggle">
      <input type="checkbox" id="voice-on" checked>
      🔊 Voice on
    </label>
    <div class="delay-note">
      voice generation takes 15-45 seconds - please be patient
    </div>
  </aside>
  <main class="chat-panel">
    <div class="chat-header">Conversation</div>
    <div class="messages" id="messages">
      <div class="msg bot">
        <div class="bubble">Hey there! 👋 I'm here and ready to chat. Ask me anything you'd like.</div>
        <span class="msg-time" id="greeting-time"></span>
      </div>
      <div class="typing-bubble" id="typing">
        <span></span><span></span><span></span>
      </div>
      <div class="gen-voice" id="gen-voice">🎙️ Generating voice...</div>
    </div>
    <div class="input-bar">
      <div class="input-wrap">
        <textarea id="user-input" rows="1" placeholder="Type a message…"></textarea>
      </div>
      <button class="send-btn" id="send-btn" title="Send">&#10148;</button>
    </div>
  </main>
</div>
<audio id="tts-audio" style="display:none"></audio>

<script>
// Silent debug logger - view via browser Console (F12), no on-page UI.
var debugStartTime = null;
function dlog(msg) {
  if (debugStartTime === null) debugStartTime = performance.now();
  var elapsed = ((performance.now() - debugStartTime) / 1000).toFixed(2);
  console.log('[+' + elapsed + 's] ' + msg);
}
window.addEventListener('error', function(e) {
  dlog('❌ JS ERROR: ' + e.message);
});
window.addEventListener('unhandledrejection', function(e) {
  dlog('❌ UNHANDLED PROMISE REJECTION: ' + (e.reason && e.reason.message ? e.reason.message : e.reason));
});
</script>

<script>
// ============================================================
//  CONFIGURE THESE
// ============================================================
var HF_SPACE_URL = 'https://zaktree-papa-jerry.hf.space';
var BASE_SYSTEM_PROMPT = 'You are Papa Jerry, a warm and loving grandfather chatting with family. Speak with warmth, and gentle humor. Because your words are converted to spoken audio and family members are waiting to hear you, always keep replies short — 2 to 3 sentences — even when being thoughtful or wise.';
var SYSTEM_PROMPT = BASE_SYSTEM_PROMPT; 
var POLL_INTERVAL = 4000;               
// ============================================================

var chatHistory = [];
var busy = false;
var currentBotMsgId = null;

var msgsEl      = document.getElementById('messages');
var inputEl     = document.getElementById('user-input');
var sendBtn     = document.getElementById('send-btn');
var typing      = document.getElementById('typing');
var genVoiceEl  = document.getElementById('gen-voice');
var voiceOn     = document.getElementById('voice-on');
var voiceToggle = document.getElementById('voice-toggle');
var speakBadge  = document.getElementById('speaking-badge');
var ttsAudio    = document.getElementById('tts-audio');

document.getElementById('greeting-time').textContent = _time();

// Dynamic loader built to ingest 'family' and 'other' data fields safely
function loadFactsFromServer() {
  fetch('facts.json')
    .then(function(r) { return r.json(); })
    .then(function(facts) {
      var factsText = "\n\nHere are some facts you know about specific people:\n";
      for (var person in facts) {
        var location = facts[person].location || "unknown";
        var job = facts[person].job || "unknown";
        var hobbies = facts[person].hobbies || "unknown";
        
        // Dynamic additions: Append context chunks string conditionally
        var familyDetails = facts[person].family ? " Family connections: " + facts[person].family + "." : "";
        var otherDetails = facts[person].other ? " Additional information: " + facts[person].other + "." : "";

        factsText += "- " + person + " lives in " + location + 
                     ", works as a " + job + 
                     ", and their hobbies include " + hobbies + "." + 
                     familyDetails + otherDetails + "\n";
      }
      SYSTEM_PROMPT = BASE_SYSTEM_PROMPT + factsText;
      console.log("AI context initialized with multi-field profile definitions.");
    })
    .catch(function(err) { 
      console.log("No facts loaded or file empty, applying base prompt fallback.", err); 
    });
}

loadFactsFromServer();

voiceOn.addEventListener('change', function() {
  voiceToggle.classList.toggle('on', voiceOn.checked);
  voiceToggle.lastChild.textContent = voiceOn.checked ? ' Voice on' : ' Voice off';
});

inputEl.addEventListener('input', function() {
  this.style.height = 'auto';
  this.style.height = Math.min(this.scrollHeight, 120) + 'px';
});

inputEl.addEventListener('keydown', function(e) {
  if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
});

sendBtn.addEventListener('click', send);

function unlockAudio() {
  dlog('unlockAudio() called (click gesture)');
  try {
    ttsAudio.muted = true;
    var p = ttsAudio.play();
    if (p && p.catch) p.catch(function(e) { dlog('unlock play() rejected: ' + e.message); });
    ttsAudio.pause();
    ttsAudio.currentTime = 0;
    dlog('unlockAudio() completed OK');
  } catch (e) { dlog('unlockAudio() threw: ' + e.message); }
}

function send() {
  var text = inputEl.value.trim();
  if (!text || busy) return;
  debugStartTime = performance.now();
  dlog('--- NEW MESSAGE: "' + text + '" ---');
  if (voiceOn.checked) unlockAudio();
  addMessage('user', text);
  chatHistory.push({ role: 'user', content: text });
  inputEl.value = '';
  inputEl.style.height = 'auto';
  setTyping(true);
  busy = true;
  sendBtn.disabled = true;
  currentBotMsgId = 'msg-' + Date.now();

  fetch('/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      messages: [{ role: 'system', content: SYSTEM_PROMPT }].concat(chatHistory)
    })
  })
  .then(function(r) { return r.json(); })
  .then(function(data) {
    setTyping(false);
    if (!data.choices || !data.choices[0]) {
      addMessage('bot', 'Sorry, I could not get a response. Please try again.');
      done(); return;
    }
    var reply = data.choices[0].message.content;
    chatHistory.push({ role: 'assistant', content: reply });
    
    addMessage('bot', reply, currentBotMsgId);
    
    if (voiceOn.checked) {
      speak(reply);
    } else {
      done();
    }
  })
  .catch(function(err) {
    setTyping(false);
    addMessage('bot', 'Connection error: ' + err.message);
    done();
  });
}

var voiceStartTime = 0;
var UI_CounterInterval = null;

function startVoiceTimer() {
  voiceStartTime = performance.now();
  genVoiceEl.textContent = '🎙️ Generating voice... 0s';
  genVoiceEl.classList.add('visible');
  UI_CounterInterval = setInterval(function() {
    var elapsed = Math.round((performance.now() - voiceStartTime) / 1000);
    genVoiceEl.textContent = '🎙️ Generating voice... ' + elapsed + 's';
  }, 1000);
}

function stopVoiceTimer() {
  if (UI_CounterInterval) { clearInterval(UI_CounterInterval); UI_CounterInterval = null; }
  genVoiceEl.classList.remove('visible');
}

// Holds each clip's blob URL after its one-and-only fetch, so "Replay
// Voice" reuses it directly instead of ever hitting the network again.
var audioBlobCache = {};

function speak(text) {
  startVoiceTimer();
  var url = HF_SPACE_URL + '/speak?text=' + encodeURIComponent(text);
  dlog('speak(): sending GET /speak');
  fetch(url)
    .then(function(r) {
      dlog('speak response received, HTTP status ' + r.status + ' (server generation: ' + (r.headers.get('X-Generation-Seconds') || '?') + 's)');
      if (!r.ok) throw new Error('HTTP ' + r.status);
      return r.blob();
    })
    .then(function(blob) {
      dlog('blob received, size ' + blob.size + ' bytes, type ' + blob.type);
      var blobUrl = URL.createObjectURL(blob);
      // Cached immediately - this is the ONLY fetch of this clip that
      // will ever happen. No second request means no second (very
      // expensive) generation on the server.
      audioBlobCache[currentBotMsgId] = blobUrl;
      setupReplayButton(currentBotMsgId, blobUrl);
      playAudio(blobUrl);
    })
    .catch(function(e) { dlog('❌ /speak failed: ' + e.message); stopVoiceTimer(); done(); });
}

function playAudio(src) {
  dlog('playAudio() called, src=' + src.slice(0, 80));
  if (busy && !ttsAudio.paused) {
    ttsAudio.pause();
  }
  speakBadge.classList.add('active');
  ttsAudio.muted = false;
  ttsAudio.src = src;

  ttsAudio.oncanplay = function() { dlog('audio event: canplay'); };
  ttsAudio.onwaiting = function() { dlog('audio event: waiting (buffering)'); };
  ttsAudio.onstalled = function() { dlog('audio event: stalled'); };
  ttsAudio.onplaying = function() {
    dlog('🔊 audio event: PLAYING (actually audible now)');
    if (UI_CounterInterval) {
      var accurateSeconds = ((performance.now() - voiceStartTime) / 1000).toFixed(1);
      stopVoiceTimer();
      injectVoiceDuration(currentBotMsgId, accurateSeconds);
    }
    var targetMsg = document.getElementById(currentBotMsgId);
    var replayBtn = targetMsg && targetMsg.querySelector('.replay-btn');
    if (replayBtn) replayBtn.classList.add('visible');
  };

  var playPromise = ttsAudio.play();
  if (playPromise && playPromise.then) {
    playPromise.then(function() {
      dlog('play() promise RESOLVED (browser allowed playback)');
    }).catch(function(e) {
      dlog('❌ play() promise REJECTED: ' + e.name + ' - ' + e.message);
    });
  }

  ttsAudio.onended = function() {
    dlog('audio event: ended');
    speakBadge.classList.remove('active');
    done();
  };
  ttsAudio.onerror = function() { dlog('❌ audio event: error - ' + (ttsAudio.error ? ttsAudio.error.message : 'unknown')); speakBadge.classList.remove('active'); done(); };
}

function done() {
  busy = false;
  sendBtn.disabled = false;
  inputEl.focus();
}

function addMessage(role, text, elementId) {
  var msg = document.createElement('div');
  msg.className = 'msg ' + role;
  if (elementId) msg.id = elementId;
  
  var bubble = document.createElement('div');
  bubble.className = 'bubble';
  bubble.textContent = text;
  var time = document.createElement('span');
  time.className = 'msg-time';
  time.textContent = _time();
  msg.appendChild(bubble);
  msg.appendChild(time);
  
  if (role === 'bot') {
    var replayBtn = document.createElement('button');
    replayBtn.className = 'replay-btn';
    replayBtn.innerHTML = '▶️ Replay Voice';
    msg.appendChild(replayBtn);
  }

  msgsEl.insertBefore(msg, typing);
  msgsEl.scrollTop = msgsEl.scrollHeight;
}

function injectVoiceDuration(elementId, seconds) {
  var targetMsg = document.getElementById(elementId);
  if (!targetMsg) return;

  var durationEl = document.createElement('div');
  durationEl.style.fontSize = '11px';
  durationEl.style.color = 'var(--muted)';
  durationEl.style.marginTop = '4px';
  durationEl.style.padding = '0 4px';
  durationEl.textContent = '⏱️ Generated in ' + seconds + 's';

  var replayBtn = targetMsg.querySelector('.replay-btn');
  if (replayBtn) {
    targetMsg.insertBefore(durationEl, replayBtn);
  } else {
    targetMsg.appendChild(durationEl);
  }
  msgsEl.scrollTop = msgsEl.scrollHeight;
}

function setupReplayButton(elementId, audioSrc) {
  var targetMsg = document.getElementById(elementId);
  if (!targetMsg) return;
  
  var btn = targetMsg.querySelector('.replay-btn');
  if (!btn) return;
  
  btn.onclick = function() {
    speakBadge.classList.add('active');
    ttsAudio.src = audioSrc;
    ttsAudio.play();
    ttsAudio.onended = function() { speakBadge.classList.remove('active'); };
    ttsAudio.onerror = function() { speakBadge.classList.remove('active'); };
  };
  // Not made visible here - the "playing" handler in playAudio() reveals
  // it once the clip actually starts sounding, so it doesn't show up
  // before there's anything to replay yet.
}

function setTyping(show) {
  typing.classList.toggle('visible', show);
  msgsEl.scrollTop = msgsEl.scrollHeight;
}

// Global UI clock time builder string
function _time() {
  var d = new Date(), h = d.getHours(), m = d.getMinutes();
  var ampm = h >= 12 ? 'pm' : 'am';
  h = h % 12 || 12;
  return h + ':' + (m < 10 ? '0' : '') + m + ' ' + ampm;
}
</script>
</body>
</html>