File size: 45,705 Bytes
86a8165
 
 
 
 
 
 
 
 
 
df128e1
 
 
 
 
 
 
86a8165
 
df128e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
 
 
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
 
86a8165
 
 
 
 
 
df128e1
 
 
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
 
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
df128e1
 
86a8165
 
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
 
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
 
 
86a8165
 
 
 
df128e1
 
 
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
df128e1
 
 
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86a8165
 
 
 
 
 
 
 
df128e1
86a8165
 
 
 
df128e1
 
 
 
 
 
 
86a8165
 
df128e1
 
86a8165
df128e1
 
86a8165
 
 
 
 
df128e1
 
86a8165
df128e1
86a8165
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
 
 
 
86a8165
 
 
 
 
 
df128e1
 
 
 
 
86a8165
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df128e1
86a8165
 
 
df128e1
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
/* ═══════════════════════════════════════════════════════════
   λ…Έμ½”λ”© Python+  β€”  Frontend Application Logic
   ═══════════════════════════════════════════════════════════ */

'use strict';

// ──────────────────────────────────────────────────────────────
// State
// ──────────────────────────────────────────────────────────────
const state = {
  currentStep:  1,
  sessionId:    null,
  fileName:     null,
  dfInfo:       null,       // 컬럼 정보 μ €μž₯
  currentJobId: null,
  pendingJobId: null,
  completedJobs: [],
};

let analysisMode = 'structured'; // 'structured' | 'free'

