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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f09b9f0
 
 
 
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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
/**

 * NODE COMPONENT VIEWS FOR NANO BANANA EDITOR

 * 

 * This file contains all the visual node components for the Nano Banana Editor,

 * a visual node-based AI image processing application. Each node represents a

 * specific image transformation or effect that can be chained together to create

 * complex image processing workflows.

 * 

 * ARCHITECTURE OVERVIEW:

 * - Each node is a self-contained React component with its own state and UI

 * - Nodes use a common dragging system (useNodeDrag hook) for positioning

 * - All nodes follow a consistent structure: Header + Content + Output

 * - Nodes communicate through a connection system using input/output ports

 * - Processing is handled asynchronously with loading states and error handling

 * 

 * NODE TYPES AVAILABLE:

 * - BackgroundNodeView: Change/generate image backgrounds (color, preset, upload, AI-generated)

 * - ClothesNodeView: Add/modify clothing on subjects (preset garments or custom uploads)

 * - StyleNodeView: Apply artistic styles and filters (anime, fine art, cinematic styles)

 * - EditNodeView: General text-based image editing (natural language instructions)

 * - CameraNodeView: Apply camera effects and settings (focal length, aperture, film styles)

 * - AgeNodeView: Transform subject age (AI-powered age progression/regression)

 * - FaceNodeView: Modify facial features and accessories (hair, makeup, expressions)

 * - LightningNodeView: Apply professional lighting effects

 * - PosesNodeView: Modify body poses and positioning

 * 

 * COMMON PATTERNS:

 * - All nodes support drag-and-drop for repositioning in the editor

 * - Input/output ports allow chaining nodes together in processing pipelines

 * - File upload via drag-drop, file picker, or clipboard paste where applicable

 * - Real-time preview of settings and processed results

 * - History navigation for viewing different processing results

 * - Error handling with user-friendly error messages

 * - AI-powered prompt improvement using Gemini API where applicable

 * 

 * USER WORKFLOW:

 * 1. Add nodes to the editor canvas

 * 2. Configure each node's settings (colors, styles, uploaded images, etc.)

 * 3. Connect nodes using input/output ports to create processing chains

 * 4. Process individual nodes or entire chains

 * 5. Preview results, navigate history, and download final images

 * 

 * TECHNICAL DETAILS:

 * - Uses React hooks for state management (useState, useEffect, useRef)

 * - Custom useNodeDrag hook handles node positioning and drag interactions

 * - Port component manages connection logic between nodes

 * - All image data is handled as base64 data URLs for browser compatibility

 * - Processing results are cached with history navigation support

 * - Responsive UI components from shadcn/ui component library

 */
// Enable React Server Components client-side rendering for this file
"use client";

// Import React core functionality for state management and lifecycle hooks
import React, { useState, useRef, useEffect } from "react";

// Import reusable UI components from the shadcn/ui component library
import { Button } from "../components/ui/button";       // Standard button component
import { Select } from "../components/ui/select";       // Dropdown selection component  
import { Textarea } from "../components/ui/textarea";   // Multi-line text input component
import { Slider } from "../components/ui/slider";       // Range slider input component
import { ColorPicker } from "../components/ui/color-picker"; // Color selection component
import { Checkbox } from "../components/ui/checkbox";   // Checkbox input component

/**

 * Helper function to download processed images

 * Creates a temporary download link and triggers the browser's download mechanism

 * 

 * @param dataUrl Base64 data URL of the image to download

 * @param filename Desired filename for the downloaded image

 */
function downloadImage(dataUrl: string, filename: string) {
  const link = document.createElement('a');  // Create an invisible anchor element for download
  link.href = dataUrl;                       // Set the base64 image data as the link target
  link.download = filename;                  // Specify the filename for the downloaded file
  document.body.appendChild(link);           // Temporarily add link to DOM (Firefox requirement)
  link.click();                             // Programmatically trigger the download
  document.body.removeChild(link);          // Remove the temporary link element from DOM
}

/**

 * Helper function to copy image to clipboard

 * Converts the image data URL to blob and copies it to clipboard

 * 

 * @param dataUrl Base64 data URL of the image to copy

 */
async function copyImageToClipboard(dataUrl: string) {
  try {
    // Fetch the data URL and convert it to a Blob object
    const response = await fetch(dataUrl);          // Fetch the base64 data URL
    const blob = await response.blob();             // Convert response to Blob format
    
    // The browser clipboard API only supports PNG format for images
    // If the image is not PNG, we need to convert it first
    if (blob.type !== 'image/png') {
      // Create a canvas element to handle image format conversion
      const canvas = document.createElement('canvas');    // Create invisible canvas
      const ctx = canvas.getContext('2d');                // Get 2D drawing context
      const img = new Image();                            // Create image element
      
      // Wait for the image to load before processing
      await new Promise((resolve) => {
        img.onload = () => {                              // When image loads
          canvas.width = img.width;                       // Set canvas width to match image
          canvas.height = img.height;                     // Set canvas height to match image
          ctx?.drawImage(img, 0, 0);                      // Draw image onto canvas
          resolve(void 0);                                // Resolve the promise
        };
        img.src = dataUrl;                                // Start loading the image
      });
      
      // Convert the canvas content to PNG blob
      const pngBlob = await new Promise<Blob>((resolve) => {
        canvas.toBlob((blob) => resolve(blob!), 'image/png');  // Convert canvas to PNG blob
      });
      
      // Write the converted PNG blob to clipboard
      await navigator.clipboard.write([
        new ClipboardItem({ 'image/png': pngBlob })       // Create clipboard item with PNG data
      ]);
    } else {
      // Image is already PNG, copy directly to clipboard
      await navigator.clipboard.write([
        new ClipboardItem({ 'image/png': blob })          // Copy original blob to clipboard
      ]);
    }
  } catch (error) {
    // Handle any errors that occur during the copy process
    console.error('Failed to copy image to clipboard:', error);
  }
}

/**

 * REUSABLE OUTPUT SECTION COMPONENT

 * 

 * This component provides a standardized output display for all node types.

 * It handles the common functionality that every node needs for showing results:

 * 

 * Key Features:

 * - Displays processed output images with click-to-copy functionality

 * - Provides download functionality with custom filenames

 * - Visual feedback when images are copied to clipboard

 * - Consistent styling across all node types

 * - Hover effects and tooltips for better UX

 * 

 * User Interactions:

 * - Left-click or right-click image to copy to clipboard

 * - Click download button to save image with timestamp

 * - Visual feedback shows when image is successfully copied

 * 

 * Technical Implementation:

 * - Converts images to clipboard-compatible format (PNG)

 * - Uses browser's native download API

 * - Provides visual feedback through temporary styling changes

 * - Handles both base64 data URLs and regular image URLs

 * 

 * @param nodeId - Unique identifier for the node (for potential future features)

 * @param output - Optional current output image (base64 data URL or image URL)

 * @param downloadFileName - Filename to use when downloading (should include extension)

 */
function NodeOutputSection({

  nodeId,              // Unique identifier for the node

  output,              // Optional current output image (base64 data URL)

  downloadFileName,    // Filename to use when downloading the image

}: {

  nodeId: string;                                                           // Node ID type definition

  output?: string;                                                          // Optional output image string

  downloadFileName: string;                                                 // Required download filename

}) {
  // If no image is available, don't render anything
  if (!output) return null;
  
  return (
    // Main container for output section with vertical spacing
    <div className="space-y-2">

      {/* Output header container */}

      <div className="space-y-1">

        {/* Header row with title */}

        <div className="flex items-center justify-between">

          {/* Output section label */}

          <div className="text-xs text-white/70">Output</div>

        </div>

        {/* Output image with click-to-copy functionality */}

        <img 

          src={output}  // Display the output image

          className="w-full rounded cursor-pointer hover:opacity-80 transition-all duration-200 hover:ring-2 hover:ring-white/30"  // Styling with hover effects

          alt="Output"  // Accessibility description

          onClick={() => copyImageToClipboard(output)} // Left-click copies to clipboard

          onContextMenu={(e) => { // Right-click context menu handler

            e.preventDefault(); // Prevent browser context menu from appearing

            copyImageToClipboard(output); // Copy image to clipboard

            

            // Show brief visual feedback when image is copied

            const img = e.currentTarget; // Get the image element

            const originalTitle = img.title; // Store original tooltip text

            img.title = "Copied to clipboard!"; // Update tooltip to show success

            img.style.filter = "brightness(1.2)"; // Brighten the image briefly

            img.style.transform = "scale(0.98)"; // Slightly scale down the image

            

            // Reset visual feedback after 300ms

            setTimeout(() => {

              img.title = originalTitle; // Restore original tooltip

              img.style.filter = ""; // Remove brightness filter

              img.style.transform = ""; // Reset scale transform

            }, 300);

          }}

          title="💾 Click or right-click to copy image to clipboard" // Tooltip instruction

        />

      </div>

      {/* Download button for saving the current image */}

      <Button

        className="w-full"                                              // Full width button

        variant="secondary"                                              // Secondary button styling

        onClick={() => downloadImage(output, downloadFileName)}         // Trigger download when clicked

      >

        📥 Download Output

      </Button>

      {/* End of main output section container */}

    </div>
  );
}

/* ========================================

   TYPE DEFINITIONS (TEMPORARY)

   ======================================== */
// Temporary type definitions - these should be imported from page.tsx in production
// These are placeholder types that allow TypeScript to compile without errors
type BackgroundNode = any;  // Node for background modification operations
type ClothesNode = any;     // Node for clothing modification operations  
type BlendNode = any;       // Node for image blending operations
type EditNode = any;        // Node for general image editing operations
type CameraNode = any;      // Node for camera effect operations
type AgeNode = any;         // Node for age transformation operations
type FaceNode = any;        // Node for facial feature modification operations

/**

 * Utility function to combine CSS class names conditionally

 * Filters out falsy values and joins remaining strings with spaces

 * Same implementation as in page.tsx for consistent styling across components

 * 

 * @param args Array of class name strings or falsy values

 * @returns Combined class name string with falsy values filtered out

 */
function cx(...args: Array<string | false | null | undefined>) {
  return args.filter(Boolean).join(" ");  // Remove falsy values and join with spaces
}

/* ========================================

   SHARED COMPONENTS AND HOOKS

   ======================================== */

/**

 * Custom React hook for node dragging functionality

 * 

 * Handles the complex pointer event logic for dragging nodes around the editor.

 * Maintains local position state for smooth dragging while updating the parent

 * component's position when the drag operation completes.

 * 

 * Key Features:

 * - Smooth local position updates during drag

 * - Pointer capture for reliable drag behavior

 * - Prevents event bubbling to avoid conflicts

 * - Syncs with parent position updates

 * 

 * @param node The node object containing current position

 * @param onUpdatePosition Callback to update node position in parent state

 * @returns Object with position and event handlers for dragging

 */
