File size: 46,274 Bytes
488ed84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/* ═══════════════════════════════════════════════════════════════════════════

   x86 PCB Design Simulator β€” Frontend Application

   ═══════════════════════════════════════════════════════════════════════════ */

// ── Tab Navigation ──────────────────────────────────────────────────────────
document.querySelectorAll('.tab').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.tab').forEach(b => b.classList.remove('active'));
        document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
        btn.classList.add('active');
        document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
    });
});

// ── Helpers ─────────────────────────────────────────────────────────────────
async function api(endpoint, body) {
    const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
    });
    if (!res.ok) {
        const err = await res.json().catch(() => ({ detail: res.statusText }));
        throw new Error(err.detail || 'API error');
    }
    return res.json();
}

function loading(el) {
    el.innerHTML = '<div class="loading"><span class="spinner"></span> Running simulation…</div>';
}

function fmt(n) { return typeof n === 'number' ? n.toLocaleString() : n; }

const COLORS = {
    accent: '#4fc3f7', accent2: '#7c4dff', green: '#66bb6a', red: '#ef5350',
    orange: '#ffa726', yellow: '#ffee58', cyan: '#26c6da', pink: '#ec407a',
    teal: '#26a69a', grid: '#2e3d5f', text: '#8899b4', white: '#e0e6f0',
};