// ──────────────────────────────────────────────────────────────
// 뢄석 μœ ν˜• μ„€μ • (μ‚¬νšŒκ³Όν•™ 연ꡬ μ „μš©)
// ──────────────────────────────────────────────────────────────
const ANALYSIS_TYPES = [
  {
    id: 'descriptive',
    label: 'πŸ“Š κΈ°μˆ ν†΅κ³„',
    desc: 'ν‰κ· Β·ν‘œμ€€νŽΈμ°¨Β·λΆ„ν¬ μš”μ•½',
    vars: [
      { key: 'targets', label: '뢄석할 μˆ˜μΉ˜ν˜• λ³€μˆ˜', type: 'numeric', multi: true }
    ],
    build(v) {
      return `λ‹€μŒ μˆ˜μΉ˜ν˜• λ³€μˆ˜λ“€μ˜ κΈ°μˆ ν†΅κ³„λ₯Ό λΆ„μ„ν•΄μ£Όμ„Έμš”: ${v.targets.join(', ')}. 평균, ν‘œμ€€νŽΈμ°¨, μ΅œμ†Ÿκ°’, μ΅œλŒ“κ°’, 쀑앙값, μ™œλ„, 첨도λ₯Ό ν¬ν•¨ν•œ ν‘œμ™€ νžˆμŠ€ν† κ·Έλž¨, λ°•μŠ€ν”Œλ‘―μ„ κ·Έλ €μ£Όμ„Έμš”.`;
    }
  },
  {
    id: 'ttest',
    label: 'πŸ“ˆ λ…λ¦½ν‘œλ³Έ t-κ²€μ •',
    desc: '두 μ§‘λ‹¨μ˜ 평균 비ꡐ',
    vars: [
      { key: 'group',  label: '집단 λ³€μˆ˜ (λ²”μ£Όν˜•)', type: 'categorical', multi: false },
      { key: 'target', label: '쒅속 λ³€μˆ˜ (μˆ˜μΉ˜ν˜•)', type: 'numeric',    multi: false }
    ],
    build(v) {
      return `${v.group} λ³€μˆ˜λ₯Ό κΈ°μ€€μœΌλ‘œ 두 μ§‘λ‹¨μ˜ ${v.target} 평균 차이λ₯Ό λ…λ¦½ν‘œλ³Έ t-κ²€μ •μœΌλ‘œ λΆ„μ„ν•΄μ£Όμ„Έμš”. 각 μ§‘λ‹¨μ˜ κΈ°μˆ ν†΅κ³„, Levene λ“±λΆ„μ‚° κ²€μ •, tν†΅κ³„λŸ‰, pκ°’, Cohen's d 효과크기λ₯Ό ν¬ν•¨ν•˜κ³  집단별 λ°•μŠ€ν”Œλ‘―μ„ κ·Έλ €μ£Όμ„Έμš”.`;
    }
  },
  {
    id: 'paired_ttest',
    label: 'πŸ”„ λŒ€μ‘ν‘œλ³Έ t-κ²€μ •',
    desc: '사전-사후 평균 비ꡐ',
    vars: [
      { key: 'pre',  label: '사전 λ³€μˆ˜ (μˆ˜μΉ˜ν˜•)', type: 'numeric', multi: false },
      { key: 'post', label: '사후 λ³€μˆ˜ (μˆ˜μΉ˜ν˜•)', type: 'numeric', multi: false }
    ],
    build(v) {
      return `${v.pre}(사전)κ³Ό ${v.post}(사후)의 평균 차이λ₯Ό λŒ€μ‘ν‘œλ³Έ t-κ²€μ •μœΌλ‘œ λΆ„μ„ν•΄μ£Όμ„Έμš”. κΈ°μˆ ν†΅κ³„, tν†΅κ³„λŸ‰, pκ°’, Cohen's d 효과크기λ₯Ό ν¬ν•¨ν•˜κ³  사전-사후 λ³€ν™” μ‹œκ°ν™”λ₯Ό κ·Έλ €μ£Όμ„Έμš”.`;
    }
  },
  {
    id: 'anova',
    label: 'πŸ“‰ μΌμ›λ°°μΉ˜ ANOVA',
    desc: 'μ„Έ 집단 μ΄μƒμ˜ 평균 비ꡐ',
    vars: [
      { key: 'group',  label: '집단 λ³€μˆ˜ (λ²”μ£Όν˜•)', type: 'categorical', multi: false },
      { key: 'target', label: '쒅속 λ³€μˆ˜ (μˆ˜μΉ˜ν˜•)', type: 'numeric',    multi: false }
    ],
    build(v) {
      return `${v.group} λ³€μˆ˜λ₯Ό κΈ°μ€€μœΌλ‘œ ${v.target}의 집단 κ°„ 평균 차이λ₯Ό μΌμ›λ°°μΉ˜ ANOVA둜 λΆ„μ„ν•΄μ£Όμ„Έμš”. Fν†΅κ³„λŸ‰, pκ°’, 사후검정(Tukey HSD), 효과크기(Ξ·Β²)λ₯Ό ν¬ν•¨ν•˜κ³  집단별 λ°•μŠ€ν”Œλ‘―μ„ κ·Έλ €μ£Όμ„Έμš”.`;
    }
  },
  {
    id: 'correlation',
    label: 'πŸ”— 상관뢄석',
    desc: 'λ³€μˆ˜ κ°„ Pearson 상관관계',
    vars: [
      { key: 'targets', label: '뢄석할 μˆ˜μΉ˜ν˜• λ³€μˆ˜λ“€', type: 'numeric', multi: true }
    ],
    build(v) {
      return `λ‹€μŒ λ³€μˆ˜λ“€ κ°„μ˜ Pearson 상관뢄석을 μ‹€μ‹œν•΄μ£Όμ„Έμš”: ${v.targets.join(', ')}. μƒκ΄€κ³„μˆ˜ ν–‰λ ¬ν‘œ(rκ°’, pκ°’ 포함)와 상관행렬 νžˆνŠΈλ§΅μ„ μ œκ³΅ν•΄μ£Όμ„Έμš”.`;
    }
  },
  {
    id: 'regression',
    label: 'πŸ“ νšŒκ·€λΆ„μ„',
    desc: '쒅속~독립 λ³€μˆ˜ 예츑 관계',
    vars: [
      { key: 'dependent',    label: '쒅속 λ³€μˆ˜ (μˆ˜μΉ˜ν˜•)',         type: 'numeric', multi: false },
      { key: 'independents', label: '독립 λ³€μˆ˜λ“€ (μˆ˜μΉ˜ν˜•, 닀쀑)', type: 'numeric', multi: true  }
    ],
    build(v) {
      return `${v.dependent}λ₯Ό μ’…μ†λ³€μˆ˜λ‘œ, ${v.independents.join(', ')}λ₯Ό λ…λ¦½λ³€μˆ˜λ‘œ ν•˜λŠ” λ‹€μ€‘νšŒκ·€λΆ„μ„μ„ μ‹€μ‹œν•΄μ£Όμ„Έμš”. RΒ², μˆ˜μ • RΒ², Fν†΅κ³„λŸ‰, pκ°’, 각 λ…λ¦½λ³€μˆ˜μ˜ λΉ„ν‘œμ€€ν™” κ³„μˆ˜(B), ν‘œμ€€ν™” κ³„μˆ˜(Ξ²), tκ°’, p값을 ν¬ν•¨ν•΄μ£Όμ„Έμš”.`;
    }
  },
  {
    id: 'frequency',
    label: 'πŸ“‹ λΉˆλ„λΆ„μ„',
    desc: 'λ²”μ£Όν˜• λ³€μˆ˜ 뢄포',
    vars: [
      { key: 'target', label: '뢄석할 λ²”μ£Όν˜• λ³€μˆ˜', type: 'categorical', multi: false }
    ],
    build(v) {
      return `${v.target} λ³€μˆ˜μ˜ λΉˆλ„λΆ„μ„μ„ μ‹€μ‹œν•΄μ£Όμ„Έμš”. λΉˆλ„ν‘œ(λΉˆλ„, λ°±λΆ„μœ¨, λˆ„μ λ°±λΆ„μœ¨)와 λ§‰λŒ€κ·Έλž˜ν”„λ₯Ό μ œκ³΅ν•΄μ£Όμ„Έμš”.`;
    }
  },
  {
    id: 'crosstab',
    label: 'πŸ“Š ꡐ차뢄석 (χ²)',
    desc: '두 λ²”μ£Όν˜• λ³€μˆ˜μ˜ 관계',
    vars: [
      { key: 'var1', label: 'λ³€μˆ˜ 1 (λ²”μ£Όν˜•)', type: 'categorical', multi: false },
      { key: 'var2', label: 'λ³€μˆ˜ 2 (λ²”μ£Όν˜•)', type: 'categorical', multi: false }
    ],
    build(v) {
      return `${v.var1}κ³Ό ${v.var2}의 ꡐ차뢄석을 μ‹€μ‹œν•΄μ£Όμ„Έμš”. κ΅μ°¨ν‘œ, 카이제곱 ν†΅κ³„λŸ‰, pκ°’, CramΓ©r's V 효과크기λ₯Ό ν¬ν•¨ν•˜κ³  λˆ„μ  λ§‰λŒ€κ·Έλž˜ν”„λ₯Ό κ·Έλ €μ£Όμ„Έμš”.`;
    }
  },
  {
    id: 'reliability',
    label: 'πŸ” 신뒰도 뢄석 (Cronbach Ξ±)',
    desc: '척도 λ¬Έν•­μ˜ 내적 일관성',
    vars: [
      { key: 'items', label: '척도 λ¬Έν•­λ“€ (μˆ˜μΉ˜ν˜•, 닀쀑선택)', type: 'numeric', multi: true }
    ],
    build(v) {
      return `λ‹€μŒ λ¬Έν•­λ“€λ‘œ κ΅¬μ„±λœ μ²™λ„μ˜ 신뒰도 뢄석(Cronbach Ξ±)을 μ‹€μ‹œν•΄μ£Όμ„Έμš”: ${v.items.join(', ')}. 전체 Cronbach Ξ±κ°’, 각 λ¬Έν•­ 제거 μ‹œ Ξ±κ°’ λ³€ν™”, λ¬Έν•­-전체 μƒκ΄€κ³„μˆ˜λ₯Ό ν¬ν•¨ν•œ κ²°κ³Όν‘œλ₯Ό μ œκ³΅ν•΄μ£Όμ„Έμš”.`;
    }
  }
];

// ──────────────────────────────────────────────────────────────
// Init
// ──────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  checkApiHealth();
  restoreSession();
  setupDropZone();
  setupQueryInput();
});

// ──────────────────────────────────────────────────────────────
// API health check
// ──────────────────────────────────────────────────────────────
async function checkApiHealth() {
  try {
    const res  = await fetch('/api/health');
    const data = await res.json();
    const dot  = document.getElementById('apiDot');
    const txt  = document.getElementById('apiStatusText');
    if (data.api_key_configured) {
      dot.className = 'dot';
      txt.textContent = 'Claude API 연결됨';
    } else {
      dot.className = 'dot error';
      txt.textContent = 'API ν‚€ λ―Έμ„€μ •';
      showToast('⚠️ ANTHROPIC_API_KEYκ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. .env νŒŒμΌμ„ ν™•μΈν•˜μ„Έμš”.', 6000);
    }
  } catch {
    document.getElementById('apiDot').className = 'dot error';
    document.getElementById('apiStatusText').textContent = 'μ„œλ²„ μ—°κ²° μ‹€νŒ¨';
  }
}