function useNodeDrag(node: any, onUpdatePosition?: (id: string, x: number, y: number) => void) {
  const [localPos, setLocalPos] = useState({ x: node.x, y: node.y });  // Local position for smooth dragging
  const dragging = useRef(false);                                      // Track drag state
  const start = useRef<{ sx: number; sy: number; ox: number; oy: number } | null>(null);  // Drag start coordinates
  
  // Sync local position when parent position changes
  useEffect(() => {
    setLocalPos({ x: node.x, y: node.y });
  }, [node.x, node.y]);
  
  /**

   * Handle pointer down - start dragging

   * Captures the pointer and records starting positions

   */
  const onPointerDown = (e: React.PointerEvent) => {
    e.stopPropagation();                                             // Prevent event bubbling
    dragging.current = true;                                         // Mark as dragging
    start.current = { sx: e.clientX, sy: e.clientY, ox: localPos.x, oy: localPos.y };  // Record start positions
    (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); // Capture pointer for reliable tracking
  };
  
  /**

   * Handle pointer move - update position during drag

   * Calculates new position based on mouse movement delta

   */
  const onPointerMove = (e: React.PointerEvent) => {
    if (!dragging.current || !start.current) return;  // Only process if actively dragging
    const dx = e.clientX - start.current.sx;           // Calculate horizontal movement
    const dy = e.clientY - start.current.sy;           // Calculate vertical movement
    const newX = start.current.ox + dx;                // New X position
    const newY = start.current.oy + dy;                // New Y position
    setLocalPos({ x: newX, y: newY });                 // Update local position for immediate visual feedback
    if (onUpdatePosition) onUpdatePosition(node.id, newX, newY);  // Update parent state
  };
  
  /**

   * Handle pointer up - end dragging

   * Releases pointer capture and resets drag state

   */
  const onPointerUp = (e: React.PointerEvent) => {
    dragging.current = false;                                         // End dragging
    start.current = null;                                            // Clear start position
    (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);  // Release pointer
  };
  
  return { localPos, onPointerDown, onPointerMove, onPointerUp };
}

/**

 * Port component for node connections

 * 

 * Renders the small circular connection points on nodes that users can

 * drag between to create connections. Handles the pointer events for

 * starting and ending connection operations.

 * 

 * Types of ports:

 * - Input ports (left side): Receive connections from other nodes

 * - Output ports (right side): Send connections to other nodes

 * 

 * @param className Additional CSS classes to apply

 * @param nodeId The ID of the node this port belongs to

 * @param isOutput Whether this is an output port (true) or input port (false)

 * @param onStartConnection Callback when starting a connection from this port

 * @param onEndConnection Callback when ending a connection at this port

 */
function Port({ 

  className, 

  nodeId,

  isOutput,

  onStartConnection,

  onEndConnection,

  onDisconnect

}: { 

  className?: string;

  nodeId?: string;

  isOutput?: boolean;

  onStartConnection?: (nodeId: string) => void;

  onEndConnection?: (nodeId: string) => void;

  onDisconnect?: (nodeId: string) => void;

}) {
  /**

   * Handle starting a connection (pointer down on output port)

   */
  const handlePointerDown = (e: React.PointerEvent) => {
    e.stopPropagation();  // Prevent triggering node drag
    if (isOutput && nodeId && onStartConnection) {
      onStartConnection(nodeId);  // Start connection from this output port
    }
  };
  
  /**

   * Handle ending a connection (pointer up on input port)

   */
  const handlePointerUp = (e: React.PointerEvent) => {
    e.stopPropagation();  // Prevent bubbling
    if (!isOutput && nodeId && onEndConnection) {
      onEndConnection(nodeId);  // End connection at this input port
    }
  };

  /**

   * Handle clicking on input port to disconnect

   * Allows users to remove connections by clicking on input ports

   */
  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();                    // Prevent event from bubbling to parent elements
    if (!isOutput && nodeId && onDisconnect) {
      onDisconnect(nodeId);                 // Disconnect from this input port
    }
  };

  return (
    <div 

      className={cx("nb-port", className)}              // Combine base port classes with custom ones

      onPointerDown={handlePointerDown}                 // Start connection drag from output ports

      onPointerUp={handlePointerUp}                     // End connection drag at input ports

      onPointerEnter={handlePointerUp}                  // Also accept connections on hover (better UX)

      onClick={handleClick}                             // Allow clicking input ports to disconnect

      title={

        isOutput 

          ? "Drag from here to connect to another node's input" 

          : "Drop connections here or click to disconnect"

      }

    />
  );
}

/**

 * BACKGROUND NODE VIEW COMPONENT

 * 

 * Allows users to change or generate image backgrounds using various methods:

 * - Solid colors with color picker

 * - Preset background images (beach, office, studio, etc.)

 * - Custom uploaded images via file upload or drag/drop

 * - AI-generated backgrounds from text descriptions

 * 

 * Key Features:

 * - Multiple background source types (color/preset/upload/custom prompt)

 * - Drag and drop image upload functionality

 * - Paste image from clipboard support

 * - AI-powered prompt improvement using Gemini

 * - Real-time preview of uploaded images

 * - Connection management for node-based workflow

 * 

 * @param node - Background node data containing backgroundType, backgroundColor, etc.

 * @param onDelete - Callback to delete this node from the editor

 * @param onUpdate - Callback to update node properties (backgroundType, colors, images, etc.)

 * @param onStartConnection - Callback when user starts dragging from output port

 * @param onEndConnection - Callback when user drops connection on input port

 * @param onProcess - Callback to process this node and apply background changes

 * @param onUpdatePosition - Callback to update node position when dragged

 * @param getNodeHistoryInfo - Function to get processing history for this node

 * @param navigateNodeHistory - Function to navigate through different processing results

 * @param getCurrentNodeImage - Function to get the current processed image

 */