// Shared chart helpers
function drawGrid(ctx, pad, cw, ch, yLabels, xLabels) {
    ctx.strokeStyle = COLORS.grid;
    ctx.lineWidth = 0.5;
    ctx.font = '11px Segoe UI';
    ctx.fillStyle = COLORS.text;

    if (yLabels) {
        for (let i = 0; i < yLabels.length; i++) {
            const y = pad.t + ch * (1 - i / (yLabels.length - 1));
            ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
            ctx.textAlign = 'right';
            ctx.fillText(yLabels[i], pad.l - 6, y + 4);
        }
    }
    if (xLabels) {
        ctx.textAlign = 'center';
        for (let i = 0; i < xLabels.length; i++) {
            const x = pad.l + (i / (xLabels.length - 1)) * cw;
            ctx.fillText(xLabels[i], x, pad.t + ch + 18);
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// STACKUP TAB
// ═══════════════════════════════════════════════════════════════════════════

document.getElementById('stackup-run').addEventListener('click', async () => {
    const statsEl = document.getElementById('stackup-stats');
    const tableEl = document.getElementById('stackup-table');
    const refsEl = document.getElementById('stackup-refs');
    loading(statsEl);
    tableEl.innerHTML = ''; refsEl.innerHTML = '';

    try {
        const data = await api('/api/stackup', {});

        statsEl.innerHTML = `

            <div class="stat-card"><div class="label">Total Thickness</div><div class="value accent">${data.total_thickness_mil} mil</div></div>

            <div class="stat-card"><div class="label">Thickness (mm)</div><div class="value cyan">${data.total_thickness_mm} mm</div></div>

            <div class="stat-card"><div class="label">Copper Layers</div><div class="value green">${data.copper_layer_count}</div></div>

            <div class="stat-card"><div class="label">Dielectric Layers</div><div class="value orange">${data.dielectric_layer_count}</div></div>

        `;

        // Draw stackup visual
        drawStackup(data.layers);

        // Layer table
        tableEl.innerHTML = `<table>

            <thead><tr><th>Layer</th><th>Type</th><th>Material</th><th>Thickness (mil)</th><th>Details</th></tr></thead>

            <tbody>${data.layers.map(l => `<tr>

                <td><strong>${l.name}</strong></td>

                <td>${l.type}</td>

                <td>${l.material}</td>

                <td>${l.thickness_mil}</td>

                <td>${l.type === 'dielectric'

                    ? `Ξ΅r=${l.er}, ${l.capacitance_pf_per_sq_in} pF/inΒ²`

                    : l.sheet_resistance_mohm_sq ? `${l.sheet_resistance_mohm_sq} mΞ©/β–‘` : (l.net || '')

                }</td>

            </tr>`).join('')}</tbody>

        </table>`;

        // Signal routing references
        refsEl.innerHTML = `<h3 style="color:var(--accent);margin-bottom:0.5rem;font-size:1rem;">Signal Layer Reference Planes</h3>

        <table>

            <thead><tr><th>Signal Layer</th><th>Ref Above</th><th>Dist Above (mil)</th><th>Ref Below</th><th>Dist Below (mil)</th><th>Routing Type</th></tr></thead>

            <tbody>${data.signal_layers.map(s => `<tr>

                <td><strong>${s.layer}</strong></td>

                <td>${s.ref_above || 'β€”'}</td>

                <td>${s.dist_to_ref_above_mil || 'β€”'}</td>

                <td>${s.ref_below || 'β€”'}</td>

                <td>${s.dist_to_ref_below_mil || 'β€”'}</td>

                <td><span class="badge ${s.routing_type === 'stripline' ? 'pass' : 'warn'}">${s.routing_type}</span></td>

            </tr>`).join('')}</tbody>

        </table>`;
    } catch (e) {
        statsEl.innerHTML = `<div class="stat-card"><div class="value red">${e.message}</div></div>`;
    }
});

function drawStackup(layers) {
    const canvas = document.getElementById('stackup-visual');
    const ctx = canvas.getContext('2d');
    const W = canvas.width = canvas.parentElement.clientWidth - 32;
    const H = canvas.height = Math.max(420, layers.length * 45 + 80);
    ctx.clearRect(0, 0, W, H);

    const pad = { l: 140, r: 40, t: 40, b: 30 };
    const cw = W - pad.l - pad.r;
    const totalMil = layers.reduce((s, l) => s + l.thickness_mil, 0);
    const minH = 18;
    let y = pad.t;

    ctx.fillStyle = COLORS.white;
    ctx.font = 'bold 13px Segoe UI';
    ctx.textAlign = 'center';
    ctx.fillText('PCB Cross-Section (5-Layer Stackup)', W / 2, 22);

    layers.forEach(l => {
        const h = Math.max(minH, (l.thickness_mil / totalMil) * (H - pad.t - pad.b) * 0.9);

        let color;
        if (l.type === 'signal') color = '#d4a056';
        else if (l.type === 'plane') color = '#c06030';
        else color = l.material.includes('Prepreg') ? '#3a6040' : '#2a5050';

        // Layer rectangle
        ctx.fillStyle = color;
        ctx.fillRect(pad.l, y, cw, h);
        ctx.strokeStyle = '#0b0f19';
        ctx.lineWidth = 1;
        ctx.strokeRect(pad.l, y, cw, h);

        // Pattern for copper layers
        if (l.type === 'signal' || l.type === 'plane') {
            ctx.save();
            ctx.globalAlpha = 0.3;
            ctx.strokeStyle = '#fff';
            ctx.lineWidth = 0.5;
            for (let px = pad.l + 8; px < pad.l + cw; px += 14) {
                ctx.beginPath(); ctx.moveTo(px, y + 2); ctx.lineTo(px, y + h - 2); ctx.stroke();
            }
            ctx.restore();
        }

        // Label left
        ctx.fillStyle = COLORS.white;
        ctx.font = '11px Segoe UI';
        ctx.textAlign = 'right';
        ctx.fillText(l.name, pad.l - 8, y + h / 2 + 4);

        // Thickness right
        ctx.fillStyle = COLORS.text;
        ctx.textAlign = 'left';
        ctx.fillText(`${l.thickness_mil} mil`, pad.l + cw + 6, y + h / 2 + 4);

        y += h + 2;
    });
}


// ═══════════════════════════════════════════════════════════════════════════
// IMPEDANCE TAB
// ═══════════════════════════════════════════════════════════════════════════

document.getElementById('imp-run').addEventListener('click', async () => {
    const statsEl = document.getElementById('imp-stats');
    const tableEl = document.getElementById('imp-table');
    loading(statsEl); tableEl.innerHTML = '';

    try {
        const data = await api('/api/impedance', {
            trace_type: document.getElementById('imp-type').value,
            trace_width_mil: parseFloat(document.getElementById('imp-width').value),
            trace_spacing_mil: parseFloat(document.getElementById('imp-spacing').value),
            dielectric_thickness_mil: parseFloat(document.getElementById('imp-height').value),
            copper_thickness_oz: parseFloat(document.getElementById('imp-copper').value),
            er: parseFloat(document.getElementById('imp-er').value),
            frequency_ghz: parseFloat(document.getElementById('imp-freq').value),
        });

        let stats = `

            <div class="stat-card"><div class="label">Single-Ended Zβ‚€</div><div class="value accent">${data.single_ended_impedance_ohm} Ξ©</div></div>

            <div class="stat-card"><div class="label">Effective Ξ΅r</div><div class="value cyan">${data.effective_er}</div></div>

            <div class="stat-card"><div class="label">Prop. Delay</div><div class="value teal">${data.propagation_delay_ps_per_inch} ps/in</div></div>

            <div class="stat-card"><div class="label">Velocity</div><div class="value green">${data.velocity_mm_per_ns} mm/ns</div></div>

            <div class="stat-card"><div class="label">Skin Depth</div><div class="value orange">${data.skin_depth_um} Β΅m</div></div>

            <div class="stat-card"><div class="label">Total Loss</div><div class="value red">${data.total_loss_db_per_inch} dB/in</div></div>

        `;
        if (data.differential_impedance_ohm) {
            stats += `<div class="stat-card"><div class="label">Differential Z</div><div class="value pink">${data.differential_impedance_ohm} Ξ©</div></div>`;
            stats += `<div class="stat-card"><div class="label">Coupling Factor</div><div class="value accent2">${data.coupling_factor_k}</div></div>`;
        }
        statsEl.innerHTML = stats;

        // Draw loss vs frequency chart
        drawImpedanceChart(data.frequency_sweep);

        // Frequency sweep table
        tableEl.innerHTML = `<table>

            <thead><tr><th>Frequency</th><th>Skin Depth (Β΅m)</th><th>Conductor Loss (dB/in)</th><th>Dielectric Loss (dB/in)</th><th>Total Loss (dB/in)</th></tr></thead>

            <tbody>${data.frequency_sweep.map(s => `<tr>

                <td>${s.freq_ghz} GHz</td>

                <td>${s.skin_depth_um}</td>

                <td>${s.conductor_loss_db_in}</td>

                <td>${s.dielectric_loss_db_in}</td>

                <td><strong>${s.total_loss_db_in}</strong></td>

            </tr>`).join('')}</tbody>

        </table>`;
    } catch (e) {
        statsEl.innerHTML = `<div class="stat-card"><div class="value red">${e.message}</div></div>`;
    }
});

function drawImpedanceChart(sweep) {
    const canvas = document.getElementById('imp-chart');
    const ctx = canvas.getContext('2d');
    const W = canvas.width = canvas.parentElement.clientWidth - 32;
    const H = canvas.height = 350;
    ctx.clearRect(0, 0, W, H);

    const pad = { t: 35, r: 30, b: 50, l: 60 };
    const cw = W - pad.l - pad.r;
    const ch = H - pad.t - pad.b;
    const maxLoss = Math.max(...sweep.map(s => s.total_loss_db_in), 0.1) * 1.2;

    // Grid
    for (let i = 0; i <= 5; i++) {
        const y = pad.t + ch * (1 - i / 5);
        const val = (maxLoss * i / 5).toFixed(2);
        ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
        ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
        ctx.fillStyle = COLORS.text; ctx.font = '11px Segoe UI'; ctx.textAlign = 'right';
        ctx.fillText(val, pad.l - 6, y + 4);
    }

    // X labels
    ctx.textAlign = 'center';
    sweep.forEach((s, i) => {
        const x = pad.l + (i / (sweep.length - 1)) * cw;
        ctx.fillStyle = COLORS.text; ctx.fillText(s.freq_ghz + ' GHz', x, H - pad.b + 18);
    });

    // Lines
    const datasets = [
        { key: 'conductor_loss_db_in', color: COLORS.orange, label: 'Conductor' },
        { key: 'dielectric_loss_db_in', color: COLORS.cyan, label: 'Dielectric' },
        { key: 'total_loss_db_in', color: COLORS.red, label: 'Total' },
    ];

    datasets.forEach(ds => {
        ctx.beginPath();
        ctx.strokeStyle = ds.color;
        ctx.lineWidth = ds.key === 'total_loss_db_in' ? 2.5 : 1.5;
        sweep.forEach((s, i) => {
            const x = pad.l + (i / (sweep.length - 1)) * cw;
            const y = pad.t + ch * (1 - s[ds.key] / maxLoss);
            if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
        });
        ctx.stroke();
    });

    // Legend
    let lx = pad.l + 10;
    datasets.forEach(ds => {
        ctx.fillStyle = ds.color;
        ctx.fillRect(lx, pad.t + 5, 16, 3);
        ctx.fillStyle = COLORS.text;
        ctx.font = '11px Segoe UI'; ctx.textAlign = 'left';
        ctx.fillText(ds.label, lx + 20, pad.t + 12);
        lx += 100;
    });

    ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
    ctx.fillText('Loss vs Frequency (dB/inch)', pad.l, pad.t - 10);
}


// ═══════════════════════════════════════════════════════════════════════════
// SIGNAL INTEGRITY TAB
// ═══════════════════════════════════════════════════════════════════════════

(async function initSI() {
    try {
        const res = await fetch('/api/interfaces');
        const data = await res.json();
        const sel = document.getElementById('si-iface');
        sel.innerHTML = Object.keys(data.interfaces).map(k =>
            `<option value="${k}" ${k === 'PCIe-5.0' ? 'selected' : ''}>${k} (${data.interfaces[k].data_rate_gbps} Gbps)</option>`
        ).join('');
    } catch (e) {}
})();

document.getElementById('si-run').addEventListener('click', async () => {
    const statsEl = document.getElementById('si-stats');
    const checksEl = document.getElementById('si-checks');
    loading(statsEl); checksEl.innerHTML = '';

    try {
        const data = await api('/api/signal-integrity', {
            interface: document.getElementById('si-iface').value,
            trace_length_mm: parseFloat(document.getElementById('si-length').value),
            trace_width_mil: parseFloat(document.getElementById('si-width').value),
            layer: document.getElementById('si-layer').value,
            via_count: parseInt(document.getElementById('si-vias').value),
            er: parseFloat(document.getElementById('si-er').value),
            loss_tangent: parseFloat(document.getElementById('si-loss').value),
        });

        if (data.error) {
            statsEl.innerHTML = `<div class="stat-card"><div class="value red">${data.error}</div></div>`;
            return;
        }

        statsEl.innerHTML = `

            <div class="stat-card"><div class="label">Interface</div><div class="value accent">${data.interface}</div></div>

            <div class="stat-card"><div class="label">Data Rate</div><div class="value cyan">${data.interface_info.data_rate_gbps} Gbps</div></div>

            <div class="stat-card"><div class="label">Prop. Delay</div><div class="value teal">${data.propagation_delay_ns} ns</div></div>

            <div class="stat-card"><div class="label">Total IL</div><div class="value ${data.total_insertion_loss_db < 10 ? 'green' : 'red'}">${data.total_insertion_loss_db} dB</div></div>

            <div class="stat-card"><div class="label">Eye Height</div><div class="value ${data.eye_height_pct > 50 ? 'green' : 'orange'}">${data.eye_height_pct}%</div></div>

            <div class="stat-card"><div class="label">Eye Width</div><div class="value ${data.eye_width_pct > 50 ? 'green' : 'orange'}">${data.eye_width_pct}%</div></div>

            <div class="stat-card"><div class="label">Bit Period</div><div class="value accent">${data.bit_period_ps} ps</div></div>

            <div class="stat-card"><div class="label">Ξ» @ Nyquist</div><div class="value pink">${data.wavelength_at_nyquist_mm} mm</div></div>

        `;

        // Eye diagram
        drawEyeDiagram(data);

        // Loss breakdown chart
        drawSILossChart(data.loss_breakdown);

        // Design checks
        checksEl.innerHTML = data.design_checks.map(c => `

            <div class="step-card ${c.pass ? 'pass' : 'fail'}">

                <div class="step-header">${c.pass ? 'βœ“' : 'βœ—'} ${c.check}</div>

                <div class="step-detail">Value: <span>${c.value}</span> Β· Limit: <span>${c.limit}</span></div>

            </div>

        `).join('');

        // Skew info
        checksEl.innerHTML += `

            <div class="step-card" style="border-left-color:var(--accent)">

                <div class="step-header" style="color:var(--accent)">Length Matching</div>

                <div class="step-detail">Tolerance: <span>Β±${data.length_match_tolerance_mil} mil</span> Β· Skew budget: <span>${data.skew_budget_ps} ps</span></div>

            </div>

        `;
    } catch (e) {
        statsEl.innerHTML = `<div class="stat-card"><div class="value red">${e.message}</div></div>`;
    }
});

function drawEyeDiagram(data) {
    const canvas = document.getElementById('si-eye-chart');
    const ctx = canvas.getContext('2d');
    const W = canvas.width = canvas.parentElement.clientWidth - 32;
    const H = canvas.height = 300;
    ctx.clearRect(0, 0, W, H);

    const pad = { t: 35, r: 20, b: 30, l: 20 };
    const cw = W - pad.l - pad.r;
    const ch = H - pad.t - pad.b;
    const cx = pad.l + cw / 2;
    const cy = pad.t + ch / 2;

    ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'center';
    ctx.fillText('Eye Diagram (Estimated)', W / 2, 18);

    // Background
    ctx.fillStyle = '#0d1525';
    ctx.fillRect(pad.l, pad.t, cw, ch);

    const eyeH = (data.eye_height_pct / 100) * ch * 0.4;
    const eyeW = (data.eye_width_pct / 100) * cw * 0.35;
    const jitter = (100 - data.eye_width_pct) / 100 * 0.3;
    const noise = (100 - data.eye_height_pct) / 100 * 0.5;

    // Draw many overlapping traces to form eye pattern
    ctx.globalAlpha = 0.08;
    ctx.strokeStyle = COLORS.green;
    ctx.lineWidth = 1.5;

    for (let trace = 0; trace < 120; trace++) {
        ctx.beginPath();
        const jitterOff = (Math.random() - 0.5) * jitter * cw * 0.3;
        const noiseOff = (Math.random() - 0.5) * noise * ch * 0.3;
        const bits = [Math.random() > 0.5 ? 1 : 0, Math.random() > 0.5 ? 1 : 0, Math.random() > 0.5 ? 1 : 0];

        for (let bi = 0; bi < 3; bi++) {
            const xStart = pad.l + (bi / 3) * cw + jitterOff;
            const xEnd = pad.l + ((bi + 1) / 3) * cw + jitterOff;
            const yLow = cy + ch * 0.35 + noiseOff;
            const yHigh = cy - ch * 0.35 + noiseOff;
            const yVal = bits[bi] ? yHigh : yLow;

            if (bi === 0) {
                ctx.moveTo(xStart, yVal);
            }

            // Transition
            const nextY = bi < 2 ? (bits[bi + 1] ? yHigh : yLow) : yVal;
            const rise = cw * 0.03;
            ctx.lineTo(xEnd - rise, yVal);
            ctx.lineTo(xEnd + rise, nextY);
        }
        ctx.stroke();
    }
    ctx.globalAlpha = 1.0;

    // Eye opening rectangle
    ctx.strokeStyle = COLORS.accent;
    ctx.lineWidth = 2;
    ctx.setLineDash([4, 4]);
    ctx.strokeRect(cx - eyeW, cy - eyeH, eyeW * 2, eyeH * 2);
    ctx.setLineDash([]);

    // Labels
    ctx.fillStyle = COLORS.accent;
    ctx.font = '11px Segoe UI';
    ctx.textAlign = 'center';
    ctx.fillText(`Eye Height: ${data.eye_height_pct}%`, cx, cy + eyeH + 16);
    ctx.fillText(`Eye Width: ${data.eye_width_pct}%`, cx, cy - eyeH - 8);
}

function drawSILossChart(losses) {
    const canvas = document.getElementById('si-loss-chart');
    const ctx = canvas.getContext('2d');
    const W = canvas.width = canvas.parentElement.clientWidth - 32;
    const H = canvas.height = 300;
    ctx.clearRect(0, 0, W, H);

    const pad = { t: 35, r: 20, b: 55, l: 55 };
    const cw = W - pad.l - pad.r;
    const ch = H - pad.t - pad.b;
    const maxLoss = Math.max(...losses.map(l => l.total_loss_db), 1) * 1.3;
    const barW = Math.min(50, cw / (losses.length * 4));

    ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
    ctx.fillText('Loss Breakdown by Frequency', pad.l, 18);

    // Grid
    for (let i = 0; i <= 4; i++) {
        const y = pad.t + ch * (1 - i / 4);
        ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
        ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
        ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'right';
        ctx.fillText((maxLoss * i / 4).toFixed(1) + ' dB', pad.l - 6, y + 4);
    }

    const catColors = [COLORS.orange, COLORS.cyan, COLORS.pink];
    const catKeys = ['conductor_loss_db', 'dielectric_loss_db', 'via_loss_db'];
    const catLabels = ['Conductor', 'Dielectric', 'Via'];

    losses.forEach((l, li) => {
        const cx = pad.l + (li + 0.5) * (cw / losses.length);
        let yBase = pad.t + ch;

        catKeys.forEach((key, ki) => {
            const val = l[key];
            const h = (val / maxLoss) * ch;
            ctx.fillStyle = catColors[ki];
            ctx.fillRect(cx - barW / 2, yBase - h, barW, h);
            yBase -= h;
        });

        // Label
        ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'center';
        ctx.fillText(l.label, cx, H - pad.b + 16);
        ctx.fillText(l.frequency_ghz + ' GHz', cx, H - pad.b + 30);
    });

    // Legend
    let lx = pad.l + cw - 220;
    catLabels.forEach((label, i) => {
        ctx.fillStyle = catColors[i]; ctx.fillRect(lx, pad.t + 4, 12, 10);
        ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'left';
        ctx.fillText(label, lx + 16, pad.t + 13);
        lx += 72;
    });
}


// ═══════════════════════════════════════════════════════════════════════════
// PDN TAB
// ═══════════════════════════════════════════════════════════════════════════

(async function initPDN() {
    try {
        const res = await fetch('/api/power-rails');
        const data = await res.json();
        const sel = document.getElementById('pdn-rail');
        sel.innerHTML = data.rails.map(r =>
            `<option value="${r.name}" ${r.name === 'VCORE' ? 'selected' : ''}>${r.name} (${r.voltage}V β€” ${r.description})</option>`
        ).join('');
    } catch (e) {}
})();

document.getElementById('pdn-run').addEventListener('click', async () => {
    const statsEl = document.getElementById('pdn-stats');
    loading(statsEl);

    try {
        const data = await api('/api/pdn', {
            rail: document.getElementById('pdn-rail').value,
            load_current_a: parseFloat(document.getElementById('pdn-current').value),
            plane_area_sq_in: parseFloat(document.getElementById('pdn-area').value),
            decap_count: parseInt(document.getElementById('pdn-decap-n').value),
            decap_value_uf: parseFloat(document.getElementById('pdn-decap-v').value),
            bulk_cap_count: parseInt(document.getElementById('pdn-bulk-n').value),
            bulk_cap_uf: parseFloat(document.getElementById('pdn-bulk-v').value),
        });

        if (data.error) {
            statsEl.innerHTML = `<div class="stat-card"><div class="value red">${data.error}</div></div>`;
            return;
        }

        const vc = data.verdict === 'PASS' ? 'green' : (data.verdict === 'MARGINAL' ? 'orange' : 'red');
        statsEl.innerHTML = `

            <div class="stat-card"><div class="label">Rail</div><div class="value accent">${data.rail}</div></div>

            <div class="stat-card"><div class="label">Target Z</div><div class="value cyan">${data.target_impedance_mohm.toFixed(2)} mΞ©</div></div>

            <div class="stat-card"><div class="label">Plane Cap</div><div class="value teal">${data.plane_capacitance_nf} nF</div></div>

            <div class="stat-card"><div class="label">DC Drop</div><div class="value orange">${data.dc_voltage_drop_mv} mV</div></div>

            <div class="stat-card"><div class="label">Violations</div><div class="value ${data.target_violations > 10 ? 'red' : 'green'}">${data.target_violations}/${data.total_freq_points}</div></div>

            <div class="stat-card"><div class="label">Verdict</div><div class="value ${vc}">${data.verdict}</div></div>

        `;

        drawPDNChart(data);
    } catch (e) {
        statsEl.innerHTML = `<div class="stat-card"><div class="value red">${e.message}</div></div>`;
    }
});

function drawPDNChart(data) {
    const canvas = document.getElementById('pdn-chart');
    const ctx = canvas.getContext('2d');
    const W = canvas.width = canvas.parentElement.clientWidth - 32;
    const H = canvas.height = 380;
    ctx.clearRect(0, 0, W, H);

    const pad = { t: 35, r: 30, b: 55, l: 70 };
    const cw = W - pad.l - pad.r;
    const ch = H - pad.t - pad.b;
    const profile = data.impedance_profile;

    // Log scale for Y (impedance) and X (frequency)
    const zValues = profile.map(p => p.z_magnitude_mohm);
    const minZ = Math.max(0.01, Math.min(...zValues) * 0.5);
    const maxZ = Math.max(...zValues) * 2;
    const logMinZ = Math.log10(minZ);
    const logMaxZ = Math.log10(maxZ);

    const freqs = profile.map(p => p.freq_hz);
    const logMinF = Math.log10(freqs[0]);
    const logMaxF = Math.log10(freqs[freqs.length - 1]);

    function xPos(f) { return pad.l + ((Math.log10(f) - logMinF) / (logMaxF - logMinF)) * cw; }
    function yPos(z) { return pad.t + ch * (1 - (Math.log10(Math.max(z, minZ)) - logMinZ) / (logMaxZ - logMinZ)); }

    // Grid
    ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
    ctx.font = '10px Segoe UI'; ctx.fillStyle = COLORS.text;

    // Y grid (log)
    for (let exp = Math.floor(logMinZ); exp <= Math.ceil(logMaxZ); exp++) {
        const z = Math.pow(10, exp);
        if (z < minZ || z > maxZ) continue;
        const y = yPos(z);
        ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
        ctx.textAlign = 'right';
        ctx.fillText(z >= 1 ? z.toFixed(0) + ' mΞ©' : z.toFixed(2) + ' mΞ©', pad.l - 4, y + 4);
    }

    // X grid (log freq)
    const freqLabels = [1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10];
    const freqNames = ['1kHz', '10kHz', '100kHz', '1MHz', '10MHz', '100MHz', '1GHz', '10GHz'];
    ctx.textAlign = 'center';
    freqLabels.forEach((f, i) => {
        if (f < freqs[0] || f > freqs[freqs.length - 1]) return;
        const x = xPos(f);
        ctx.beginPath(); ctx.moveTo(x, pad.t); ctx.lineTo(x, pad.t + ch); ctx.stroke();
        ctx.fillText(freqNames[i], x, H - pad.b + 18);
    });

    // Target impedance line
    ctx.strokeStyle = COLORS.red;
    ctx.lineWidth = 2;
    ctx.setLineDash([6, 4]);
    const yTarget = yPos(data.target_impedance_mohm);
    ctx.beginPath(); ctx.moveTo(pad.l, yTarget); ctx.lineTo(pad.l + cw, yTarget); ctx.stroke();
    ctx.setLineDash([]);
    ctx.fillStyle = COLORS.red; ctx.font = '11px Segoe UI'; ctx.textAlign = 'left';
    ctx.fillText(`Z_target = ${data.target_impedance_mohm.toFixed(2)} mΞ©`, pad.l + 5, yTarget - 8);

    // PDN impedance curve
    ctx.beginPath();
    ctx.strokeStyle = COLORS.accent;
    ctx.lineWidth = 2.5;
    profile.forEach((p, i) => {
        const x = xPos(p.freq_hz);
        const y = yPos(p.z_magnitude_mohm);
        if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
    });
    ctx.stroke();

    // Fill violations
    ctx.globalAlpha = 0.12;
    profile.forEach((p, i) => {
        if (!p.meets_target && i > 0) {
            const x = xPos(p.freq_hz);
            const y = yPos(p.z_magnitude_mohm);
            ctx.fillStyle = COLORS.red;
            ctx.fillRect(x - 3, Math.min(y, yTarget), 6, Math.abs(y - yTarget));
        }
    });
    ctx.globalAlpha = 1.0;

    ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
    ctx.fillText('PDN Impedance Profile (log-log)', pad.l, pad.t - 10);

    // Legend
    ctx.fillStyle = COLORS.accent; ctx.fillRect(W - pad.r - 160, pad.t + 5, 14, 3);
    ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI';
    ctx.fillText('Z_PDN', W - pad.r - 142, pad.t + 12);
    ctx.fillStyle = COLORS.red; ctx.fillRect(W - pad.r - 80, pad.t + 5, 14, 3);
    ctx.fillText('Z_target', W - pad.r - 62, pad.t + 12);
}


// ═══════════════════════════════════════════════════════════════════════════
// THERMAL TAB
// ═══════════════════════════════════════════════════════════════════════════

const thCopper = document.getElementById('th-copper');
const thCopperVal = document.getElementById('th-copper-val');
thCopper.addEventListener('input', () => { thCopperVal.textContent = thCopper.value + '%'; });

document.getElementById('th-run').addEventListener('click', async () => {
    const statsEl = document.getElementById('th-stats');
    const resEl = document.getElementById('th-resistances');
    loading(statsEl); resEl.innerHTML = '';

    try {
        const data = await api('/api/thermal', {
            cpu_tdp_w: parseFloat(document.getElementById('th-tdp').value),
            board_area_sq_in: parseFloat(document.getElementById('th-area').value),
            ambient_temp_c: parseFloat(document.getElementById('th-ambient').value),
            copper_coverage_pct: parseFloat(thCopper.value),
            airflow_lfm: parseFloat(document.getElementById('th-airflow').value),
            heatsink: document.getElementById('th-heatsink').value === 'true',
        });

        const tjC = data.tj_max_verdict === 'SAFE' ? 'green' : (data.tj_max_verdict === 'WARNING' ? 'orange' : 'red');
        const vrmC = data.vrm_verdict === 'SAFE' ? 'green' : (data.vrm_verdict === 'WARNING' ? 'orange' : 'red');

        statsEl.innerHTML = `

            <div class="stat-card"><div class="label">Junction Temp</div><div class="value ${tjC}">${data.junction_temp_c}Β°C</div></div>

            <div class="stat-card"><div class="label">Board Under CPU</div><div class="value orange">${data.board_temp_under_cpu_c}Β°C</div></div>

            <div class="stat-card"><div class="label">Board Average</div><div class="value teal">${data.board_avg_temp_c}Β°C</div></div>

            <div class="stat-card"><div class="label">VRM Surface</div><div class="value ${vrmC}">${data.vrm_surface_temp_c}Β°C</div></div>

            <div class="stat-card"><div class="label">Thermal Vias</div><div class="value cyan">${data.thermal_vias_under_cpu}</div></div>

            <div class="stat-card"><div class="label">k Lateral</div><div class="value accent">${data.effective_k_lateral_w_mk} W/mK</div></div>

        `;

        drawThermalHeatmap(data);
        drawThermalBar(data);

        resEl.innerHTML = `<h3 style="color:var(--accent);margin-bottom:0.5rem;font-size:0.95rem;">Thermal Resistances</h3>

        <table>

            <thead><tr><th>Parameter</th><th>Value</th></tr></thead>

            <tbody>

                <tr><td>R_junction-case</td><td>${data.r_junction_case} Β°C/W</td></tr>

                <tr><td>R_case-sink</td><td>${data.r_case_sink} Β°C/W</td></tr>

                <tr><td>R_sink-ambient</td><td>${data.r_sink_ambient} Β°C/W</td></tr>

                <tr><td>R_PCB through</td><td>${data.r_pcb_through} Β°C/W</td></tr>

                <tr><td>Convection h</td><td>${data.convection_coeff_w_m2k} W/(mΒ²Β·K)</td></tr>

                <tr><td>k_through-plane</td><td>${data.effective_k_through_w_mk} W/(mΒ·K)</td></tr>

            </tbody>

        </table>`;
    } catch (e) {
        statsEl.innerHTML = `<div class="stat-card"><div class="value red">${e.message}</div></div>`;
    }
});

function drawThermalHeatmap(data) {
    const canvas = document.getElementById('th-heatmap');
    const ctx = canvas.getContext('2d');
    const W = canvas.width = canvas.parentElement.clientWidth - 32;
    const H = canvas.height = W;  // Square
    ctx.clearRect(0, 0, W, H);

    const map = data.thermal_map;
    const rows = map.length;
    const cols = map[0].length;
    const pad = 40;
    const cellW = (W - pad * 2) / cols;
    const cellH = (H - pad * 2) / rows;

    // Find min/max temps
    let minT = Infinity, maxT = -Infinity;
    map.forEach(row => row.forEach(t => { minT = Math.min(minT, t); maxT = Math.max(maxT, t); }));
    const range = maxT - minT || 1;

    ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'center';
    ctx.fillText('Board Temperature Distribution (Β°C)', W / 2, 18);

    // Draw cells
    map.forEach((row, ri) => {
        row.forEach((temp, ci) => {
            const x = pad + ci * cellW;
            const y = pad + ri * cellH;
            const norm = (temp - minT) / range;

            // Blue β†’ Green β†’ Yellow β†’ Red
            let r, g, b;
            if (norm < 0.33) {
                const t = norm / 0.33;
                r = Math.round(30 + t * 30); g = Math.round(60 + t * 140); b = Math.round(200 - t * 80);
            } else if (norm < 0.66) {
                const t = (norm - 0.33) / 0.33;
                r = Math.round(60 + t * 195); g = Math.round(200 - t * 20); b = Math.round(120 - t * 100);
            } else {
                const t = (norm - 0.66) / 0.34;
                r = Math.round(255); g = Math.round(180 - t * 130); b = Math.round(20 - t * 20);
            }

            ctx.fillStyle = `rgb(${r},${g},${b})`;
            ctx.fillRect(x, y, cellW + 0.5, cellH + 0.5);

            // Temperature label for select cells
            if (ri % 3 === 1 && ci % 3 === 1) {
                ctx.fillStyle = norm > 0.5 ? '#000' : '#fff';
                ctx.font = '9px Segoe UI';
                ctx.textAlign = 'center';
                ctx.fillText(temp.toFixed(0) + 'Β°', x + cellW / 2, y + cellH / 2 + 3);
            }
        });
    });

    // CPU label at center
    const cpuX = pad + (cols / 2 - 1) * cellW;
    const cpuY = pad + (rows / 2 - 1) * cellH;
    ctx.strokeStyle = '#fff';
    ctx.lineWidth = 2;
    ctx.strokeRect(cpuX, cpuY, cellW * 3, cellH * 3);
    ctx.fillStyle = '#fff'; ctx.font = 'bold 10px Segoe UI'; ctx.textAlign = 'center';
    ctx.fillText('CPU', cpuX + cellW * 1.5, cpuY + cellH * 1.5 + 4);

    // VRM label
    ctx.fillStyle = '#fff'; ctx.font = '9px Segoe UI';
    ctx.fillText('VRM', pad + cellW * 1.5, pad + cellH * 1.5 + 4);

    // Color scale
    const scaleW = 15;
    const scaleH = H - pad * 2;
    const scaleX = W - pad + 5;
    for (let i = 0; i < scaleH; i++) {
        const norm = 1 - i / scaleH;
        let r, g, b;
        if (norm < 0.33) { const t = norm / 0.33; r = Math.round(30 + t * 30); g = Math.round(60 + t * 140); b = Math.round(200 - t * 80); }
        else if (norm < 0.66) { const t = (norm - 0.33) / 0.33; r = Math.round(60 + t * 195); g = Math.round(200 - t * 20); b = Math.round(120 - t * 100); }
        else { const t = (norm - 0.66) / 0.34; r = 255; g = Math.round(180 - t * 130); b = Math.round(20 - t * 20); }
        ctx.fillStyle = `rgb(${r},${g},${b})`;
        ctx.fillRect(scaleX, pad + i, scaleW, 1);
    }
    ctx.fillStyle = COLORS.text; ctx.font = '9px Segoe UI'; ctx.textAlign = 'left';
    ctx.fillText(maxT.toFixed(0) + 'Β°C', scaleX + scaleW + 3, pad + 8);
    ctx.fillText(minT.toFixed(0) + 'Β°C', scaleX + scaleW + 3, H - pad + 4);
}

function drawThermalBar(data) {
    const canvas = document.getElementById('th-bar-chart');
    const ctx = canvas.getContext('2d');
    const W = canvas.width = canvas.parentElement.clientWidth - 32;
    const H = canvas.height = 280;
    ctx.clearRect(0, 0, W, H);

    const pad = { t: 35, r: 20, b: 55, l: 55 };
    const cw = W - pad.l - pad.r;
    const ch = H - pad.t - pad.b;

    const temps = [
        { label: 'Junction', val: data.junction_temp_c, color: COLORS.red },
        { label: 'VRM', val: data.vrm_surface_temp_c, color: COLORS.orange },
        { label: 'Under CPU', val: data.board_temp_under_cpu_c, color: COLORS.yellow },
        { label: 'Board Avg', val: data.board_avg_temp_c, color: COLORS.green },
        { label: 'Ambient', val: data.ambient_temp_c, color: COLORS.accent },
    ];

    const maxT = Math.max(...temps.map(t => t.val), 105) * 1.1;
    const barW = Math.min(50, cw / (temps.length * 2));

    ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
    ctx.fillText('Temperature Comparison (Β°C)', pad.l, 18);

    // Grid
    for (let i = 0; i <= 5; i++) {
        const y = pad.t + ch * (1 - i / 5);
        ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
        ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
        ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'right';
        ctx.fillText(Math.round(maxT * i / 5) + 'Β°C', pad.l - 4, y + 4);
    }

    // Tj_max line at 100Β°C
    const y100 = pad.t + ch * (1 - 100 / maxT);
    ctx.strokeStyle = COLORS.red; ctx.lineWidth = 1.5; ctx.setLineDash([5, 4]);
    ctx.beginPath(); ctx.moveTo(pad.l, y100); ctx.lineTo(pad.l + cw, y100); ctx.stroke();
    ctx.setLineDash([]);
    ctx.fillStyle = COLORS.red; ctx.font = '9px Segoe UI'; ctx.textAlign = 'right';
    ctx.fillText('T_j max = 100Β°C', pad.l + cw, y100 - 5);

    temps.forEach((t, i) => {
        const cx = pad.l + (i + 0.5) * (cw / temps.length);
        const h = (t.val / maxT) * ch;
        const grad = ctx.createLinearGradient(0, pad.t + ch - h, 0, pad.t + ch);
        grad.addColorStop(0, t.color);
        grad.addColorStop(1, t.color + '44');
        ctx.fillStyle = grad;
        ctx.fillRect(cx - barW / 2, pad.t + ch - h, barW, h);

        ctx.fillStyle = COLORS.white; ctx.font = 'bold 11px Segoe UI'; ctx.textAlign = 'center';
        ctx.fillText(t.val.toFixed(0) + 'Β°', cx, pad.t + ch - h - 6);

        ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI';
        ctx.fillText(t.label, cx, H - pad.b + 18);
    });
}


// ═══════════════════════════════════════════════════════════════════════════
// CROSSTALK TAB
// ═══════════════════════════════════════════════════════════════════════════

document.getElementById('xt-run').addEventListener('click', async () => {
    const statsEl = document.getElementById('xt-stats');
    const recEl = document.getElementById('xt-recommendation');
    loading(statsEl); recEl.innerHTML = '';

    try {
        const data = await api('/api/crosstalk', {
            trace_type: document.getElementById('xt-type').value,
            aggressor_width_mil: parseFloat(document.getElementById('xt-width').value),
            victim_width_mil: parseFloat(document.getElementById('xt-width').value),
            spacing_mil: parseFloat(document.getElementById('xt-spacing').value),
            parallel_length_mm: parseFloat(document.getElementById('xt-length').value),
            dielectric_height_mil: parseFloat(document.getElementById('xt-height').value),
            er: parseFloat(document.getElementById('xt-er').value),
            frequency_ghz: parseFloat(document.getElementById('xt-freq').value),
        });

        const nextC = data.next_db < -25 ? 'green' : (data.next_db < -15 ? 'orange' : 'red');
        const fextC = data.fext_db < -30 ? 'green' : (data.fext_db < -20 ? 'orange' : 'red');

        statsEl.innerHTML = `

            <div class="stat-card"><div class="label">NEXT</div><div class="value ${nextC}">${data.next_db} dB</div></div>

            <div class="stat-card"><div class="label">FEXT</div><div class="value ${fextC}">${data.fext_db} dB</div></div>

            <div class="stat-card"><div class="label">3W Rule</div><div class="value ${data.three_w_rule_met ? 'green' : 'red'}">${data.three_w_rule_met ? 'MET' : 'NOT MET'}</div></div>

            <div class="stat-card"><div class="label">Guard Trace Ξ”</div><div class="value teal">${data.guard_trace_reduction_db} dB</div></div>

            <div class="stat-card"><div class="label">Elec. Length</div><div class="value accent">${data.electrical_length_wavelengths}Ξ»</div></div>

        `;

        drawCrosstalkChart(data.spacing_sweep);

        recEl.innerHTML = `

            <div class="step-card ${data.next_db < -25 && data.fext_db < -30 ? 'pass' : 'warn'}">

                <div class="step-header">${data.next_db < -25 && data.fext_db < -30 ? 'βœ“ Acceptable Crosstalk' : '⚠ Crosstalk Advisory'}</div>

                <div class="step-detail">${data.recommendation}</div>

            </div>

        `;
    } catch (e) {
        statsEl.innerHTML = `<div class="stat-card"><div class="value red">${e.message}</div></div>`;
    }
});

function drawCrosstalkChart(sweep) {
    const canvas = document.getElementById('xt-chart');
    const ctx = canvas.getContext('2d');
    const W = canvas.width = canvas.parentElement.clientWidth - 32;
    const H = canvas.height = 350;
    ctx.clearRect(0, 0, W, H);

    const pad = { t: 35, r: 30, b: 50, l: 55 };
    const cw = W - pad.l - pad.r;
    const ch = H - pad.t - pad.b;

    const allVals = sweep.flatMap(s => [s.next_db, s.fext_db]);
    const minDB = Math.min(...allVals, -70);
    const maxDB = Math.max(...allVals, -5);
    const rangeDB = maxDB - minDB || 1;

    // Grid
    ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
    for (let i = 0; i <= 5; i++) {
        const y = pad.t + ch * (1 - i / 5);
        const val = Math.round(minDB + rangeDB * i / 5);
        ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
        ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'right';
        ctx.fillText(val + ' dB', pad.l - 4, y + 4);
    }

    // X labels
    ctx.textAlign = 'center';
    sweep.forEach((s, i) => {
        const x = pad.l + (i / (sweep.length - 1)) * cw;
        if (i % 2 === 0) {
            ctx.fillStyle = COLORS.text; ctx.fillText(s.spacing_mil + ' mil', x, H - pad.b + 16);
        }
    });

    // NEXT line
    ctx.beginPath(); ctx.strokeStyle = COLORS.orange; ctx.lineWidth = 2;
    sweep.forEach((s, i) => {
        const x = pad.l + (i / (sweep.length - 1)) * cw;
        const y = pad.t + ch * (1 - (s.next_db - minDB) / rangeDB);
        if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
    });
    ctx.stroke();

    // FEXT line
    ctx.beginPath(); ctx.strokeStyle = COLORS.cyan; ctx.lineWidth = 2;
    sweep.forEach((s, i) => {
        const x = pad.l + (i / (sweep.length - 1)) * cw;
        const y = pad.t + ch * (1 - (s.fext_db - minDB) / rangeDB);
        if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
    });
    ctx.stroke();

    // Legend
    ctx.fillStyle = COLORS.orange; ctx.fillRect(pad.l + 10, pad.t + 5, 16, 3);
    ctx.fillStyle = COLORS.text; ctx.font = '11px Segoe UI'; ctx.textAlign = 'left';
    ctx.fillText('NEXT', pad.l + 30, pad.t + 12);
    ctx.fillStyle = COLORS.cyan; ctx.fillRect(pad.l + 90, pad.t + 5, 16, 3);
    ctx.fillStyle = COLORS.text; ctx.fillText('FEXT', pad.l + 110, pad.t + 12);

    ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
    ctx.fillText('Crosstalk vs Trace Spacing', pad.l, pad.t - 10);

    ctx.fillStyle = COLORS.text; ctx.font = '11px Segoe UI'; ctx.textAlign = 'center';
    ctx.fillText('Trace Spacing (mil)', W / 2, H - 5);
}