// ──────────────────────────────────────────────────────────────
// Session persistence
// ──────────────────────────────────────────────────────────────
function saveSession() {
  try {
    localStorage.setItem('ncp_session', JSON.stringify({
      sessionId:     state.sessionId,
      fileName:      state.fileName,
      currentStep:   state.currentStep,
      completedJobs: state.completedJobs,
    }));
  } catch {}
}

async function restoreSession() {
  try {
    const raw = localStorage.getItem('ncp_session');
    if (!raw) return;
    const saved = JSON.parse(raw);
    if (!saved.sessionId) return;

    const res = await fetch(`/api/session/${saved.sessionId}`);
    if (!res.ok) { localStorage.removeItem('ncp_session'); return; }

    state.sessionId    = saved.sessionId;
    state.fileName     = saved.fileName;
    state.completedJobs = saved.completedJobs || [];

    showFileMeta(saved.fileName, null);
    document.getElementById('btnToPreview').disabled = false;

    const step = Math.min(saved.currentStep || 1, 4);
    if (step >= 3) await loadPreview();
    if (step >= 4) rebuildChatHistory();
    goToStep(step, true);
  } catch {
    localStorage.removeItem('ncp_session');
  }
}

// ──────────────────────────────────────────────────────────────
// Step navigation
// ──────────────────────────────────────────────────────────────
function goToStep(step, skipSave = false) {
  document.querySelectorAll('.content-section').forEach(s => s.classList.remove('active'));
  document.getElementById(`section-${step}`).classList.add('active');

  document.querySelectorAll('.step-item').forEach(el => {
    const n = parseInt(el.dataset.step);
    el.classList.remove('active', 'done', 'clickable');
    if (n < step)  { el.classList.add('done', 'clickable'); el.onclick = () => goToStep(n); }
    if (n === step) el.classList.add('active');
  });

  state.currentStep = step;
  if (!skipSave) saveSession();

  if (step === 3 && state.sessionId) loadPreview();
  if (step === 4) {
    document.getElementById('chatFileName').textContent = state.fileName ? `β€” ${state.fileName}` : '';
    // ꡬ쑰화 뢄석 νŒ¨λ„ λ Œλ”λ§
    setTimeout(() => renderStructuredPanel(), 50);
  }
  if (step === 5) renderDownloadSection();
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

// ──────────────────────────────────────────────────────────────
// File upload β€” drag & drop setup
// ──────────────────────────────────────────────────────────────
function setupDropZone() {
  const zone  = document.getElementById('dropZone');
  const input = document.getElementById('fileInput');

  input.addEventListener('change', () => {
    if (input.files[0]) handleUpload(input.files[0]);
  });

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

async function handleUpload(file) {
  const ext = file.name.split('.').pop().toLowerCase();
  if (!['xlsx', 'xls', 'csv'].includes(ext)) {
    showAlert('alertUpload', 'error', `μ§€μ›ν•˜μ§€ μ•ŠλŠ” 파일 ν˜•μ‹μž…λ‹ˆλ‹€ (.${ext}). xlsx, xls, csv 파일만 κ°€λŠ₯ν•©λ‹ˆλ‹€.`);
    return;
  }
  if (file.size > 50 * 1024 * 1024) {
    showAlert('alertUpload', 'error', `파일 크기가 λ„ˆλ¬΄ ν½λ‹ˆλ‹€ (${(file.size/1024/1024).toFixed(1)} MB). μ΅œλŒ€ 50 MBμž…λ‹ˆλ‹€.`);
    return;
  }

  clearAlert('alertUpload');
  document.getElementById('uploadingIndicator').classList.remove('hidden');
  document.getElementById('fileMeta').classList.add('hidden');
  document.getElementById('btnToPreview').disabled = true;

  const form = new FormData();
  form.append('file', file);

  try {
    const res  = await fetch('/api/upload', { method: 'POST', body: form });
    const data = await res.json();

    if (!res.ok) {
      showAlert('alertUpload', 'error', data.detail || 'μ—…λ‘œλ“œ μ‹€νŒ¨');
      return;
    }

    state.sessionId     = data.session_id;
    state.fileName      = data.file_name;
    state.completedJobs = [];
    saveSession();

    showFileMeta(data.file_name, `${data.rows.toLocaleString()}ν–‰ Γ— ${data.cols}μ—΄  Β·  ${data.size_mb} MB`);
    document.getElementById('btnToPreview').disabled = false;
    showToast(`βœ… "${data.file_name}" μ—…λ‘œλ“œ μ™„λ£Œ!`);

  } catch {
    showAlert('alertUpload', 'error', 'μ„œλ²„μ™€ 톡신 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄μ£Όμ„Έμš”.');
  } finally {
    document.getElementById('uploadingIndicator').classList.add('hidden');
  }
}

function showFileMeta(name, stats) {
  const icons = { xlsx: 'πŸ“Š', xls: 'πŸ“Š', csv: 'πŸ“‹' };
  const ext = (name || '').split('.').pop().toLowerCase();
  document.getElementById('fileIconSpan').textContent  = icons[ext] || 'πŸ“„';
  document.getElementById('uploadedFileName').textContent = name || 'β€”';
  document.getElementById('uploadedFileStats').textContent = stats || '';
  document.getElementById('fileMeta').classList.remove('hidden');
}

// ──────────────────────────────────────────────────────────────
// Sample data
// ──────────────────────────────────────────────────────────────
async function loadSampleData() {
  const btn = document.getElementById('btnSample');
  btn.disabled = true;
  btn.textContent = '⏳ λ‘œλ”© 쀑…';

  try {
    const res  = await fetch('/api/sample/load');
    const data = await res.json();
    if (!res.ok) { showToast('μƒ˜ν”Œ 데이터 λ‘œλ“œ μ‹€νŒ¨: ' + (data.detail || '')); return; }

    state.sessionId     = data.session_id;
    state.fileName      = data.file_name;
    state.completedJobs = [];
    saveSession();

    showFileMeta(data.file_name, `${data.rows.toLocaleString()}ν–‰ Γ— ${data.cols}μ—΄  Β·  μƒ˜ν”Œ 데이터`);
    document.getElementById('btnToPreview').disabled = false;
    showToast('βœ… μƒ˜ν”Œ 데이터 λ‘œλ“œ μ™„λ£Œ! 미리보기둜 μ΄λ™ν•©λ‹ˆλ‹€.');
    goToStep(3);
  } catch {
    showToast('μƒ˜ν”Œ 데이터 λ‘œλ“œ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.');
  } finally {
    btn.disabled = false;
    btn.textContent = '✨ μƒ˜ν”Œ λ°μ΄ν„°λ‘œ μ²΄ν—˜ν•˜κΈ°';
  }
}

// ──────────────────────────────────────────────────────────────
// Data preview
// ──────────────────────────────────────────────────────────────
async function loadPreview() {
  if (!state.sessionId) return;
  try {
    const res  = await fetch(`/api/preview/${state.sessionId}`);
    const data = await res.json();
    if (!res.ok) return;

    state.dfInfo = data.df_info;   // ← 컬럼 정보 μ €μž₯

    renderMetaGrid(data.df_info);
    renderColBadges(data.df_info);
    renderColAccordion(data.df_info);
    renderPreviewTable(data.df_info, data.preview);

    // 이미 뢄석 단계에 μžˆλ‹€λ©΄ νŒ¨λ„ κ°±μ‹ 
    if (state.currentStep === 4) renderStructuredPanel();
  } catch {}
}

function renderMetaGrid(info) {
  const [rows, cols] = info.shape;
  const numCols  = info.columns.filter(c => c.type === 'μˆ˜μΉ˜ν˜•').length;
  const catCols  = info.columns.filter(c => c.type === 'λ²”μ£Όν˜•').length;

  document.getElementById('metaGrid').innerHTML = `
    <div class="meta-item"><div class="num">${rows.toLocaleString()}</div><div class="label">전체 ν–‰ 수</div></div>
    <div class="meta-item"><div class="num">${cols}</div><div class="label">전체 μ—΄ 수</div></div>
    <div class="meta-item"><div class="num">${numCols}</div><div class="label">μˆ˜μΉ˜ν˜• λ³€μˆ˜</div></div>
    <div class="meta-item"><div class="num">${catCols}</div><div class="label">λ²”μ£Όν˜• λ³€μˆ˜</div></div>
    <div class="meta-item"><div class="num">${info.missing_cols}</div><div class="label">결츑치 포함 μ—΄</div></div>
  `;
}

function renderColBadges(info) {
  const counts = { μˆ˜μΉ˜ν˜•: 0, λ²”μ£Όν˜•: 0, λ¬Έμžν˜•: 0, λ‚ μ§œν˜•: 0 };
  info.columns.forEach(c => { if (counts[c.type] !== undefined) counts[c.type]++; });
  const map    = { μˆ˜μΉ˜ν˜•: 'num', λ²”μ£Όν˜•: 'cat', λ¬Έμžν˜•: 'text', λ‚ μ§œν˜•: 'date' };
  const labels = { μˆ˜μΉ˜ν˜•: 'μˆ˜μΉ˜ν˜•', λ²”μ£Όν˜•: 'λ²”μ£Όν˜•', λ¬Έμžν˜•: 'λ¬Έμžν˜•', λ‚ μ§œν˜•: 'λ‚ μ§œν˜•' };
  let html = '';
  for (const [k, v] of Object.entries(counts)) {
    if (v > 0) html += `<span class="badge badge-${map[k]}">${labels[k]} ${v}개</span>`;
  }
  if (info.missing_cols > 0)
    html += `<span class="badge badge-miss">결츑치 포함 ${info.missing_cols}μ—΄</span>`;
  document.getElementById('colBadges').innerHTML = html;
}

function renderColAccordion(info) {
  const badgeClass = { μˆ˜μΉ˜ν˜•: 'badge-num', λ²”μ£Όν˜•: 'badge-cat', λ¬Έμžν˜•: 'badge-text', λ‚ μ§œν˜•: 'badge-date' };
  const rows = info.columns.map(c => {
    const bc = badgeClass[c.type] || 'badge-text';
    const missStr   = c.missing > 0
      ? `<span class="badge badge-miss" style="font-size:.7rem">결츑 ${c.missing}개 (${c.missing_pct}%)</span>`
      : '';
    const sampleStr = c.sample.slice(0, 5)
      .map(s => `<code style="background:#f1f5f9;padding:1px 5px;border-radius:3px;font-size:.75rem">${escHtml(String(s))}</code>`)
      .join(' ');
    return `<tr>
      <td style="font-weight:700;white-space:nowrap">${escHtml(c.name)}</td>
      <td><span class="badge ${bc}">${c.type}</span></td>
      <td>${c.unique.toLocaleString()}</td>
      <td>${missStr || 'β€”'}</td>
      <td style="max-width:240px;overflow:hidden">${sampleStr}</td>
    </tr>`;
  }).join('');

  document.getElementById('colInfoAccordion').innerHTML = `
    <details>
      <summary style="cursor:pointer;font-weight:700;font-size:.88rem;padding:6px 0;color:var(--blue)">
        β–Ά 컬럼 상세 정보 (${info.columns.length}개)
      </summary>
      <div style="overflow:auto;margin-top:8px;border:1px solid var(--border);border-radius:8px">
        <table style="width:100%;border-collapse:collapse;font-size:.82rem">
          <thead>
            <tr style="background:#f8fafc">
              <th style="padding:8px 12px;text-align:left;border-bottom:2px solid var(--border)">컬럼λͺ…</th>
              <th style="padding:8px 12px;text-align:left;border-bottom:2px solid var(--border)">μœ ν˜•</th>
              <th style="padding:8px 12px;text-align:left;border-bottom:2px solid var(--border)">κ³ μœ κ°’</th>
              <th style="padding:8px 12px;text-align:left;border-bottom:2px solid var(--border)">결츑치</th>
              <th style="padding:8px 12px;text-align:left;border-bottom:2px solid var(--border)">μƒ˜ν”Œκ°’</th>
            </tr>
          </thead>
          <tbody>${rows}</tbody>
        </table>
      </div>
    </details>`;
}

function renderPreviewTable(info, preview) {
  if (!preview || preview.length === 0) {
    document.getElementById('previewTableWrap').innerHTML = '<p class="text-muted text-sm" style="padding:20px">데이터가 μ—†μŠ΅λ‹ˆλ‹€.</p>';
    return;
  }
  const badgeClass = { μˆ˜μΉ˜ν˜•: 'badge-num', λ²”μ£Όν˜•: 'badge-cat', λ¬Έμžν˜•: 'badge-text', λ‚ μ§œν˜•: 'badge-date' };
  const colMap = Object.fromEntries(info.columns.map(c => [c.name, c]));
  const cols   = Object.keys(preview[0]);

  const ths = cols.map(col => {
    const meta = colMap[col];
    const bc   = meta ? (badgeClass[meta.type] || 'badge-text') : 'badge-text';
    return `<th>${escHtml(col)}<span class="type-tag"><span class="badge ${bc}" style="font-size:.65rem;padding:1px 5px">${meta ? meta.type : ''}</span></span></th>`;
  }).join('');

  const trs = preview.map(row =>
    `<tr>${cols.map(c => `<td title="${escHtml(String(row[c]))}">${escHtml(String(row[c]))}</td>`).join('')}</tr>`
  ).join('');

  document.getElementById('previewTableWrap').innerHTML = `
    <table class="preview-table">
      <thead><tr>${ths}</tr></thead>
      <tbody>${trs}</tbody>
    </table>`;
}

// ──────────────────────────────────────────────────────────────
// ꡬ쑰화 뢄석 νŒ¨λ„
// ──────────────────────────────────────────────────────────────
function renderStructuredPanel() {
  // .suggestions μžλ¦¬μ— ꡬ쑰화 νŒ¨λ„ μ£Όμž…
  const suggestionsEl = document.querySelector('.suggestions');
  if (!suggestionsEl) return;

  if (!state.dfInfo) {
    suggestionsEl.innerHTML = '<p style="font-size:.82rem;color:var(--muted);padding:4px 0">데이터λ₯Ό λ¨Όμ € μ—…λ‘œλ“œν•΄μ£Όμ„Έμš”.</p>';
    return;
  }

  const typeOptions = ANALYSIS_TYPES.map(t =>
    `<option value="${t.id}">${t.label} β€” ${t.desc}</option>`
  ).join('');

  suggestionsEl.innerHTML = `
    <div style="width:100%">
      <!-- λͺ¨λ“œ ν† κΈ€ -->
      <div style="display:flex;gap:6px;margin-bottom:10px">
        <button id="btnModeStructured"
          onclick="setMode('structured')"
          style="padding:5px 12px;border-radius:6px;font-size:.8rem;font-weight:600;cursor:pointer;
                 border:1.5px solid #6366f1;background:${analysisMode==='structured'?'#6366f1':'#fff'};
                 color:${analysisMode==='structured'?'#fff':'#6366f1'}">
          πŸŽ› ꡬ쑰화 뢄석
        </button>
        <button id="btnModeFree"
          onclick="setMode('free')"
          style="padding:5px 12px;border-radius:6px;font-size:.8rem;font-weight:600;cursor:pointer;
                 border:1.5px solid #6366f1;background:${analysisMode==='free'?'#6366f1':'#fff'};
                 color:${analysisMode==='free'?'#fff':'#6366f1'}">
          ✏️ 직접 μž…λ ₯
        </button>
      </div>

      <!-- ꡬ쑰화 폼 -->
      <div id="structuredFormArea" style="${analysisMode==='structured'?'':'display:none'}">

        <!-- 뢄석 μœ ν˜• -->
        <div style="margin-bottom:8px">
          <label style="font-size:.78rem;font-weight:700;color:var(--muted);display:block;margin-bottom:3px">
            뢄석 μœ ν˜• 선택
          </label>
          <select id="analysisTypeSelect"
                  onchange="updateVarSelectors(this.value)"
                  style="width:100%;padding:7px 10px;border:1.5px solid var(--border);
                         border-radius:8px;font-size:.85rem;background:#fff;cursor:pointer">
            <option value="">β€” 뢄석 μœ ν˜•μ„ μ„ νƒν•˜μ„Έμš” β€”</option>
            ${typeOptions}
          </select>
        </div>

        <!-- λ³€μˆ˜ 선택 (동적 λ Œλ”λ§) -->
        <div id="varSelectorArea"></div>

        <!-- μΆ”κ°€ μš”μ²­ -->
        <div id="additionalNotesArea" style="display:none;margin-bottom:8px">
          <label style="font-size:.78rem;font-weight:700;color:var(--muted);display:block;margin-bottom:3px">
            μΆ”κ°€ μš”μ²­ <span style="font-weight:400">(선택사항)</span>
          </label>
          <input type="text" id="additionalNotes"
                 placeholder="예: κ²°κ³Όλ₯Ό Excel둜 μ €μž₯ν•΄μ€˜, μ†Œμˆ˜μ  3μžλ¦¬κΉŒμ§€ ν‘œμ‹œ"
                 style="width:100%;padding:7px 10px;border:1.5px solid var(--border);
                        border-radius:8px;font-size:.82rem;box-sizing:border-box" />
        </div>

        <button id="btnStructuredSubmit"
                onclick="submitStructuredAnalysis()"
                disabled
                style="padding:9px 22px;background:#6366f1;color:#fff;border:none;
                       border-radius:8px;font-size:.88rem;font-weight:700;cursor:pointer;
                       opacity:0.5;transition:opacity .2s">
          πŸ” 뢄석 μ‹œμž‘
        </button>
      </div>
    </div>`;

  // 직접 μž…λ ₯ λͺ¨λ“œμ—μ„œλŠ” textarea ν‘œμ‹œ
  const inputRow = document.querySelector('.chat-input-row');
  if (inputRow) {
    inputRow.style.display = analysisMode === 'free' ? '' : 'none';
  }
}

function setMode(mode) {
  analysisMode = mode;
  renderStructuredPanel();
}

function updateVarSelectors(typeId) {
  const area      = document.getElementById('varSelectorArea');
  const notesArea = document.getElementById('additionalNotesArea');
  const submitBtn = document.getElementById('btnStructuredSubmit');

  if (!typeId || !state.dfInfo) {
    if (area)      area.innerHTML = '';
    if (notesArea) notesArea.style.display = 'none';
    if (submitBtn) { submitBtn.disabled = true; submitBtn.style.opacity = '0.5'; }
    return;
  }

  const type = ANALYSIS_TYPES.find(t => t.id === typeId);
  if (!type) return;

  const numCols = state.dfInfo.columns.filter(c => c.type === 'μˆ˜μΉ˜ν˜•').map(c => c.name);
  const catCols = state.dfInfo.columns.filter(c => c.type === 'λ²”μ£Όν˜•').map(c => c.name);

  let html = '';
  type.vars.forEach(v => {
    const cols       = v.type === 'numeric' ? numCols : catCols;
    const colOptions = cols.map(col =>
      `<option value="${escHtml(col)}">${escHtml(col)}</option>`
    ).join('');

    if (cols.length === 0) {
      html += `<div style="margin-bottom:8px;padding:8px;background:#fff7ed;border-radius:6px;font-size:.8rem;color:#92400e">
        ⚠️ ${escHtml(v.label)}: ${v.type === 'numeric' ? 'μˆ˜μΉ˜ν˜•' : 'λ²”μ£Όν˜•'} λ³€μˆ˜κ°€ μ—†μŠ΅λ‹ˆλ‹€.
      </div>`;
      return;
    }

    if (v.multi) {
      html += `
        <div style="margin-bottom:8px">
          <label style="font-size:.78rem;font-weight:700;color:var(--muted);display:block;margin-bottom:3px">
            ${escHtml(v.label)}
            <span style="font-weight:400"> β€” Ctrl+클릭으둜 μ—¬λŸ¬ 개 선택</span>
          </label>
          <select id="var-${v.key}" multiple size="${Math.min(cols.length, 5)}"
                  style="width:100%;border:1.5px solid var(--border);border-radius:8px;
                         font-size:.82rem;padding:4px 6px;cursor:pointer">
            ${colOptions}
          </select>
        </div>`;
    } else {
      html += `
        <div style="margin-bottom:8px">
          <label style="font-size:.78rem;font-weight:700;color:var(--muted);display:block;margin-bottom:3px">
            ${escHtml(v.label)}
          </label>
          <select id="var-${v.key}"
                  style="width:100%;padding:7px 10px;border:1.5px solid var(--border);
                         border-radius:8px;font-size:.85rem;background:#fff;cursor:pointer">
            <option value="">β€” 선택 β€”</option>
            ${colOptions}
          </select>
        </div>`;
    }
  });

  area.innerHTML = html;
  if (notesArea) notesArea.style.display = '';
  if (submitBtn) { submitBtn.disabled = false; submitBtn.style.opacity = '1'; }
}

function buildQueryFromStructured() {
  const typeId = document.getElementById('analysisTypeSelect').value;
  const type   = ANALYSIS_TYPES.find(t => t.id === typeId);
  if (!type) return null;

  const vars  = {};
  let   valid = true;

  type.vars.forEach(v => {
    const el = document.getElementById(`var-${v.key}`);
    if (!el) { valid = false; return; }
    if (v.multi) {
      const selected = Array.from(el.selectedOptions).map(o => o.value).filter(Boolean);
      if (selected.length === 0) { valid = false; return; }
      vars[v.key] = selected;
    } else {
      if (!el.value) { valid = false; return; }
      vars[v.key] = el.value;
    }
  });

  if (!valid) return null;

  let query = type.build(vars);
  const notes = document.getElementById('additionalNotes');
  if (notes && notes.value.trim()) {
    query += ` μΆ”κ°€ μš”μ²­: ${notes.value.trim()}`;
  }
  return query;
}

function submitStructuredAnalysis() {
  const query = buildQueryFromStructured();
  if (!query) {
    showToast('⚠️ 뢄석 μœ ν˜•κ³Ό λ³€μˆ˜λ₯Ό λͺ¨λ‘ μ„ νƒν•΄μ£Όμ„Έμš”.');
    return;
  }
  _doSendAnalysis(query);
}

// ──────────────────────────────────────────────────────────────
// Analysis β€” unified send
// ──────────────────────────────────────────────────────────────
function setupQueryInput() {
  const input = document.getElementById('queryInput');
  input.addEventListener('keydown', e => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendAnalysis(); }
  });
}