export function BackgroundNodeView({

  node,

  onDelete,

  onUpdate,

  onStartConnection,

  onEndConnection,

  onProcess,

  onUpdatePosition,

  apiToken

}: any) {
  // Use custom drag hook to handle node positioning in the editor
  const { localPos, onPointerDown, onPointerMove, onPointerUp } = useNodeDrag(node, onUpdatePosition);
  
  /**

   * Handle image file upload from file input

   * Converts uploaded file to base64 data URL for storage and preview

   */
  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files?.length) {
      const reader = new FileReader();                              // Create file reader
      reader.onload = () => {
        onUpdate(node.id, { customBackgroundImage: reader.result }); // Store base64 data URL
      };
      reader.readAsDataURL(e.target.files[0]);                    // Convert file to base64
    }
  };
  
  /**

   * Handle image paste from clipboard

   * Supports both image files and image URLs pasted from clipboard

   */
  const handleImagePaste = (e: React.ClipboardEvent) => {
    const items = e.clipboardData.items;                           // Get clipboard items
    
    // First, try to find image files in clipboard
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.startsWith("image/")) {                   // Check if item is an image
        const file = items[i].getAsFile();                        // Get image file
        if (file) {
          const reader = new FileReader();                         // Create file reader
          reader.onload = () => {
            onUpdate(node.id, { customBackgroundImage: reader.result }); // Store base64 data
          };
          reader.readAsDataURL(file);                              // Convert to base64
          return;                                                  // Exit early if image found
        }
      }
    }
    
    // If no image files, check for text that might be image URLs
    const text = e.clipboardData.getData("text");                 // Get text from clipboard
    if (text && (text.startsWith("http") || text.startsWith("data:image"))) {
      onUpdate(node.id, { customBackgroundImage: text });         // Use URL directly
    }
  };
  
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    if (files && files.length) {
      const reader = new FileReader();
      reader.onload = () => {
        onUpdate(node.id, { customBackgroundImage: reader.result });
      };
      reader.readAsDataURL(files[0]);
    }
  };
  
  return (
    <div 

      className="nb-node absolute text-white w-[320px]" 

      style={{ left: localPos.x, top: localPos.y }}

      onDrop={handleDrop}

      onDragOver={(e) => e.preventDefault()}

      onPaste={handleImagePaste}

    >

      <div 

        className="nb-header px-3 py-2 flex items-center justify-between rounded-t-[14px] cursor-grab active:cursor-grabbing"

        onPointerDown={onPointerDown}

        onPointerMove={onPointerMove}

        onPointerUp={onPointerUp}

      >

        <Port className="in" nodeId={node.id} isOutput={false} onEndConnection={onEndConnection} onDisconnect={(nodeId) => onUpdate(nodeId, { input: undefined })} />

        <div className="font-semibold text-sm flex-1 text-center">BACKGROUND</div>

        <div className="flex items-center gap-1">

          <Button

            variant="ghost"

            size="icon"

            className="text-destructive hover:bg-destructive/20 h-6 w-6"

            onClick={(e) => {

              e.stopPropagation();

              e.preventDefault();

              if (confirm('Delete this node?')) {

                onDelete(node.id);

              }

            }}

            onPointerDown={(e) => e.stopPropagation()}

            title="Delete node"

            aria-label="Delete node"

          >

            ×

          </Button>

          <Port className="out" nodeId={node.id} isOutput={true} onStartConnection={onStartConnection} />

        </div>

      </div>

      {/* Node Content Area - Contains all controls, inputs, and outputs */}

      <div className="p-3 space-y-3">

        {node.input && (

          <div className="flex justify-end mb-2">

            <Button

              variant="ghost"

              size="sm"

              onClick={() => onUpdate(node.id, { input: undefined })}

              className="text-xs"

            >

              Clear Connection                                    {/* Remove input connection to this node */}

            </Button>

          </div>

        )}

        <Select 

          className="w-full"

          value={node.backgroundType || "color"}

          onChange={(e) => onUpdate(node.id, { backgroundType: (e.target as HTMLSelectElement).value })}

        >

          <option value="color">Solid Color</option>

          <option value="gradient">Gradient Color</option>

          <option value="image">Preset Background</option>

          <option value="city">City Scene</option>

          <option value="photostudio">Photo Studio</option>

          <option value="upload">Upload Image</option>

          <option value="custom">Custom Prompt</option>

        </Select>

        

        {node.backgroundType === "color" && (

          <ColorPicker

            className="w-full"

            value={node.backgroundColor || "#ffffff"}

            onChange={(e) => onUpdate(node.id, { backgroundColor: (e.target as HTMLInputElement).value })}

          />

        )}

        

        {node.backgroundType === "gradient" && (

          <div className="space-y-3">

            <label className="text-xs text-white/70">Gradient Direction</label>

            <Select 

              className="w-full"

              value={node.gradientDirection || "to right"}

              onChange={(e) => onUpdate(node.id, { gradientDirection: (e.target as HTMLSelectElement).value })}

            >

              <option value="to right">Left to Right</option>

              <option value="to left">Right to Left</option>

              <option value="to bottom">Top to Bottom</option>

              <option value="to top">Bottom to Top</option>

              <option value="to bottom right">Diagonal Top-Left to Bottom-Right</option>

              <option value="to bottom left">Diagonal Top-Right to Bottom-Left</option>

              <option value="to top right">Diagonal Bottom-Left to Top-Right</option>

              <option value="to top left">Diagonal Bottom-Right to Top-Left</option>

              <option value="radial">Radial (Center to Edge)</option>

            </Select>

            <label className="text-xs text-white/70">Start Color</label>

            <ColorPicker

              className="w-full"

              value={node.gradientStartColor || "#ff6b6b"}

              onChange={(e) => onUpdate(node.id, { gradientStartColor: (e.target as HTMLInputElement).value })}

            />

            <label className="text-xs text-white/70">End Color</label>

            <ColorPicker

              className="w-full"

              value={node.gradientEndColor || "#4ecdc4"}

              onChange={(e) => onUpdate(node.id, { gradientEndColor: (e.target as HTMLInputElement).value })}

            />

            <div 

              className="w-full h-8 rounded-md border border-white/20"

              style={{

                background: node.gradientDirection === "radial" 

                  ? `radial-gradient(circle, ${node.gradientStartColor || "#ff6b6b"} 0%, ${node.gradientEndColor || "#4ecdc4"} 100%)`

                  : `linear-gradient(${node.gradientDirection || "to right"}, ${node.gradientStartColor || "#ff6b6b"} 0%, ${node.gradientEndColor || "#4ecdc4"} 100%)`

              }}

              title="Gradient Preview"

            />

          </div>

        )}

        

        {node.backgroundType === "image" && (

          <Select 

            className="w-full"

            value={node.backgroundImage || ""}

            onChange={(e) => onUpdate(node.id, { backgroundImage: (e.target as HTMLSelectElement).value })}

          >

            <option value="">Select Background</option>

            <option value="beach">Beach</option>

            <option value="office">Office</option>

            <option value="studio">Studio</option>

            <option value="nature">Nature</option>

            <option value="city">City Skyline</option>

          </Select>

        )}

        

        {node.backgroundType === "city" && (

          <div className="space-y-3">

            <label className="text-xs text-white/70">City Scene Type</label>

            <Select 

              className="w-full"

              value={node.citySceneType || "busy_street"}

              onChange={(e) => onUpdate(node.id, { citySceneType: (e.target as HTMLSelectElement).value })}

            >

              <option value="busy_street">Busy Street with Close Pedestrians</option>

              <option value="tokyo_shibuya">Tokyo Shibuya Crossing</option>

              <option value="tokyo_subway">Tokyo Subway</option>

              <option value="times_square">Times Square NYC</option>

              <option value="downtown_skyline">Downtown Skyline</option>

              <option value="urban_crosswalk">Urban Crosswalk Scene</option>

              <option value="shopping_district">Shopping District</option>

              <option value="city_park">City Park</option>

              <option value="rooftop_view">Rooftop City View</option>

              <option value="blade_runner_street">Blade Runner Style Street</option>

              <option value="matrix_alley">Matrix Style Urban Alley</option>

            </Select>

            <label className="text-xs text-white/70">Time of Day</label>

            <Select 

              className="w-full"

              value={node.cityTimeOfDay || "daytime"}

              onChange={(e) => onUpdate(node.id, { cityTimeOfDay: (e.target as HTMLSelectElement).value })}

            >

              <option value="golden_hour">Golden Hour</option>

              <option value="daytime">Daytime</option>

              <option value="blue_hour">Blue Hour</option>

              <option value="night">Night with City Lights</option>

              <option value="dawn">Dawn</option>

              <option value="overcast">Overcast Day</option>

            </Select>

          </div>

        )}

        

        {node.backgroundType === "photostudio" && (

          <div className="space-y-3">

            <label className="text-xs text-white/70">Studio Setup</label>

            <Select 

              className="w-full"

              value={node.studioSetup || "white_seamless"}

              onChange={(e) => onUpdate(node.id, { studioSetup: (e.target as HTMLSelectElement).value })}

            >

              <option value="white_seamless">White Seamless Background</option>

              <option value="black_seamless">Black Seamless Background</option>

              <option value="grey_seamless">Grey Seamless Background</option>

              <option value="colored_seamless">Colored Seamless Background</option>

              <option value="textured_backdrop">Textured Backdrop</option>

              <option value="infinity_cove">Infinity Cove</option>

            </Select>

            {node.studioSetup === "colored_seamless" && (

              <>

                <label className="text-xs text-white/70">Background Color</label>

                <ColorPicker

                  className="w-full"

                  value={node.studioBackgroundColor || "#ffffff"}

                  onChange={(e) => onUpdate(node.id, { studioBackgroundColor: (e.target as HTMLInputElement).value })}

                />

              </>

            )}

            <label className="text-xs text-white/70">Lighting Setup</label>

            <Select 

              className="w-full"

              value={node.studioLighting || "key_fill"}

              onChange={(e) => onUpdate(node.id, { studioLighting: (e.target as HTMLSelectElement).value })}

            >

              <option value="key_fill">Key + Fill Light</option>

              <option value="three_point">Three-Point Lighting</option>

              <option value="beauty_lighting">Beauty Lighting</option>

              <option value="dramatic_lighting">Dramatic Single Light</option>

              <option value="soft_lighting">Soft Diffused Lighting</option>

              <option value="hard_lighting">Hard Directional Lighting</option>

            </Select>

            <div className="flex items-center gap-2">

              <input

                type="checkbox"

                checked={node.faceCamera || false}

                onChange={(e) => onUpdate(node.id, { faceCamera: (e.target as HTMLInputElement).checked })}

                className="w-4 h-4"

              />

              <label className="text-xs text-white/70">Position character to face camera</label>

            </div>

          </div>

        )}

        

        {node.backgroundType === "upload" && (

          <div className="space-y-2">

            {node.customBackgroundImage ? (

              <div className="relative">

                <img src={node.customBackgroundImage} className="w-full rounded" alt="Custom Background" />

                <Button 

                  variant="destructive"

                  size="sm"

                  className="absolute top-2 right-2"

                  onClick={() => onUpdate(node.id, { customBackgroundImage: null })}

                >

                  Remove

                </Button>

              </div>

            ) : (

              <label className="block">

                <input

                  type="file"

                  accept="image/*"

                  className="hidden"

                  onChange={handleImageUpload}

                />

                <div className="border-2 border-dashed border-white/20 rounded-lg p-4 text-center cursor-pointer hover:border-white/40">

                  <p className="text-xs text-white/60">Drop, upload, or paste background image</p>

                  <p className="text-xs text-white/40 mt-1">JPG, PNG, WEBP</p>

                </div>

              </label>

            )}

          </div>

        )}

        

        {node.backgroundType === "custom" && (

          <div className="space-y-2">

            <Textarea

              className="w-full"

              placeholder="Describe the background..."

              value={node.customPrompt || ""}

              onChange={(e) => onUpdate(node.id, { customPrompt: (e.target as HTMLTextAreaElement).value })}

              rows={2}

            />

            <Button

              variant="outline"

              size="sm"

              className="w-full text-xs"

              onClick={async () => {

                if (!node.customPrompt) {

                  alert('Please enter a background description first');

                  return;

                }

                

                try {

                  const response = await fetch('/api/improve-prompt', {

                    method: 'POST',

                    headers: { 'Content-Type': 'application/json' },

                    body: JSON.stringify({

                      prompt: node.customPrompt,

                      type: 'background',

                      apiToken: apiToken || undefined

                    })

                  });

                  

                  if (response.ok) {

                    const { improvedPrompt } = await response.json();

                    onUpdate(node.id, { customPrompt: improvedPrompt });

                  } else {

                    alert('Failed to improve prompt. Please try again.');

                  }

                } catch (error) {

                  console.error('Error improving prompt:', error);

                  alert('Failed to improve prompt. Please try again.');

                }

              }}

              title="Use Gemini 2.5 Flash to improve your background prompt"

            >

              ✨ Improve with Gemini

            </Button>

          </div>

        )}

        

        <Button 

          className="w-full"

          onClick={() => onProcess(node.id)}

          disabled={node.isRunning}

          title={!node.input ? "Connect an input first" : "Process all unprocessed nodes in chain"}

        >

          {node.isRunning ? "Processing..." : "Apply Background"}

        </Button>

        

        <NodeOutputSection

          nodeId={node.id}

          output={node.output}

          downloadFileName={`background-${Date.now()}.png`}

        />

        {node.error && (

          <div className="text-xs text-red-400 mt-2">{node.error}</div>

        )}

      </div>
    </div>
  );
}

/**

 * CLOTHES NODE VIEW COMPONENT

 * 

 * Allows users to add or modify clothing on subjects in images.

 * Supports both preset clothing options and custom uploaded garments.

 * 

 * Key Features:

 * - Preset clothing gallery (Sukajan, Blazer, Suit, Women's Outfit)

 * - Custom clothing upload via drag/drop, file picker, or clipboard paste

 * - Visual selection interface with thumbnails

 * - Real-time preview of selected clothing

 * - Integration with AI processing pipeline

 * 

 * The node processes input images and applies the selected clothing using

 * AI models that understand garment fitting and realistic clothing application.

 * 

 * @param node - Clothes node data containing clothesImage, selectedPreset, etc.

 * @param onDelete - Callback to delete this node

 * @param onUpdate - Callback to update node properties

 * @param onStartConnection - Callback when starting connection from output

 * @param onEndConnection - Callback when ending connection at input

 * @param onProcess - Callback to process this node

 * @param onUpdatePosition - Callback to update node position

 * @param getNodeHistoryInfo - Function to get processing history

 * @param navigateNodeHistory - Function to navigate history

 * @param getCurrentNodeImage - Function to get current image

 */
