File size: 63,169 Bytes
0b2295a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f02caca
 
 
0b2295a
f02caca
 
0b2295a
f02caca
 
0b2295a
f02caca
0b2295a
 
f02caca
 
 
0b2295a
f02caca
0b2295a
 
f02caca
 
0b2295a
f02caca
0b2295a
 
f02caca
 
 
 
 
 
 
0b2295a
 
f02caca
 
0b2295a
 
 
 
 
f02caca
0b2295a
 
f02caca
 
 
0b2295a
 
f02caca
 
0b2295a
 
 
f02caca
0b2295a
 
 
f02caca
 
 
0b2295a
 
f02caca
 
0b2295a
 
f02caca
 
 
 
 
 
 
 
 
 
 
0b2295a
 
 
f02caca
0b2295a
 
f02caca
 
 
0b2295a
 
f02caca
 
 
 
 
0b2295a
 
f02caca
 
 
 
0b2295a
 
 
 
f02caca
fd832fc
 
 
 
0b2295a
fd832fc
 
 
 
 
 
 
 
 
0b2295a
f02caca
 
 
0b2295a
 
f02caca
 
 
 
 
 
0b2295a
 
f02caca
 
 
 
 
0b2295a
 
f02caca
 
 
 
0b2295a
 
 
f02caca
 
0b2295a
 
 
f02caca
0b2295a
 
fd832fc
 
 
 
 
 
 
 
 
 
 
 
 
0b2295a
fd832fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b2295a
 
 
f02caca
fd832fc
 
 
 
0b2295a
fd832fc
 
 
 
 
 
 
 
 
0b2295a
f02caca
 
 
 
 
 
 
 
 
 
 
 
0b2295a
 
f02caca
 
 
 
 
0b2295a
 
f02caca
 
 
 
0b2295a
 
fd832fc
 
 
 
 
 
 
0b2295a
fd832fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b2295a
f02caca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b2295a
 
f02caca
0b2295a
f02caca
 
 
0b2295a
 
 
f02caca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b2295a
 
 
f02caca
 
 
 
0b2295a
f02caca
 
 
fd832fc
 
 
 
 
f02caca
0b2295a
f02caca
fd832fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b2295a
 
 
 
f02caca
0b2295a
 
 
f02caca
0b2295a
fd832fc
0b2295a
f02caca
0b2295a
fd832fc
0b2295a
 
 
 
fd832fc
0b2295a
 
 
fd832fc
 
 
 
 
 
0b2295a
 
 
fd832fc
 
 
 
 
 
f02caca
 
 
fd832fc
0b2295a
 
 
fd832fc
0b2295a
 
 
 
 
fd832fc
 
 
 
 
 
 
 
0b2295a
 
 
 
 
 
 
 
f02caca
0b2295a
fd832fc
 
 
 
