File size: 34,145 Bytes
9879274
 
 
c80854f
0fe09d3
c80854f
 
 
9879274
c80854f
9879274
4261cb3
c80854f
 
 
9879274
0fe09d3
c80854f
 
 
9879274
 
c80854f
9879274
c80854f
4261cb3
c80854f
 
 
9879274
c80854f
 
4261cb3
c80854f
9879274
c80854f
9879274
4261cb3
c80854f
 
 
4261cb3
c80854f
 
 
4261cb3
c80854f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4261cb3
c80854f
 
9879274
c80854f
 
4261cb3
c80854f
 
 
 
 
 
 
 
 
 
 
 
 
4261cb3
c80854f
 
4261cb3
c80854f
4261cb3
c80854f
 
 
9879274
4261cb3
c80854f
 
9879274
4261cb3
c80854f
 
4261cb3
c80854f
4261cb3
c80854f
 
9879274
 
c80854f
 
4261cb3
c80854f
4261cb3
 
c80854f
 
4261cb3
 
c80854f
 
 
0fe09d3
 
c80854f
0fe09d3
c80854f
78505c8
c80854f
 
 
 
 
 
 
 
4261cb3
c80854f
 
 
 
 
 
 
 
 
0fe09d3
c80854f
 
 
0fe09d3
c80854f
 
 
0fe09d3
 
c80854f
0fe09d3
 
 
 
 
c80854f
0fe09d3
c80854f
 
9879274
 
 
 
 
 
 
c80854f
 
78505c8
0fe09d3
9879274
 
 
c80854f
 
9879274
 
c80854f
 
78505c8
 
c80854f
9879274
 
 
 
 
 
 
c80854f
9879274
 
 
 
 
 
 
 
 
c80854f
9879274
0fe09d3
 
9879274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c80854f
9879274
0fe09d3
 
 
 
9879274
 
c80854f
 
0fe09d3
c80854f
0fe09d3
c80854f
0fe09d3
c80854f
9879274
c80854f
 
9879274
c80854f
 
0fe09d3
 
c80854f
 
0fe09d3
c80854f
 
0fe09d3
c80854f
 
9879274
c80854f
 
 
9879274
 
 
c80854f
9879274
c80854f
78505c8
9879274
 
 
 
 
78505c8
 
c80854f
 
9879274
 
 
 
 
78505c8
 
c80854f
9879274
c80854f
9879274
c80854f
9879274
 
c80854f
 
 
 
 
9879274
78505c8
c80854f
78505c8
 
 
c80854f
 
 
9879274
c80854f
9879274
c80854f
9879274
 
 
c80854f
9879274
c80854f
9879274
c80854f
 
 
 
 
9879274
c80854f
9879274
c80854f
 
9879274
c80854f
 
78505c8
4261cb3
c80854f
 
 
4261cb3
c80854f
4261cb3
 
 
 
 
0fe09d3
4261cb3
 
 
0fe09d3
c80854f
4261cb3
c80854f
4261cb3
 
 
c80854f
78505c8
 
c80854f
78505c8
0fe09d3
 
 
c80854f
0fe09d3
c80854f
0fe09d3
c80854f
0fe09d3
 
 
 
c80854f
0fe09d3
c80854f
0fe09d3
9879274
c80854f
78505c8
c80854f
 
 
0fe09d3
78505c8
 
0fe09d3
 
 
 
c80854f
0fe09d3
 
 
c80854f
 
 
 
 
 
 
0fe09d3
 
c80854f
 
 
9879274
0fe09d3
 
c80854f
9879274
c80854f
 
 
0fe09d3
c80854f
78505c8
 
c80854f
78505c8
c80854f
 
0fe09d3
78505c8
 
0fe09d3
 
78505c8
 
 
 
c80854f
 
78505c8
c80854f
 
 
78505c8
 