export function ClothesNodeView({ node, onDelete, onUpdate, onStartConnection, onEndConnection, onProcess, onUpdatePosition, getNodeHistoryInfo, navigateNodeHistory, getCurrentNodeImage }: any) {
  // Handle node dragging functionality
  const { localPos, onPointerDown, onPointerMove, onPointerUp } = useNodeDrag(node, onUpdatePosition);
  
  /**

   * Preset clothing options available for quick selection

   * Each preset includes a display name and path to the reference image

   */
  const presetClothes = [
    { name: "Sukajan", path: "/clothes/sukajan.png" },           // Japanese-style embroidered jacket
    { name: "Blazer", path: "/clothes/blazzer.png" },            // Business blazer/jacket
    { name: "Suit", path: "/clothes/suit.png" },                 // Formal business suit
    { name: "Women's Outfit", path: "/clothes/womenoutfit.png" }, // Women's clothing ensemble
  ];

  const onDrop = async (e: React.DragEvent) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    if (files && files.length) {
      const reader = new FileReader();
      reader.onload = () => onUpdate(node.id, { clothesImage: reader.result, selectedPreset: null });
      reader.readAsDataURL(files[0]);
    }
  };

  const onPaste = async (e: React.ClipboardEvent) => {
    const items = e.clipboardData.items;
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.startsWith("image/")) {
        const file = items[i].getAsFile();
        if (file) {
          const reader = new FileReader();
          reader.onload = () => onUpdate(node.id, { clothesImage: reader.result, selectedPreset: null });
          reader.readAsDataURL(file);
          return;
        }
      }
    }
    const text = e.clipboardData.getData("text");
    if (text && (text.startsWith("http") || text.startsWith("data:image"))) {
      onUpdate(node.id, { clothesImage: text, selectedPreset: null });
    }
  };

  const selectPreset = (presetPath: string, presetName: string) => {
    onUpdate(node.id, { clothesImage: presetPath, selectedPreset: presetName });
  };
  
  return (
    <div 

      className="nb-node absolute text-white w-[320px]"

      style={{ left: localPos.x, top: localPos.y }}

      onDrop={onDrop}

      onDragOver={(e) => e.preventDefault()}

      onPaste={onPaste}

    >

      <div 

        className="nb-header px-3 py-2 flex items-center justify-between rounded-t-[14px] cursor-grab active:cursor-grabbing"

        onPointerDown={onPointerDown}

        onPointerMove={onPointerMove}

        onPointerUp={onPointerUp}

      >

        <Port className="in" nodeId={node.id} isOutput={false} onEndConnection={onEndConnection} onDisconnect={(nodeId) => onUpdate(nodeId, { input: undefined })} />

        <div className="font-semibold text-sm flex-1 text-center">CLOTHES</div>

        <div className="flex items-center gap-1">

          <Button

            variant="ghost"

            size="icon"

            className="text-destructive hover:bg-destructive/20 h-6 w-6"

            onClick={(e) => {

              e.stopPropagation();

              e.preventDefault();

              if (confirm('Delete this node?')) {

                onDelete(node.id);

              }

            }}

            onPointerDown={(e) => e.stopPropagation()}

            title="Delete node"

            aria-label="Delete node"

          >

            ×

          </Button>

          <Port className="out" nodeId={node.id} isOutput={true} onStartConnection={onStartConnection} />

        </div>

      </div>

      {/* Node Content Area - Contains all controls, inputs, and outputs */}

      <div className="p-3 space-y-3">

        {node.input && (

          <div className="flex justify-end mb-2">

            <Button

              variant="ghost"

              size="sm"

              onClick={() => onUpdate(node.id, { input: undefined })}

              className="text-xs"

            >

              Clear Connection                                    {/* Remove input connection to this node */}

            </Button>

          </div>

        )}

        <div className="text-xs text-white/70">Clothes Reference</div>

        

        {/* Preset clothes options */}

        <div className="flex gap-2">

          {presetClothes.map((preset) => (

            <button

              key={preset.name}

              className={`flex-1 p-2 rounded border ${

                node.selectedPreset === preset.name

                  ? "border-indigo-400 bg-indigo-500/20"

                  : "border-white/20 hover:border-white/40"

              }`}

              onClick={() => selectPreset(preset.path, preset.name)}

            >

              <img src={preset.path} alt={preset.name} className="w-full h-28 object-contain rounded mb-1" />

              <div className="text-xs">{preset.name}</div>

            </button>

          ))}

        </div>

        

        <div className="text-xs text-white/50 text-center">— or —</div>

        

        {/* Custom image upload */}

        {node.clothesImage && !node.selectedPreset ? (

          <div className="relative">

            <img src={node.clothesImage} className="w-full rounded" alt="Clothes" />

            <Button 

              variant="destructive"

              size="sm"

              className="absolute top-2 right-2"

              onClick={() => onUpdate(node.id, { clothesImage: null, selectedPreset: null })}

            >

              Remove

            </Button>

          </div>

        ) : !node.selectedPreset ? (

          <label className="block">

            <input

              type="file"

              accept="image/*"

              className="hidden"

              onChange={(e) => {

                if (e.target.files?.length) {

                  const reader = new FileReader();

                  reader.onload = () => onUpdate(node.id, { clothesImage: reader.result, selectedPreset: null });

                  reader.readAsDataURL(e.target.files[0]);

                }

              }}

            />

            <div className="border-2 border-dashed border-white/20 rounded-lg p-6 text-center cursor-pointer hover:border-white/40 transition-colors">

              <div className="text-white/40 text-lg mb-2">📁</div>

              <p className="text-sm text-white/70 font-medium">Drop, upload, or paste clothes image</p>

              <p className="text-xs text-white/50 mt-1">JPG, PNG, WebP supported</p>

            </div>

          </label>

        ) : null}

        

        <Button 

          className="w-full"

          onClick={() => onProcess(node.id)}

          disabled={node.isRunning || !node.clothesImage}

          title={!node.input ? "Connect an input first" : "Process all unprocessed nodes in chain"}

        >

          {node.isRunning ? "Processing..." : "Apply Clothes"}

        </Button>

        <NodeOutputSection

          nodeId={node.id}

          output={node.output}

          downloadFileName={`clothes-${Date.now()}.png`}

        />

        {node.error && (

          <div className="text-xs text-red-400 mt-2">{node.error}</div>

        )}

      </div>

    </div>
  );
}

/**

 * AGE NODE VIEW COMPONENT

 * 

 * Allows users to transform the apparent age of subjects in images.

 * Uses AI age transformation models to make people appear older or younger

 * while maintaining facial features and identity.

 * 

 * Key Features:

 * - Slider-based age selection (18-100 years)

 * - Real-time age value display

 * - Preserves facial identity during transformation

 * - Smooth age progression/regression

 * 

 * The AI models understand facial aging patterns and can:

 * - Add/remove wrinkles and age lines

 * - Adjust skin texture and tone

 * - Modify facial structure subtly

 * - Maintain eye color and basic facial features

 * 

 * @param node - Age node data containing targetAge, input, output, etc.

 * @param onDelete - Callback to delete this node

 * @param onUpdate - Callback to update node properties (targetAge)

 * @param onStartConnection - Callback when starting connection from output

 * @param onEndConnection - Callback when ending connection at input

 * @param onProcess - Callback to process age transformation

 * @param onUpdatePosition - Callback to update node position

 * @param getNodeHistoryInfo - Function to get processing history

 * @param navigateNodeHistory - Function to navigate history

 * @param getCurrentNodeImage - Function to get current image

 */
export function AgeNodeView({ node, onDelete, onUpdate, onStartConnection, onEndConnection, onProcess, onUpdatePosition, getNodeHistoryInfo, navigateNodeHistory, getCurrentNodeImage }: any) {
  // Handle node dragging functionality
  const { localPos, onPointerDown, onPointerMove, onPointerUp } = useNodeDrag(node, onUpdatePosition);
  
  return (
    <div className="nb-node absolute text-white w-[280px]" style={{ left: localPos.x, top: localPos.y }}>

      <div 

        className="nb-header px-3 py-2 flex items-center justify-between rounded-t-[14px] cursor-grab active:cursor-grabbing"

        onPointerDown={onPointerDown}

        onPointerMove={onPointerMove}

        onPointerUp={onPointerUp}

      >

        <Port className="in" nodeId={node.id} isOutput={false} onEndConnection={onEndConnection} onDisconnect={(nodeId) => onUpdate(nodeId, { input: undefined })} />

        <div className="font-semibold text-sm flex-1 text-center">AGE</div>

        <div className="flex items-center gap-1">

          <Button

            variant="ghost"

            size="icon"

            className="text-destructive hover:bg-destructive/20 h-6 w-6"

            onClick={(e) => {

              e.stopPropagation();

              e.preventDefault();

              if (confirm('Delete this node?')) {

                onDelete(node.id);

              }

            }}

            onPointerDown={(e) => e.stopPropagation()}

            title="Delete node"

            aria-label="Delete node"

          >

            ×

          </Button>

          <Port className="out" nodeId={node.id} isOutput={true} onStartConnection={onStartConnection} />

        </div>

      </div>

      {/* Node Content Area - Contains all controls, inputs, and outputs */}

      <div className="p-3 space-y-3">

        {node.input && (

          <div className="flex justify-end mb-2">

            <Button

              variant="ghost"

              size="sm"

              onClick={() => onUpdate(node.id, { input: undefined })}

              className="text-xs"

            >

              Clear Connection                                    {/* Remove input connection to this node */}

            </Button>

          </div>

        )}

        <div>

          <Slider

            label="Target Age"

            valueLabel={`${node.targetAge || 30} years`}

            min={18}

            max={100}

            value={node.targetAge || 30}

            onChange={(e) => onUpdate(node.id, { targetAge: parseInt((e.target as HTMLInputElement).value) })}

          />

        </div>

        <Button 

          className="w-full"

          onClick={() => onProcess(node.id)}

          disabled={node.isRunning}

          title={!node.input ? "Connect an input first" : "Process all unprocessed nodes in chain"}

        >

          {node.isRunning ? "Processing..." : "Apply Age"}

        </Button>

        <NodeOutputSection

          nodeId={node.id}

          output={node.output}

          downloadFileName={`age-${Date.now()}.png`}

        />

        {node.error && (

          <div className="text-xs text-red-400 mt-2">{node.error}</div>

        )}

      </div>

    </div>
  );
}

/**

 * CAMERA NODE VIEW COMPONENT

 * 

 * Applies professional camera settings and photographic effects to images.

 * Simulates various camera equipment, settings, and photographic techniques

 * to achieve specific visual styles and technical characteristics.

 * 

 * Key Features:

 * - Complete camera settings simulation (focal length, aperture, shutter speed, ISO)

 * - Film stock emulation (Kodak, Fuji, Ilford, etc.)

 * - Professional lighting setups (studio, natural, dramatic)

 * - Composition guides (rule of thirds, golden ratio, etc.)

 * - Bokeh effects and depth of field control

 * - Color temperature and white balance adjustment

 * - Aspect ratio modifications

 * 

 * Technical Settings Available:

 * - Focal lengths from fisheye (8mm) to telephoto (400mm)

 * - Aperture range from f/0.95 to f/22

 * - Shutter speeds from 1/8000s to 30s

 * - ISO values from 50 to 12800

 * - Professional lighting setups

 * - Film stock characteristics

 * 

 * @param node - Camera node data containing all camera settings

 * @param onDelete - Callback to delete this node

 * @param onUpdate - Callback to update camera settings

 * @param onStartConnection - Callback when starting connection from output

 * @param onEndConnection - Callback when ending connection at input

 * @param onProcess - Callback to process camera effects

 * @param onUpdatePosition - Callback to update node position

 * @param getNodeHistoryInfo - Function to get processing history

 * @param navigateNodeHistory - Function to navigate history

 * @param getCurrentNodeImage - Function to get current image

 */
