File size: 33,170 Bytes
facf506
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{% extends "base.html" %}
{% block title %}Configure Model - Data2Model{% endblock %}

{% block content %}
<div class="container my-5">
<div class="row">
<div class="col-lg-9 mx-auto">

  <!-- Dataset Summary -->
  <div class="card shadow mb-4">
    <div class="card-header bg-info text-white">
      <h5 class="mb-0"><i class="fas fa-database"></i> Dataset Summary β€” {{ data.filename }}</h5>
    </div>
    <div class="card-body">
      <div class="row text-center">
        <div class="col-6 col-md-3 mb-2">
          <div class="stat-box"><span class="stat-num">{{ data.analysis.shape[0] }}</span><br><small>Rows</small></div>
        </div>
        <div class="col-6 col-md-3 mb-2">
          <div class="stat-box"><span class="stat-num">{{ data.analysis.shape[1] }}</span><br><small>Columns</small></div>
        </div>
        <div class="col-6 col-md-3 mb-2">
          <div class="stat-box text-primary"><span class="stat-num">{{ data.analysis.numeric_columns|length }}</span><br><small>Numeric</small></div>
        </div>
        <div class="col-6 col-md-3 mb-2">
          <div class="stat-box text-warning"><span class="stat-num">{{ data.analysis.categorical_columns|length }}</span><br><small>Categorical</small></div>
        </div>
      </div>

      <!-- Column Type Overview (FIX 8) -->
      <div class="mt-3">
        <strong>Detected Column Types:</strong>
        <div class="mt-2 d-flex flex-wrap gap-2">
          {% for col in data.analysis.columns %}
            {% if col in data.analysis.categorical_columns %}
              <span class="badge bg-warning text-dark"><i class="fas fa-tag"></i> {{ col }} (cat)</span>
            {% else %}
              <span class="badge bg-primary"><i class="fas fa-hashtag"></i> {{ col }} (num)</span>
            {% endif %}
          {% endfor %}
        </div>
        <small class="text-muted mt-1 d-block">
          Blue = numeric, Yellow = categorical. You can override below.
        </small>
      </div>

      {% if data.analysis.duplicates > 0 %}
      <div class="alert alert-secondary mt-3 mb-0 py-2">
        <i class="fas fa-copy"></i> {{ data.analysis.duplicates }} duplicate rows will be removed automatically.
      </div>
      {% endif %}
    </div>
  </div>

  <!-- ═══════════════════════════════════════════════════════════════════ -->
  <!-- DASHBOARD: DATA VISUALIZATIONS                                      -->
  <!-- ═══════════════════════════════════════════════════════════════════ -->
  {% if data.viz_plots %}
  <div class="card shadow mb-4 border-info">
    <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
      <h5 class="mb-0"><i class="fas fa-chart-bar"></i> Data Dashboard</h5>
      <button class="btn btn-sm btn-light" type="button" data-bs-toggle="collapse" data-bs-target="#dashboardCollapse" aria-expanded="true" aria-controls="dashboardCollapse">
        Toggle Dashboard
      </button>
    </div>
    <div id="dashboardCollapse" class="collapse show">
      <div class="card-body bg-light">
        <!-- Overview & Correlation -->
        <div class="row mb-4">
          <div class="col-md-6 mb-3">
            {% if data.viz_plots.data_quality %}
              <img src="{{ data.viz_plots.data_quality }}" class="img-fluid rounded shadow-sm w-100" alt="Data Quality">
            {% endif %}
          </div>
          <div class="col-md-6 mb-3">
            {% if data.viz_plots.correlation_heatmap %}
              <img src="{{ data.viz_plots.correlation_heatmap }}" class="img-fluid rounded shadow-sm w-100" alt="Correlation Heatmap">
            {% else %}
              <div class="alert alert-secondary h-100 d-flex align-items-center justify-content-center">
                Not enough numeric columns for correlation heatmap.
              </div>
            {% endif %}
          </div>
        </div>
        
        <!-- Distributions -->
        <div class="row">
          <div class="col-12 mb-4">
            {% if data.viz_plots.numeric_histograms %}
              <img src="{{ data.viz_plots.numeric_histograms }}" class="img-fluid rounded shadow-sm w-100" alt="Numeric Histograms">
            {% endif %}
          </div>
          <div class="col-12 mb-4">
            {% if data.viz_plots.categorical_distributions %}
              <img src="{{ data.viz_plots.categorical_distributions }}" class="img-fluid rounded shadow-sm w-100" alt="Categorical Distributions">
            {% endif %}
          </div>
        </div>
      </div>
    </div>
  </div>
  {% endif %}

  <!-- Main Form -->
  <form action="{{ url_for('train_model') }}" method="post" id="configForm">
    <input type="hidden" name="filepath"  value="{{ data.filepath }}">
    <input type="hidden" name="file_type" value="{{ data.file_type }}">

    <!-- ═══════════════════════════════════════════════════════════════════ -->
    <!-- SECTION 1: NULL VALUE HANDLING (FIX 1 & 2)                        -->
    <!-- ═══════════════════════════════════════════════════════════════════ -->
    {% if data.analysis.missing_values %}
    <div class="card shadow mb-4 border-warning">
      <div class="card-header bg-warning text-dark">
        <h5 class="mb-0"><i class="fas fa-exclamation-triangle"></i> Null Value Imputation</h5>
      </div>
      <div class="card-body">
        <p class="text-muted mb-3">
          Configure how missing values are handled for each feature. 
          <strong>Statistical imputation is highly recommended</strong> to prevent unnecessary data loss compared to deleting records.
        </p>
        <div class="table-responsive">
          <table class="table table-bordered table-sm align-middle">
            <thead class="table-light">
              <tr>
                <th>Column</th>
                <th>Missing Count</th>
                <th>Type</th>
                <th>Imputation Strategy</th>
              </tr>
            </thead>
            <tbody>
              {% for col in data.analysis.columns %}
              {% set count = data.analysis.missing_values.get(col, 0) %}
              {% if count > 0 %}
              <tr class="imputation-row" data-column="{{ col }}">
                <td><strong>{{ col }}</strong></td>
                <td>
                  <span class="badge bg-danger">{{ count }} missing</span>
                </td>
                <td class="col-type-td">
                  {% if col in data.analysis.categorical_columns %}
                    <span class="badge bg-warning text-dark">Categorical</span>
                  {% else %}
                    <span class="badge bg-primary">Numeric</span>
                  {% endif %}
                </td>
                <td>
                  <div class="d-flex flex-column gap-1">
                    <select class="form-select form-select-sm imputation-select" name="null_{{ col }}" onchange="toggleCustomInput(this, 'custom_input_{{ loop.index }}')">
                      {% if col in data.analysis.categorical_columns %}
                        <option value="auto" selected>Auto (smart mode)</option>
                        <option value="mode">Mode (most frequent) βœ“ Recommended</option>
                        <option value="zero">Fill with 'Unknown'</option>
                        <option value="custom">Custom Constant...</option>
                        <option value="drop">Delete rows with missing</option>
                      {% else %}
                        <option value="auto" selected>Auto (smart median)</option>
                        <option value="median">Median βœ“ Recommended</option>
                        <option value="mean">Mean</option>
                        <option value="mode">Mode</option>
                        <option value="zero">Fill with 0</option>
                        <option value="custom">Custom Constant...</option>
                        <option value="drop">Delete rows with missing</option>
                      {% endif %}
                    </select>
                    <input type="text" class="form-control form-control-sm mt-1 custom-impute-val" name="null_custom_{{ col }}" id="custom_input_{{ loop.index }}" style="display:none;" placeholder="Enter custom value...">
                  </div>
                </td>
              </tr>
              {% endif %}
              {% endfor %}
            </tbody>
          </table>
        </div>
      </div>
    </div>
    {% endif %}

    <!-- ═══════════════════════════════════════════════════════════════════ -->
    <!-- SECTION 2: DATA TYPE OVERRIDE (FIX 8)                             -->
    <!-- ═══════════════════════════════════════════════════════════════════ -->
    {% if data.analysis.numeric_columns %}
    <div class="card shadow mb-4">
      <div class="card-header bg-secondary text-white">
        <h5 class="mb-0"><i class="fas fa-exchange-alt"></i> Data Type Override <small class="fw-normal">(optional)</small></h5>
      </div>
      <div class="card-body">
        <p class="text-muted mb-3">
          Numeric columns detected below. If any column is actually a <strong>category / product code / identifier</strong> (e.g. ID, category numbers), tick the box so it gets correctly treated as a categorical column rather than scaled as a continuous value.
        </p>
        <div class="row">
          {% for col in data.analysis.numeric_columns %}
          <div class="col-md-4 col-sm-6 mb-2">
            <div class="form-check">
              <input class="form-check-input override-checkbox" type="checkbox" name="cat_override" value="{{ col }}" id="co_{{ loop.index }}">
              <label class="form-check-label" for="co_{{ loop.index }}">
                <span class="badge bg-primary me-1">num</span> {{ col }}
                <small class="text-muted">({{ data.analysis.col_stats[col].unique }} unique)</small>
              </label>
            </div>
          </div>
          {% endfor %}
        </div>
      </div>
    </div>
    {% endif %}

    <!-- ═══════════════════════════════════════════════════════════════════ -->
    <!-- SECTION 2.5: DELETE COLUMNS FEATURE                                 -->
    <!-- ═══════════════════════════════════════════════════════════════════ -->
    <div class="card shadow mb-4 border-danger">
      <div class="card-header bg-danger text-white">
        <h5 class="mb-0"><i class="fas fa-trash-alt"></i> Drop Columns <small class="fw-normal">(optional)</small></h5>
      </div>
      <div class="card-body">
        <p class="text-muted mb-3">
          Select any columns you want to completely <strong>delete</strong> from the dataset before training. These columns will be ignored.
        </p>
        <div class="row">
          {% for col in data.analysis.columns %}
          <div class="col-md-4 col-sm-6 mb-2">
            <div class="form-check">
              <input class="form-check-input drop-checkbox" type="checkbox" name="drop_columns" value="{{ col }}" id="drop_{{ loop.index }}">
              <label class="form-check-label text-danger" for="drop_{{ loop.index }}">
                {{ col }}
              </label>
            </div>
          </div>
          {% endfor %}
        </div>
      </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════════ -->
    <!-- SECTION 3: PROBLEM CONFIGURATION (FIX 3)                          -->
    <!-- ═══════════════════════════════════════════════════════════════════ -->
    <div class="card shadow mb-4">
      <div class="card-header bg-primary text-white">
        <h5 class="mb-0"><i class="fas fa-cog"></i> Problem Configuration</h5>
      </div>
      <div class="card-body">

        <!-- Problem Type (FIX 3) -->
        <div class="mb-3">
          <label class="form-label fw-bold">Problem Type</label>
          <select class="form-select" id="problem_type" name="problem_type">
            <option value="auto" selected>Auto Detect</option>
            <option value="classification">Classification (predict a category)</option>
            <option value="regression">Regression (predict a number)</option>
            <option value="clustering">Clustering β€” Unsupervised</option>
            <option value="dimensionality_reduction">Dimensionality Reduction β€” Unsupervised</option>
            <option value="association">Association β€” Unsupervised</option>
          </select>
        </div>

        <!-- Target Column β€” hidden for unsupervised (FIX 3) -->
        <div class="mb-3" id="target_col_section">
          <label class="form-label fw-bold">
            Target Column <span class="text-danger">*</span>
          </label>
          <select class="form-select" id="target_column" name="target_column">
            <option value="">β€” Select Target Column β€”</option>
            {% for col in data.analysis.columns %}
            <option value="{{ col }}">{{ col }}</option>
            {% endfor %}
          </select>
          <div class="form-text">The column you want to predict</div>
        </div>

        <!-- Split Type (FIX 4) -->
        <div class="mb-3" id="split_section">
          <label class="form-label fw-bold">Data Split Strategy</label>
          <div class="row g-2">
            <div class="col-md-6">
              <div class="form-check card p-3 border split-card" id="card_tt">
                <input class="form-check-input" type="radio" name="split_type" value="train_test"
                       id="split_tt" checked>
                <label class="form-check-label w-100" for="split_tt">
                  <strong>Train / Test Split</strong>
                  <div class="text-muted small mt-1">Standard evaluation.<br>e.g. 80% train, 20% test</div>
                </label>
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-check card p-3 border split-card" id="card_ttv">
                <input class="form-check-input" type="radio" name="split_type" value="train_test_val"
                       id="split_ttv">
                <label class="form-check-label w-100" for="split_ttv">
                  <strong>Train / Test / Validation Split</strong>
                  <div class="text-muted small mt-1">Better model tuning.<br>e.g. 60% / 20% / 20%</div>
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- Split sizes -->
        <div class="row g-3" id="split_sizes">
          <div class="col-md-6" id="test_size_box">
            <label class="form-label fw-bold">Test Set Size</label>
            <select class="form-select" name="test_size">
              <option value="0.2" selected>20% (Recommended)</option>
              <option value="0.25">25%</option>
              <option value="0.3">30%</option>
              <option value="0.15">15%</option>
            </select>
          </div>
          <div class="col-md-6" id="val_size_box" style="display:none;">
            <label class="form-label fw-bold">Validation Set Size</label>
            <select class="form-select" name="val_size">
              <option value="0.2" selected>20% (Recommended)</option>
              <option value="0.15">15%</option>
              <option value="0.1">10%</option>
            </select>
          </div>
        </div>

      </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════════ -->
    <!-- SECTION 4: PER-COLUMN SCALING (FIX 5 & 6)                        -->
    <!-- ═══════════════════════════════════════════════════════════════════ -->
    {% if data.analysis.numeric_columns %}
    <div class="card shadow mb-4" id="numeric_scaling_card">
      <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-balance-scale"></i> Scaling β€” Numeric Columns</h5>
        <div>
          <label class="text-white me-2 small">Apply same to all:</label>
          <select class="form-select form-select-sm d-inline-block w-auto" id="globalScaling">
            <option value="">β€” Pick β€”</option>
            <option value="standard">Standard</option>
            <option value="minmax">Min-Max</option>
            <option value="robust">Robust</option>
            <option value="normalizer">Normalizer</option>
            <option value="none">None</option>
          </select>
        </div>
      </div>
      <div class="card-body">
        <p class="text-muted small mb-3">
          Choose a scaling method per column. Continuous features are standardly scaled, while categorical overrides will be excluded.
        </p>
        <div class="table-responsive">
          <table class="table table-sm table-bordered align-middle">
            <thead class="table-light">
              <tr><th>Column</th><th>Scaling Method</th></tr>
            </thead>
            <tbody>
              {% for col in data.analysis.numeric_columns %}
              <tr class="scaling-row" data-column="{{ col }}">
                <td><span class="badge bg-primary">num</span> {{ col }}</td>
                <td>
                  <select class="form-select form-select-sm scaling-col" name="scale_{{ col }}">
                    <option value="standard" selected>Standard (z-score)</option>
                    <option value="minmax">Min-Max [0,1]</option>
                    <option value="robust">Robust (outlier-safe)</option>
                    <option value="normalizer">Normalizer</option>
                    <option value="none">No Scaling</option>
                  </select>
                </td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      </div>
    </div>
    {% endif %}

    <!-- ═══════════════════════════════════════════════════════════════════ -->
    <!-- SECTION 5: PER-COLUMN ENCODING (FIX 5 & 7)                       -->
    <!-- ═══════════════════════════════════════════════════════════════════ -->
    <div class="card shadow mb-4" id="categorical_encoding_card" {% if not data.analysis.categorical_columns %}style="display:none;"{% endif %}>
      <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-tags"></i> Encoding β€” Categorical Columns</h5>
        <div>
          <label class="me-2 small">Apply same to all:</label>
          <select class="form-select form-select-sm d-inline-block w-auto" id="globalEncoding">
            <option value="">β€” Pick β€”</option>
            <option value="auto">Auto</option>
            <option value="onehot">One-Hot</option>
            <option value="label">Label</option>
            <option value="ordinal">Ordinal</option>
            <option value="target">Target</option>
            <option value="binary">Binary</option>
          </select>
        </div>
      </div>
      <div class="card-body">
        <p class="text-muted small mb-3">
          Choose an encoding method per column. Each column can use a different method.
        </p>
        <div class="table-responsive">
          <table class="table table-sm table-bordered align-middle">
            <thead class="table-light">
              <tr><th>Column</th><th>Unique Values</th><th>Encoding Method</th></tr>
            </thead>
            <tbody id="encoding_table_body">
              <!-- Regular Categorical Columns -->
              {% for col in data.analysis.categorical_columns %}
              <tr class="encoding-row" data-column="{{ col }}">
                <td><span class="badge bg-warning text-dark">cat</span> {{ col }}</td>
                <td><span class="badge bg-secondary">{{ data.analysis.col_stats[col].unique }}</span></td>
                <td>
                  <select class="form-select form-select-sm encoding-col" name="encode_{{ col }}">
                    <option value="auto" selected>Auto (smart detect)</option>
                    <option value="onehot">One-Hot Encoding</option>
                    <option value="label">Label Encoding</option>
                    <option value="ordinal">Ordinal Encoding</option>
                    <option value="target">Target Encoding</option>
                    <option value="binary">Binary (LabelBinarizer)</option>
                  </select>
                </td>
              </tr>
              {% endfor %}

              <!-- Pre-rendered Hidden Overridden Numeric Columns -->
              {% if data.analysis.numeric_columns %}
                {% for col in data.analysis.numeric_columns %}
                <tr class="encoding-row" data-column="{{ col }}" id="enc_row_{{ col }}" style="display:none;">
                  <td><span class="badge bg-warning text-dark">cat</span> {{ col }} <span class="badge bg-info text-white">overridden</span></td>
                  <td><span class="badge bg-secondary">{{ data.analysis.col_stats[col].unique }}</span></td>
                  <td>
                    <select class="form-select form-select-sm encoding-col" name="encode_{{ col }}" disabled>
                      <option value="auto" selected>Auto (smart detect)</option>
                      <option value="onehot">One-Hot Encoding</option>
                      <option value="label">Label Encoding</option>
                      <option value="ordinal">Ordinal Encoding</option>
                      <option value="target">Target Encoding</option>
                      <option value="binary">Binary (LabelBinarizer)</option>
                    </select>
                  </td>
                </tr>
                {% endfor %}
              {% endif %}
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Submit -->
    <div class="d-grid gap-2">
      <button type="submit" class="btn btn-primary btn-lg" id="trainBtn">
        <i class="fas fa-play"></i> Start Training
      </button>
      <a href="{{ url_for('index') }}" class="btn btn-outline-secondary">
        <i class="fas fa-arrow-left"></i> Back to Home
      </a>
    </div>

  </form>