// 직접 μž…λ ₯ 전솑
async function sendAnalysis() {
  const input = document.getElementById('queryInput');
  const query = input.value.trim();
  if (!query) return;
  input.value = '';
  await _doSendAnalysis(query);
}

// λ‚΄λΆ€ 곡톡 전솑 둜직
async function _doSendAnalysis(query) {
  if (!state.sessionId) { showToast('λ¨Όμ € νŒŒμΌμ„ μ—…λ‘œλ“œν•΄μ£Όμ„Έμš”.'); return; }
  if (state.pendingJobId) { showToast('이전 뢄석이 μ§„ν–‰ μ€‘μž…λ‹ˆλ‹€. μž μ‹œ κΈ°λ‹€λ €μ£Όμ„Έμš”.'); return; }

  // μž…λ ₯ 잠금
  document.getElementById('queryInput').disabled = true;
  document.getElementById('btnSend').disabled = true;
  const sb = document.getElementById('btnStructuredSubmit');
  if (sb) { sb.disabled = true; sb.style.opacity = '0.5'; }

  appendUserMessage(query);
  const statusId = appendStatusMessage('Claudeκ°€ 뢄석 κ³„νšμ„ 수립 μ€‘μž…λ‹ˆλ‹€β€¦');

  try {
    const res  = await fetch('/api/analyze', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body:    JSON.stringify({
        session_id: state.sessionId,
        query,
        job_id: state.currentJobId || null,
      }),
    });
    const data = await res.json();

    if (!res.ok) {
      updateStatusMessage(statusId, '❌ ' + (data.detail || 'μš”μ²­ μ‹€νŒ¨'));
      unlockInput();
      return;
    }

    state.pendingJobId = data.job_id;
    pollJob(data.job_id, statusId, query);

  } catch {
    updateStatusMessage(statusId, '❌ μ„œλ²„μ™€ 톡신 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.');
    unlockInput();
  }
}