export function CameraNodeView({ node, onDelete, onUpdate, onStartConnection, onEndConnection, onProcess, onUpdatePosition, getNodeHistoryInfo, navigateNodeHistory, getCurrentNodeImage }: any) {
  // Handle node dragging functionality
  const { localPos, onPointerDown, onPointerMove, onPointerUp } = useNodeDrag(node, onUpdatePosition);
  
  // Camera lens focal length options (affects field of view and perspective)
  const focalLengths = ["None", "8mm", "12mm", "24mm", "35mm", "50mm", "85mm", "100mm", "135mm"];
  
  // Aperture settings (affects depth of field and exposure)
  const apertures = ["None", "f/0.95", "f/1.2", "f/1.4", "f/1.8", "f/2", "f/2.8", "f/4", "f/5.6","f/11"];
  
  // Shutter speed options (affects motion blur and exposure)
  const shutterSpeeds = ["None", "1/1000s", "1/250s","1/30s","1/15", "5s", ];
  
  // White balance presets for different lighting conditions
  const whiteBalances = ["None", "2800K candlelight", "3200K tungsten", "4000K fluorescent", "5600K daylight", "6500K cloudy", "7000K shade", "8000K blue sky"];
  
  // Camera angle and perspective options
  const angles = ["None", "eye level", "low angle", "high angle", "Dutch tilt", "bird's eye", "worm's eye", "over the shoulder", "POV"];
  
  // ISO sensitivity values (affects image noise and exposure)
  const isoValues = ["None",  "ISO 100", "ISO 400", "ISO 1600", "ISO 6400"];
  
  // Film stock emulation for different photographic styles
  const filmStyles = ["None","RAW","Kodak Portra", "Fuji Velvia", "Kodak Gold 200","Black & White", "Sepia", "Vintage", "Film Noir"];
  
  // Professional lighting setups and natural lighting conditions
  const lightingTypes = ["None", "Natural Light", "Golden Hour", "Blue Hour", "Studio Lighting", "Rembrandt", "Split Lighting", "Butterfly Lighting", "Loop Lighting", "Rim Lighting", "Silhouette", "High Key", "Low Key"];
  
  // Bokeh (background blur) styles for different lens characteristics
  const bokehStyles = ["None", "Smooth Bokeh", "Swirly Bokeh", "Hexagonal Bokeh", "Cat Eye Bokeh", "Bubble Bokeh"];

  // Motion blur options
  const motionBlurOptions = ["None", "Light Motion Blur", "Medium Motion Blur", "Heavy Motion Blur", "Radial Blur", "Zoom Blur"];

  return (
    <div className="nb-node absolute text-white w-[360px]" style={{ left: localPos.x, top: localPos.y }}>

      <div 

        className="nb-header px-3 py-2 flex items-center justify-between rounded-t-[14px] cursor-grab active:cursor-grabbing"

        onPointerDown={onPointerDown}

        onPointerMove={onPointerMove}

        onPointerUp={onPointerUp}

      >

        <Port className="in" nodeId={node.id} isOutput={false} onEndConnection={onEndConnection} onDisconnect={(nodeId) => onUpdate(nodeId, { input: undefined })} />

        <div className="font-semibold text-sm flex-1 text-center">CAMERA</div>

        <div className="flex items-center gap-1">

          <Button

            variant="ghost"

            size="icon"

            className="text-destructive hover:bg-destructive/20 h-6 w-6"

            onClick={(e) => {

              e.stopPropagation();

              e.preventDefault();

              if (confirm('Delete this node?')) {

                onDelete(node.id);

              }

            }}

            onPointerDown={(e) => e.stopPropagation()}

            title="Delete node"

            aria-label="Delete node"

          >

            ×

          </Button>

          <Port className="out" nodeId={node.id} isOutput={true} onStartConnection={onStartConnection} />

        </div>

      </div>

      <div className="p-3 space-y-2 max-h-[500px] overflow-y-auto scrollbar-thin">

        {node.input && (

          <div className="flex justify-end mb-2">

            <Button

              variant="ghost"

              size="sm"

              onClick={() => onUpdate(node.id, { input: undefined })}

              className="text-xs"

            >

              Clear Connection                                    {/* Remove input connection to this node */}

            </Button>

          </div>

        )}

        {/* Basic Camera Settings Section */}

        <div className="text-xs text-white/50 font-semibold mb-1">Basic Settings</div>

        <div className="grid grid-cols-2 gap-2">                     {/* 2-column grid for compact layout */}

          {/* Motion Blur Control - adds movement effects */}

          <div>

            <label className="text-xs text-white/70">Motion Blur</label>

            <Select 

              className="w-full"

              value={node.motionBlur || "None"}                   // Default to "None" if not set

              onChange={(e) => onUpdate(node.id, { motionBlur: (e.target as HTMLSelectElement).value })}

              title="Select Motion Blur Effect"

            >

              {motionBlurOptions.map(f => <option key={f} value={f}>{f}</option>)}

            </Select>

          </div>

          {/* Focal Length Control - affects field of view and perspective */}

          <div>

            <label className="text-xs text-white/70">Focal Length</label>

            <Select 

              className="w-full"

              value={node.focalLength || "None"}                   // Default to "None" if not set

              onChange={(e) => onUpdate(node.id, { focalLength: (e.target as HTMLSelectElement).value })}

              title="Select lens focal length - affects field of view and perspective distortion"

            >

              {focalLengths.map(f => <option key={f} value={f}>{f}</option>)}

            </Select>

          </div>

          

          {/* Aperture Control - affects depth of field and exposure */}

          <div>

            <label className="text-xs text-white/70">Aperture</label>

            <Select 

              className="w-full"

              value={node.aperture || "None"}                     // Default to "None" if not set

              onChange={(e) => onUpdate(node.id, { aperture: (e.target as HTMLSelectElement).value })}

              title="Select aperture value - lower f-numbers create shallower depth of field"

            >

              {apertures.map(a => <option key={a} value={a}>{a}</option>)}

            </Select>

          </div>

          

          {/* Shutter Speed Control - affects motion blur and exposure */}

          <div>

            <label className="text-xs text-white/70">Shutter Speed</label>

            <Select 

              className="w-full"

              value={node.shutterSpeed || "None"}                 // Default to "None" if not set

              onChange={(e) => onUpdate(node.id, { shutterSpeed: (e.target as HTMLSelectElement).value })}

              title="Select shutter speed - faster speeds freeze motion, slower speeds create blur"

            >

              {shutterSpeeds.map(s => <option key={s} value={s}>{s}</option>)}

            </Select>

          </div>

          

          {/* ISO Control - affects sensor sensitivity and image noise */}

          <div>

            <label className="text-xs text-white/70">ISO</label>

            <Select 

              className="w-full"

              value={node.iso || "None"}                          // Default to "None" if not set

              onChange={(e) => onUpdate(node.id, { iso: (e.target as HTMLSelectElement).value })}

              title="Select ISO value - higher values increase sensitivity but add noise"

            >

              {isoValues.map(i => <option key={i} value={i}>{i}</option>)}

            </Select>

          </div>

        </div>

        

        {/* Creative Settings */}

        <div className="text-xs text-white/50 font-semibold mb-1 mt-3">Creative Settings</div>

        <div className="grid grid-cols-2 gap-2">

          <div>

            <label className="text-xs text-white/70">White Balance</label>

            <Select 

              className="w-full"

              value={node.whiteBalance || "None"}

              onChange={(e) => onUpdate(node.id, { whiteBalance: (e.target as HTMLSelectElement).value })}

            >

              {whiteBalances.map(w => <option key={w} value={w}>{w}</option>)}

            </Select>

          </div>

          <div>

            <label className="text-xs text-white/70">Film Style</label>

            <Select 

              className="w-full"

              value={node.filmStyle || "None"}

              onChange={(e) => onUpdate(node.id, { filmStyle: (e.target as HTMLSelectElement).value })}

            >

              {filmStyles.map(f => <option key={f} value={f}>{f}</option>)}

            </Select>

          </div>

          <div>

            <label className="text-xs text-white/70">Lighting</label>

            <Select 

              className="w-full"

              value={node.lighting || "None"}

              onChange={(e) => onUpdate(node.id, { lighting: (e.target as HTMLSelectElement).value })}

            >

              {lightingTypes.map(l => <option key={l} value={l}>{l}</option>)}

            </Select>

          </div>

          <div>

            <label className="text-xs text-white/70">Bokeh Style</label>

            <Select 

              className="w-full"

              value={node.bokeh || "None"}

              onChange={(e) => onUpdate(node.id, { bokeh: (e.target as HTMLSelectElement).value })}

            >

              {bokehStyles.map(b => <option key={b} value={b}>{b}</option>)}

            </Select>

          </div>

        </div>

        

        {/* Composition Settings */}

        <div className="text-xs text-white/50 font-semibold mb-1 mt-3">Composition</div>

        <div className="grid grid-cols-2 gap-2">

          <div>

            <label className="text-xs text-white/70">Camera Angle</label>

            <Select 

              className="w-full"

              value={node.angle || "None"}

              onChange={(e) => onUpdate(node.id, { angle: (e.target as HTMLSelectElement).value })}

            >

              {angles.map(a => <option key={a} value={a}>{a}</option>)}

            </Select>

          </div>

        </div>

        <Button 

          className="w-full"

          onClick={() => onProcess(node.id)}

          disabled={node.isRunning}

          title={!node.input ? "Connect an input first" : "Process all unprocessed nodes in chain"}

        >

          {node.isRunning ? "Processing..." : "Apply Camera Settings"}

        </Button>

        <div className="mt-2">

          <NodeOutputSection

            nodeId={node.id}

            output={node.output}

            downloadFileName={`camera-${Date.now()}.png`}

          />

        </div>

        {node.error && (

          <div className="text-xs text-red-400 mt-2">{node.error}</div>

        )}

      </div>

    </div>
  );
}

/**

 * FACE NODE VIEW COMPONENT

 * 

 * Provides comprehensive facial feature modification capabilities.

 * Allows users to change various aspects of faces in images including

 * hairstyles, expressions, facial hair, accessories, and makeup.

 * 

 * Key Features:

 * - Hairstyle modifications (short, long, curly, straight, etc.)

 * - Facial expression changes (happy, sad, surprised, etc.)

 * - Beard and mustache styling options

 * - Accessory addition (sunglasses, hats)

 * - Makeup application with preset styles

 * - Skin enhancement (pimple removal)

 * 

 * The AI models can:

 * - Preserve facial identity while making changes

 * - Apply realistic hair textures and colors

 * - Generate natural-looking expressions

 * - Add accessories that fit properly

 * - Apply makeup that matches lighting and skin tone

 * 

 * @param node - Face node data containing all face modification settings

 * @param onDelete - Callback to delete this node

 * @param onUpdate - Callback to update face settings

 * @param onStartConnection - Callback when starting connection from output

 * @param onEndConnection - Callback when ending connection at input

 * @param onProcess - Callback to process face modifications

 * @param onUpdatePosition - Callback to update node position

 * @param getNodeHistoryInfo - Function to get processing history

 * @param navigateNodeHistory - Function to navigate history

 * @param getCurrentNodeImage - Function to get current image

 */