</div>
</div>
</div>

<!-- Loading Overlay -->
<div id="loadingOverlay" style="display:none;">
  <div class="spinner-container">
    <div class="spinner-border text-primary" role="status" style="width:4rem;height:4rem;">
      <span class="visually-hidden">Loading...</span>
    </div>
    <h4 class="mt-3 text-white">Training Models...</h4>
    <p class="text-white-50">Testing all algorithms and selecting the best one</p>
  </div>
</div>

<style>
.stat-box { background:#f8f9fa; border-radius:8px; padding:12px; }
.stat-num { font-size:1.8rem; font-weight:700; }
.split-card { cursor:pointer; transition:border-color .2s; }
.split-card.active { border-color:#0d6efd !important; background:#f0f5ff; }

#loadingOverlay {
  position:fixed; top:0; left:0; width:100%; height:100%; 
  background:rgba(0,0,0,0.85); z-index:9999;
  display:flex; align-items:center; justify-content:center;
}
.spinner-container { text-align:center; }
</style>

<script>
// ── Show loading on form submit ──────────────────────────────────────────
document.getElementById('configForm').addEventListener('submit', function() {
  document.getElementById('loadingOverlay').style.display = 'flex';
});

// ── Custom Imputation Input toggling ──────────────────────────────────────
function toggleCustomInput(selectObj, inputId) {
  const customInput = document.getElementById(inputId);
  if (selectObj.value === 'custom') {
    customInput.style.display = '';
    customInput.required = true;
  } else {
    customInput.style.display = 'none';
    customInput.required = false;
  }
}

// ── Data Type Override Coordination ───────────────────────────────────────
document.querySelectorAll('.override-checkbox').forEach(cb => {
  cb.addEventListener('change', function() {
    const col = this.value;
    const isChecked = this.checked;
    
    // Scaling row
    const scaleRow = document.querySelector(`.scaling-row[data-column="${col}"]`);
    if (scaleRow) {
      scaleRow.style.display = isChecked ? 'none' : '';
      scaleRow.querySelector('select').disabled = isChecked;
    }
    
    // Encoding row (pre-rendered hidden overridden rows)
    const encodeRow = document.getElementById(`enc_row_${col}`);
    if (encodeRow) {
      encodeRow.style.display = isChecked ? '' : 'none';
      encodeRow.querySelector('select').disabled = !isChecked;
    }
    
    // Update target badge and options in Imputation table (display Categorical vs Numeric)
    const imputeRow = document.querySelector(`.imputation-row[data-column="${col}"]`);
    if (imputeRow) {
      const typeTd = imputeRow.querySelector('.col-type-td');
      if (typeTd) {
        if (isChecked) {
          typeTd.innerHTML = '<span class="badge bg-warning text-dark">Categorical (overridden)</span>';
        } else {
          typeTd.innerHTML = '<span class="badge bg-primary">Numeric</span>';
        }
      }
    }
    
    // Update categorical encoding card visibility
    updateEncodingCardVisibility();
    
    // Re-apply target hiding in case target column was changed or overridden
    hideTargetFromPreprocessing();
  });
});

function updateEncodingCardVisibility() {
  const card = document.getElementById('categorical_encoding_card');
  if (!card) return;
  
  // Find visible encoding rows
  const visibleRows = Array.from(card.querySelectorAll('.encoding-row')).filter(row => {
    return row.style.display !== 'none';
  });
  
  card.style.display = visibleRows.length > 0 ? '' : 'none';
}

// ── Toggle Target Column & Splits for Unsupervised ────────────────────────
const problemType  = document.getElementById('problem_type');
const targetSec    = document.getElementById('target_col_section');
const splitSec     = document.getElementById('split_section');
const splitSizes   = document.getElementById('split_sizes');
const targetInput  = document.getElementById('target_column');

const UNSUPERVISED = ['clustering', 'dimensionality_reduction', 'association'];

function toggleUnsupervised() {
  const isUnsup = UNSUPERVISED.includes(problemType.value);
  targetSec.style.display  = isUnsup ? 'none' : '';
  splitSec.style.display   = isUnsup ? 'none' : '';
  splitSizes.style.display = isUnsup ? 'none' : '';
  targetInput.required     = !isUnsup;
  
  if (isUnsup) {
    targetInput.value = '';
    hideTargetFromPreprocessing();
  }
}

problemType.addEventListener('change', toggleUnsupervised);
toggleUnsupervised();

// ── Show/hide validation size box ─────────────────────────────────────────
document.querySelectorAll('input[name="split_type"]').forEach(radio => {
  radio.addEventListener('change', () => {
    const isVal = document.getElementById('split_ttv').checked;
    document.getElementById('val_size_box').style.display = isVal ? '' : 'none';
    
    // highlight selected card
    document.getElementById('card_tt').classList.toggle('active', !isVal);
    document.getElementById('card_ttv').classList.toggle('active', isVal);
  });
});

// ── Split card click ──────────────────────────────────────────────────────
document.querySelectorAll('.split-card').forEach(card => {
  card.addEventListener('click', () => {
    const radio = card.querySelector('input[type="radio"]');
    radio.checked = true;
    radio.dispatchEvent(new Event('change'));
  });
});

// ── Hide Target Column from Preprocessing Tables ──────────────────────────
function hideTargetFromPreprocessing() {
  const targetCol = targetInput.value;
  
  // Check if it's dropped
  const isDropped = document.querySelector(`.drop-checkbox[value="${targetCol}"]`)?.checked;
  if (isDropped && targetCol) {
      alert(`You cannot select a dropped column ('${targetCol}') as the Target Column! Please uncheck it in the 'Drop Columns' section or select a different target.`);
      targetInput.value = ''; // Reset target column
      return hideTargetFromPreprocessing(); // Re-run with empty target
  }
  
  // Imputation rows
  document.querySelectorAll('.imputation-row').forEach(row => {
    const colName = row.getAttribute('data-column');
    const dropped = document.querySelector(`.drop-checkbox[value="${colName}"]`)?.checked;
    row.style.display = ((targetCol && colName === targetCol) || dropped) ? 'none' : '';
  });
  
  // Scaling rows (continuous numeric)
  document.querySelectorAll('.scaling-row').forEach(row => {
    const colName = row.getAttribute('data-column');
    const isOverride = document.querySelector(`.override-checkbox[value="${colName}"]`)?.checked;
    const dropped = document.querySelector(`.drop-checkbox[value="${colName}"]`)?.checked;
    
    if (targetCol && colName === targetCol) {
      row.style.display = 'none';
    } else if (isOverride || dropped) {
      row.style.display = 'none'; // Overridden columns are hidden in scaling table
    } else {
      row.style.display = '';
    }
  });
  
  // Encoding rows (categorical + overridden numeric)
  document.querySelectorAll('.encoding-row').forEach(row => {
    const colName = row.getAttribute('data-column');
    const isOverride = document.querySelector(`.override-checkbox[value="${colName}"]`)?.checked;
    const dropped = document.querySelector(`.drop-checkbox[value="${colName}"]`)?.checked;
    const isInitiallyCategorical = !document.querySelector(`.override-checkbox[value="${colName}"]`);
    
    if ((targetCol && colName === targetCol) || dropped) {
      row.style.display = 'none';
    } else if (isInitiallyCategorical) {
      row.style.display = ''; // Regular categorical column
    } else if (isOverride) {
      row.style.display = ''; // Overridden numeric column is shown
    } else {
      row.style.display = 'none'; // Unchecked numeric column is hidden
    }
  });
  
  // Update encoding card visibility
  updateEncodingCardVisibility();
}

// Listen to target column changes
targetInput.addEventListener('change', hideTargetFromPreprocessing);
document.querySelectorAll('.drop-checkbox').forEach(cb => {
  cb.addEventListener('change', hideTargetFromPreprocessing);
});
hideTargetFromPreprocessing(); // Run on page load

// ── Global selectors ──────────────────────────────────────────────────────
document.getElementById('globalScaling')?.addEventListener('change', function() {
  if (!this.value) return;
  document.querySelectorAll('.scaling-col:not([disabled])').forEach(s => s.value = this.value);
});

document.getElementById('globalEncoding')?.addEventListener('change', function() {
  if (!this.value) return;
  document.querySelectorAll('.encoding-col:not([disabled])').forEach(s => s.value = this.value);
});
</script>
{% endblock %}