File size: 27,952 Bytes
20605da
 
 
 
 
 
 
 
f73daf2
20605da
 
 
 
5a34c77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f73daf2
 
 
 
 
 
 
 
 
 
5a34c77
f73daf2
 
5a34c77
f73daf2
 
5a34c77
f73daf2
20605da
5a34c77
f73daf2
5a34c77
 
f73daf2
 
5a34c77
f73daf2
5a34c77
 
 
f73daf2
5a34c77
f73daf2
 
 
5a34c77
 
f73daf2
5a34c77
f73daf2
 
5a34c77
 
 
 
 
20605da
f73daf2
5a34c77
 
f73daf2
5a34c77
20605da
5a34c77
 
20605da
f73daf2
5a34c77
f73daf2
 
5a34c77
 
 
 
 
 
 
 
 
 
 
 
 
 
20605da
f73daf2
 
5a34c77
 
f73daf2
5a34c77
 
f73daf2
5a34c77
 
 
 
 
 
 
20605da
5a34c77
 
 
 
 
 
 
 
 
 
 
 
 
f73daf2
 
20605da
 
5a34c77
 
f73daf2
5a34c77
 
 
f73daf2
 
 
 
 
5a34c77
f73daf2
5a34c77
f73daf2
 
5a34c77
 
20605da
5a34c77
 
 
 
f73daf2
20605da
f73daf2
5a34c77
f73daf2
5a34c77
 
f73daf2
 
5a34c77
f73daf2
 
20605da
f73daf2
20605da
 
 
5a34c77
f73daf2
5a34c77
 
f73daf2
 
 
 
 
 
 
5a34c77
f73daf2
 
 
 
 
5a34c77
 
f73daf2
 
5a34c77
 
f73daf2
 
5a34c77
 
f73daf2
 
 
5a34c77
f73daf2
 
 
 
5a34c77
20605da
 
 
 
 
 
f73daf2
20605da
 
 
f73daf2
 
 
 
 
 
5a34c77
f73daf2
 
5a34c77
f73daf2
20605da
 
 
f73daf2
20605da
 
 
 
 
f73daf2
20605da
 
 
 
 
 
 
 
 
 
 
 
5a34c77
20605da
 
 
 
 
 
 
f73daf2
20605da
5a34c77
20605da
 
 
 
f73daf2
5a34c77
20605da
f73daf2
20605da
 
 
 
 
f73daf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20605da
 
 
 
5a34c77
20605da
f73daf2
 
20605da
f73daf2
 
 
 
 
 
 
20605da
f73daf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20605da
 
 
f73daf2
 
 
 
 
 
 
 
20605da
 
 
f73daf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20605da
f73daf2
 
20605da
 
 
 
f73daf2
5a34c77
f73daf2
 
 
5a34c77
 
f73daf2
 
5a34c77
f73daf2
20605da
f73daf2
5a34c77
 
 
 
 
 
 
 
 
 
 
 
 
f73daf2
 
 
 
 
 
20605da
 
f73daf2
 
 
20605da
 
f73daf2
 
 
 
 
20605da
 
f73daf2
 
 
 
 
 
20605da
f73daf2
20605da
f73daf2
 
 
a4b3957
 