export function FaceNodeView({ node, onDelete, onUpdate, onStartConnection, onEndConnection, onProcess, onUpdatePosition, getNodeHistoryInfo, navigateNodeHistory, getCurrentNodeImage }: any) {
  // Handle node dragging functionality
  const { localPos, onPointerDown, onPointerMove, onPointerUp } = useNodeDrag(node, onUpdatePosition);
  
  // Available hairstyle options for hair modification
  const hairstyles = ["None", "short", "long", "curly", "straight", "bald", "mohawk", "ponytail"];
  
  // Facial expression options for emotion changes
  const expressions = ["None", "happy", "serious", "smiling", "laughing", "sad", "surprised", "angry"];
  
  // Beard and facial hair styling options
  const beardStyles = ["None", "stubble", "goatee", "full beard", "mustache", "clean shaven"];

  return (
    <div className="nb-node absolute text-white w-[340px]" style={{ left: localPos.x, top: localPos.y }}>

      <div 

        className="nb-header px-3 py-2 flex items-center justify-between rounded-t-[14px] cursor-grab active:cursor-grabbing"

        onPointerDown={onPointerDown}

        onPointerMove={onPointerMove}

        onPointerUp={onPointerUp}

      >

        <Port className="in" nodeId={node.id} isOutput={false} onEndConnection={onEndConnection} onDisconnect={(nodeId) => onUpdate(nodeId, { input: undefined })} />

        <div className="font-semibold text-sm flex-1 text-center">FACE</div>

        <div className="flex items-center gap-1">

          <Button

            variant="ghost"

            size="icon"

            className="text-destructive hover:bg-destructive/20 h-6 w-6"

            onClick={(e) => {

              e.stopPropagation();

              e.preventDefault();

              if (confirm('Delete this node?')) {

                onDelete(node.id);

              }

            }}

            onPointerDown={(e) => e.stopPropagation()}

            title="Delete node"

            aria-label="Delete node"

          >

            ×

          </Button>

          <Port className="out" nodeId={node.id} isOutput={true} onStartConnection={onStartConnection} />

        </div>

      </div>

      <div className="p-3 space-y-2 max-h-[500px] overflow-y-auto scrollbar-thin">

        {node.input && (

          <div className="flex justify-end mb-2">

            <Button

              variant="ghost"

              size="sm"

              onClick={() => onUpdate(node.id, { input: undefined })}

              className="text-xs"

            >

              Clear Connection                                    {/* Remove input connection to this node */}

            </Button>

          </div>

        )}

        {/* Face Enhancement Checkboxes - toggleable options for face improvements and accessories */}

        <div className="space-y-2">

          {/* Pimple removal option for skin enhancement */}

          <label className="flex items-center gap-2 text-xs cursor-pointer">

            <Checkbox 

              checked={node.faceOptions?.removePimples || false}    // Default to false if not set

              onChange={(e) => onUpdate(node.id, { 

                faceOptions: { 

                  ...node.faceOptions,                             // Preserve existing options

                  removePimples: (e.target as HTMLInputElement).checked // Update pimple removal setting

                }

              })}

            />

            Remove pimples                                          {/* Clean up skin imperfections */}

          </label>

          

          {/* Sunglasses addition option */}

          <label className="flex items-center gap-2 text-xs cursor-pointer">

            <Checkbox 

              checked={node.faceOptions?.addSunglasses || false}    // Default to false if not set

              onChange={(e) => onUpdate(node.id, { 

                faceOptions: { 

                  ...node.faceOptions,                             // Preserve existing options

                  addSunglasses: (e.target as HTMLInputElement).checked // Update sunglasses setting

                }

              })}

            />

            Add sunglasses                                          {/* Add stylish sunglasses accessory */}

          </label>

          

          {/* Hat addition option */}

          <label className="flex items-center gap-2 text-xs cursor-pointer">

            <Checkbox 

              checked={node.faceOptions?.addHat || false}           // Default to false if not set

              onChange={(e) => onUpdate(node.id, { 

                faceOptions: { 

                  ...node.faceOptions,                             // Preserve existing options

                  addHat: (e.target as HTMLInputElement).checked   // Update hat setting

                }

              })}

            />

            Add hat                                                 {/* Add hat accessory */}

          </label>

        </div>

        

        <div>

          <label className="text-xs text-white/70">Hairstyle</label>

          <Select 

            className="w-full"

            value={node.faceOptions?.changeHairstyle || "None"}

            onChange={(e) => onUpdate(node.id, { 

              faceOptions: { ...node.faceOptions, changeHairstyle: (e.target as HTMLSelectElement).value }

            })}

          >

            {hairstyles.map(h => <option key={h} value={h}>{h}</option>)}

          </Select>

        </div>

        

        <div>

          <label className="text-xs text-white/70">Expression</label>

          <Select 

            className="w-full"

            value={node.faceOptions?.facialExpression || "None"}

            onChange={(e) => onUpdate(node.id, { 

              faceOptions: { ...node.faceOptions, facialExpression: (e.target as HTMLSelectElement).value }

            })}

          >

            {expressions.map(e => <option key={e} value={e}>{e}</option>)}

          </Select>

        </div>

        

        <div>

          <label className="text-xs text-white/70">Beard</label>

          <Select 

            className="w-full"

            value={node.faceOptions?.beardStyle || "None"}

            onChange={(e) => onUpdate(node.id, { 

              faceOptions: { ...node.faceOptions, beardStyle: (e.target as HTMLSelectElement).value }

            })}

          >

            {beardStyles.map(b => <option key={b} value={b}>{b}</option>)}

          </Select>

        </div>



        {/* Makeup Selection Section - allows users to choose makeup application */}

        <div>

          <label className="text-xs text-white/70">Makeup</label>

          <div className="grid grid-cols-2 gap-2 mt-2">              {/* 2-column grid for makeup options */}

            

            {/* No Makeup Option - removes or prevents makeup application */}

            <button

              className={`p-1 rounded border transition-colors ${

                !node.faceOptions?.selectedMakeup || node.faceOptions?.selectedMakeup === "None"

                  ? "border-indigo-400 bg-indigo-500/20"             // Highlighted when selected

                  : "border-white/20 hover:border-white/40"           // Default and hover states

              }`}

              onClick={() => onUpdate(node.id, { 

                faceOptions: { 

                  ...node.faceOptions,                               // Preserve other face options

                  selectedMakeup: "None",                            // Set makeup to none

                  makeupImage: null                                   // Clear makeup image reference

                }

              })}

              title="No makeup application - natural look"

            >

              {/* Visual placeholder for no makeup option */}

              <div className="w-full h-24 flex items-center justify-center text-xs text-white/60 border border-dashed border-white/20 rounded mb-1">

                No Makeup                                             {/* Text indicator for no makeup */}

              </div>

              <div className="text-xs">None</div>                  {/* Option label */}

            </button>

            

            {/* Makeup Application Option - applies preset makeup style */}

            <button

              className={`p-1 rounded border transition-colors ${

                node.faceOptions?.selectedMakeup === "Makeup"

                  ? "border-indigo-400 bg-indigo-500/20"             // Highlighted when selected

                  : "border-white/20 hover:border-white/40"           // Default and hover states

              }`}

              onClick={() => onUpdate(node.id, { 

                faceOptions: { 

                  ...node.faceOptions,                               // Preserve other face options

                  selectedMakeup: "Makeup",                          // Set makeup type

                  makeupImage: "/makeup/makeup1.png"                 // Reference image for makeup style

                }

              })}

              title="Apply makeup style - enhances facial features"

            >

              {/* Makeup preview image */}

              <img 

                src="/makeup/makeup1.png" 

                alt="Makeup Style Preview" 

                className="w-full h-24 object-contain rounded mb-1"

                title="Preview of makeup style that will be applied"

              />

              <div className="text-xs">Makeup</div>               {/* Option label */}

            </button>

          </div>

        </div>

        

        <Button 

          className="w-full"

          onClick={() => onProcess(node.id)}

          disabled={node.isRunning}

          title={!node.input ? "Connect an input first" : "Process all unprocessed nodes in chain"}

        >

          {node.isRunning ? "Processing..." : "Apply Face Changes"}

        </Button>

        <div className="mt-2">

          <NodeOutputSection

            nodeId={node.id}

            output={node.output}

            downloadFileName={`face-${Date.now()}.png`}

          />

        </div>

        {node.error && (

          <div className="text-xs text-red-400 mt-2">{node.error}</div>

        )}

      </div>

    </div>
  );
}

/**

 * STYLE NODE VIEW COMPONENT

 * 

 * Applies artistic style transfer to images, transforming them to match

 * various artistic movements, pop culture aesthetics, and visual styles.

 * 

 * Key Features:

 * - Wide variety of artistic styles (anime, fine art, pop culture)

 * - Adjustable style strength for subtle or dramatic transformations

 * - Preserves original image content while applying style characteristics

 * - Real-time style preview and processing

 * 

 * Style Categories Available:

 * - Anime styles (90s anime, My Hero Academia, Dragon Ball Z)

 * - Fine art movements (Ukiyo-e, Cubism, Post-Impressionism)

 * - Modern aesthetics (Cyberpunk, Steampunk)

 * - Pop culture (Simpsons, Family Guy, Arcane)

 * - Cinematic styles (Breaking Bad, Stranger Things)

 * 

 * The AI style transfer models can:

 * - Apply artistic brushstrokes and textures

 * - Adapt color palettes to match target styles

 * - Maintain subject recognition while stylizing

 * - Handle various image compositions and subjects

 * 

 * @param node - Style node data containing stylePreset, styleStrength, etc.

 * @param onDelete - Callback to delete this node

 * @param onUpdate - Callback to update style settings

 * @param onStartConnection - Callback when starting connection from output

 * @param onEndConnection - Callback when ending connection at input

 * @param onProcess - Callback to process style transfer

 * @param onUpdatePosition - Callback to update node position

 * @param getNodeHistoryInfo - Function to get processing history

 * @param navigateNodeHistory - Function to navigate history

 * @param getCurrentNodeImage - Function to get current image

 */