function unlockInput() {
  document.getElementById('queryInput').disabled = false;
  document.getElementById('btnSend').disabled    = false;
  const sb = document.getElementById('btnStructuredSubmit');
  if (sb) { sb.disabled = false; sb.style.opacity = '1'; }
  if (analysisMode === 'free') document.getElementById('queryInput').focus();
}

// ──────────────────────────────────────────────────────────────
// Job polling
// ──────────────────────────────────────────────────────────────
const STATUS_LABELS = {
  pending:         '뢄석 μš”μ²­ λŒ€κΈ° 쀑…',
  generating_code: 'Claudeκ°€ Python μ½”λ“œλ₯Ό 생성 쀑…',
  executing:       'μ½”λ“œ μ‹€ν–‰ 쀑… (μ΅œλŒ€ 120초)',
  completed:       'βœ… 뢄석 μ™„λ£Œ!',
  error:           '❌ 였λ₯˜ λ°œμƒ',
};

async function pollJob(jobId, statusId, query) {
  let attempts = 0;
  const maxAttempts = 90;

  const tick = async () => {
    try {
      const res = await fetch(`/api/job/${jobId}`);
      const job = await res.json();
      attempts++;

      updateStatusMessage(statusId, STATUS_LABELS[job.status] || job.status);

      if (job.status === 'completed') {
        state.pendingJobId  = null;
        state.currentJobId  = jobId;
        state.completedJobs.push({ jobId, query, results: job.results, files: job.files || [] });
        saveSession();

        renderResults(job);
        document.getElementById('btnToDownload').disabled = false;
        unlockInput();
        showToast('뢄석이 μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€!');

      } else if (job.status === 'error') {
        state.pendingJobId = null;
        appendSystemMessage(`❌ ${job.error || 'μ•Œ 수 μ—†λŠ” 였λ₯˜'}`);
        unlockInput();

      } else if (attempts < maxAttempts) {
        setTimeout(tick, 2000);
      } else {
        state.pendingJobId = null;
        appendSystemMessage('⏰ 응닡 μ‹œκ°„μ΄ μ΄ˆκ³Όλ˜μ—ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄μ£Όμ„Έμš”.');
        unlockInput();
      }
    } catch {
      if (attempts < maxAttempts) setTimeout(tick, 3000);
      else {
        state.pendingJobId = null;
        appendSystemMessage('⚠️ μ„œλ²„ 연결이 λŠμ–΄μ‘ŒμŠ΅λ‹ˆλ‹€.');
        unlockInput();
      }
    }
  };

  setTimeout(tick, 1000);
}

