zaktree commited on
Commit
a18b9a5
ยท
verified ยท
1 Parent(s): 58d6089

Create index.html

Browse files
Files changed (1) hide show
  1. index.html +469 -0
index.html ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Chat with Me</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <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">
9
+ <style>
10
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
11
+ :root {
12
+ --bg: #0d0d0f; --surface: #16161a; --border: rgba(255,255,255,0.08);
13
+ --accent: #c8a96e; --text: #e8e4dc; --muted: rgba(232,228,220,0.45);
14
+ --user-bg: #1e2533; --bot-bg: #1a1a1e; --radius: 18px;
15
+ --font-head: 'DM Serif Display', Georgia, serif;
16
+ --font-body: 'DM Sans', system-ui, sans-serif;
17
+ }
18
+ html, body { height: 100%; background: var(--bg); color: var(--text); font-family: var(--font-body); font-size: 16px; line-height: 1.6; }
19
+ .shell { display: grid; grid-template-columns: 320px 1fr; grid-template-rows: 100vh; max-width: 1100px; margin: 0 auto; }
20
+ .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; }
21
+ .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; }
22
+
23
+ .avatar-wrap { position: relative; width: 220px; height: 290px; }
24
+
25
+ .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; }
26
+ .avatar-ring.r2 { inset: -12px; opacity: 0.1; animation-delay: 0.6s; }
27
+ @keyframes pulse-ring { 0%, 100% { transform: scale(1); opacity: 0.3; } 50% { transform: scale(1.03); opacity: 0.1; } }
28
+
29
+ .avatar-img {
30
+ width: 220px;
31
+ height: 290px;
32
+ border-radius: 16px;
33
+ object-fit: cover;
34
+ object-position: center center;
35
+ border: 1.5px solid rgba(200, 169, 110, 0.4);
36
+ display: block;
37
+ background: var(--surface);
38
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
39
+ }
40
+
41
+ .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; }
42
+ .speaking-badge.active { display: flex; }
43
+ .speaking-dots { display: flex; gap: 3px; }
44
+ .speaking-dots span { width: 4px; height: 4px; border-radius: 50%; background: var(--accent); animation: bounce-dot 1s ease-in-out infinite; }
45
+ .speaking-dots span:nth-child(2) { animation-delay: 0.15s; }
46
+ .speaking-dots span:nth-child(3) { animation-delay: 0.30s; }
47
+ @keyframes bounce-dot { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-5px); } }
48
+ .bot-name { font-family: var(--font-head); font-size: 1.6rem; color: var(--text); text-align: center; }
49
+ .bot-tagline { font-size: 13px; color: var(--muted); text-align: center; max-width: 220px; line-height: 1.5; }
50
+ .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; }
51
+ .voice-toggle:hover { border-color: var(--accent); color: var(--accent); }
52
+ .voice-toggle input { display: none; }
53
+ .voice-toggle.on { border-color: var(--accent); color: var(--accent); }
54
+
55
+ .delay-note { font-size: 12px; color: var(--muted); text-align: center; max-width: 200px; line-height: 1.4; font-style: italic; margin-top: -4px; }
56
+
57
+ .chat-panel { display: flex; flex-direction: column; height: 100vh; }
58
+ .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; }
59
+ .messages { flex: 1; overflow-y: auto; padding: 1.75rem; display: flex; flex-direction: column; gap: 1rem; scroll-behavior: smooth; }
60
+ .messages::-webkit-scrollbar { width: 4px; }
61
+ .messages::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
62
+ .msg { display: flex; flex-direction: column; max-width: 78%; gap: 4px; animation: msg-in 0.25s ease-out both; }
63
+ @keyframes msg-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
64
+ .msg.user { align-self: flex-end; align-items: flex-end; }
65
+ .msg.bot { align-self: flex-start; align-items: flex-start; }
66
+ .bubble { padding: 0.75rem 1.1rem; border-radius: var(--radius); font-size: 15px; line-height: 1.65; }
67
+ .msg.user .bubble { background: var(--user-bg); border-bottom-right-radius: 4px; border: 1px solid rgba(126,159,199,0.2); }
68
+ .msg.bot .bubble { background: var(--bot-bg); border-bottom-left-radius: 4px; border: 1px solid var(--border); }
69
+ .msg-time { font-size: 11px; color: var(--muted); padding: 0 4px; }
70
+
71
+ .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; }
72
+ .replay-btn.visible { display: flex; }
73
+ .replay-btn:hover { background: rgba(200, 169, 110, 0.1); border-color: var(--accent); }
74
+
75
+ .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; }
76
+ .typing-bubble.visible { display: flex; }
77
+ .typing-bubble span { width: 6px; height: 6px; border-radius: 50%; background: var(--muted); animation: bounce-dot 1s ease-in-out infinite; }
78
+ .typing-bubble span:nth-child(2) { animation-delay: 0.15s; }
79
+ .typing-bubble span:nth-child(3) { animation-delay: 0.30s; }
80
+ .gen-voice { font-size: 12px; color: var(--muted); padding: 4px 8px; display: none; }
81
+ .gen-voice.visible { display: block; }
82
+ .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); }
83
+ .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; }
84
+ .input-wrap:focus-within { border-color: rgba(200,169,110,0.4); }
85
+ #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; }
86
+ #user-input::placeholder { color: var(--muted); }
87
+ .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; }
88
+ .send-btn:hover { opacity: 0.85; }
89
+ .send-btn:active { transform: scale(0.95); }
90
+ .send-btn:disabled { opacity: 0.35; cursor: not-allowed; }
91
+ @media (max-width: 660px) {
92
+ .shell { grid-template-columns: 1fr; grid-template-rows: auto 1fr; height: 100vh; }
93
+ .sidebar { flex-direction: row; border-right: none; border-bottom: 1px solid var(--border); padding: 1rem 1.25rem; gap: 1rem; justify-content: flex-start; }
94
+ .avatar-wrap { width: 56px; height: 56px; flex-shrink: 0; }
95
+ .avatar-img { width: 56px; height: 56px; border-radius: 8px; }
96
+ .avatar-ring, .avatar-ring.r2 { display: none; }
97
+ .bot-tagline, .voice-toggle, .speaking-badge, .delay-note { display: none !important; }
98
+ .bot-name { font-size: 1.1rem; }
99
+ .chat-panel { height: 0; min-height: 0; }
100
+ }
101
+ </style>
102
+ </head>
103
+ <body>
104
+ <div class="shell">
105
+ <aside class="sidebar">
106
+ <div class="avatar-wrap">
107
+ <div class="avatar-ring"></div>
108
+ <div class="avatar-ring r2"></div>
109
+ <img id="avatar-static" class="avatar-img" src="me.jpg"
110
+ onerror="this.style.background='#2a2a30';this.src=''" alt="Avatar">
111
+ </div>
112
+ <div class="speaking-badge" id="speaking-badge">
113
+ <div class="speaking-dots"><span></span><span></span><span></span></div>
114
+ Speaking
115
+ </div>
116
+ <div>
117
+ <h1 class="bot-name">Papa Jerry</h1>
118
+ <p class="bot-tagline">Ask me anything โ€” I'm here to help.</p>
119
+ </div>
120
+ <label class="voice-toggle on" id="voice-toggle">
121
+ <input type="checkbox" id="voice-on" checked>
122
+ ๐Ÿ”Š Voice on
123
+ </label>
124
+ <div class="delay-note">
125
+ voice generation takes 15-45 seconds - please be patient
126
+ </div>
127
+ </aside>
128
+ <main class="chat-panel">
129
+ <div class="chat-header">Conversation</div>
130
+ <div class="messages" id="messages">
131
+ <div class="msg bot">
132
+ <div class="bubble">Hey there! ๐Ÿ‘‹ I'm here and ready to chat. Ask me anything you'd like.</div>
133
+ <span class="msg-time" id="greeting-time"></span>
134
+ </div>
135
+ <div class="typing-bubble" id="typing">
136
+ <span></span><span></span><span></span>
137
+ </div>
138
+ <div class="gen-voice" id="gen-voice">๐ŸŽ™๏ธ Generating voice...</div>
139
+ </div>
140
+ <div class="input-bar">
141
+ <div class="input-wrap">
142
+ <textarea id="user-input" rows="1" placeholder="Type a messageโ€ฆ"></textarea>
143
+ </div>
144
+ <button class="send-btn" id="send-btn" title="Send">&#10148;</button>
145
+ </div>
146
+ </main>
147
+ </div>
148
+ <audio id="tts-audio" style="display:none"></audio>
149
+
150
+ <script>
151
+ // Silent debug logger - view via browser Console (F12), no on-page UI.
152
+ var debugStartTime = null;
153
+ function dlog(msg) {
154
+ if (debugStartTime === null) debugStartTime = performance.now();
155
+ var elapsed = ((performance.now() - debugStartTime) / 1000).toFixed(2);
156
+ console.log('[+' + elapsed + 's] ' + msg);
157
+ }
158
+ window.addEventListener('error', function(e) {
159
+ dlog('โŒ JS ERROR: ' + e.message);
160
+ });
161
+ window.addEventListener('unhandledrejection', function(e) {
162
+ dlog('โŒ UNHANDLED PROMISE REJECTION: ' + (e.reason && e.reason.message ? e.reason.message : e.reason));
163
+ });
164
+ </script>
165
+
166
+ <script>
167
+ // ============================================================
168
+ // CONFIGURE THESE
169
+ // ============================================================
170
+ var HF_SPACE_URL = 'https://zaktree-papa-jerry.hf.space';
171
+ 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.';
172
+ var SYSTEM_PROMPT = BASE_SYSTEM_PROMPT;
173
+ var POLL_INTERVAL = 4000;
174
+ // ============================================================
175
+
176
+ var chatHistory = [];
177
+ var busy = false;
178
+ var currentBotMsgId = null;
179
+
180
+ var msgsEl = document.getElementById('messages');
181
+ var inputEl = document.getElementById('user-input');
182
+ var sendBtn = document.getElementById('send-btn');
183
+ var typing = document.getElementById('typing');
184
+ var genVoiceEl = document.getElementById('gen-voice');
185
+ var voiceOn = document.getElementById('voice-on');
186
+ var voiceToggle = document.getElementById('voice-toggle');
187
+ var speakBadge = document.getElementById('speaking-badge');
188
+ var ttsAudio = document.getElementById('tts-audio');
189
+
190
+ document.getElementById('greeting-time').textContent = _time();
191
+
192
+ // Dynamic loader built to ingest 'family' and 'other' data fields safely
193
+ function loadFactsFromServer() {
194
+ fetch('facts.json')
195
+ .then(function(r) { return r.json(); })
196
+ .then(function(facts) {
197
+ var factsText = "\n\nHere are some facts you know about specific people:\n";
198
+ for (var person in facts) {
199
+ var location = facts[person].location || "unknown";
200
+ var job = facts[person].job || "unknown";
201
+ var hobbies = facts[person].hobbies || "unknown";
202
+
203
+ // Dynamic additions: Append context chunks string conditionally
204
+ var familyDetails = facts[person].family ? " Family connections: " + facts[person].family + "." : "";
205
+ var otherDetails = facts[person].other ? " Additional information: " + facts[person].other + "." : "";
206
+
207
+ factsText += "- " + person + " lives in " + location +
208
+ ", works as a " + job +
209
+ ", and their hobbies include " + hobbies + "." +
210
+ familyDetails + otherDetails + "\n";
211
+ }
212
+ SYSTEM_PROMPT = BASE_SYSTEM_PROMPT + factsText;
213
+ console.log("AI context initialized with multi-field profile definitions.");
214
+ })
215
+ .catch(function(err) {
216
+ console.log("No facts loaded or file empty, applying base prompt fallback.", err);
217
+ });
218
+ }
219
+
220
+ loadFactsFromServer();
221
+
222
+ voiceOn.addEventListener('change', function() {
223
+ voiceToggle.classList.toggle('on', voiceOn.checked);
224
+ voiceToggle.lastChild.textContent = voiceOn.checked ? ' Voice on' : ' Voice off';
225
+ });
226
+
227
+ inputEl.addEventListener('input', function() {
228
+ this.style.height = 'auto';
229
+ this.style.height = Math.min(this.scrollHeight, 120) + 'px';
230
+ });
231
+
232
+ inputEl.addEventListener('keydown', function(e) {
233
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
234
+ });
235
+
236
+ sendBtn.addEventListener('click', send);
237
+
238
+ function unlockAudio() {
239
+ dlog('unlockAudio() called (click gesture)');
240
+ try {
241
+ ttsAudio.muted = true;
242
+ var p = ttsAudio.play();
243
+ if (p && p.catch) p.catch(function(e) { dlog('unlock play() rejected: ' + e.message); });
244
+ ttsAudio.pause();
245
+ ttsAudio.currentTime = 0;
246
+ dlog('unlockAudio() completed OK');
247
+ } catch (e) { dlog('unlockAudio() threw: ' + e.message); }
248
+ }
249
+
250
+ function send() {
251
+ var text = inputEl.value.trim();
252
+ if (!text || busy) return;
253
+ debugStartTime = performance.now();
254
+ dlog('--- NEW MESSAGE: "' + text + '" ---');
255
+ if (voiceOn.checked) unlockAudio();
256
+ addMessage('user', text);
257
+ chatHistory.push({ role: 'user', content: text });
258
+ inputEl.value = '';
259
+ inputEl.style.height = 'auto';
260
+ setTyping(true);
261
+ busy = true;
262
+ sendBtn.disabled = true;
263
+ currentBotMsgId = 'msg-' + Date.now();
264
+
265
+ fetch('/chat', {
266
+ method: 'POST',
267
+ headers: {
268
+ 'Content-Type': 'application/json'
269
+ },
270
+ body: JSON.stringify({
271
+ messages: [{ role: 'system', content: SYSTEM_PROMPT }].concat(chatHistory)
272
+ })
273
+ })
274
+ .then(function(r) { return r.json(); })
275
+ .then(function(data) {
276
+ setTyping(false);
277
+ if (!data.choices || !data.choices[0]) {
278
+ addMessage('bot', 'Sorry, I could not get a response. Please try again.');
279
+ done(); return;
280
+ }
281
+ var reply = data.choices[0].message.content;
282
+ chatHistory.push({ role: 'assistant', content: reply });
283
+
284
+ addMessage('bot', reply, currentBotMsgId);
285
+
286
+ if (voiceOn.checked) {
287
+ speak(reply);
288
+ } else {
289
+ done();
290
+ }
291
+ })
292
+ .catch(function(err) {
293
+ setTyping(false);
294
+ addMessage('bot', 'Connection error: ' + err.message);
295
+ done();
296
+ });
297
+ }
298
+
299
+ var voiceStartTime = 0;
300
+ var UI_CounterInterval = null;
301
+
302
+ function startVoiceTimer() {
303
+ voiceStartTime = performance.now();
304
+ genVoiceEl.textContent = '๐ŸŽ™๏ธ Generating voice... 0s';
305
+ genVoiceEl.classList.add('visible');
306
+ UI_CounterInterval = setInterval(function() {
307
+ var elapsed = Math.round((performance.now() - voiceStartTime) / 1000);
308
+ genVoiceEl.textContent = '๐ŸŽ™๏ธ Generating voice... ' + elapsed + 's';
309
+ }, 1000);
310
+ }
311
+
312
+ function stopVoiceTimer() {
313
+ if (UI_CounterInterval) { clearInterval(UI_CounterInterval); UI_CounterInterval = null; }
314
+ genVoiceEl.classList.remove('visible');
315
+ }
316
+
317
+ // Holds each clip's blob URL after its one-and-only fetch, so "Replay
318
+ // Voice" reuses it directly instead of ever hitting the network again.
319
+ var audioBlobCache = {};
320
+
321
+ function speak(text) {
322
+ startVoiceTimer();
323
+ var url = HF_SPACE_URL + '/speak?text=' + encodeURIComponent(text);
324
+ dlog('speak(): sending GET /speak');
325
+ fetch(url)
326
+ .then(function(r) {
327
+ dlog('speak response received, HTTP status ' + r.status + ' (server generation: ' + (r.headers.get('X-Generation-Seconds') || '?') + 's)');
328
+ if (!r.ok) throw new Error('HTTP ' + r.status);
329
+ return r.blob();
330
+ })
331
+ .then(function(blob) {
332
+ dlog('blob received, size ' + blob.size + ' bytes, type ' + blob.type);
333
+ var blobUrl = URL.createObjectURL(blob);
334
+ // Cached immediately - this is the ONLY fetch of this clip that
335
+ // will ever happen. No second request means no second (very
336
+ // expensive) generation on the server.
337
+ audioBlobCache[currentBotMsgId] = blobUrl;
338
+ setupReplayButton(currentBotMsgId, blobUrl);
339
+ playAudio(blobUrl);
340
+ })
341
+ .catch(function(e) { dlog('โŒ /speak failed: ' + e.message); stopVoiceTimer(); done(); });
342
+ }
343
+
344
+ function playAudio(src) {
345
+ dlog('playAudio() called, src=' + src.slice(0, 80));
346
+ if (busy && !ttsAudio.paused) {
347
+ ttsAudio.pause();
348
+ }
349
+ speakBadge.classList.add('active');
350
+ ttsAudio.muted = false;
351
+ ttsAudio.src = src;
352
+
353
+ ttsAudio.oncanplay = function() { dlog('audio event: canplay'); };
354
+ ttsAudio.onwaiting = function() { dlog('audio event: waiting (buffering)'); };
355
+ ttsAudio.onstalled = function() { dlog('audio event: stalled'); };
356
+ ttsAudio.onplaying = function() {
357
+ dlog('๐Ÿ”Š audio event: PLAYING (actually audible now)');
358
+ if (UI_CounterInterval) {
359
+ var accurateSeconds = ((performance.now() - voiceStartTime) / 1000).toFixed(1);
360
+ stopVoiceTimer();
361
+ injectVoiceDuration(currentBotMsgId, accurateSeconds);
362
+ }
363
+ var targetMsg = document.getElementById(currentBotMsgId);
364
+ var replayBtn = targetMsg && targetMsg.querySelector('.replay-btn');
365
+ if (replayBtn) replayBtn.classList.add('visible');
366
+ };
367
+
368
+ var playPromise = ttsAudio.play();
369
+ if (playPromise && playPromise.then) {
370
+ playPromise.then(function() {
371
+ dlog('play() promise RESOLVED (browser allowed playback)');
372
+ }).catch(function(e) {
373
+ dlog('โŒ play() promise REJECTED: ' + e.name + ' - ' + e.message);
374
+ });
375
+ }
376
+
377
+ ttsAudio.onended = function() {
378
+ dlog('audio event: ended');
379
+ speakBadge.classList.remove('active');
380
+ done();
381
+ };
382
+ ttsAudio.onerror = function() { dlog('โŒ audio event: error - ' + (ttsAudio.error ? ttsAudio.error.message : 'unknown')); speakBadge.classList.remove('active'); done(); };
383
+ }
384
+
385
+ function done() {
386
+ busy = false;
387
+ sendBtn.disabled = false;
388
+ inputEl.focus();
389
+ }
390
+
391
+ function addMessage(role, text, elementId) {
392
+ var msg = document.createElement('div');
393
+ msg.className = 'msg ' + role;
394
+ if (elementId) msg.id = elementId;
395
+
396
+ var bubble = document.createElement('div');
397
+ bubble.className = 'bubble';
398
+ bubble.textContent = text;
399
+ var time = document.createElement('span');
400
+ time.className = 'msg-time';
401
+ time.textContent = _time();
402
+ msg.appendChild(bubble);
403
+ msg.appendChild(time);
404
+
405
+ if (role === 'bot') {
406
+ var replayBtn = document.createElement('button');
407
+ replayBtn.className = 'replay-btn';
408
+ replayBtn.innerHTML = 'โ–ถ๏ธ Replay Voice';
409
+ msg.appendChild(replayBtn);
410
+ }
411
+
412
+ msgsEl.insertBefore(msg, typing);
413
+ msgsEl.scrollTop = msgsEl.scrollHeight;
414
+ }
415
+
416
+ function injectVoiceDuration(elementId, seconds) {
417
+ var targetMsg = document.getElementById(elementId);
418
+ if (!targetMsg) return;
419
+
420
+ var durationEl = document.createElement('div');
421
+ durationEl.style.fontSize = '11px';
422
+ durationEl.style.color = 'var(--muted)';
423
+ durationEl.style.marginTop = '4px';
424
+ durationEl.style.padding = '0 4px';
425
+ durationEl.textContent = 'โฑ๏ธ Generated in ' + seconds + 's';
426
+
427
+ var replayBtn = targetMsg.querySelector('.replay-btn');
428
+ if (replayBtn) {
429
+ targetMsg.insertBefore(durationEl, replayBtn);
430
+ } else {
431
+ targetMsg.appendChild(durationEl);
432
+ }
433
+ msgsEl.scrollTop = msgsEl.scrollHeight;
434
+ }
435
+
436
+ function setupReplayButton(elementId, audioSrc) {
437
+ var targetMsg = document.getElementById(elementId);
438
+ if (!targetMsg) return;
439
+
440
+ var btn = targetMsg.querySelector('.replay-btn');
441
+ if (!btn) return;
442
+
443
+ btn.onclick = function() {
444
+ speakBadge.classList.add('active');
445
+ ttsAudio.src = audioSrc;
446
+ ttsAudio.play();
447
+ ttsAudio.onended = function() { speakBadge.classList.remove('active'); };
448
+ ttsAudio.onerror = function() { speakBadge.classList.remove('active'); };
449
+ };
450
+ // Not made visible here - the "playing" handler in playAudio() reveals
451
+ // it once the clip actually starts sounding, so it doesn't show up
452
+ // before there's anything to replay yet.
453
+ }
454
+
455
+ function setTyping(show) {
456
+ typing.classList.toggle('visible', show);
457
+ msgsEl.scrollTop = msgsEl.scrollHeight;
458
+ }
459
+
460
+ // Global UI clock time builder string
461
+ function _time() {
462
+ var d = new Date(), h = d.getHours(), m = d.getMinutes();
463
+ var ampm = h >= 12 ? 'pm' : 'am';
464
+ h = h % 12 || 12;
465
+ return h + ':' + (m < 10 ? '0' : '') + m + ' ' + ampm;
466
+ }
467
+ </script>
468
+ </body>
469
+ </html>