export function StyleNodeView({ node, onDelete, onUpdate, onStartConnection, onEndConnection, onProcess, onUpdatePosition, getNodeHistoryInfo, navigateNodeHistory, getCurrentNodeImage }: any) {
  // Handle node dragging functionality
  const { localPos, onPointerDown, onPointerMove, onPointerUp } = useNodeDrag(node, onUpdatePosition);
  
  /**

   * Available artistic style options with descriptive labels

   * Each style represents a different artistic movement or pop culture aesthetic

   */
  const styleOptions = [
    { value: "90s-anime", label: "90's Anime Style" },
    { value: "mha", label: "My Hero Academia Style" },
    { value: "dbz", label: "Dragon Ball Z Style" },
    { value: "ukiyo-e", label: "Ukiyo-e Style" },
    { value: "spiderverse", label: "Spiderverse Style" },
    { value: "cubism", label: "Cubism Style" },
    { value: "van-gogh", label: "Post-Impressionist (Van Gogh) Style" },
    { value: "simpsons", label: "Simpsons Style" },
    { value: "family-guy", label: "Family Guy Style" },
    { value: "pixar", label: "Pixar Style" },
    { value: "manga", label: "Manga Style" },
  ];
  
  return (
    <div 

      className="nb-node absolute text-white w-[320px]" 

      style={{ left: localPos.x, top: localPos.y }}

    >

      <div 

        className="nb-header px-3 py-2 flex items-center justify-between rounded-t-[14px] cursor-grab active:cursor-grabbing"

        onPointerDown={onPointerDown}

        onPointerMove={onPointerMove}

        onPointerUp={onPointerUp}

      >

        <Port className="in" nodeId={node.id} isOutput={false} onEndConnection={onEndConnection} onDisconnect={(nodeId) => onUpdate(nodeId, { input: undefined })} />

        <div className="font-semibold text-sm flex-1 text-center">STYLE</div>

        <div className="flex items-center gap-1">

          <Button

            variant="ghost"

            size="icon"

            className="text-destructive hover:bg-destructive/20 h-6 w-6"

            onClick={(e) => {

              e.stopPropagation();

              e.preventDefault();

              if (confirm('Delete this node?')) {

                onDelete(node.id);

              }

            }}

            onPointerDown={(e) => e.stopPropagation()}

            title="Delete node"

            aria-label="Delete node"

          >

            ×

          </Button>

          <Port className="out" nodeId={node.id} isOutput={true} onStartConnection={onStartConnection} />

        </div>

      </div>

      {/* Node Content Area - Contains all controls, inputs, and outputs */}

      <div className="p-3 space-y-3">

        {node.input && (

          <div className="flex justify-end mb-2">

            <Button

              variant="ghost"

              size="sm"

              onClick={() => onUpdate(node.id, { input: undefined })}

              className="text-xs"

            >

              Clear Connection                                    {/* Remove input connection to this node */}

            </Button>

          </div>

        )}

        <div className="text-xs text-white/70">Art Style</div>

        <div className="text-xs text-white/50 mb-2">Select an artistic style to apply to your image</div>

        <Select

          className="w-full bg-black border-white/20 text-white focus:border-white/40 [&>option]:bg-black [&>option]:text-white"

          value={node.stylePreset || ""}

          onChange={(e) => onUpdate(node.id, { stylePreset: (e.target as HTMLSelectElement).value })}

        >

          <option value="" className="bg-black">Select a style...</option>

          {styleOptions.map(opt => (

            <option key={opt.value} value={opt.value} className="bg-black">

              {opt.label}

            </option>

          ))}

        </Select>

        {/* Style Strength Slider - controls how strongly the style is applied */}

        <div>

          <Slider

            label="Style Strength"                                 // Slider label

            valueLabel={`${node.styleStrength || 50}%`}            // Display current percentage value

            min={0}                                                 // Minimum strength (subtle effect)

            max={100}                                               // Maximum strength (full style transfer)

            value={node.styleStrength || 50}                       // Current value (default 50%)

            onChange={(e) => onUpdate(node.id, { 

              styleStrength: parseInt((e.target as HTMLInputElement).value) // Update strength value

            })}

            title="Adjust how strongly the artistic style is applied - lower values are more subtle"

          />

        </div>

        {/* Style Processing Button - triggers the style transfer operation */}

        <Button 

          className="w-full"

          onClick={() => onProcess(node.id)}                        // Start style transfer processing

          disabled={node.isRunning || !node.stylePreset}           // Disable if processing or no style selected

          title={

            !node.input ? "Connect an input first" :               // No input connection

            !node.stylePreset ? "Select a style first" :           // No style selected

            "Apply the selected artistic style to your input image" // Ready to process

          }

        >

          {/* Dynamic button text based on processing state */}

          {node.isRunning ? "Applying Style..." : "Apply Style Transfer"}

        </Button>

        <NodeOutputSection

          nodeId={node.id}

          output={node.output}

          downloadFileName={`style-${Date.now()}.png`}

        />

        {node.error && (

          <div className="text-xs text-red-400 mt-2">{node.error}</div>

        )}

      </div>

    </div>
  );
}

/**

 * LIGHTNING NODE VIEW COMPONENT

 * 

 * Applies professional lighting effects to images to enhance mood,

 * atmosphere, and visual impact. Simulates various lighting setups

 * commonly used in photography and cinematography.

 * 

 * Key Features:

 * - Professional lighting presets (studio, natural, dramatic)

 * - Visual preset selection with thumbnails

 * - Realistic lighting simulation

 * - Shadow and highlight adjustment

 * 

 * Lighting Types Available:

 * - Studio Light: Controlled, even lighting for professional portraits

 * - Natural Light: Soft, organic lighting that mimics daylight

 * - Dramatic Light: High-contrast lighting for artistic effect

 * 

 * The lighting effects can:

 * - Add realistic shadows and highlights

 * - Enhance subject dimensionality

 * - Create mood and atmosphere

 * - Simulate professional lighting equipment

 * 

 * @param node - Lightning node data containing selectedLighting, lightingImage

 * @param onDelete - Callback to delete this node

 * @param onUpdate - Callback to update lighting settings

 * @param onStartConnection - Callback when starting connection from output

 * @param onEndConnection - Callback when ending connection at input

 * @param onProcess - Callback to process lighting effects

 * @param onUpdatePosition - Callback to update node position

 * @param getNodeHistoryInfo - Function to get processing history

 * @param navigateNodeHistory - Function to navigate history

 * @param getCurrentNodeImage - Function to get current image

 */
export function LightningNodeView({ node, onDelete, onUpdate, onStartConnection, onEndConnection, onProcess, onUpdatePosition, getNodeHistoryInfo, navigateNodeHistory, getCurrentNodeImage }: any) {
  // Handle node dragging functionality
  const { localPos, onPointerDown, onPointerMove, onPointerUp } = useNodeDrag(node, onUpdatePosition);
  
  /**

   * Available lighting preset options with text descriptions

   * Each preset uses detailed lighting prompts instead of reference images

   */
  const presetLightings = [
    { 
      name: "Moody Cinematic", 
      path: "/lighting/light1.png",
      prompt: "Moody cinematic portrait lighting with a sharp vertical beam of warm orange-red light cutting across the face and neck, contrasted with cool teal ambient fill on the surrounding areas. Strong chiaroscuro effect, deep shadows, high contrast between warm and cool tones, dramatic spotlight strip"
    },
    { 
      name: "Dual-Tone Neon", 
      path: "/lighting/light2.png",
      prompt: "Cinematic portrait lighting with strong dual-tone rim lights: deep blue light illuminating the front-left side of the face, intense red light as a rim light from the back-right, dark black background, high contrast, minimal fill light, dramatic neon glow"
    },
    { 
      name: "Natural Shadow Play", 
      path: "/lighting/light3.png",
      prompt: "DRAMATIC natural shadow play with hard directional sunlight filtering through foliage, creating bold contrasting patterns of light and shadow across the subject. Strong chiaroscuro effect with deep blacks and bright highlights, dappled leaf shadows dancing across face and body, creating an artistic interplay of illumination and darkness. Emphasize the sculptural quality of light carving through shadow, with sharp shadow edges and brilliant sun-kissed highlights for maximum visual impact"
    },
  ];

  /**

   * Handle selection of a lighting preset

   * Updates with the text prompt instead of reference image

   */
  const selectLighting = (lightingPath: string, lightingName: string, lightingPrompt: string) => {
    onUpdate(node.id, { 
      lightingPrompt: lightingPrompt,                              // Text prompt for lighting effect
      selectedLighting: lightingName                               // Name of selected lighting preset
    });
  };
  
  return (
    <div className="nb-node absolute text-white w-[320px]" style={{ left: localPos.x, top: localPos.y }}>

      <div 

        className="nb-header px-3 py-2 flex items-center justify-between rounded-t-[14px] cursor-grab active:cursor-grabbing"

        onPointerDown={onPointerDown}

        onPointerMove={onPointerMove}

        onPointerUp={onPointerUp}

      >

        <Port className="in" nodeId={node.id} isOutput={false} onEndConnection={onEndConnection} onDisconnect={(nodeId) => onUpdate(nodeId, { input: undefined })} />

        <div className="font-semibold text-sm flex-1 text-center">LIGHTNING</div>

        <div className="flex items-center gap-1">

          <Button

            variant="ghost"

            size="icon"

            className="text-destructive hover:bg-destructive/20 h-6 w-6"

            onClick={(e) => {

              e.stopPropagation();

              e.preventDefault();

              if (confirm('Delete this node?')) {

                onDelete(node.id);

              }

            }}

            onPointerDown={(e) => e.stopPropagation()}

            title="Delete node"

            aria-label="Delete node"

          >

            ×

          </Button>

          <Port className="out" nodeId={node.id} isOutput={true} onStartConnection={onStartConnection} />

        </div>

      </div>

      {/* Node Content Area - Contains all controls, inputs, and outputs */}

      <div className="p-3 space-y-3">

        {node.input && (

          <div className="flex justify-end mb-2">

            <Button

              variant="ghost"

              size="sm"

              onClick={() => onUpdate(node.id, { input: undefined })}

              className="text-xs"

            >

              Clear Connection                                    {/* Remove input connection to this node */}

            </Button>

          </div>

        )}

        <div className="text-xs text-white/70">Lighting Presets</div>

        

        <div className="grid grid-cols-2 gap-2">

          {presetLightings.map((preset) => (

            <button

              key={preset.name}

              className={`p-2 rounded border ${

                node.selectedLighting === preset.name

                  ? "border-indigo-400 bg-indigo-500/20"

                  : "border-white/20 hover:border-white/40"

              }`}

              onClick={() => selectLighting(preset.path, preset.name, preset.prompt)}

            >

              <img 

                src={preset.path} 

                alt={preset.name} 

                className="w-full h-24 object-contain rounded mb-1"

                title="Click to select lighting"

              />

              <div className="text-xs">{preset.name}</div>

            </button>

          ))}

        </div>

        

        <Button 

          className="w-full"

          onClick={() => onProcess(node.id)}

          disabled={node.isRunning || !node.selectedLighting}

          title={!node.input ? "Connect an input first" : !node.selectedLighting ? "Select a lighting preset first" : "Apply lighting effect"}

        >

          {node.isRunning ? "Processing..." : "Apply Lighting"}

        </Button>

        

        <NodeOutputSection

          nodeId={node.id}

          output={node.output}

          downloadFileName={`lightning-${Date.now()}.png`}

        />

        {node.error && (

          <div className="text-xs text-red-400 mt-2">{node.error}</div>

        )}

      </div>

    </div>
  );
}


/**

 * POSES NODE VIEW COMPONENT

 * 

 * Modifies the pose and body positioning of subjects in images.

 * Uses AI-powered pose estimation and transfer to change how people

 * are positioned while maintaining natural proportions and anatomy.

 * 

 * Key Features:

 * - Multiple preset poses (standing, sitting variations)

 * - Visual pose selection with reference thumbnails

 * - Natural pose transfer that preserves identity

 * - Anatomically correct pose adjustments

 * 

 * Pose Categories Available:

 * - Standing poses: Various upright positions and postures

 * - Sitting poses: Different seated positions and arrangements

 * 

 * The AI pose models can:

 * - Detect and map human body keypoints

 * - Transfer poses while maintaining proportions

 * - Adjust clothing to fit new poses naturally

 * - Preserve facial features and identity

 * - Handle complex body positioning

 * 

 * @param node - Poses node data containing selectedPose, poseImage

 * @param onDelete - Callback to delete this node

 * @param onUpdate - Callback to update pose settings

 * @param onStartConnection - Callback when starting connection from output

 * @param onEndConnection - Callback when ending connection at input

 * @param onProcess - Callback to process pose modifications

 * @param onUpdatePosition - Callback to update node position

 * @param getNodeHistoryInfo - Function to get processing history

 * @param navigateNodeHistory - Function to navigate history

 * @param getCurrentNodeImage - Function to get current image

 */