// ──────────────────────────────────────────────────────────────
// Results rendering
// ──────────────────────────────────────────────────────────────
function renderResults(job) {
  const r = job.results || {};

  document.getElementById('resultsEmpty').classList.add('hidden');
  document.getElementById('resultsTabs').classList.remove('hidden');

  document.getElementById('summaryContent').innerHTML = `
    <div class="alert alert-success" style="margin-bottom:14px">
      <span>βœ…</span>
      <div>${escHtml(r.summary || '뢄석이 μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.')}</div>
    </div>
    ${r.method ? `
    <div class="flex gap-8 items-center mb-12">
      <span class="font-bold text-sm">톡계 기법:</span>
      <span class="badge badge-num">${escHtml(r.method)}</span>
    </div>` : ''}
    ${r.preprocessing && r.preprocessing.length ? `
    <div class="font-bold text-sm mb-12">μ „μ²˜λ¦¬ λ‚΄μ—­</div>
    <ul style="padding-left:18px;font-size:.85rem;color:var(--muted);line-height:1.9">
      ${r.preprocessing.map(p => `<li>${escHtml(p)}</li>`).join('')}
    </ul>` : ''}
    ${r.log ? `<div class="alert alert-warn mt-12"><span>⚠️</span><div>${escHtml(r.log)}</div></div>` : ''}`;

  if (r.tables && r.tables.length) {
    document.getElementById('tablesContent').innerHTML = r.tables.map(t => `
      <div class="table-title">${escHtml(t.title || '')}</div>
      <div class="table-wrap">${t.html || ''}</div>`).join('<hr class="divider">');
  } else {
    document.getElementById('tablesContent').innerHTML =
      '<p class="text-muted text-sm">이번 λΆ„μ„μ—μ„œλŠ” ν‘œ κ²°κ³Όκ°€ μ—†μŠ΅λ‹ˆλ‹€.</p>';
  }

  if (r.charts && r.charts.length) {
    document.getElementById('chartsContent').innerHTML = r.charts.map(f =>
      `<img class="chart-img" src="/results/${job.job_id}/${encodeURIComponent(f)}" alt="${escHtml(f)}" loading="lazy" />`
    ).join('');
  } else {
    document.getElementById('chartsContent').innerHTML =
      '<p class="text-muted text-sm">이번 λΆ„μ„μ—μ„œλŠ” κ·Έλž˜ν”„κ°€ μƒμ„±λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.</p>';
  }

  document.getElementById('interpContent').innerHTML = r.interpretation
    ? `<div class="interp-block">${escHtml(r.interpretation).replace(/\n/g, '<br>')}</div>`
    : '<p class="text-muted text-sm">해석 정보가 μ—†μŠ΅λ‹ˆλ‹€.</p>';

  const codeHtml = job.code ? `
    <div class="log-section-title">μ‹€ν–‰λœ Python μ½”λ“œ</div>
    <details class="code-toggle" style="margin-bottom:14px">
      <summary>Python μ½”λ“œ 보기 (${(job.code.match(/\n/g)||[]).length + 1}쀄)</summary>
      <div class="log-block" style="margin-top:8px">${escHtml(job.code)}</div>
    </details>` : '';

  const prepHtml = r.preprocessing && r.preprocessing.length ? `
    <div class="log-section-title">μ „μ²˜λ¦¬ λ‚΄μ—­</div>
    <div style="margin-bottom:14px">${r.preprocessing.map(p => `<span class="log-pill">${escHtml(p)}</span>`).join('')}</div>` : '';

  const methodHtml = r.method ? `
    <div class="log-section-title">μ‚¬μš© 톡계 기법</div>
    <div style="margin-bottom:14px"><span class="log-pill">${escHtml(r.method)}</span></div>` : '';

  const pkgHtml = r.packages && r.packages.length ? `
    <div class="log-section-title">μ‚¬μš© νŒ¨ν‚€μ§€</div>
    <div style="margin-bottom:14px">${r.packages.map(p => `<span class="log-pill">${escHtml(p)}</span>`).join('')}</div>` : '';

  const errHtml = job.stderr ? `
    <div class="log-section-title">였λ₯˜ 둜그</div>
    <div class="log-block" style="color:#FCA5A5">${escHtml(job.stderr.slice(0, 2000))}</div>` : '';

  document.getElementById('logContent').innerHTML = codeHtml + prepHtml + methodHtml + pkgHtml + errHtml
    || '<p class="text-muted text-sm">둜그 정보가 μ—†μŠ΅λ‹ˆλ‹€.</p>';

  if (r.charts && r.charts.length) switchTab('charts');
  else if (r.tables && r.tables.length) switchTab('tables');
  else switchTab('summary');

  document.getElementById('resultStatus').innerHTML =
    `<span class="status-badge status-completed">βœ“ μ™„λ£Œ</span>`;

  scrollChat();
}