f73daf2
20605da
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>QueryMind — Natural Language to SQL</title>
  <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=JetBrains+Mono:wght@400;600&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet" />
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

    :root {
      /* ── Core palette: slate/blue professional ── */
      --bg:          #0d1117;
      --surface:     #161b22;
      --card:        #1c2128;
      --card2:       #21262d;
      --border:      #30363d;
      --border2:     #3d444d;

      /* ── Accent: cool indigo-blue ── */
      --accent:      #58a6ff;
      --accent2:     #388bfd;
      --accent-dim:  rgba(88,166,255,0.08);
      --accent-glow: rgba(88,166,255,0.18);

      /* ── SQL syntax colors (VSCode Dark+ inspired) ── */
      --sql-keyword: #ff7b72;   /* red-orange — SELECT FROM WHERE */
      --sql-func:    #d2a8ff;   /* purple — COUNT AVG MAX */
      --sql-string:  #a5d6ff;   /* light blue — 'string values' */
      --sql-num:     #79c0ff;   /* blue — numbers */
      --sql-comment: #484f58;   /* grey — comments */
      --sql-op:      #ffa657;   /* orange — = < > operators */
      --sql-table:   #56d364;   /* green — table/column identifiers */
      --sql-default: #c9d1d9;   /* light grey — base text */

      /* ── Semantic ── */
      --danger:      #f85149;
      --success:     #3fb950;
      --warn:        #d29922;
      --text:        #e6edf3;
      --text2:       #8b949e;
      --muted:       #484f58;

      --mono:        'JetBrains Mono', monospace;
      --sans:        'Inter', sans-serif;
      --radius:      8px;
      --radius-lg:   14px;
      --sidebar-w:   280px;
      --header-h:    54px;
    }

    html, body { height: 100%; background: var(--bg); color: var(--text); font-family: var(--sans); font-size: 14px; line-height: 1.6; overflow-x: hidden; }

    /* ── Layout ── */
    #app { display: grid; grid-template-rows: var(--header-h) 1fr; grid-template-columns: var(--sidebar-w) 1fr; height: 100vh; }

    /* ── Header ── */
    header { grid-column: 1/-1; display: flex; align-items: center; gap: 12px; padding: 0 20px; background: var(--surface); border-bottom: 1px solid var(--border); z-index: 100; }
    .logo-wrap { display: flex; align-items: center; gap: 10px; }
    .logo-icon { width: 30px; height: 30px; background: linear-gradient(135deg, #388bfd, #58a6ff); border-radius: 7px; display: flex; align-items: center; justify-content: center; font-size: 15px; flex-shrink: 0; box-shadow: 0 0 12px rgba(88,166,255,0.3); }
    .logo-text { font-family: var(--mono); font-weight: 600; font-size: 14px; color: var(--text); letter-spacing: -0.2px; }
    .logo-text span { color: var(--accent); }
    #menu-btn { display: none; background: none; border: none; cursor: pointer; color: var(--text2); font-size: 20px; padding: 4px; margin-right: 4px; line-height: 1; }
    .header-right { margin-left: auto; display: flex; align-items: center; gap: 8px; }
    .clear-btn { background: none; border: 1px solid var(--border2); color: var(--text2); font-size: 10px; padding: 4px 10px; border-radius: 5px; cursor: pointer; font-family: var(--mono); letter-spacing: 0.8px; transition: all 0.15s; text-transform: uppercase; }
    .clear-btn:hover { border-color: var(--danger); color: var(--danger); background: rgba(248,81,73,0.06); }
    .status-wrap { display: flex; align-items: center; gap: 6px; }
    .status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); animation: blink 3s ease-in-out infinite; }
    .status-dot.ready { background: var(--success); animation: pulse-ok 2.5s ease-in-out infinite; }
    @keyframes blink { 0%,100%{opacity:.4} 50%{opacity:1} }
    @keyframes pulse-ok { 0%,100%{box-shadow:0 0 0 0 rgba(63,185,80,0.4)} 50%{box-shadow:0 0 0 5px transparent} }
    .badge { font-family: var(--mono); font-size: 10px; padding: 3px 8px; border-radius: 4px; border: 1px solid var(--border2); color: var(--text2); letter-spacing: 0.5px; }
    .badge.active { border-color: rgba(88,166,255,0.4); color: var(--accent); background: var(--accent-dim); }

    /* ── Sidebar ── */
    aside { background: var(--surface); border-right: 1px solid var(--border); display: flex; flex-direction: column; overflow: hidden; transition: transform 0.25s ease; }
    .aside-section { padding: 16px 14px 12px; border-bottom: 1px solid var(--border); }
    .section-label { font-family: var(--mono); font-size: 9px; letter-spacing: 1.5px; color: var(--muted); text-transform: uppercase; margin-bottom: 10px; }

    /* Upload */
    .upload-zone { border: 1.5px dashed var(--border2); border-radius: var(--radius); padding: 18px 12px; text-align: center; cursor: pointer; transition: all 0.2s; position: relative; background: var(--card); }
    .upload-zone:hover, .upload-zone.dragover { border-color: var(--accent); background: var(--accent-dim); box-shadow: 0 0 0 3px rgba(88,166,255,0.08); }
    .upload-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; }
    .upload-icon { font-size: 20px; margin-bottom: 6px; display: block; }
    .upload-zone p { font-size: 12px; color: var(--text2); line-height: 1.5; }
    .upload-zone p strong { color: var(--text); font-weight: 500; }

    /* File info */
    #file-info { display: none; background: var(--card); border: 1px solid var(--border2); border-radius: var(--radius); padding: 11px; font-size: 12px; margin-top: 10px; }
    #file-info.show { display: block; }
    .file-name { font-family: var(--mono); font-size: 10px; color: var(--accent); word-break: break-all; margin-bottom: 7px; font-weight: 600; }
    .file-info-row { display: flex; justify-content: space-between; color: var(--text2); margin-bottom: 3px; }
    .file-info-row span:first-child { color: var(--muted); }
    .schema-label { font-family: var(--mono); font-size: 9px; letter-spacing: 1px; color: var(--muted); text-transform: uppercase; margin-top: 9px; margin-bottom: 4px; }
    #schema-box { display: none; font-family: var(--mono); font-size: 10px; color: var(--text2); background: var(--bg); border: 1px solid var(--border); border-radius: 5px; padding: 8px; max-height: 100px; overflow-y: auto; white-space: pre-wrap; word-break: break-all; line-height: 1.7; }
    #schema-box.show { display: block; }

    /* Suggestions */
    .aside-section.suggestions { flex: 1; overflow-y: auto; }
    #suggestions-list { display: flex; flex-direction: column; gap: 5px; }
    .suggestion-chip { padding: 7px 10px; border-radius: 6px; border: 1px solid var(--border); background: transparent; font-size: 11px; color: var(--text2); cursor: pointer; transition: all 0.15s; text-align: left; font-family: var(--sans); line-height: 1.4; }
    .suggestion-chip:hover { border-color: var(--accent2); color: var(--text); background: var(--accent-dim); }

    /* ── Main ── */
    main { display: flex; flex-direction: column; overflow: hidden; background: var(--bg); }
    #chat { flex: 1; overflow-y: auto; padding: 20px 24px; display: flex; flex-direction: column; gap: 16px; scroll-behavior: smooth; }

    /* Empty state */
    #empty-state { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; color: var(--text2); text-align: center; padding: 40px 20px; }
    .empty-icon { font-size: 38px; animation: float 4s ease-in-out infinite; filter: drop-shadow(0 4px 12px rgba(88,166,255,0.2)); }
    @keyframes float { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-8px)} }
    #empty-state h2 { font-size: 15px; color: var(--text); font-weight: 500; }
    #empty-state p { font-size: 12px; max-width: 300px; line-height: 1.7; color: var(--text2); }

    /* ── Messages ── */
    .msg { display: flex; flex-direction: column; gap: 3px; max-width: 800px; width: 100%; }
    .msg.user { align-self: flex-end; align-items: flex-end; max-width: 75%; }
    .msg.assistant { align-self: flex-start; align-items: flex-start; }
    .msg-meta { font-size: 10px; color: var(--muted); font-family: var(--mono); padding: 0 4px; }
    .bubble { padding: 11px 15px; border-radius: var(--radius-lg); font-size: 13.5px; line-height: 1.65; }
    .msg.user .bubble { background: var(--accent2); color: #fff; border-bottom-right-radius: 4px; font-weight: 400; }
    .msg.assistant .bubble { background: var(--card); border: 1px solid var(--border); border-bottom-left-radius: 4px; color: var(--text); width: 100%; }

    /* ── SQL Block ── */
    .sql-block { background: #010409; border: 1px solid var(--border2); border-radius: var(--radius); margin-top: 10px; overflow: hidden; }
    .sql-block-header { display: flex; align-items: center; justify-content: space-between; padding: 7px 12px; background: var(--card2); border-bottom: 1px solid var(--border); }
    .sql-block-label { display: flex; align-items: center; gap: 6px; }
    .sql-dot { width: 8px; height: 8px; border-radius: 50%; }
    .sql-dot-r { background: #f85149; }
    .sql-dot-y { background: #d29922; }
    .sql-dot-g { background: #3fb950; }
    .sql-block-header span.sql-lang { font-family: var(--mono); font-size: 9px; letter-spacing: 1.5px; text-transform: uppercase; color: var(--text2); margin-left: 4px; }
    .copy-btn { background: none; border: 1px solid var(--border2); color: var(--text2); font-size: 10px; padding: 3px 8px; border-radius: 4px; cursor: pointer; font-family: var(--mono); transition: all 0.15s; }
    .copy-btn:hover { border-color: var(--accent); color: var(--accent); }

    /* SQL syntax highlighting */
    .sql-code { padding: 16px 18px; font-family: var(--mono); font-size: 12.5px; line-height: 2; color: var(--sql-default); white-space: pre-wrap; word-break: break-word; }
    .sql-code .kw  { color: var(--sql-keyword); font-weight: 600; }   /* SELECT FROM WHERE */
    .sql-code .fn  { color: var(--sql-func); }                          /* COUNT AVG */
    .sql-code .st  { color: var(--sql-string); }                        /* 'strings' */
    .sql-code .nm  { color: var(--sql-num); }                           /* numbers */
    .sql-code .cm  { color: var(--sql-comment); font-style: italic; }   /* -- comments */
    .sql-code .op  { color: var(--sql-op); }                            /* = < > */
    .sql-code .id  { color: var(--sql-table); }                         /* identifiers */

    /* ── Result Table ── */
    .result-table-wrap { margin-top: 10px; border: 1px solid var(--border); border-radius: var(--radius); overflow: auto; max-height: 280px; }
    table { width: 100%; border-collapse: collapse; font-size: 12px; }
    thead th { position: sticky; top: 0; background: var(--card2); padding: 8px 13px; text-align: left; font-family: var(--mono); font-size: 10px; color: var(--accent); letter-spacing: 0.8px; border-bottom: 1px solid var(--border2); white-space: nowrap; }
    tbody tr { border-bottom: 1px solid var(--border); transition: background 0.1s; }
    tbody tr:last-child { border-bottom: none; }
    tbody tr:hover { background: rgba(88,166,255,0.04); }
    td { padding: 7px 13px; color: var(--text2); white-space: nowrap; font-size: 12px; }
    .result-count { font-family: var(--mono); font-size: 10px; color: var(--muted); margin-top: 5px; padding-left: 2px; }

    /* Error */
    .error-bubble { background: rgba(248,81,73,0.06); border: 1px solid rgba(248,81,73,0.25); border-radius: var(--radius); padding: 10px 14px; font-size: 12px; color: #ffa198; margin-top: 8px; font-family: var(--mono); }

    /* Thinking */
    .thinking { display: flex; gap: 5px; align-items: center; padding: 12px 16px; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-lg); border-bottom-left-radius: 4px; }
    .thinking span { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); animation: think 1.2s ease-in-out infinite; }
    .thinking span:nth-child(2){animation-delay:.2s} .thinking span:nth-child(3){animation-delay:.4s}
    @keyframes think { 0%,60%,100%{transform:translateY(0);opacity:.3} 30%{transform:translateY(-6px);opacity:1} }

    /* ── Input Bar ── */
    .input-bar { padding: 12px 20px 14px; background: var(--surface); border-top: 1px solid var(--border); }
    .input-row { display: flex; gap: 9px; align-items: flex-end; }
    #question-input { flex: 1; background: var(--card); border: 1.5px solid var(--border2); border-radius: var(--radius); padding: 10px 13px; font-size: 14px; font-family: var(--sans); color: var(--text); resize: none; min-height: 44px; max-height: 120px; outline: none; transition: border-color 0.2s, box-shadow 0.2s; line-height: 1.5; }
    #question-input:focus { border-color: var(--accent2); box-shadow: 0 0 0 3px rgba(88,166,255,0.1); }
    #question-input::placeholder { color: var(--muted); }
    #question-input:disabled { opacity: 0.4; cursor: not-allowed; }
    #send-btn { background: var(--accent2); color: #fff; border: none; border-radius: var(--radius); width: 44px; height: 44px; cursor: pointer; font-size: 18px; display: flex; align-items: center; justify-content: center; transition: all 0.2s; flex-shrink: 0; font-weight: 700; }
    #send-btn:hover { background: var(--accent); box-shadow: 0 0 12px rgba(88,166,255,0.35); transform: scale(1.04); }
    #send-btn:disabled { opacity: 0.3; cursor: not-allowed; transform: none; box-shadow: none; }
    .input-hint { font-size: 11px; color: var(--muted); margin-top: 5px; padding-left: 2px; }

    /* Toast */
    #toast { position: fixed; bottom: 20px; right: 20px; background: var(--card2); border: 1px solid var(--border2); border-radius: var(--radius); padding: 9px 15px; font-size: 12px; font-family: var(--mono); color: var(--text); z-index: 9999; transform: translateY(50px); opacity: 0; transition: all 0.3s cubic-bezier(.34,1.56,.64,1); pointer-events: none; max-width: 280px; }
    #toast.show { transform: translateY(0); opacity: 1; }
    #toast.success { border-color: rgba(63,185,80,0.4); color: #56d364; }
    #toast.error { border-color: rgba(248,81,73,0.4); color: #ffa198; }

    /* Loading bar */
    #loading-bar { position: fixed; top: 0; left: 0; right: 0; height: 2px; background: linear-gradient(90deg, var(--accent2), var(--accent), #79c0ff); z-index: 10000; transform: scaleX(0); transform-origin: left; transition: transform 0.3s ease; }
    #loading-bar.active { transform: scaleX(0.8); }
    #loading-bar.done { transform: scaleX(1); opacity: 0; transition: opacity 0.4s 0.1s; }

    /* Scrollbar */
    ::-webkit-scrollbar { width: 5px; height: 5px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 10px; }
    ::-webkit-scrollbar-thumb:hover { background: var(--text2); }

    /* Mobile overlay */
    #overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.6); z-index: 90; backdrop-filter: blur(2px); }
    #overlay.show { display: block; }

    /* ── RESPONSIVE ── */
    @media (max-width: 900px) {
      :root { --sidebar-w: 240px; }
      #chat { padding: 14px 16px; }
      .input-bar { padding: 10px 16px 12px; }
      .msg.user { max-width: 85%; }
    }

    @media (max-width: 640px) {
      :root { --header-h: 50px; }
      #app { grid-template-columns: 1fr; }
      #menu-btn { display: flex; align-items: center; }
      aside { position: fixed; top: var(--header-h); left: 0; width: 80vw; max-width: 300px; height: calc(100vh - var(--header-h)); z-index: 95; transform: translateX(-100%); box-shadow: 6px 0 24px rgba(0,0,0,0.5); }
      aside.open { transform: translateX(0); }
      main { grid-column: 1; }
      .msg { max-width: 100%; }
      .msg.user { max-width: 88%; }
      #chat { padding: 12px; gap: 12px; }
      .bubble { padding: 10px 13px; font-size: 13px; }
      .sql-code { font-size: 11px; padding: 12px; line-height: 1.8; }
      td, thead th { padding: 6px 10px; font-size: 11px; }
      .input-bar { padding: 8px 12px 10px; }
      .input-hint { display: none; }
      .status-wrap .badge { display: none; }
      #toast { bottom: 12px; right: 12px; left: 12px; max-width: none; }
    }

    @media (max-width: 380px) {
      .logo-text { font-size: 13px; }
      .clear-btn { padding: 3px 7px; font-size: 9px; }
    }
  </style>
</head>
<body>
<div id="loading-bar"></div>
<div id="toast"></div>
<div id="overlay" onclick="closeSidebar()"></div>

<div id="app">
  <header>
    <button id="menu-btn" onclick="toggleSidebar()"></button>
    <div class="logo-wrap">
      <div class="logo-icon"></div>
      <div class="logo-text">Query<span>Mind</span></div>
    </div>
    <div class="header-right">
      <button class="clear-btn" onclick="clearChat()">Clear</button>
      <div class="status-wrap">
        <span id="status-dot" class="status-dot"></span>
        <span id="status-label" class="badge">Loading</span>
      </div>
    </div>
  </header>

  <aside id="sidebar">
    <div class="aside-section">
      <div class="section-label">Data Source</div>
      <div class="upload-zone" id="upload-zone">
        <input type="file" id="csv-input" accept=".csv" />
        <span class="upload-icon">📂</span>
        <p><strong>Drop CSV here</strong><br/>or click to browse</p>
      </div>
      <div id="file-info">
        <div class="file-name" id="file-name-display"></div>
        <div class="file-info-row"><span>Rows</span><span id="row-count"></span></div>
        <div class="file-info-row"><span>Columns</span><span id="col-count"></span></div>
        <div class="schema-label">Schema</div>
        <div id="schema-box"></div>
      </div>
    </div>
    <div class="aside-section suggestions">
      <div class="section-label">Example Queries</div>
      <div id="suggestions-list">
        <div class="suggestion-chip" style="cursor:default;font-style:italic;">Upload CSV to see examples</div>
      </div>
    </div>
  </aside>

  <main>
    <div id="chat">
      <div id="empty-state">
        <div class="empty-icon">🗂️</div>
        <h2>Ask anything about your data</h2>
        <p>Upload a CSV from the sidebar, then ask a question in plain English. QueryMind converts it to SQL and shows results instantly.</p>
      </div>
    </div>
    <div class="input-bar">
      <div class="input-row">
        <textarea id="question-input" placeholder="e.g. Show top 10 rows by sales…" rows="1" disabled></textarea>
        <button id="send-btn" disabled title="Send (Enter)"></button>
      </div>
      <div class="input-hint">Enter to send &nbsp;·&nbsp; Shift+Enter new line</div>
    </div>
  </main>
</div>

<script>
  let sessionId=null, isLoading=false, columns=[];

  const chat=document.getElementById('chat'), emptyState=document.getElementById('empty-state'),
    input=document.getElementById('question-input'), sendBtn=document.getElementById('send-btn'),
    csvInput=document.getElementById('csv-input'), uploadZone=document.getElementById('upload-zone'),
    fileInfo=document.getElementById('file-info'), fileNameDisp=document.getElementById('file-name-display'),
    rowCountEl=document.getElementById('row-count'), colCountEl=document.getElementById('col-count'),
    schemaBox=document.getElementById('schema-box'), suggList=document.getElementById('suggestions-list'),
    statusDot=document.getElementById('status-dot'), statusLabel=document.getElementById('status-label'),
    loadingBar=document.getElementById('loading-bar'), toast=document.getElementById('toast'),
    sidebar=document.getElementById('sidebar'), overlay=document.getElementById('overlay');

  function toggleSidebar(){ sidebar.classList.toggle('open'); overlay.classList.toggle('show'); }
  function closeSidebar(){ sidebar.classList.remove('open'); overlay.classList.remove('show'); }

  async function checkHealth(){
    try{
      const d=await(await fetch('/health')).json();
      if(d.status==='ok'){ statusDot.classList.add('ready'); statusLabel.textContent=d.model.split('/').pop().toUpperCase(); statusLabel.classList.add('active'); }
    }catch{ statusLabel.textContent='OFFLINE'; }
  }
  checkHealth();

  let toastTimer;
  function showToast(msg,type='success'){ toast.textContent=msg; toast.className=`show ${type}`; clearTimeout(toastTimer); toastTimer=setTimeout(()=>toast.className='',3200); }

  function startLoading(){ loadingBar.className='active'; isLoading=true; sendBtn.disabled=true; input.disabled=true; }
  function stopLoading(){ loadingBar.className='done'; isLoading=false; if(sessionId){sendBtn.disabled=false;input.disabled=false;} setTimeout(()=>loadingBar.className='',600); }

  uploadZone.addEventListener('dragover',e=>{e.preventDefault();uploadZone.classList.add('dragover');});
  uploadZone.addEventListener('dragleave',()=>uploadZone.classList.remove('dragover'));
  uploadZone.addEventListener('drop',e=>{e.preventDefault();uploadZone.classList.remove('dragover');const f=e.dataTransfer.files[0];if(f)handleUpload(f);});
  csvInput.addEventListener('change',e=>{if(e.target.files[0])handleUpload(e.target.files[0]);});

  async function handleUpload(file){
    if(!file.name.endsWith('.csv')){showToast('Only .csv files accepted','error');return;}
    startLoading();
    const fd=new FormData(); fd.append('file',file);
    try{
      const r=await fetch('/upload',{method:'POST',body:fd});
      const d=await r.json();
      if(!r.ok)throw new Error(d.detail||'Upload failed');
      sessionId=d.session_id; columns=d.columns;
      fileNameDisp.textContent=file.name;
      rowCountEl.textContent=d.row_count.toLocaleString();
      colCountEl.textContent=d.columns.length;
      schemaBox.textContent=d.schema;
      schemaBox.classList.add('show'); fileInfo.classList.add('show');
      buildSuggestions(d.columns,d.table_name);
      showToast(`✓ Loaded ${d.row_count.toLocaleString()} rows`,'success');
      emptyState.style.display='none'; closeSidebar();
      addMsg('assistant',`<strong>File loaded:</strong> <code>${file.name}</code><br/>Table <code>${d.table_name}</code> · ${d.row_count.toLocaleString()} rows · ${d.columns.length} columns.<br/><br/>Columns: <code>${d.columns.join(', ')}</code><br/><br/>Ask me anything about this data in plain English.`);
    }catch(e){showToast(e.message,'error');}
    stopLoading();
  }

  function buildSuggestions(cols,table){
    const numCol=cols.find(c=>/num|price|val|amt|count|qty|sal|rev|cost/i.test(c))||cols[1]||cols[0];
    const qs=[`Show the first 10 rows`,`Count total number of records`,`How many unique values in ${cols[0]}?`,`What is the average of ${numCol}?`,`Show rows where ${cols[0]} is not null`,`Group by ${cols[0]} and count records`];
    suggList.innerHTML='';
    qs.forEach(q=>{
      const btn=document.createElement('button'); btn.className='suggestion-chip'; btn.textContent=q;
      btn.onclick=()=>{input.value=q;input.focus();closeSidebar();sendQuery();};
      suggList.appendChild(btn);
    });
  }

  input.addEventListener('input',()=>{input.style.height='auto';input.style.height=Math.min(input.scrollHeight,120)+'px';});
  input.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();if(!isLoading&&sessionId&&input.value.trim())sendQuery();}});
  sendBtn.addEventListener('click',()=>{if(!isLoading&&sessionId&&input.value.trim())sendQuery();});

  async function sendQuery(){
    const question=input.value.trim(); if(!question||!sessionId)return;
    addMsg('user',escapeHtml(question));
    input.value=''; input.style.height='auto';
    startLoading(); const thinkId=addThinking();
    try{
      const r=await fetch('/query',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sessionId,question})});
      const d=await r.json(); removeThinking(thinkId);
      if(!r.ok)throw new Error(d.detail||'Query failed');
      addMsg('assistant',buildResultHtml(d.sql,d.results));
    }catch(e){
      removeThinking(thinkId);
      addMsg('assistant',`<div class="error-bubble">⚠ ${escapeHtml(e.message)}</div>`);
      showToast(e.message,'error');
    }
    stopLoading();
  }

  function highlightSQL(raw){
    const kw=/\b(SELECT|FROM|WHERE|AND|OR|NOT|IN|IS|NULL|LIKE|BETWEEN|ORDER\s+BY|GROUP\s+BY|HAVING|LIMIT|OFFSET|DISTINCT|AS|JOIN|LEFT|RIGHT|INNER|OUTER|ON|UNION|ALL|INSERT|UPDATE|DELETE|CREATE|TABLE|DROP|ALTER|WITH|CASE|WHEN|THEN|ELSE|END|EXISTS|BY|ASC|DESC|INTO|VALUES|SET)\b/gi;
    const fn=/\b(COUNT|SUM|AVG|MAX|MIN|COALESCE|NULLIF|IFNULL|ROUND|FLOOR|CEIL|ABS|LENGTH|UPPER|LOWER|TRIM|SUBSTR|REPLACE|CAST|DATE|DATETIME|NOW|RANDOM|IIF|GROUP_CONCAT)\b/gi;
    return escapeHtml(raw)
      .replace(/(--[^\n]*)/g,m=>`<span class="cm">${m}</span>`)
      .replace(/('(?:[^'\\]|\\.)*')/g,m=>`<span class="st">${m}</span>`)
      .replace(/\b(\d+(?:\.\d+)?)\b/g,m=>`<span class="nm">${m}</span>`)
      .replace(kw,m=>`<span class="kw">${m}</span>`)
      .replace(fn,m=>`<span class="fn">${m}</span>`)
      .replace(/(?<![<\w])([=<>!]+|[+\-*\/])(?![\w>])/g,m=>`<span class="op">${m}</span>`);
  }

  function buildResultHtml(sql,results){
    let html=`
      <div class="sql-block">
        <div class="sql-block-header">
          <div class="sql-block-label">
            <span class="sql-dot sql-dot-r"></span>
            <span class="sql-dot sql-dot-y"></span>
            <span class="sql-dot sql-dot-g"></span>
            <span class="sql-lang">SQL</span>
          </div>
          <button class="copy-btn" onclick="copySql(this)">Copy</button>
        </div>
        <div class="sql-code">${highlightSQL(sql)}</div>
      </div>`;
    if(!results||results.length===0) return html+`<div style="margin-top:9px;font-size:12px;color:var(--muted);">No rows returned.</div>`;
    const cols=Object.keys(results[0]);
    let tbl=`<div class="result-table-wrap"><table><thead><tr>${cols.map(c=>`<th>${escapeHtml(c)}</th>`).join('')}</tr></thead><tbody>`;
    results.forEach(row=>{tbl+=`<tr>${cols.map(c=>`<td>${row[c]===null?`<span style="color:var(--muted)">null</span>`:escapeHtml(String(row[c]))}</td>`).join('')}</tr>`;});
    tbl+=`</tbody></table></div><div class="result-count">${results.length.toLocaleString()} row${results.length!==1?'s':''} returned</div>`;
    return html+tbl;
  }

  window.copySql=function(btn){
    const code=btn.closest('.sql-block').querySelector('.sql-code').textContent;
    navigator.clipboard.writeText(code).then(()=>{btn.textContent='Copied!';setTimeout(()=>btn.textContent='Copy',1600);});
  };

  function addMsg(role,html){
    const now=new Date().toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
    const div=document.createElement('div'); div.className=`msg ${role}`;
    div.innerHTML=`<div class="msg-meta">${role==='user'?'You':'QueryMind'} · ${now}</div><div class="bubble">${html}</div>`;
    chat.appendChild(div); chat.scrollTop=chat.scrollHeight; return div;
  }

  let tc=0;
  function addThinking(){
    const id='think-'+(++tc), div=document.createElement('div');
    div.id=id; div.className='msg assistant';
    div.innerHTML=`<div class="msg-meta">QueryMind</div><div class="thinking"><span></span><span></span><span></span></div>`;
    chat.appendChild(div); chat.scrollTop=chat.scrollHeight; return id;
  }
  function removeThinking(id){const el=document.getElementById(id);if(el)el.remove();}

  function clearChat(){
    chat.innerHTML=''; emptyState.style.display='';
    chat.appendChild(emptyState); showToast('Chat cleared','success');
  }

  function escapeHtml(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
</script>
</body>
</html>