export function PosesNodeView({ node, onDelete, onUpdate, onStartConnection, onEndConnection, onProcess, onUpdatePosition, getNodeHistoryInfo, navigateNodeHistory, getCurrentNodeImage }: any) {
  // Handle node dragging functionality
  const { localPos, onPointerDown, onPointerMove, onPointerUp } = useNodeDrag(node, onUpdatePosition);
  
  /**

   * Available pose preset options with text descriptions

   * Each preset uses detailed pose prompts instead of reference images

   */
  const presetPoses = [
    { 
      name: "Dynamic Standing", 
      path: "/poses/stand1.png",
      prompt: "A dynamic standing pose with the figure's weight shifted to one side. The right arm extends forward in a pointing gesture while the left arm hangs naturally. The figure has a slight hip tilt and appears to be in mid-movement, creating an energetic, directional composition."
    },
    { 
      name: "Arms Crossed", 
      path: "/poses/stand2.png",
      prompt: "A relaxed standing pose with arms crossed over the torso. The weight is distributed fairly evenly, with one leg slightly forward. The figure's posture suggests a casual, confident stance with the head tilted slightly downward in a contemplative manner."
    },
    { 
      name: "Seated Composed", 
      path: "/poses/sit1.png",
      prompt: "A seated pose on what appears to be a stool or high chair. The figure sits with legs crossed at the knee, creating an asymmetrical but balanced composition. The hands rest on the lap, and the overall posture is upright and composed."
    },
    { 
      name: "Relaxed Lean", 
      path: "/poses/sit2.png",
      prompt: "A more relaxed seated pose with the figure leaning to one side. One leg is bent and raised while the other extends downward. The figure appears to be resting or in casual repose, with arms supporting the body and creating a diagonal flow through the composition."
    },
  ];

  /**

   * Handle selection of a pose preset

   * Updates with the text prompt instead of reference image

   */
  const selectPose = (posePath: string, poseName: string, posePrompt: string) => {
    onUpdate(node.id, { 
      posePrompt: posePrompt,                                      // Text prompt for pose effect
      selectedPose: poseName                                       // Name of selected pose preset
    });
  };
  
  return (
    <div className="nb-node absolute text-white w-[320px]" style={{ left: localPos.x, top: localPos.y }}>

      <div 

        className="nb-header px-3 py-2 flex items-center justify-between rounded-t-[14px] cursor-grab active:cursor-grabbing"

        onPointerDown={onPointerDown}

        onPointerMove={onPointerMove}

        onPointerUp={onPointerUp}

      >

        <Port className="in" nodeId={node.id} isOutput={false} onEndConnection={onEndConnection} onDisconnect={(nodeId) => onUpdate(nodeId, { input: undefined })} />

        <div className="font-semibold text-sm flex-1 text-center">POSES</div>

        <div className="flex items-center gap-1">

          <Button

            variant="ghost"

            size="icon"

            className="text-destructive hover:bg-destructive/20 h-6 w-6"

            onClick={(e) => {

              e.stopPropagation();

              e.preventDefault();

              if (confirm('Delete this node?')) {

                onDelete(node.id);

              }

            }}

            onPointerDown={(e) => e.stopPropagation()}

            title="Delete node"

            aria-label="Delete node"

          >

            ×

          </Button>

          <Port className="out" nodeId={node.id} isOutput={true} onStartConnection={onStartConnection} />

        </div>

      </div>

      {/* Node Content Area - Contains all controls, inputs, and outputs */}

      <div className="p-3 space-y-3">

        {node.input && (

          <div className="flex justify-end mb-2">

            <Button

              variant="ghost"

              size="sm"

              onClick={() => onUpdate(node.id, { input: undefined })}

              className="text-xs"

            >

              Clear Connection                                    {/* Remove input connection to this node */}

            </Button>

          </div>

        )}

        <div className="text-xs text-white/70">Pose References</div>

        

        <div className="grid grid-cols-2 gap-2">

          {presetPoses.map((preset) => (

            <button

              key={preset.name}

              className={`p-2 rounded border ${

                node.selectedPose === preset.name

                  ? "border-indigo-400 bg-indigo-500/20"

                  : "border-white/20 hover:border-white/40"

              }`}

              onClick={() => selectPose(preset.path, preset.name, preset.prompt)}

            >

              <img 

                src={preset.path} 

                alt={preset.name} 

                className="w-full h-24 object-contain rounded mb-1"

                title="Click to select pose"

              />

              <div className="text-xs">{preset.name}</div>

            </button>

          ))}

        </div>

        

        <Button 

          className="w-full"

          onClick={() => onProcess(node.id)}

          disabled={node.isRunning || !node.selectedPose}

          title={!node.input ? "Connect an input first" : !node.selectedPose ? "Select a pose first" : "Apply pose modification"}

        >

          {node.isRunning ? "Processing..." : "Apply Pose"}

        </Button>

        

        <NodeOutputSection

          nodeId={node.id}

          output={node.output}

          downloadFileName={`poses-${Date.now()}.png`}

        />

        {node.error && (

          <div className="text-xs text-red-400 mt-2">{node.error}</div>

        )}

      </div>

    </div>
  );
}

/**

 * EDIT NODE VIEW COMPONENT

 * 

 * This node allows users to perform general text-based image editing operations.

 * Users can describe what they want to change about an image using natural language,

 * and the AI will attempt to apply those changes.

 * 

 * Features:

 * - Natural language editing prompts (e.g., "make it brighter", "add vintage effect")

 * - AI-powered prompt improvement using Gemini

 * - Real-time editing processing

 * - Output history with navigation

 * - Connection management for input/output workflow

 * 

 * @param node - The edit node data containing editPrompt, input, output, etc.

 * @param onDelete - Callback to delete this node

 * @param onUpdate - Callback to update node properties

 * @param onStartConnection - Callback when starting a connection from output port

 * @param onEndConnection - Callback when ending a connection at input port

 * @param onProcess - Callback to process this node

 * @param onUpdatePosition - Callback to update node position when dragged

 * @param getNodeHistoryInfo - Function to get history information for this node

 * @param navigateNodeHistory - Function to navigate through node history

 * @param getCurrentNodeImage - Function to get the current image for this node

 */
export function EditNodeView({

  node,

  onDelete,

  onUpdate,

  onStartConnection,

  onEndConnection,

  onProcess,

  onUpdatePosition,

  getNodeHistoryInfo,

  navigateNodeHistory,

  getCurrentNodeImage,

  apiToken

}: any) {
  // Use custom hook for drag functionality - handles position updates during dragging
  const { localPos, onPointerDown, onPointerMove, onPointerUp } = useNodeDrag(node, onUpdatePosition);
  
  /**

   * Handle prompt improvement using Gemini API

   * Takes the user's basic edit description and enhances it for better AI processing

   */
  const handlePromptImprovement = async () => {
    // Validate that user has entered a prompt
    if (!node.editPrompt?.trim()) {
      alert('Please enter an edit description first');
      return;
    }
    
    try {
      // Call the API to improve the prompt
      const response = await fetch('/api/improve-prompt', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          prompt: node.editPrompt.trim(),
          type: 'edit',
          apiToken: apiToken || undefined
        })
      });
      
      if (response.ok) {
        const { improvedPrompt } = await response.json();
        onUpdate(node.id, { editPrompt: improvedPrompt });
      } else {
        alert('Failed to improve prompt. Please try again.');
      }
    } catch (error) {
      console.error('Error improving prompt:', error);
      alert('Failed to improve prompt. Please try again.');
    }
  };

  /**

   * Handle delete node action with confirmation

   */
  const handleDeleteNode = (e: React.MouseEvent) => {
    e.stopPropagation();  // Prevent triggering drag
    e.preventDefault();
    
    if (confirm('Delete this node?')) {
      onDelete(node.id);
    }
  };

  /**

   * Handle clearing the input connection

   */
  const handleClearConnection = () => {
    onUpdate(node.id, { input: undefined });
  };

  /**

   * Handle edit prompt changes

   */
  const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    onUpdate(node.id, { editPrompt: e.target.value });
  };

  return (
    <div className="nb-node absolute text-white w-[320px]" style={{ left: localPos.x, top: localPos.y }}>

      {/* Node Header - Contains title, delete button, and connection ports */}

      <div 

        className="nb-header px-3 py-2 flex items-center justify-between rounded-t-[14px] cursor-grab active:cursor-grabbing"

        onPointerDown={onPointerDown}    // Start dragging

        onPointerMove={onPointerMove}    // Handle drag movement

        onPointerUp={onPointerUp}        // End dragging

      >

        {/* Input port (left side) - where connections come in */}

        <Port className="in" nodeId={node.id} isOutput={false} onEndConnection={onEndConnection} onDisconnect={(nodeId) => onUpdate(nodeId, { input: undefined })} />

        

        {/* Node title */}

        <div className="font-semibold text-sm flex-1 text-center">EDIT</div>

        

        <div className="flex items-center gap-1">

          {/* Delete button */}

          <Button

            variant="ghost"

            size="icon"

            className="text-destructive hover:bg-destructive/20 h-6 w-6"

            onClick={handleDeleteNode}

            onPointerDown={(e) => e.stopPropagation()}  // Prevent drag when clicking delete

            title="Delete node"

            aria-label="Delete node"

          >

            ×

          </Button>

          

          {/* Output port (right side) - where connections go out */}

          <Port className="out" nodeId={node.id} isOutput={true} onStartConnection={onStartConnection} />

        </div>

      </div>

      

      {/* Node Content - Contains all the controls and outputs */}

      {/* Node Content Area - Contains all controls, inputs, and outputs */}

      <div className="p-3 space-y-3">

        {/* Show clear connection button if node has input */}

        {node.input && (

          <div className="flex justify-end mb-2">

            <Button

              variant="ghost"

              size="sm"

              onClick={handleClearConnection}

              className="text-xs"

              title="Remove input connection"

            >

              Clear Connection                                    {/* Remove input connection to this node */}

            </Button>

          </div>

        )}

        

        {/* Edit prompt input and improvement section */}

        <div className="space-y-2">

          <div className="text-xs text-white/70 mb-1">Edit Instructions</div>

          <Textarea

            className="w-full"

            placeholder="Describe what to edit (e.g., 'make it brighter', 'add more contrast', 'make it look vintage')"

            value={node.editPrompt || ""}

            onChange={handlePromptChange}

            rows={3}

          />

          

          {/* AI-powered prompt improvement button */}

          <Button

            variant="outline"

            size="sm"

            className="w-full text-xs"

            onClick={handlePromptImprovement}

            title="Use Gemini 2.5 Flash to improve your edit prompt"

            disabled={!node.editPrompt?.trim()}

          >

            ✨ Improve with Gemini

          </Button>

        </div>

        

        {/* Process button - starts the editing operation */}

        <Button 

          className="w-full"

          onClick={() => onProcess(node.id)}

          disabled={node.isRunning || !node.editPrompt?.trim()}

          title={

            !node.input ? "Connect an input first" : 

            !node.editPrompt?.trim() ? "Enter edit instructions first" :

            "Apply the edit to the input image"

          }

        >

          {node.isRunning ? "Processing..." : "Apply Edit"}

        </Button>

        

        {/* Output section with history navigation and download */}

        <NodeOutputSection

          nodeId={node.id}

          output={node.output}

          downloadFileName={`edit-${Date.now()}.png`}

        />

        

        {/* Error display */}

        {node.error && (

          <div className="text-xs text-red-400 mt-2 p-2 bg-red-900/20 rounded">

            {node.error}

          </div>

        )}

      </div>

    </div>
  );
}