// ──────────────────────────────────────────────────────────────
// Tab switching
// ──────────────────────────────────────────────────────────────
function switchTab(name) {
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));

  const btns   = document.querySelectorAll('.tab-btn');
  const tabMap = { summary: 0, tables: 1, charts: 2, interpretation: 3, log: 4 };
  if (btns[tabMap[name]]) btns[tabMap[name]].classList.add('active');
  const pane = document.getElementById(`tab-${name}`);
  if (pane) pane.classList.add('active');
}

// ──────────────────────────────────────────────────────────────
// Download section
// ──────────────────────────────────────────────────────────────
function renderDownloadSection() {
  if (!state.completedJobs.length) {
    document.getElementById('downloadSections').innerHTML =
      '<div class="alert alert-info"><span>ℹ️</span><div>아직 μ™„λ£Œλœ 뢄석이 μ—†μŠ΅λ‹ˆλ‹€. λ¨Όμ € 뢄석을 μˆ˜ν–‰ν•΄μ£Όμ„Έμš”.</div></div>';
    return;
  }

  const iconMap = { png: 'πŸ–Ό', xlsx: 'πŸ“Š', csv: 'πŸ“‹', txt: 'πŸ“', json: 'βš™οΈ' };
  const typeMap = { png: 'κ·Έλž˜ν”„ 이미지', xlsx: 'Excel 파일', csv: 'CSV 데이터', txt: 'ν…μŠ€νŠΈ 파일', json: 'JSON 데이터' };

  const html = state.completedJobs.map((job, idx) => {
    if (!job.files || !job.files.length) return '';
    const items = job.files.map(f => {
      const ext = f.split('.').pop().toLowerCase();
      return `
        <div class="download-item">
          <span class="download-icon">${iconMap[ext] || 'πŸ“„'}</span>
          <div class="download-info">
            <div class="download-name">${escHtml(f)}</div>
            <div class="download-type">${typeMap[ext] || '파일'}</div>
          </div>
          <a class="btn btn-secondary btn-sm" href="/api/download/${job.jobId}/${encodeURIComponent(f)}" download="${escHtml(f)}">
            ⬇ λ‹€μš΄λ‘œλ“œ
          </a>
        </div>`;
    }).join('');

    return `
      <div style="margin-bottom:24px">
        <div class="font-bold mb-12">뢄석 ${idx + 1}: <span class="text-muted" style="font-weight:400">${escHtml(job.query.length > 80 ? job.query.slice(0,80)+'…' : job.query)}</span></div>
        <div class="download-list">${items}</div>
      </div>`;
  }).join('<hr class="divider">');

  document.getElementById('downloadSections').innerHTML = html || '<p class="text-muted text-sm">λ‹€μš΄λ‘œλ“œν•  파일이 μ—†μŠ΅λ‹ˆλ‹€.</p>';
}