c80854f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Enhanced Multi-Source AI Chatbot</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Multi-source chatbot with DuckDuckGo, Wikipedia, Weather APIs, and offline fallbacks">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #0b1020; --bg2: #0f1630; --panel: #0f1732; --text: #e7ecff; --muted: #a3b1d9;
      --accent: #6ea8fe; --accent2: #8ad1ff; --bubble-user: #1a254f; --bubble-bot: #141e3d;
      --shadow: 0 10px 30px rgba(0,0,0,.35); --radius: 14px;
    }
    * { box-sizing: border-box }
    body {
      margin: 0; padding: 0; height: 100%; font-family: Inter, system-ui, -apple-system, sans-serif;
      color: var(--text); background: radial-gradient(1200px 800px at 10% -20%, #20306a 0%, transparent 60%),
        radial-gradient(900px 700px at 110% 10%, #1b3c7a 0%, transparent 60%),
        radial-gradient(700px 900px at 50% 120%, #1a365d 0%, transparent 60%),
        linear-gradient(180deg, var(--bg), var(--bg2)); background-attachment: fixed;
    }
    .app { display: flex; flex-direction: column; min-height: 100%; max-width: 1100px; margin: 0 auto; }
    header {
      position: sticky; top: 0; z-index: 10; backdrop-filter: saturate(180%) blur(8px);
      background: linear-gradient(180deg, rgba(10,16,34,.8), rgba(10,16,34,.35));
      border-bottom: 1px solid rgba(255,255,255,.06);
    }
    .topbar { display: flex; align-items: center; justify-content: space-between; padding: 14px 18px; gap: 12px; }
    .brand { display: flex; align-items: center; gap: 12px; min-width: 0; }
    .logo {
      width: 36px; height: 36px; border-radius: 10px;
      background: conic-gradient(from 210deg, #6ea8fe, #8ad1ff, #6ea8fe);
      box-shadow: 0 6px 16px rgba(110,168,254,.35), inset 0 0 18px rgba(255,255,255,.2); position: relative;
    }
    .logo::after {
      content: ""; position: absolute; inset: 3px; border-radius: 8px;
      background: radial-gradient(120px 80px at 30% 20%, rgba(255,255,255,.5), transparent 40%),
        linear-gradient(180deg, rgba(255,255,255,.12), rgba(0,0,0,.18));
    }
    .title { font-weight: 800; letter-spacing: .2px; font-size: 18px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .subtitle { font-size: 12px; color: var(--muted); }
    .links { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
    .btn {
      appearance: none; border: none; cursor: pointer; font: inherit; color: inherit; padding: 10px 14px;
      border-radius: 10px; background: #1a254f; color: #dfe8ff; display: inline-flex; align-items: center; gap: 8px;
      border: 1px solid rgba(255,255,255,.08); transition: transform .08s ease, background .2s ease, border-color .2s ease, opacity .2s ease;
    }
    .btn:hover { transform: translateY(-1px); border-color: rgba(255,255,255,.18) }
    .btn.secondary { background: #0f1732 }
    .btn.ghost { background: transparent; border-color: rgba(255,255,255,.1) }
    .btn:disabled { opacity: .6; cursor: not-allowed; transform: none }
    .icon { width: 18px; height: 18px; display: inline-block; }
    main { flex: 1; display: flex; flex-direction: column; padding: 12px; }
    .chat { flex: 1; overflow: auto; padding: 12px; padding-bottom: 24px; scroll-behavior: smooth; }
    .messages { display: flex; flex-direction: column; gap: 12px; }
    .row { display: flex; gap: 10px; align-items: flex-end; }
    .row.user { justify-content: flex-end }
    .row.bot { justify-content: flex-start }
    .avatar {
      width: 32px; height: 32px; border-radius: 50%; background: #172046; display: flex; align-items: center; justify-content: center;
      font-size: 14px; font-weight: 700; border: 1px solid rgba(255,255,255,.08); box-shadow: var(--shadow); flex-shrink: 0;
    }
    .avatar.bot { background: radial-gradient(100px 80px at 20% 10%, #2a3d7a, #192555) }
    .avatar.user { background: radial-gradient(120px 90px at 30% 10%, #1a2c5f, #0e1736) }
    .bubble {
      max-width: min(800px, 86vw); padding: 12px 14px; border-radius: var(--radius);
      border: 1px solid rgba(255,255,255,.08); box-shadow: var(--shadow); line-height: 1.55; position: relative;
      word-wrap: break-word; overflow-wrap: anywhere;
    }
    .bubble.user { background: linear-gradient(180deg, #152152, #101a3e); border-top-right-radius: 6px }
    .bubble.bot { background: linear-gradient(180deg, #111a3b, #0c1431); border-bottom-left-radius: 6px }
    .meta { font-size: 12px; color: var(--muted); margin-bottom: 6px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
    .badge { padding: 2px 8px; border-radius: 999px; background: #0c1330; border: 1px solid rgba(255,255,255,.08); font-size: 11px; color: #c7d5ff; }
    .answer { font-size: 15px; color: #e9efff }
    .answer p { margin: 0 0 10px 0 }
    .answer ul, .answer ol { margin: 6px 0 10px 18px }
    .answer a { color: var(--accent2); text-decoration: underline }
    .sources { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
    .source {
      font-size: 12px; color: #c7d5ff; background: #0c1330; border: 1px solid rgba(255,255,255,.08);
      padding: 4px 8px; border-radius: 8px;
    }
    .source.multi { background: #0d1b3a; border-color: #4a90e2 }
    .composer {
      position: sticky; bottom: 0; z-index: 9; display: flex; gap: 10px; align-items: flex-end; padding: 12px;
      background: linear-gradient(180deg, rgba(10,16,34,.0), rgba(10,16,34,.85)); backdrop-filter: blur(8px);
      border-top: 1px solid rgba(255,255,255,.06);
    }
    .input-wrap {
      flex: 1; display: flex; gap: 10px; align-items: flex-end; background: linear-gradient(180deg, #0e1633, #0b122b);
      border: 1px solid rgba(255,255,255,.08); border-radius: 14px; padding: 8px; box-shadow: var(--shadow);
    }
    textarea {
      flex: 1; resize: none; border: none; outline: none; background: transparent; color: var(--text); font: inherit;
      line-height: 1.4; max-height: 200px; min-height: 40px; padding: 8px 10px;
    }
    .actions { display: flex; gap: 8px; align-items: center; }
    .small-btn {
      width: 38px; height: 38px; border-radius: 10px; border: 1px solid rgba(255,255,255,.1); background: #0e1633;
      display: flex; align-items: center; justify-content: center; cursor: pointer;
      transition: transform .08s ease, border-color .2s ease, background .2s ease;
    }
    .small-btn:hover { transform: translateY(-1px); border-color: rgba(255,255,255,.2) }
    .small-btn:disabled { opacity: .6; cursor: not-allowed; transform: none }
    .suggestions {
      position: absolute; left: 12px; right: 12px; bottom: 64px; display: flex; flex-wrap: wrap; gap: 8px; pointer-events: none;
    }
    .chip {
      pointer-events: auto; background: #0d1431; border: 1px solid rgba(255,255,255,.1); color: #d8e4ff;
      padding: 6px 10px; border-radius: 999px; font-size: 12px; cursor: pointer;
      transition: transform .08s ease, background .2s ease, border-color .2s ease;
    }
    .chip:hover { transform: translateY(-1px); background: #121c44; border-color: rgba(255,255,255,.2) }
    .typing { display: inline-flex; align-items: center; gap: 6px; }
    .dot { width: 6px; height: 6px; background: #c7d5ff; border-radius: 50%; opacity: .8; animation: blink 1.4s infinite ease-in-out; }
    .dot:nth-child(2) { animation-delay: .2s }
    .dot:nth-child(3) { animation-delay: .4s }
    @keyframes blink { 0%,80%,100% { transform: translateY(0); opacity: .5 } 40% { transform: translateY(-3px); opacity: 1 } }
    .hint { font-size: 12px; color: var(--muted); padding: 4px 2px 0 2px; }
    .footer-note { text-align: center; font-size: 12px; color: var(--muted); padding: 10px 0 18px; }
    .data-source-indicator {
      display: inline-flex; align-items: center; gap: 4px; font-size: 11px; padding: 2px 6px; border-radius: 6px;
      background: rgba(74, 144, 226, 0.2); border: 1px solid rgba(74, 144, 226, 0.4);
    }
    .data-source-indicator.wiki { background: rgba(74, 226, 144, 0.2); border-color: rgba(74, 226, 144, 0.4); }
    .data-source-indicator.weather { background: rgba(250, 204, 21, 0.2); border-color: rgba(250, 204, 21, 0.4); }
    .data-source-indicator.calc { background: rgba(168, 85, 247, 0.2); border-color: rgba(168, 85, 247, 0.4); }
    .data-source-indicator.offline { background: rgba(248, 113, 113, 0.2); border-color: rgba(248, 113, 113, 0.4); }
    .source-badge { font-size: 10px; padding: 1px 4px; border-radius: 3px; background: rgba(255,255,255,0.1); margin-left: 4px; }
    .mono {
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 12px;
      background: #0b1434; border: 1px solid rgba(255,255,255,.08); border-radius: 8px; padding: 10px; overflow: auto;
    }
    .search-results { background: #0d1431; border: 1px solid rgba(255,255,255,.1); border-radius: 8px; padding: 10px; margin: 8px 0; }
    .search-result { margin-bottom: 8px; padding-bottom: 8px; border-bottom: 1px solid rgba(255,255,255,.05); }
    .search-result:last-child { margin-bottom: 0; padding-bottom: 0; border-bottom: none; }
    .search-result-title { font-weight: 600; color: #8ad1ff; text-decoration: none; }
    .search-result-title:hover { text-decoration: underline; }
    .search-result-snippet { font-size: 13px; color: #c7d5ff; margin-top: 2px; }
    .status {
      position: fixed; bottom: 10px; right: 12px; background: rgba(12,19,48,0.8);
      border: 1px solid rgba(255,255,255,.1); padding: 6px 10px; border-radius: 999px; font-size: 12px; color: var(--muted);
      display: flex; align-items: center; gap: 8px; backdrop-filter: blur(6px);
    }
    .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #facc15; box-shadow: 0 0 8px #facc15; }
    .status-dot.ok { background: #4ade80; box-shadow: 0 0 8px #4ade80; }
    .status-dot.err { background: #f87171; box-shadow: 0 0 8px #f87171; }
    @media (max-width: 720px) {
      .topbar { padding: 12px }
      .title { font-size: 17px }
      .links { display: none }
      .bubble { max-width: min(760px, 92vw) }
      .suggestions { bottom: 60px }
    }
    .chat::-webkit-scrollbar { width: 10px }
    .chat::-webkit-scrollbar-thumb { background: #16214a; border-radius: 10px; border: 2px solid transparent; background-clip: padding-box; }
    .chat::-webkit-scrollbar-track { background: transparent }
    .fade-in { animation: fadeIn .22s ease-out; }
    @keyframes fadeIn { from { opacity: 0; transform: translateY(6px) } to { opacity: 1; transform: translateY(0) } }
  </style>
</head>
<body>
  <div class="app">
    <header>
      <div class="topbar">
        <div class="brand">
          <div class="logo"></div>
          <div>
            <div class="title">Enhanced Multi-Source AI Chatbot</div>
            <div class="subtitle">DuckDuckGo, Wikipedia, Weather, Calculator + Offline Fallbacks</div>
          </div>
        </div>
        <div class="links">
          <a class="btn ghost" href="https://duckduckgo.com/" target="_blank" rel="noopener">
            <svg class="icon" viewBox="0 0 24 24" fill="none"><path d="M12 2a10 10 0 1 0 .001 20.001A10 10 0 0 0 12 2Zm0 0c2.5 0 4.5 5 4.5 5s-2 5-4.5 5-4.5-5-4.5-5 2-5 4.5-5Zm0 10c4.5 0 6 5 6 5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
            DuckDuckGo
          </a>
          <a class="btn ghost" href="https://en.wikipedia.org/" target="_blank" rel="noopener">
            <svg class="icon" viewBox="0 0 24 24" fill="none"><path d="M4 4h16v16H4z" stroke="currentColor" stroke-width="2"/><path d="M7 8h10M7 12h10M7 16h6" stroke="currentColor" stroke-width="2"/></svg>
            Wikipedia
          </a>
          <button id="exportBtn" class="btn secondary" title="Export chat">
            <svg class="icon" viewBox="0 0 24 24" fill="none"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
            Export
          </button>
          <button id="clearBtn" class="btn" title="Clear chat">
            <svg class="icon" viewBox="0 0 24 24" fill="none"><path d="M3 6h18M8 6v12m8-12v12M5 6l1 14a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2L19 6M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
            Clear
          </button>
          <a class="btn" href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" rel="noopener">Built with anycoder</a>
        </div>
      </div>
    </header>
    <main>
      <div class="chat" id="chat">
        <div class="messages" id="messages">
          <div class="row bot fade-in">
            <div class="avatar bot">🤖</div>
            <div class="bubble bot">
              <div class="meta"><span class="badge">Bot</span><span>Multi-Source AI Assistant</span></div>
              <div class="answer">
                <p>Hi! I'm your enhanced AI assistant with multiple data sources including DuckDuckGo Instant Answers, Wikipedia, Weather APIs, Calculator, and robust offline fallbacks.</p>
                <p class="hint">Try asking about: facts, definitions, weather, time zones, calculations, historical events, or general knowledge.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="suggestions" id="suggestions"></div>
      <div class="composer">
        <div class="input-wrap">
          <textarea id="prompt" rows="1" placeholder="Ask me anything... (Shift+Enter = newline)"></textarea>
          <div class="actions">
            <button class="small-btn" id="stopBtn" disabled title="Stop">
              <svg class="icon" viewBox="0 0 24 24" fill="none"><rect x="6" y="6" width="12" height="12" rx="2" stroke="currentColor" stroke-width="2"/></svg>
            </button>
            <button class="small-btn" id="sendBtn" title="Send (Enter)">
              <svg class="icon" viewBox="0 0 24 24" fill="none"><path d="M5 12h7m0 0-4-4m4 4-4 4M19 12h-7m0 0 4-4m-4 4 4 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </button>
          </div>
        </div>
      </div>
    </main>
    <div class="footer-note">Enhanced with multiple data sources: DuckDuckGo, Wikipedia, Open-Meteo Weather API, Calculator, and offline knowledge.</div>
  </div>
  <div class="status" id="status">
    <span class="status-dot" id="statusDot"></span>
    <span id="statusText">Checking network...</span>
  </div>
  <script>
    // Utilities
    const $ = (sel, el=document) => el.querySelector(sel), $$ = (sel, el=document) => [...el.querySelectorAll(sel)];
    const escapeHTML = s => s.replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
    const nowTime = () => new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
    
    function updateTextareaHeight() {
      const el = $('#prompt'); el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 200) + 'px';
    }
    
    // DOM elements
    const chatEl = $('#chat'), messagesEl = $('#messages'), promptEl = $('#prompt'), sendBtn = $('#sendBtn'), stopBtn = $('#stopBtn'), suggestionsEl = $('#suggestions'), clearBtn = $('#clearBtn'), exportBtn = $('#exportBtn'), statusDot = $('#statusDot'), statusText = $('#statusText');
    
    // State
    let history = [], abortController = null, lastQuery = '', offlineMode = false;
    
    // Network indicator
    function updateNetworkStatus() {
      if (navigator.onLine) { statusDot.className = 'status-dot ok'; statusText.textContent = 'Online'; offlineMode = false; }
      else { statusDot.className = 'status-dot err'; statusText.textContent = 'Offline'; offlineMode = true; }
    }
    window.addEventListener('online', updateNetworkStatus); window.addEventListener('offline', updateNetworkStatus); updateNetworkStatus();
    
    // Suggestions
    const defaultChips = ['weather in Tokyo', 'time in London', 'define artificial intelligence', 'who was Einstein', 'sqrt(144)', 'USD to EUR', 'prime factors of 91', 'Python programming history', 'what is machine learning', 'how tall is Mount Everest', 'capital of France', 'latest news about AI', 'JavaScript vs Python', 'quantum computing explained'];
    
    function renderSuggestions(items=defaultChips){
      suggestionsEl.innerHTML = ''; items.forEach(text => {
        const chip = document.createElement('button'); chip.className = 'chip'; chip.textContent = text;
        chip.onclick = () => { promptEl.value = text; updateTextareaHeight(); promptEl.focus(); };
        suggestionsEl.appendChild(chip);
      });
    }
    
    function buildPromptChips(q){
      q = q.trim(); const chips = [];
      const hasWeather = /\b(weather|temperature|forecast)\b/i.test(q);
      const hasDefine = /\b(define|meaning|definition|what does)\b/i.test(q);
      const hasConvert = /\b(to|in|°)\b/i.test(q) || /\b(c|f|cm|inch|kg|lb)\b/.test(q);
      const hasTime = /\b(time|datetime|date)\b/i.test(q);
      const hasWho = /\b(who is|who's|who’re)\b/i.test(q);
      const hasCalc = /[\d\+\-\*\/\^\(\)\.]/.test(q);
      const hasHistory = /\b(history|historical)\b/i.test(q);
      const hasScience = /\b(science|scientific)\b/i.test(q);
      
      if (q && !hasWeather) chips.push(q.replace(/\b(what is|what's)\b/i,'') + ' weather');
      if (q && !hasDefine) chips.push('define ' + q.replace(/\b(define|meaning|definition|what does)\b/i,'').trim());
      if (q && !hasConvert && /(?:\d|\b)(°\s?[cf]|celsius|fahrenheit|cm|inch|kg|lb)\b/i.test(q)) chips.push(q + ' to fahrenheit');
      if (q && !hasTime) chips.push('time in ' + q.replace(/\b(what is|what's|time in|date|datetime)\b/ig,'').trim());
      if (q && !hasWho) chips.push('who is ' + q.replace(/\b(who is|who's|who’re)\b/ig,'').trim());
      if (q && !hasCalc) chips.push(q.replace(/\b(calculate|compute|solve)\b/i,'').trim());
      if (q && !hasHistory) chips.push(q + ' history');
      if (q && !hasScience) chips.push(q + ' science');
      
      const unique = [...new Set(chips)].filter(Boolean).slice(0,6);
      if (unique.length === 0) renderSuggestions(defaultChips); else renderSuggestions(unique);
    }
    
    // Message helpers
    function addMessage(role, contentHTML, meta = {}){
      const row = document.createElement('div'); row.className = `row ${role} fade-in`;
      const avatar = document.createElement('div'); avatar.className = `avatar ${role}`; avatar.textContent = role === 'bot' ? '🤖' : '🙂';
      const bubble = document.createElement('div'); bubble.className = `bubble ${role}`;
      const metaEl = document.createElement('div'); metaEl.className = 'meta';
      const badge = document.createElement('span'); badge.className = 'badge'; badge.textContent = role === 'bot' ? (meta.badge || 'AI Assistant') : 'You';
      metaEl.appendChild(badge);
      if (meta.source) {
        const sourceEl = document.createElement('span'); sourceEl.className = `data-source-indicator ${meta.source.className || ''}`;
        sourceEl.innerHTML = `${meta.source.icon || '📡'} ${meta.source.name}`;
        metaEl.appendChild(sourceEl);
      }
      if (meta.note){ const note = document.createElement('span'); note.textContent = meta.note; note.style.color = 'var(--muted)'; metaEl.appendChild(note); }
      const answer = document.createElement('div'); answer.className = 'answer'; answer.innerHTML = contentHTML;
      bubble.appendChild(metaEl); bubble.appendChild(answer);
      if (meta.sources && meta.sources.length){
        const sources = document.createElement('div'); sources.className = 'sources';
        meta.sources.forEach(src => {
          const s = document.createElement('a'); s.className = `source ${src.multi ? 'multi' : ''}`; s.href = src.href; s.target = '_blank'; s.rel = 'noopener noreferrer'; s.textContent = src.label || src.href; sources.appendChild(s);
        });
        bubble.appendChild(sources);
      }
      row.appendChild(avatar); row.appendChild(bubble); messagesEl.appendChild(row); chatEl.scrollTop = chatEl.scrollHeight; return bubble;
    }
    
    function addTyping(){
      const row = document.createElement('div'); row.className = 'row bot fade-in'; row.dataset.typing = '1';
      const avatar = document.createElement('div'); avatar.className = 'avatar bot'; avatar.textContent = '🤖';
      const bubble = document.createElement('div'); bubble.className = 'bubble bot';
      const metaEl = document.createElement('div'); metaEl.className = 'meta';
      const badge = document.createElement('span'); badge.className = 'badge'; badge.textContent = 'AI Assistant';
      metaEl.appendChild(badge);
      const answer = document.createElement('div'); answer.className = 'answer';
      answer.innerHTML = `<span class="typing"><span class="dot"></span><span class="dot"></span><span class="dot"></span></span>`;
      bubble.appendChild(metaEl); bubble.appendChild(answer);
      row.appendChild(avatar); row.appendChild(bubble); messagesEl.appendChild(row); chatEl.scrollTop = chatEl.scrollHeight; return row;
    }
    function removeTyping(){ const t = $('[data-typing="1"]', messagesEl); if (t) t.remove(); }
    
    // CORS proxy list
    const CORS_PROXIES = [
      target => `https://cors.isomorphic-git.org/${target}`,
      targetapi.codetabs => `https://.com/v1/proxy?quest=${encodeURIComponent(target)}`,
      target => `https://corsproxy.io/?${encodeURIComponent(target)}`
    ];
    
    async function fetchWithCorsProxies(targetUrl, signal){
      let lastErr = null;
      for (const buildProxy of CORS_PROXIES){
        const proxyUrl = buildProxy(targetUrl);
        try{
          const res = await fetch(proxyUrl, { signal, headers: { 'Accept': 'application/json, text/plain, */*' } });
          if (!res.ok) throw new Error(`HTTP ${res.status}`);
          const contentType = res.headers.get('content-type') || '';
          const text = await res.text();
          let data = text;
          if (contentType.includes('application/json')) { try { data = JSON.parse(text); } catch {} }
          return data;
        }catch(err){ lastErr = err; }
      }
      throw lastErr || new Error('All CORS proxies failed');
    }
    
    // Data Source Classes
    class DataSource {
      constructor(name, icon, className) { this.name = name; this.icon = icon; this.className = className; }
      async search(query, signal) { throw new Error('Not implemented'); }
      getPriority() { return 50; }
      canHandle() { return false; }
    }
    
    class OfflineSource extends DataSource {
      constructor() { super('Offline', '💾', 'offline'); }
      canHandle() { return offlineMode; }
      getPriority() { return 5; }
      async search(query, signal) {
        const kb = LocalKnowledgeBase;
        const found = kb.search(query);
        if (found) {
          return { found: true, html: found.html, sources: found.sources || [], note: found.note || 'Offline knowledge', raw: { query } };
        }
        return { found: false, html: '<p>I\'m currently offline and don\'t have information about that. Please try a rephrase or check your network connection.</p>', sources: [], note: 'Offline', raw: { query } };
      }
    }
    
    class DuckDuckGoSource extends DataSource {
      constructor() { super('DuckDuckGo', '🦆', 'ddg'); }
      buildDDGUrl(query){ const url = new URL('https://api.duckduckgo.com/'); url.searchParams.set('q', query); url.searchParams.set('format', 'json'); url.searchParams.set('no_html', '1'); url.searchParams.set('no_redirect', '1'); url.searchParams.set('skip_disambig', '1'); return url.toString(); }
      canHandle() { return true; }
      getPriority() { return 40; }
      async search(query, signal) {
        const targetUrl = this.buildDDGUrl(query);
        try {
          const data = await fetchWithCorsProxies(targetUrl, signal);
          const sources = [];
          if (Array.isArray(data.Results)) {
            data.Results.forEach(r => { if (r && r.FirstURL && r.Text) sources.push({ href: r.FirstURL, label: new URL(r.FirstURL).hostname.replace('www.','') }); });
          }
          if (data.AbstractURL) sources.push({ href: data.AbstractURL, label: new URL(data.AbstractURL).hostname.replace('www.','') });
          if (data.Answer && data.AnswerURL) sources.push({ href: data.AnswerURL, label: new URL(data.AnswerURL).hostname.replace('www.','') });
          
          let primary = ''; let note = '';
          
          if (data.Answer && data.Answer.trim()){ primary = data.Answer; note = 'Instant Answer'; }
          else if (data.Definition && data.Definition.trim()){ primary = data.Definition; note = data.DefinitionSource ? ('Definition • ' + data.DefinitionSource) : 'Definition'; if (data.DefinitionURL) sources.push({ href: data.DefinitionURL, label: new URL(data.DefinitionURL).hostname.replace('www.','') }); }
          else if (data.AbstractText && data.AbstractText.trim()){ primary = data.AbstractText; note = data.Heading ? ('About: ' + data.Heading) : (data.AbstractSource ? data.AbstractSource : 'Abstract'); }
          else if (data.RelatedTopics && data.RelatedTopics.length){
            const items = [];
            for (const t of data.RelatedTopics){
              if (t && t.Text && t.FirstURL) { items.push(`<li><a href="${t.FirstURL}" target="_blank" rel="noopener noreferrer">${escapeHTML(t.Text)}</a></li>`); }
              else if (Array.isArray(t.Topics)) {
                for (const tt of t.Topics){ if (tt && tt.Text && tt.FirstURL) { items.push(`<li><a href="${tt.FirstURL}" target="_blank" rel="noopener noreferrer">${escapeHTML(tt.Text)}</a></li>`); } }
              }
              if (items.length >= 6) break;
            }
            if (items.length){ primary = `<p>Here are some related topics I found:</p><ul>${items.join('')}</ul>`; note = 'Related topics'; }
          }
          
          if (!primary) { return { found: false, html: '<p>No direct answer from DuckDuckGo.</p>', sources, note: 'DuckDuckGo', raw: data }; }
          
          return { found: true, html: primary, sources, note, raw: data };
        } catch (err) { return { found: false, html: '<p>Failed to fetch from DuckDuckGo (possibly blocked by CORS). Try again or use a different query.</p>', sources: [], note: 'DuckDuckGo', raw: null }; }
      }
    }
    
    class WikipediaSource extends DataSource {
      constructor() { super('Wikipedia', '📚', 'wiki'); }
      canHandle() { return /\b(who is|who was|what is|what was|definition|define|history|historical|article)\b/i.test(lastQuery) || /\b[a-zA-Z]{3,}\b/.test(lastQuery); }
      getPriority() { return 35; }
      async search(query, signal) {
        try {
          const title = query.replace(/^(who is|who was|what is|what was|definition|define)\s+/i, '').trim();
          const searchUrl = `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(title)}`;
          const data = await fetchWithCorsProxies(searchUrl, signal);
          
          if (data.extract) {
            const sources = [];
            if (data.content_urls?.desktop?.page) { sources.push({ href: data.content_urls.desktop.page, label: 'Wikipedia Article', multi: true }); }
            
            let html = `<p>${escapeHTML(data.extract)}</p>`;
            if (data.extract_html) { html = data.extract_html; }
            if (data.thumbnail?.source) { html = `<img src="${data.thumbnail.source}" alt="${escapeHTML(data.title || 'Image')}" style="max-width: 200px; border-radius: 8px; margin-bottom: 10px;" /><br/>${html}`; }
            return { found: true, html, sources, note: data.title ? `Wikipedia: ${data.title}` : 'Wikipedia Article', raw: data };
          }
          return { found: false, html: '<p>No Wikipedia article found.</p>', sources: [], note: 'Wikipedia', raw: data };
        } catch (err) { return { found: false, html: '<p>Error fetching Wikipedia data.</p>', sources: [], note: 'Wikipedia', raw: null }; }
      }
    }
    
    class WeatherSource extends DataSource {
      constructor() { super('Weather', '🌤️', 'weather'); }
      canHandle() { return /\b(weather|temperature|forecast)\b/i.test(lastQuery); }
      getPriority() { return 30; }
      async search(query, signal) {
        const cityMatch = query.match(/\b(?:weather|temperature|forecast)\s+(?:in|at|for)?\s*([a-zA-Z\s,]+)/i);
        const city = cityMatch ? cityMatch[1].trim() : '';
        if (!city) { return { found: false, html: '<p>Please specify a city for weather information (e.g., "weather in Tokyo").</p>', sources: [], note: 'Weather', raw: null }; }
        
        try {
          const geoUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=1&language=en&format=json`;
          const geoData = await fetch(geoUrl, { signal }).then(r => r.json());
          if (!geoData.results || geoData.results.length === 0) { return { found: false, html: `<p>City "${city}" not found.</p>`, sources: [], note: 'Weather', raw: null }; }
          
          const { latitude, longitude, name, country_code, timezone } = geoData.results[0];
          const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current_weather=true&daily=temperature_2m_max,temperature_2m_min,precipitation_sum&timezone=${timezone}`;
          const weatherData = await fetch(weatherUrl, { signal }).then(r => r.json());
          
          if (weatherData.current_weather) {
            const current = weatherData.current_weather;
            const html = `
              <p><strong>Weather in ${name}, ${country_code}</strong></p>
              <ul>
                <li>Temperature: ${current.temperature}°C (${Math.round(current.temperature * 9/5 + 32)}°F)</li>
                <li>Wind Speed: ${current.windspeed} km/h</li>
                <li>Weather Code: ${current.weathercode}</li>
                <li>Time: ${current.time}</li>
              </ul>
              <p><em>Data provided by Open-Meteo</em></p>
            `;
            return { found: true, html, sources: [{ href: `https://open-meteo.com/`, label: 'Open-Meteo API' }], note: 'Weather Data', raw: weatherData };
          }
          return { found: false, html: '<p>Weather data not available.</p>', sources: [], note: 'Weather', raw: null };
        } catch (err) { return { found: false, html: '<p>Error fetching weather data.</p>', sources: [], note: 'Weather', raw: null }; }
      }
    }
    
    class CalculatorSource extends DataSource {
      constructor() { super('Calculator', '🧮', 'calc'); }
      canHandle() { return /[\d\+\-\*\/\^\(\)\.]/.test(lastQuery) && !/\b(what is|who|where|when|why|how)\b/i.test(lastQuery); }
      getPriority() { return 25; }
      async search(query, signal) {
        try {
          const clean = query.replace(/[^0-9+\-*/().\s]/g, '');
          if (!clean.trim()) { return { found: false, html: '<p>No calculation detected.</p>', sources: [], note: 'Calculator', raw: null }; }
          
          // Safe evaluation using Function constructor
          const result = Function(`"use strict"; return (${clean})`)();
          if (typeof result === 'number' && isFinite(result)) {
            const html = `<p><strong>Calculation:</strong> ${escapeHTML(clean)} = <strong>${result}</strong></p>`;
            return { found: true, html, sources: [], note: 'Calculator', raw: { expression: clean, result } };
          }
          return { found: false, html: '<p>Invalid expression.</p>', sources: [], note: 'Calculator', raw: null };
        } catch (err) { return { found: false, html: '<p>Calculation error.</p>', sources: [], note: 'Calculator', raw: null }; }
      }
    }
    
    // Local Knowledge Base
    const LocalKnowledgeBase = {
      data: [
        { query: 'hello|hi|hey|greetings', html: '<p>Hello! I\'m an AI assistant that can help you with facts, weather, calculations, and more. What would you like to know?</p>', note: 'Greeting' },
        { query: 'who are you|what are you|your name', html: '<p>I\'m an AI assistant with access to multiple data sources including DuckDuckGo, Wikipedia, weather APIs, and a built-in knowledge base for offline use.</p>', note: 'Identity' },
        { query: 'artificial intelligence|ai|machine learning', html: '<p>Artificial Intelligence (AI) is a branch of computer science focused on creating systems that can perform tasks typically requiring human intelligence, such as learning, reasoning, problem-solving, and understanding natural language.</p>', note: 'Definition' },
        { query: 'python programming', html: '<p>Python is a high-level, interpreted programming language known for its simple syntax and versatility. It\'s widely used in web development, data science, artificial intelligence, automation, and scientific computing.</p>', note: 'Programming' },
        { query: 'javascript', html: '<p>JavaScript is a programming language that runs in web browsers and is essential for creating interactive web pages. It can also be used on servers (Node.js) and for mobile app development.</p>', note: 'Programming' }
      ],
      search(query) {
        const lowerQuery = query.toLowerCase();
        return this.data.find(item => new RegExp(item.query, 'i').test(lowerQuery));
      }
    };
    
    // Initialize data sources
    const sources = [new OfflineSource(), new CalculatorSource(), new WeatherSource(), new WikipediaSource(), new DuckDuckGoSource()];
    
    // Search orchestrator
    async function searchMultipleSources(query, signal) {
      const availableSources = sources.filter(s => s.canHandle()).sort((a, b) => b.getPriority() - a.getPriority());
      
      for (const source of availableSources) {
        try {
          const result = await source.search(query, signal);
          if (result.found