0b2295a
 
 
 
 
fd832fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b2295a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
// Initialize the application when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', () => {
    console.log('Neural Network Playground Initialized');
    
    // Initialize the canvas and tooltip
    const canvas = document.getElementById('network-canvas');
    const tooltip = document.createElement('div');
    tooltip.className = 'canvas-tooltip';
    tooltip.innerHTML = `
        <div class="tooltip-header"></div>
        <div class="tooltip-content"></div>
    `;
    document.body.appendChild(tooltip);
    
    // Initialize drag and drop functionality
    initializeDragAndDrop();
    
    // Network configuration (from UI controls)
    let networkConfig = {
        learningRate: 0.01,
        activation: 'relu',
        batchSize: 32,
        epochs: 10
    };
    
    // Initialize UI controls
    setupUIControls();
    
    // Layer editor modal
    setupLayerEditor();
    
    // Listen for network updates
    document.addEventListener('networkUpdated', handleNetworkUpdate);
    
    // Listen for layer editor events
    document.addEventListener('openLayerEditor', handleOpenLayerEditor);
    
    // Setup UI controls and event listeners
    function setupUIControls() {
        // Learning rate slider
        const learningRateSlider = document.getElementById('learning-rate');
        const learningRateValue = document.getElementById('learning-rate-value');
        
        if (learningRateSlider && learningRateValue) {
            learningRateSlider.value = networkConfig.learningRate;
            learningRateValue.textContent = networkConfig.learningRate.toFixed(3);
            
            learningRateSlider.addEventListener('input', (e) => {
                networkConfig.learningRate = parseFloat(e.target.value);
                learningRateValue.textContent = networkConfig.learningRate.toFixed(3);
            });
        }
        
        // Activation function dropdown
        const activationSelect = document.getElementById('activation');
        if (activationSelect) {
            activationSelect.value = networkConfig.activation;
            
            activationSelect.addEventListener('change', (e) => {
                networkConfig.activation = e.target.value;
                updateActivationFunctionGraph(networkConfig.activation);
            });
        }
        
        // Initialize activation function graph
        updateActivationFunctionGraph(networkConfig.activation);
        
        // Sample data event handlers
        const sampleItems = document.querySelectorAll('.sample-item');
        sampleItems.forEach(item => {
            item.addEventListener('click', () => {
                const sampleId = item.getAttribute('data-sample');
                handleSampleSelection(sampleId);
            });
        });
        
        // Button event listeners
        const runButton = document.getElementById('run-network');
        if (runButton) {
            runButton.addEventListener('click', runNetwork);
        }
        
        const clearButton = document.getElementById('clear-canvas');
        if (clearButton) {
            clearButton.addEventListener('click', clearCanvas);
        }
        
        // Modal handlers
        setupModals();
    }
    
    // Setup modal handlers
    function setupModals() {
        const aboutModal = document.getElementById('about-modal');
        const aboutLink = document.getElementById('about-link');
        
        if (aboutLink && aboutModal) {
            aboutLink.addEventListener('click', (e) => {
                e.preventDefault();
                openModal(aboutModal);
            });
            
            const closeButtons = aboutModal.querySelectorAll('.close-modal');
            closeButtons.forEach(btn => {
                btn.addEventListener('click', () => {
                    closeModal(aboutModal);
                });
            });
            
            // Close modal when clicking outside
            aboutModal.addEventListener('click', (e) => {
                if (e.target === aboutModal) {
                    closeModal(aboutModal);
                }
            });
        }
    }
    
    // Setup layer editor modal
    function setupLayerEditor() {
        const layerEditorModal = document.getElementById('layer-editor-modal');
        
        if (layerEditorModal) {
            const closeButtons = layerEditorModal.querySelectorAll('.close-modal');
            closeButtons.forEach(btn => {
                btn.addEventListener('click', () => {
                    closeModal(layerEditorModal);
                });
            });
            
            // Close modal when clicking outside
            layerEditorModal.addEventListener('click', (e) => {
                if (e.target === layerEditorModal) {
                    closeModal(layerEditorModal);
                }
            });
            
            // Save button
            const saveButton = layerEditorModal.querySelector('.save-layer-btn');
            if (saveButton) {
                saveButton.addEventListener('click', saveLayerConfig);
            }
        }
    }
    
    // Open modal
    function openModal(modal) {
        if (modal) {
            modal.style.display = 'flex';
        }
    }
    
    // Close modal
    function closeModal(modal) {
        if (modal) {
            modal.style.display = 'none';
        }
    }
    
    // Handle network updates
    function handleNetworkUpdate(e) {
        const networkLayers = e.detail;
        console.log('Network updated:', networkLayers);
        
        // Update the properties panel
        updatePropertiesPanel(networkLayers);
    }
    
    // Update properties panel with network information
    function updatePropertiesPanel(networkLayers) {
        const propertiesPanel = document.querySelector('.props-panel');
        if (!propertiesPanel) return;
        
        // Find the properties content section
        const propsContent = propertiesPanel.querySelector('.props-content');
        if (!propsContent) return;
        
        // Basic network stats
        const layerCount = networkLayers.layers.length;
        const connectionCount = networkLayers.connections.length;
        
        let layerTypeCounts = {};
        networkLayers.layers.forEach(layer => {
            layerTypeCounts[layer.type] = (layerTypeCounts[layer.type] || 0) + 1;
        });
        
        // Check network validity
        const validationResult = window.neuralNetwork.validateNetwork(
            networkLayers.layers,
            networkLayers.connections
        );
        
        // Update network architecture section
        let networkArchitectureHTML = `
            <div class="props-section">
                <div class="props-heading">
                    <i class="icon">πŸ”</i> Network Architecture
                </div>
                <div class="props-row">
                    <div class="props-key">Total Layers</div>
                    <div class="props-value">${layerCount}</div>
                </div>
                <div class="props-row">
                    <div class="props-key">Connections</div>
                    <div class="props-value">${connectionCount}</div>
                </div>
        `;
        
        // Add layer type counts
        Object.entries(layerTypeCounts).forEach(([type, count]) => {
            networkArchitectureHTML += `
                <div class="props-row">
                    <div class="props-key">${type.charAt(0).toUpperCase() + type.slice(1)} Layers</div>
                    <div class="props-value">${count}</div>
                </div>
            `;
        });
        
        // Add validation status
        networkArchitectureHTML += `
            <div class="props-row">
                <div class="props-key">Validity</div>
                <div class="props-value" style="color: ${validationResult.valid ? 'var(--secondary-color)' : 'var(--warning-color)'}">
                    ${validationResult.valid ? 'Valid' : 'Invalid'}
                </div>
            </div>
        `;
        
        // If there are validation errors, show them
        if (!validationResult.valid && validationResult.errors.length > 0) {
            networkArchitectureHTML += `
                <div class="props-row">
                    <div class="props-key">Errors</div>
                    <div class="props-value" style="color: var(--warning-color)">
                        ${validationResult.errors.join('<br>')}
                    </div>
                </div>
            `;
        }
        
        networkArchitectureHTML += `</div>`;
        
        // Calculate total parameters if we have layers
        let totalParameters = 0;
        let totalFlops = 0;
        let totalMemory = 0;
        
        if (layerCount > 0) {
            // Calculate model stats
            const modelStatsHTML = `
                <div class="props-section">
                    <div class="props-heading">
                        <i class="icon">πŸ“Š</i> Model Statistics
                    </div>
                    <div class="props-row">
                        <div class="props-key">Parameters</div>
                        <div class="props-value">${formatNumber(totalParameters)}</div>
                    </div>
                    <div class="props-row">
                        <div class="props-key">FLOPs</div>
                        <div class="props-value">${formatNumber(totalFlops)}</div>
                    </div>
                    <div class="props-row">
                        <div class="props-key">Memory</div>
                        <div class="props-value">${formatMemorySize(totalMemory)}</div>
                    </div>
                </div>
            `;
            
            // Update the properties content
            propsContent.innerHTML = networkArchitectureHTML + modelStatsHTML;
        } else {
            // Just show basic architecture info
            propsContent.innerHTML = networkArchitectureHTML;
        }
    }
    
    // Format number with K, M, B suffixes
    function formatNumber(num) {
        if (num === 0) return '0';
        if (!num) return 'N/A';
        
        if (num >= 1e9) return (num / 1e9).toFixed(2) + 'B';
        if (num >= 1e6) return (num / 1e6).toFixed(2) + 'M';
        if (num >= 1e3) return (num / 1e3).toFixed(2) + 'K';
        return num.toString();
    }
    
    // Format memory size in bytes to KB, MB, GB
    function formatMemorySize(bytes) {
        if (bytes === 0) return '0 Bytes';
        if (!bytes) return 'N/A';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // Handle opening the layer editor
    function handleOpenLayerEditor(e) {
        const node = e.detail.node;
        const nodeType = node.getAttribute('data-type');
        const layerId = node.getAttribute('data-id');
        
        // Get current configuration
        const layerConfig = node.layerConfig || window.neuralNetwork.createNodeConfig(nodeType);
        
        // Update modal title
        const modalTitle = document.querySelector('.layer-editor-modal .modal-title');
        if (modalTitle) {
            modalTitle.textContent = `Edit ${nodeType.charAt(0).toUpperCase() + nodeType.slice(1)} Layer`;
        }
        
        // Get layer form
        const layerForm = document.querySelector('.layer-form');
        if (!layerForm) return;
        
        // Clear previous form fields
        layerForm.innerHTML = '';
        
        // Create form fields based on layer type
        switch (nodeType) {
            case 'input':
                // Input shape fields
                layerForm.innerHTML += `
                    <div class="form-group">
                        <label>Input Dimensions:</label>
                        <div class="form-row">
                            <input type="number" id="input-height" min="1" value="${layerConfig.shape[0]}" placeholder="Height">
                            <input type="number" id="input-width" min="1" value="${layerConfig.shape[1]}" placeholder="Width">
                            <input type="number" id="input-channels" min="1" value="${layerConfig.shape[2]}" placeholder="Channels">
                        </div>
                        <small>Input shape: [${layerConfig.shape.join(' Γ— ')}]</small>
                    </div>
                    <div class="form-group">
                        <label>Batch Size:</label>
                        <input type="number" id="batch-size" min="1" value="${layerConfig.batchSize}" placeholder="Batch Size">
                    </div>
                `;
                break;
                
            case 'hidden':
                // Units and activation function
                layerForm.innerHTML += `
                    <div class="form-group">
                        <label>Units:</label>
                        <input type="number" id="hidden-units" min="1" value="${layerConfig.units}" placeholder="Number of units">
                        <small>Output shape: [${layerConfig.units}]</small>
                    </div>
                    <div class="form-group">
                        <label>Activation Function:</label>
                        <select id="hidden-activation">
                            <option value="relu" ${layerConfig.activation === 'relu' ? 'selected' : ''}>ReLU</option>
                            <option value="sigmoid" ${layerConfig.activation === 'sigmoid' ? 'selected' : ''}>Sigmoid</option>
                            <option value="tanh" ${layerConfig.activation === 'tanh' ? 'selected' : ''}>Tanh</option>
                            <option value="leaky_relu" ${layerConfig.activation === 'leaky_relu' ? 'selected' : ''}>Leaky ReLU</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Dropout Rate:</label>
                        <input type="range" id="dropout-rate" min="0" max="0.9" step="0.1" value="${layerConfig.dropoutRate}">
                        <span id="dropout-value">${layerConfig.dropoutRate}</span>
                    </div>
                    <div class="form-group">
                        <label>Use Bias:</label>
                        <input type="checkbox" id="use-bias" ${layerConfig.useBias ? 'checked' : ''}>
                    </div>
                `;
                
                // Add listener for dropout rate slider
                setTimeout(() => {
                    const dropoutSlider = document.getElementById('dropout-rate');
                    const dropoutValue = document.getElementById('dropout-value');
                    if (dropoutSlider && dropoutValue) {
                        dropoutSlider.addEventListener('input', (e) => {
                            dropoutValue.textContent = e.target.value;
                        });
                    }
                }, 100);
                break;
                
            case 'output':
                // Output units and activation
                layerForm.innerHTML += `
                    <div class="form-group">
                        <label>Units:</label>
                        <input type="number" id="output-units" min="1" value="${layerConfig.units}" placeholder="Number of output units">
                        <small>Output shape: [${layerConfig.units}]</small>
                    </div>
                    <div class="form-group">
                        <label>Activation Function:</label>
                        <select id="output-activation">
                            <option value="softmax" ${layerConfig.activation === 'softmax' ? 'selected' : ''}>Softmax (Classification)</option>
                            <option value="sigmoid" ${layerConfig.activation === 'sigmoid' ? 'selected' : ''}>Sigmoid (Binary Classification)</option>
                            <option value="linear" ${layerConfig.activation === 'linear' ? 'selected' : ''}>Linear (Regression)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Use Bias:</label>
                        <input type="checkbox" id="output-use-bias" ${layerConfig.useBias ? 'checked' : ''}>
                    </div>
                `;
                break;
                
            case 'conv':
                // Convolutional layer parameters
                // Get input and output shapes - may be calculated or null at first
                const inputShape = layerConfig.inputShape || ['?', '?', '?'];
                const outputShape = layerConfig.outputShape || ['?', '?', layerConfig.filters];
                
                layerForm.innerHTML += `
                    <div class="form-group">
                        <label>Input Shape:</label>
                        <div class="form-row">
                            <input type="number" id="conv-input-h" min="1" value="${inputShape[0] === '?' ? 28 : inputShape[0]}" placeholder="Height">
                            <input type="number" id="conv-input-w" min="1" value="${inputShape[1] === '?' ? 28 : inputShape[1]}" placeholder="Width">
                            <input type="number" id="conv-input-c" min="1" value="${inputShape[2] === '?' ? 1 : inputShape[2]}" placeholder="Channels">
                        </div>
                        <small>Input dimensions: H Γ— W Γ— C</small>
                    </div>
                    <div class="form-group">
                        <label>Filters:</label>
                        <input type="number" id="conv-filters" min="1" value="${layerConfig.filters}" placeholder="Number of filters">
                        <small>Output channels</small>
                    </div>
                    <div class="form-group">
                        <label>Kernel Size:</label>
                        <div class="form-row">
                            <input type="number" id="kernel-size-h" min="1" max="7" value="${layerConfig.kernelSize[0]}" placeholder="Height">
                            <input type="number" id="kernel-size-w" min="1" max="7" value="${layerConfig.kernelSize[1]}" placeholder="Width">
                        </div>
                        <small>Filter dimensions: ${layerConfig.kernelSize.join(' Γ— ')}</small>
                    </div>
                    <div class="form-group">
                        <label>Strides:</label>
                        <div class="form-row">
                            <input type="number" id="stride-h" min="1" max="4" value="${layerConfig.strides[0]}" placeholder="Height">
                            <input type="number" id="stride-w" min="1" max="4" value="${layerConfig.strides[1]}" placeholder="Width">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Padding:</label>
                        <select id="padding-type">
                            <option value="valid" ${layerConfig.padding === 'valid' ? 'selected' : ''}>Valid (No Padding)</option>
                            <option value="same" ${layerConfig.padding === 'same' ? 'selected' : ''}>Same (Preserve Dimensions)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Activation Function:</label>
                        <select id="conv-activation">
                            <option value="relu" ${layerConfig.activation === 'relu' ? 'selected' : ''}>ReLU</option>
                            <option value="sigmoid" ${layerConfig.activation === 'sigmoid' ? 'selected' : ''}>Sigmoid</option>
                            <option value="tanh" ${layerConfig.activation === 'tanh' ? 'selected' : ''}>Tanh</option>
                            <option value="leaky_relu" ${layerConfig.activation === 'leaky_relu' ? 'selected' : ''}>Leaky ReLU</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Output Shape (calculated):</label>
                        <div class="output-shape-display" id="conv-output-shape">
                            [${outputShape.join(' Γ— ')}]
                        </div>
                        <small>Output dimensions: H Γ— W Γ— Filters</small>
                    </div>
                    <div class="form-group">
                        <label>Parameters (calculated):</label>
                        <div class="parameters-display" id="conv-parameters">
                            Calculating...
                        </div>
                    </div>
                `;
                
                // Add event listeners to calculate output shape and parameters in real-time
                setTimeout(() => {
                    const inputH = document.getElementById('conv-input-h');
                    const inputW = document.getElementById('conv-input-w');
                    const inputC = document.getElementById('conv-input-c');
                    const filters = document.getElementById('conv-filters');
                    const kernelH = document.getElementById('kernel-size-h');
                    const kernelW = document.getElementById('kernel-size-w');
                    const strideH = document.getElementById('stride-h');
                    const strideW = document.getElementById('stride-w');
                    const paddingType = document.getElementById('padding-type');
                    const outputShapeDisplay = document.getElementById('conv-output-shape');
                    const parametersDisplay = document.getElementById('conv-parameters');
                    
                    const updateOutputShape = () => {
                        const h = parseInt(inputH.value);
                        const w = parseInt(inputW.value);
                        const c = parseInt(inputC.value);
                        const f = parseInt(filters.value);
                        const kh = parseInt(kernelH.value);
                        const kw = parseInt(kernelW.value);
                        const sh = parseInt(strideH.value);
                        const sw = parseInt(strideW.value);
                        const padding = paddingType.value;
                        
                        // Calculate output dimensions
                        const pH = padding === 'same' ? Math.floor(kh / 2) : 0;
                        const pW = padding === 'same' ? Math.floor(kw / 2) : 0;
                        
                        const outH = Math.floor((h - kh + 2 * pH) / sh) + 1;
                        const outW = Math.floor((w - kw + 2 * pW) / sw) + 1;
                        
                        // Update output shape display
                        outputShapeDisplay.textContent = `[${outH} Γ— ${outW} Γ— ${f}]`;
                        
                        // Calculate parameters
                        const params = kh * kw * c * f + f; // weights + bias
                        parametersDisplay.textContent = formatNumber(params);
                        
                        // Store for saving
                        layerConfig.inputShape = [h, w, c];
                        layerConfig.outputShape = [outH, outW, f];
                        layerConfig.parameters = params;
                    };
                    
                    // Attach event listeners to all inputs
                    [inputH, inputW, inputC, filters, kernelH, kernelW, strideH, strideW, paddingType].forEach(
                        input => input.addEventListener('input', updateOutputShape)
                    );
                    
                    // Initialize values
                    updateOutputShape();
                }, 100);
                break;
                
            case 'pool':
                // Pooling layer parameters
                // Get input and output shapes
                const poolInputShape = layerConfig.inputShape || ['?', '?', '?'];
                const poolOutputShape = layerConfig.outputShape || ['?', '?', '?'];
                
                layerForm.innerHTML += `
                    <div class="form-group">
                        <label>Input Shape:</label>
                        <div class="form-row">
                            <input type="number" id="pool-input-h" min="1" value="${poolInputShape[0] === '?' ? 28 : poolInputShape[0]}" placeholder="Height">
                            <input type="number" id="pool-input-w" min="1" value="${poolInputShape[1] === '?' ? 28 : poolInputShape[1]}" placeholder="Width">
                            <input type="number" id="pool-input-c" min="1" value="${poolInputShape[2] === '?' ? 1 : poolInputShape[2]}" placeholder="Channels">
                        </div>
                        <small>Input dimensions: H Γ— W Γ— C</small>
                    </div>
                    <div class="form-group">
                        <label>Pool Size:</label>
                        <div class="form-row">
                            <input type="number" id="pool-size-h" min="1" max="4" value="${layerConfig.poolSize[0]}" placeholder="Height">
                            <input type="number" id="pool-size-w" min="1" max="4" value="${layerConfig.poolSize[1]}" placeholder="Width">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Strides:</label>
                        <div class="form-row">
                            <input type="number" id="pool-stride-h" min="1" max="4" value="${layerConfig.strides[0]}" placeholder="Height">
                            <input type="number" id="pool-stride-w" min="1" max="4" value="${layerConfig.strides[1]}" placeholder="Width">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Padding:</label>
                        <select id="pool-padding">
                            <option value="valid" ${layerConfig.padding === 'valid' ? 'selected' : ''}>Valid (No Padding)</option>
                            <option value="same" ${layerConfig.padding === 'same' ? 'selected' : ''}>Same (Preserve Dimensions)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Pool Type:</label>
                        <select id="pool-type">
                            <option value="max" selected>Max Pooling</option>
                            <option value="avg">Average Pooling</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Output Shape (calculated):</label>
                        <div class="output-shape-display" id="pool-output-shape">
                            [${poolOutputShape.join(' Γ— ')}]
                        </div>
                        <small>Output dimensions: H Γ— W Γ— C</small>
                    </div>
                `;
                
                // Add event listeners to calculate output shape in real-time
                setTimeout(() => {
                    const inputH = document.getElementById('pool-input-h');
                    const inputW = document.getElementById('pool-input-w');
                    const inputC = document.getElementById('pool-input-c');
                    const poolH = document.getElementById('pool-size-h');
                    const poolW = document.getElementById('pool-size-w');
                    const strideH = document.getElementById('pool-stride-h');
                    const strideW = document.getElementById('pool-stride-w');
                    const paddingType = document.getElementById('pool-padding');
                    const outputShapeDisplay = document.getElementById('pool-output-shape');
                    
                    const updateOutputShape = () => {
                        const h = parseInt(inputH.value);
                        const w = parseInt(inputW.value);
                        const c = parseInt(inputC.value);
                        const ph = parseInt(poolH.value);
                        const pw = parseInt(poolW.value);
                        const sh = parseInt(strideH.value);
                        const sw = parseInt(strideW.value);
                        const padding = paddingType.value;
                        
                        // Calculate output dimensions
                        const padH = padding === 'same' ? Math.floor(ph / 2) : 0;
                        const padW = padding === 'same' ? Math.floor(pw / 2) : 0;
                        
                        const outH = Math.floor((h - ph + 2 * padH) / sh) + 1;
                        const outW = Math.floor((w - pw + 2 * padW) / sw) + 1;
                        
                        // Update output shape display
                        outputShapeDisplay.textContent = `[${outH} Γ— ${outW} Γ— ${c}]`;
                        
                        // Store for saving
                        layerConfig.inputShape = [h, w, c];
                        layerConfig.outputShape = [outH, outW, c];
                        layerConfig.parameters = 0; // Pooling has no parameters
                    };
                    
                    // Attach event listeners to all inputs
                    [inputH, inputW, inputC, poolH, poolW, strideH, strideW, paddingType].forEach(
                        input => input.addEventListener('input', updateOutputShape)
                    );
                    
                    // Initialize values
                    updateOutputShape();
                }, 100);
                break;
                
            case 'linear':
                // Linear regression layer parameters
                layerForm.innerHTML += `
                    <div class="form-group">
                        <label>Input Features:</label>
                        <input type="number" id="input-features" min="1" value="${layerConfig.inputFeatures}" placeholder="Number of input features">
                        <small>Input shape: [${layerConfig.inputFeatures}]</small>
                    </div>
                    <div class="form-group">
                        <label>Output Features:</label>
                        <input type="number" id="output-features" min="1" value="${layerConfig.outputFeatures}" placeholder="Number of output features">
                        <small>Output shape: [${layerConfig.outputFeatures}]</small>
                    </div>
                    <div class="form-group">
                        <label>Use Bias:</label>
                        <input type="checkbox" id="linear-use-bias" ${layerConfig.useBias ? 'checked' : ''}>
                    </div>
                    <div class="form-group">
                        <label>Learning Rate:</label>
                        <input type="range" id="learning-rate-slider" min="0.001" max="0.1" step="0.001" value="${layerConfig.learningRate}">
                        <span id="learning-rate-value">${layerConfig.learningRate}</span>
                    </div>
                    <div class="form-group">
                        <label>Loss Function:</label>
                        <select id="loss-function">
                            <option value="mse" ${layerConfig.lossFunction === 'mse' ? 'selected' : ''}>Mean Squared Error</option>
                            <option value="mae" ${layerConfig.lossFunction === 'mae' ? 'selected' : ''}>Mean Absolute Error</option>
                            <option value="huber" ${layerConfig.lossFunction === 'huber' ? 'selected' : ''}>Huber Loss</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Optimizer:</label>
                        <select id="optimizer">
                            <option value="sgd" ${layerConfig.optimizer === 'sgd' ? 'selected' : ''}>Stochastic Gradient Descent</option>
                            <option value="adam" ${layerConfig.optimizer === 'adam' ? 'selected' : ''}>Adam</option>
                            <option value="rmsprop" ${layerConfig.optimizer === 'rmsprop' ? 'selected' : ''}>RMSprop</option>
                        </select>
                    </div>
                `;
                
                // Add listener for learning rate slider
                setTimeout(() => {
                    const learningRateSlider = document.getElementById('learning-rate-slider');
                    const learningRateValue = document.getElementById('learning-rate-value');
                    if (learningRateSlider && learningRateValue) {
                        learningRateSlider.addEventListener('input', (e) => {
                            learningRateValue.textContent = parseFloat(e.target.value).toFixed(3);
                        });
                    }
                }, 100);
                break;
                
            default:
                layerForm.innerHTML = '<p>No editable properties for this layer type.</p>';
        }
        
        // Add a preview of calculated parameters if available
        if (nodeType !== 'input') {
            const parameterCount = window.neuralNetwork.calculateParameters(nodeType, layerConfig);
            if (parameterCount) {
                layerForm.innerHTML += `
                    <div class="form-group">
                        <label>Parameter Summary:</label>
                        <div class="parameters-summary">
                            <p>Total parameters: <strong>${formatNumber(parameterCount)}</strong></p>
                            <p>Memory usage (32-bit): ~${formatMemorySize(parameterCount * 4)}</p>
                        </div>
                    </div>
                `;
            }
        }
        
        // Add save and cancel buttons
        layerForm.innerHTML += `
            <div class="form-buttons">
                <button type="button" id="save-layer-config" class="btn-primary">Save Changes</button>
                <button type="button" id="cancel-layer-edit" class="btn-secondary">Cancel</button>
            </div>
        `;
        
        // Open the modal
        const modal = document.getElementById('layer-editor-modal');
        if (modal) {
            openModal(modal);
            
            // Add event listeners for buttons
            const saveButton = document.getElementById('save-layer-config');
            if (saveButton) {
                saveButton.addEventListener('click', () => {
                    saveLayerConfig(node, nodeType, layerId);
                    closeModal(modal);
                });
            }
            
            const cancelButton = document.getElementById('cancel-layer-edit');
            if (cancelButton) {
                cancelButton.addEventListener('click', () => {
                    closeModal(modal);
                });
            }
        }
    }
    
    // Save layer configuration
    function saveLayerConfig(node, nodeType, layerId) {
        // Get form values
        const form = document.querySelector('.layer-form');
        if (!form) return;
        
        const values = {};
        const inputs = form.querySelectorAll('input, select');
        inputs.forEach(input => {
            if (input.type === 'checkbox') {
                values[input.id] = input.checked;
            } else {
                values[input.id] = input.value;
            }
        });
        
        // Update node configuration
        node.layerConfig = node.layerConfig || {};
        const layerConfig = node.layerConfig;
        
        switch (nodeType) {
            case 'input':
                layerConfig.shape = [
                    parseInt(values['input-height']) || 28,
                    parseInt(values['input-width']) || 28,
                    parseInt(values['input-channels']) || 1
                ];
                layerConfig.batchSize = parseInt(values['batch-size']) || 32;
                layerConfig.outputShape = layerConfig.shape;
                layerConfig.parameters = 0;
                break;
                
            case 'hidden':
                layerConfig.units = parseInt(values['hidden-units']) || 128;
                layerConfig.activation = values['hidden-activation'] || 'relu';
                layerConfig.dropoutRate = parseFloat(values['dropout-rate']) || 0.2;
                layerConfig.useBias = values['use-bias'] === true;
                layerConfig.outputShape = [layerConfig.units];
                
                // Calculate parameters if input shape is available
                if (layerConfig.inputShape) {
                    const inputUnits = Array.isArray(layerConfig.inputShape) ? 
                        layerConfig.inputShape.reduce((a, b) => a * b, 1) : layerConfig.inputShape;
                    layerConfig.parameters = (inputUnits * layerConfig.units) + (layerConfig.useBias ? layerConfig.units : 0);
                }
                break;
                
            case 'output':
                layerConfig.units = parseInt(values['output-units']) || 10;
                layerConfig.activation = values['output-activation'] || 'softmax';
                layerConfig.useBias = values['output-use-bias'] === true;
                layerConfig.outputShape = [layerConfig.units];
                
                // Calculate parameters if input shape is available
                if (layerConfig.inputShape) {
                    const inputUnits = Array.isArray(layerConfig.inputShape) ? 
                        layerConfig.inputShape.reduce((a, b) => a * b, 1) : layerConfig.inputShape;
                    layerConfig.parameters = (inputUnits * layerConfig.units) + (layerConfig.useBias ? layerConfig.units : 0);
                }
                break;
                
            case 'conv':
                // Process input shape if available in form
                if (values['conv-input-h'] && values['conv-input-w'] && values['conv-input-c']) {
                    layerConfig.inputShape = [
                        parseInt(values['conv-input-h']) || 28,
                        parseInt(values['conv-input-w']) || 28,
                        parseInt(values['conv-input-c']) || 1
                    ];
                }
                
                // Process configuration
                layerConfig.filters = parseInt(values['conv-filters']) || 32;
                layerConfig.kernelSize = [
                    parseInt(values['kernel-size-h']) || 3,
                    parseInt(values['kernel-size-w']) || 3
                ];
                layerConfig.strides = [
                    parseInt(values['stride-h']) || 1,
                    parseInt(values['stride-w']) || 1
                ];
                layerConfig.padding = values['padding-type'] || 'valid';
                layerConfig.activation = values['conv-activation'] || 'relu';
                layerConfig.useBias = true; // Default to true for CNN
                
                // Calculate output shape if input shape is available
                if (layerConfig.inputShape) {
                    const padding = layerConfig.padding === 'same' ? 
                        Math.floor(layerConfig.kernelSize[0] / 2) : 0;
                        
                    const outH = Math.floor(
                        (layerConfig.inputShape[0] - layerConfig.kernelSize[0] + 2 * padding) / 
                        layerConfig.strides[0]
                    ) + 1;
                    
                    const outW = Math.floor(
                        (layerConfig.inputShape[1] - layerConfig.kernelSize[1] + 2 * padding) / 
                        layerConfig.strides[1]
                    ) + 1;
                    
                    layerConfig.outputShape = [outH, outW, layerConfig.filters];
                    
                    // Calculate parameters
                    const kernelParams = layerConfig.kernelSize[0] * layerConfig.kernelSize[1] * 
                                        layerConfig.inputShape[2] * layerConfig.filters;
                    const biasParams = layerConfig.filters;
                    layerConfig.parameters = kernelParams + biasParams;
                }
                break;
                
            case 'pool':
                // Process input shape if available in form
                if (values['pool-input-h'] && values['pool-input-w'] && values['pool-input-c']) {
                    layerConfig.inputShape = [
                        parseInt(values['pool-input-h']) || 28,
                        parseInt(values['pool-input-w']) || 28,
                        parseInt(values['pool-input-c']) || 1
                    ];
                }
                
                // Process configuration
                layerConfig.poolSize = [
                    parseInt(values['pool-size-h']) || 2,
                    parseInt(values['pool-size-w']) || 2
                ];
                layerConfig.strides = [
                    parseInt(values['pool-stride-h']) || 2,
                    parseInt(values['pool-stride-w']) || 2
                ];
                layerConfig.padding = values['pool-padding'] || 'valid';
                layerConfig.poolType = values['pool-type'] || 'max';
                
                // Calculate output shape if input shape is available
                if (layerConfig.inputShape) {
                    const poolPadding = layerConfig.padding === 'same' ? 
                        Math.floor(layerConfig.poolSize[0] / 2) : 0;
                        
                    const poolOutH = Math.floor(
                        (layerConfig.inputShape[0] - layerConfig.poolSize[0] + 2 * poolPadding) / 
                        layerConfig.strides[0]
                    ) + 1;
                    
                    const poolOutW = Math.floor(
                        (layerConfig.inputShape[1] - layerConfig.poolSize[1] + 2 * poolPadding) / 
                        layerConfig.strides[1]
                    ) + 1;
                    
                    layerConfig.outputShape = [poolOutH, poolOutW, layerConfig.inputShape[2]];
                }
                
                // Pooling has no parameters
                layerConfig.parameters = 0;
                break;
                
            case 'linear':
                layerConfig.inputFeatures = parseInt(values['input-features']) || 1;
                layerConfig.outputFeatures = parseInt(values['output-features']) || 1;
                layerConfig.useBias = values['linear-use-bias'] === true;
                layerConfig.learningRate = parseFloat(values['learning-rate-slider']) || 0.01;
                layerConfig.activation = values['linear-activation'] || 'linear';
                layerConfig.optimizer = values['optimizer'] || 'sgd';
                layerConfig.lossFunction = values['loss-function'] || 'mse';
                layerConfig.inputShape = [layerConfig.inputFeatures];
                layerConfig.outputShape = [layerConfig.outputFeatures];
                
                // Calculate parameters
                layerConfig.parameters = layerConfig.inputFeatures * layerConfig.outputFeatures;
                if (layerConfig.useBias) {
                    layerConfig.parameters += layerConfig.outputFeatures;
                }
                break;
        }
        
        // Update node title
        const nodeTitle = node.querySelector('.node-title');
        if (nodeTitle) {
            nodeTitle.textContent = nodeType.charAt(0).toUpperCase() + nodeType.slice(1);
        }
        
        // Update node data attribute
        node.setAttribute('data-name', nodeType.charAt(0).toUpperCase() + nodeType.slice(1));
        
        // Update dimensions and parameter display based on layer type
        let dimensions = '';
        switch (nodeType) {
            case 'input':
                dimensions = layerConfig.shape.join(' Γ— ');
                break;
                
            case 'hidden':
            case 'output':
                dimensions = layerConfig.units.toString();
                break;
                
            case 'conv':
                if (layerConfig.inputShape && layerConfig.outputShape) {
                    // Show input -> output shape transformation
                    dimensions = `${layerConfig.inputShape[0]}Γ—${layerConfig.inputShape[1]}Γ—${layerConfig.inputShape[2]} β†’ ${layerConfig.outputShape[0]}Γ—${layerConfig.outputShape[1]}Γ—${layerConfig.outputShape[2]}`;
                } else {
                    dimensions = `? β†’ ${layerConfig.filters} filters`;
                }
                break;
                
            case 'pool':
                if (layerConfig.inputShape && layerConfig.outputShape) {
                    // Show input -> output shape transformation
                    dimensions = `${layerConfig.inputShape[0]}Γ—${layerConfig.inputShape[1]}Γ—${layerConfig.inputShape[2]} β†’ ${layerConfig.outputShape[0]}Γ—${layerConfig.outputShape[1]}Γ—${layerConfig.outputShape[2]}`;
                } else {
                    dimensions = `? β†’ ?`;
                }
                break;
                
            case 'linear':
                dimensions = `${layerConfig.inputFeatures} β†’ ${layerConfig.outputFeatures}`;
                break;
        }
        
        // Update node dimensions display
        const nodeDimensions = node.querySelector('.node-dimensions');
        if (nodeDimensions) {
            nodeDimensions.textContent = dimensions;
        }
        
        // Update parameters display if available
        const nodeParameters = node.querySelector('.node-parameters');
        if (nodeParameters && layerConfig.parameters !== undefined) {
            nodeParameters.textContent = `Params: ${formatNumber(layerConfig.parameters)}`;
        } else if (nodeParameters) {
            nodeParameters.textContent = 'Params: ?';
        }
        
        // Update node data attribute
        node.setAttribute('data-dimensions', dimensions);
        
        // Update network layers in drag-drop module
        const networkLayers = window.dragDrop.getNetworkArchitecture();
        const layerIndex = networkLayers.layers.findIndex(layer => layer.id === layerId);
        
        if (layerIndex !== -1) {
            networkLayers.layers[layerIndex].name = nodeType.charAt(0).toUpperCase() + nodeType.slice(1);
            networkLayers.layers[layerIndex].dimensions = dimensions;
            networkLayers.layers[layerIndex].config = layerConfig;
            
            // Add parameter count to the layer
            networkLayers.layers[layerIndex].parameters = layerConfig.parameters;
        }
        
        // Trigger network updated event
        const event = new CustomEvent('networkUpdated', { detail: networkLayers });
        document.dispatchEvent(event);
        
        // Update connected nodes to propagate shape changes
        updateNodeConnections(node, layerId);
    }
    
    // Helper function to update connections between nodes when shapes change
    function updateNodeConnections(sourceNode, sourceId) {
        // Find all connections from this source node
        const connections = document.querySelectorAll(`.connection[data-source="${sourceId}"]`);
        
        connections.forEach(connection => {
            const targetId = connection.getAttribute('data-target');
            const targetNode = document.querySelector(`.canvas-node[data-id="${targetId}"]`);
            
            if (targetNode && sourceNode.layerConfig && sourceNode.layerConfig.outputShape) {
                // Update target node with source node's output shape as its input shape
                if (!targetNode.layerConfig) {
                    targetNode.layerConfig = {};
                }
                
                targetNode.layerConfig.inputShape = sourceNode.layerConfig.outputShape;
                
                // Update parameter calculation
                window.neuralNetwork.calculateParameters(
                    targetNode.getAttribute('data-type'),
                    targetNode.layerConfig,
                    sourceNode.layerConfig
                );
                
                // Update display
                updateNodeDisplay(targetNode);
                
                // Recursively update downstream nodes
                updateNodeConnections(targetNode, targetId);
            }
        });
    }
    
    // Helper function to update a node's display
    function updateNodeDisplay(node) {
        if (!node || !node.layerConfig) return;
        
        const nodeType = node.getAttribute('data-type');
        const layerConfig = node.layerConfig;
        
        // Create dimensions string
        let dimensions = '';
        switch (nodeType) {
            case 'conv':
            case 'pool':
                if (layerConfig.inputShape && layerConfig.outputShape) {
                    dimensions = `${layerConfig.inputShape[0]}Γ—${layerConfig.inputShape[1]}Γ—${layerConfig.inputShape[2]} β†’ ${layerConfig.outputShape[0]}Γ—${layerConfig.outputShape[1]}Γ—${layerConfig.outputShape[2]}`;
                }
                break;
                
            case 'hidden':
            case 'output':
                dimensions = layerConfig.units.toString();
                break;
                
            case 'linear':
                dimensions = `${layerConfig.inputFeatures} β†’ ${layerConfig.outputFeatures}`;
                break;
        }
        
        // Update dimensions display
        if (dimensions) {
            const nodeDimensions = node.querySelector('.node-dimensions');
            if (nodeDimensions) {
                nodeDimensions.textContent = dimensions;
                node.setAttribute('data-dimensions', dimensions);
            }
        }
        
        // Update parameters display
        if (layerConfig.parameters !== undefined) {
            const nodeParameters = node.querySelector('.node-parameters');
            if (nodeParameters) {
                nodeParameters.textContent = `Params: ${formatNumber(layerConfig.parameters)}`;
            }
        }
    }
    
    // Handle sample selection
    function handleSampleSelection(sampleId) {
        // Set active sample
        document.querySelectorAll('.sample-item').forEach(item => {
            item.classList.remove('active');
            if (item.getAttribute('data-sample') === sampleId) {
                item.classList.add('active');
            }
        });
        
        // Get sample data
        const sampleData = window.neuralNetwork.sampleData[sampleId];
        if (!sampleData) return;
        
        console.log(`Selected sample: ${sampleData.name}`);
        
        // Update properties panel to show sample info
        const propertiesPanel = document.querySelector('.props-panel');
        if (!propertiesPanel) return;
        
        const propsContent = propertiesPanel.querySelector('.props-content');
        if (!propsContent) return;
        
        propsContent.innerHTML = `
            <div class="props-section">
                <div class="props-heading">
                    <i class="icon">πŸ“Š</i> ${sampleData.name}
                </div>
                <div class="props-row">
                    <div class="props-key">Input Shape</div>
                    <div class="props-value">${sampleData.inputShape.join(' Γ— ')}</div>
                </div>
                <div class="props-row">
                    <div class="props-key">Classes</div>
                    <div class="props-value">${sampleData.numClasses}</div>
                </div>
                <div class="props-row">
                    <div class="props-key">Training Samples</div>
                    <div class="props-value">${sampleData.trainSamples.toLocaleString()}</div>
                </div>
                <div class="props-row">
                    <div class="props-key">Test Samples</div>
                    <div class="props-value">${sampleData.testSamples.toLocaleString()}</div>
                </div>
                <div class="props-row">
                    <div class="props-key">Description</div>
                    <div class="props-value">${sampleData.description}</div>
                </div>
            </div>
            
            <div class="props-section">
                <p class="hint-text">Click "Run Network" to train on this dataset</p>
            </div>
        `;
    }
    
    // Function to run the neural network simulation
    function runNetwork() {
        console.log('Running neural network simulation with config:', networkConfig);
        
        // Get the current network architecture
        const networkLayers = window.dragDrop.getNetworkArchitecture();
        
        // Check if we have a valid network
        if (networkLayers.layers.length === 0) {
            alert('Please add some nodes to the network first!');
            return;
        }
        
        // Validate the network
        const validationResult = window.neuralNetwork.validateNetwork(
            networkLayers.layers,
            networkLayers.connections
        );
        
        if (!validationResult.valid) {
            alert('Network is not valid: ' + validationResult.errors.join('\n'));
            return;
        }
        
        // Add animation class to all nodes
        document.querySelectorAll('.canvas-node').forEach(node => {
            node.classList.add('highlight-pulse');
        });
        
        // Animate connections to show data flow
        document.querySelectorAll('.connection').forEach((connection, index) => {
            setTimeout(() => {
                connection.style.background = 'linear-gradient(90deg, var(--primary-color), var(--accent-color))';
                
                // Reset after animation
                setTimeout(() => {
                    connection.style.background = '';
                }, 800);
            }, 300 * index);
        });
        
        // Simulate training
        simulateTraining();
        
        // Reset animations after completion
        setTimeout(() => {
            document.querySelectorAll('.canvas-node').forEach(node => {
                node.classList.remove('highlight-pulse');
            });
        }, 3000);
    }
    
    // Simulate training progress
    function simulateTraining() {
        const progressBar = document.querySelector('.progress-bar');
        const lossValue = document.getElementById('loss-value');
        const accuracyValue = document.getElementById('accuracy-value');
        
        if (!progressBar || !lossValue || !accuracyValue) return;
        
        // Reset progress
        progressBar.style.width = '0%';
        lossValue.textContent = '2.3021';
        accuracyValue.textContent = '0.12';
        
        // Simulate progress over time
        let progress = 0;
        let loss = 2.3021;
        let accuracy = 0.12;
        
        const interval = setInterval(() => {
            progress += 10;
            loss *= 0.85; // Decrease loss over time
            accuracy = Math.min(0.99, accuracy * 1.2); // Increase accuracy over time
            
            progressBar.style.width = `${progress}%`;
            lossValue.textContent = loss.toFixed(4);
            accuracyValue.textContent = accuracy.toFixed(2);
            
            if (progress >= 100) {
                clearInterval(interval);
            }
        }, 300);
    }
    
    // Function to clear all nodes from the canvas
    function clearCanvas() {
        if (window.dragDrop && typeof window.dragDrop.clearAllNodes === 'function') {
            window.dragDrop.clearAllNodes();
        }
        
        // Reset progress indicators
        const progressBar = document.querySelector('.progress-bar');
        const lossValue = document.getElementById('loss-value');
        const accuracyValue = document.getElementById('accuracy-value');
        
        if (progressBar) progressBar.style.width = '0%';
        if (lossValue) lossValue.textContent = '-';
        if (accuracyValue) accuracyValue.textContent = '-';
    }
    
    // Update activation function graph
    function updateActivationFunctionGraph(activationType) {
        const activationGraph = document.querySelector('.activation-function');
        if (!activationGraph) return;
        
        // Clear previous graph
        let canvas = activationGraph.querySelector('canvas');
        if (!canvas) {
            canvas = document.createElement('canvas');
            canvas.width = 200;
            canvas.height = 100;
            activationGraph.appendChild(canvas);
        }
        
        const ctx = canvas.getContext('2d');
        
        // Clear canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // Set background
        ctx.fillStyle = '#f8f9fa';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // Draw axes
        ctx.strokeStyle = '#ccc';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(0, canvas.height / 2);
        ctx.lineTo(canvas.width, canvas.height / 2);
        ctx.moveTo(canvas.width / 2, 0);
        ctx.lineTo(canvas.width / 2, canvas.height);
        ctx.stroke();
        
        // Draw function
        ctx.strokeStyle = 'var(--primary-color)';
        ctx.lineWidth = 2;
        ctx.beginPath();
        
        switch(activationType) {
            case 'relu':
                ctx.moveTo(0, canvas.height / 2);
                ctx.lineTo(canvas.width / 2, canvas.height / 2);
                ctx.lineTo(canvas.width, 0);
                break;
                
            case 'sigmoid':
                for (let x = 0; x < canvas.width; x++) {
                    const normalizedX = (x / canvas.width - 0.5) * 10;
                    const sigmoidY = 1 / (1 + Math.exp(-normalizedX));
                    const y = canvas.height - sigmoidY * canvas.height;
                    if (x === 0) ctx.moveTo(x, y);
                    else ctx.lineTo(x, y);
                }
                break;
                
            case 'tanh':
                for (let x = 0; x < canvas.width; x++) {
                    const normalizedX = (x / canvas.width - 0.5) * 6;
                    const tanhY = Math.tanh(normalizedX);
                    const y = canvas.height / 2 - tanhY * canvas.height / 2;
                    if (x === 0) ctx.moveTo(x, y);
                    else ctx.lineTo(x, y);
                }
                break;
                
            case 'softmax':
                // Just a representative curve for softmax
                ctx.moveTo(0, canvas.height * 0.8);
                ctx.bezierCurveTo(
                    canvas.width * 0.3, canvas.height * 0.7,
                    canvas.width * 0.6, canvas.height * 0.3,
                    canvas.width, canvas.height * 0.2
                );
                break;
                
            default: // Linear
                ctx.moveTo(0, canvas.height * 0.8);
                ctx.lineTo(canvas.width, canvas.height * 0.2);
        }
        
        ctx.stroke();
        
        // Add label
        ctx.fillStyle = 'var(--text-color)';
        ctx.font = '12px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(activationType, canvas.width / 2, canvas.height - 10);
    }
    
    // Setup node hover effects for tooltips
    canvas.addEventListener('mouseover', (e) => {
        const node = e.target.closest('.canvas-node');
        if (node) {
            const rect = node.getBoundingClientRect();
            const nodeType = node.getAttribute('data-type');
            const nodeName = node.getAttribute('data-name');
            const dimensions = node.getAttribute('data-dimensions');
            
            // Show tooltip
            tooltip.style.display = 'block';
            tooltip.style.left = `${rect.right + 10}px`;
            tooltip.style.top = `${rect.top}px`;
            
            const tooltipHeader = tooltip.querySelector('.tooltip-header');
            const tooltipContent = tooltip.querySelector('.tooltip-content');
            
            if (tooltipHeader && tooltipContent) {
                tooltipHeader.textContent = nodeName;
                
                let content = '';
                content += `<div class="tooltip-row">
                    <div class="tooltip-label">Type:</div>
                    <div class="tooltip-value">${nodeType.charAt(0).toUpperCase() + nodeType.slice(1)}</div>
                </div>`;
                
                content += `<div class="tooltip-row">
                    <div class="tooltip-label">Dimensions:</div>
                    <div class="tooltip-value">${dimensions}</div>
                </div>`;
                
                // Get config template
                const configTemplate = window.neuralNetwork.nodeConfigTemplates[nodeType];
                
                if (configTemplate) {
                    if (configTemplate.activation) {
                        content += `<div class="tooltip-row">
                            <div class="tooltip-label">Activation:</div>
                            <div class="tooltip-value">${configTemplate.activation}</div>
                        </div>`;
                    }
                    
                    if (configTemplate.description) {
                        content += `<div class="tooltip-row">
                            <div class="tooltip-label">Description:</div>
                            <div class="tooltip-value">${configTemplate.description}</div>
                        </div>`;
                    }
                }
                
                tooltipContent.innerHTML = content;
            }
        }
    });
    
    canvas.addEventListener('mouseout', (e) => {
        const node = e.target.closest('.canvas-node');
        if (node) {
            tooltip.style.display = 'none';
        }
    });
    
    // Make sure tooltip follows cursor for nodes that are being dragged
    canvas.addEventListener('mousemove', (e) => {
        const node = e.target.closest('.canvas-node');
        if (node && node.classList.contains('dragging')) {
            const rect = node.getBoundingClientRect();
            tooltip.style.left = `${rect.right + 10}px`;
            tooltip.style.top = `${rect.top}px`;
        }
    });
});