// ──────────────────────────────────────────────────────────────
// Chat helpers
// ──────────────────────────────────────────────────────────────
function appendUserMessage(text) {
  const now = new Date().toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' });
  const div = document.createElement('div');
  div.className = 'msg user';
  div.innerHTML = `
    <div class="msg-bubble">${escHtml(text.length > 200 ? text.slice(0,200)+'…' : text)}</div>
    <div class="msg-time">${now}</div>`;
  document.getElementById('chatMessages').appendChild(div);
  scrollChat();
}

function appendStatusMessage(text) {
  const id  = 'status-' + Date.now();
  const div = document.createElement('div');
  div.className = 'msg-status';
  div.id = id;
  div.innerHTML = `<div class="spinner"></div><span>${escHtml(text)}</span>`;
  document.getElementById('chatMessages').appendChild(div);
  scrollChat();
  return id;
}

function updateStatusMessage(id, text) {
  const el = document.getElementById(id);
  if (!el) return;
  el.innerHTML = `<div class="spinner"></div><span>${escHtml(text)}</span>`;
  scrollChat();
}

function appendSystemMessage(text) {
  const div = document.createElement('div');
  div.className = 'msg system';
  div.innerHTML = `<div class="msg-bubble">${escHtml(text)}</div>`;
  document.getElementById('chatMessages').appendChild(div);
  scrollChat();
}

function rebuildChatHistory() {
  const container = document.getElementById('chatMessages');
  if (state.completedJobs.length === 0) return;
  state.completedJobs.forEach(job => {
    const ud = document.createElement('div');
    ud.className = 'msg user';
    ud.innerHTML = `<div class="msg-bubble">${escHtml(job.query.length > 200 ? job.query.slice(0,200)+'…' : job.query)}</div>`;
    container.appendChild(ud);
    const sd = document.createElement('div');
    sd.className = 'msg system';
    sd.innerHTML = `<div class="msg-bubble">βœ… 뢄석이 μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€. κ²°κ³Ό νŒ¨λ„μ„ ν™•μΈν•˜μ„Έμš”.</div>`;
    container.appendChild(sd);
  });
  const lastJob = state.completedJobs[state.completedJobs.length - 1];
  if (lastJob) {
    state.currentJobId = lastJob.jobId;
    renderResults({ job_id: lastJob.jobId, results: lastJob.results, files: lastJob.files, code: null, stderr: null });
    document.getElementById('btnToDownload').disabled = false;
  }
}

function scrollChat() {
  const msgs = document.getElementById('chatMessages');
  msgs.scrollTop = msgs.scrollHeight;
}

// ──────────────────────────────────────────────────────────────
// Alert helpers
// ──────────────────────────────────────────────────────────────
function showAlert(containerId, type, msg) {
  const icons = { info: 'ℹ️', warn: '⚠️', success: 'βœ…', error: '❌' };
  document.getElementById(containerId).innerHTML = `
    <div class="alert alert-${type}">
      <span>${icons[type] || ''}</span>
      <div>${escHtml(msg)}</div>
    </div>`;
}

function clearAlert(containerId) {
  document.getElementById(containerId).innerHTML = '';
}

// ──────────────────────────────────────────────────────────────
// Toast notification
// ──────────────────────────────────────────────────────────────
let toastTimer = null;
function showToast(msg, duration = 3500) {
  const toast = document.getElementById('toast');
  toast.textContent = msg;
  toast.style.transform = 'translateY(0)';
  toast.style.opacity   = '1';
  clearTimeout(toastTimer);
  toastTimer = setTimeout(() => {
    toast.style.transform = 'translateY(100px)';
    toast.style.opacity   = '0';
  }, duration);
}

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