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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b34c4c
 
 
6988307
 
 
 
1b34c4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0da7440
1b34c4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6988307
4f59fde
1b34c4c
 
 
 
 
4eb03ea
1b34c4c
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
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client@latest/dist/index.js";

// DOM Elements
const openSettingsBtn = null;
const closeSettingsBtn = null;
const settingsModal = null;
const saveSettingsBtn = null;
const hfTokenInput = null;

const tabBtns = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');

const dropzone = document.getElementById('dropzone');
const fileInput = document.getElementById('fileInput');
const previewContainer = document.getElementById('previewContainer');
const imagePreview = document.getElementById('imagePreview');
const removePreviewBtn = document.getElementById('removePreviewBtn');

// Source selector elements
const sourceUploadBtn = document.getElementById('sourceUploadBtn');
const sourceLibraryBtn = document.getElementById('sourceLibraryBtn');
const uploadSourceContainer = document.getElementById('uploadSourceContainer');
const librarySourceContainer = document.getElementById('librarySourceContainer');
const libraryThumbnailGrid = document.getElementById('libraryThumbnailGrid');

const promptInput = document.getElementById('promptInput');
const negativePromptInput = document.getElementById('negativePromptInput');
const generatorModelSelect = document.getElementById('generatorModelSelect');
const generate2dBtn = document.getElementById('generate2dBtn');

const generate3dBtn = document.getElementById('generate3dBtn');
const statusOverlay = document.getElementById('statusOverlay');
const loaderPercentage = document.getElementById('loaderPercentage');
const statusTitle = document.getElementById('statusTitle');
const statusDesc = document.getElementById('statusDesc');

const viewerDisplay = document.getElementById('viewerDisplay');
const emptyState = document.getElementById('emptyState');
const viewerOverlay = document.getElementById('viewerOverlay');
const toggleAutoRotateBtn = document.getElementById('toggleAutoRotate');
const resetCameraBtn = document.getElementById('resetCameraBtn');
const toggleWireframeBtn = document.getElementById('toggleWireframeBtn');
const toggleNodesBtn = document.getElementById('toggleNodesBtn');
const toggleTextureBtn = document.getElementById('toggleTextureBtn');
const downloadGlbBtn = document.getElementById('downloadGlbBtn');
const downloadFbxBtn = document.getElementById('downloadFbxBtn');
const viewOnMobileBtn = document.getElementById('viewOnMobileBtn');
const mobileQrModal = document.getElementById('mobileQrModal');
const closeMobileQrModalBtn = document.getElementById('closeMobileQrModalBtn');
const mobileQrImage = document.getElementById('mobileQrImage');
const mobileQrLink = document.getElementById('mobileQrLink');
let activeGltfUrl = null;
const runTriggerRigBtn = document.getElementById('runTriggerRigBtn');
const rigTriggerPanel = document.getElementById('rigTriggerPanel');
const manualWeightPaintPanel = document.getElementById('manualWeightPaintPanel');
const activeWeightPaintCheck = document.getElementById('activeWeightPaintCheck');
const weightPaintRadiusInput = document.getElementById('weightPaintRadiusInput');
const weightPaintRadiusVal = document.getElementById('weightPaintRadiusVal');
const weightPaintStrengthInput = document.getElementById('weightPaintStrengthInput');
const weightPaintStrengthVal = document.getElementById('weightPaintStrengthVal');
const weightPaintModeSelect = document.getElementById('weightPaintModeSelect');
const saveWeightPaintBtn = document.getElementById('saveWeightPaintBtn');
const animationControlGroup = document.getElementById('animationControlGroup');
const animationSelect = document.getElementById('animationSelect');
const manualRigPanel = document.getElementById('manualRigPanel');
const manualBoneNameInput = document.getElementById('manualBoneNameInput');
const applyBoneRenameBtn = document.getElementById('applyBoneRenameBtn');
let selectedBone = null;
let currentModelCategory = 'unknown';
let lastNoBoneToastTime = 0;
const manualBoneSelect = null;
const aiClassificationBadge = document.getElementById('aiClassificationBadge');
const aiClassificationText = document.getElementById('aiClassificationText');
const boneRotX = document.getElementById('boneRotX');
const boneRotY = document.getElementById('boneRotY');
const boneRotZ = document.getElementById('boneRotZ');
const boneRotXVal = document.getElementById('boneRotXVal');
const boneRotYVal = document.getElementById('boneRotYVal');
const boneRotZVal = document.getElementById('boneRotZVal');
const resetBoneRotBtn = document.getElementById('resetBoneRotBtn');
const manualBoneMappingSelect = document.getElementById('manualBoneMappingSelect');
const toggleBonesHelperBtn = document.getElementById('toggleBonesHelperBtn');
const toggleBonesBtn = document.getElementById('toggleBonesBtn');
let threeSkeletonHelper = null;
let showSkeletonHelper = false;
let jointSpheres = [];
let showWireframe = false;
let showNodes = false;
let isWeightPaintingActive = false;
let selectedBoneMarker = null;
let weightPaintRadius = 0.10;
let weightPaintStrength = 0.50;
let weightPaintMode = 'add';
let weightVisualizerMaterial = null;
let originalMaterialsMap = new Map();
let brushHelper = null;
let lastBrushHit = null;
let activeSkinnedMeshes = [];
let spatialGrid = null;
let targetBoneIdx = -1;
let lastRaycastTime = 0;
let lastPaintTime = 0;
let lastMouseScreenX = 0;
let lastMouseScreenY = 0;
let showTextures = true;
let isAutoRotating = false;

// Trellis Parameters
const resolutionSelect = document.getElementById('resolutionSelect');
const seedInput = document.getElementById('seedInput');
const randomSeedCheck = document.getElementById('randomSeedCheck');
const decimateInput = document.getElementById('decimateInput');
const decimateVal = document.getElementById('decimateVal');
const textureSizeSelect = document.getElementById('textureSizeSelect');
const ssGuidanceInput = document.getElementById('ssGuidanceInput');
const ssGuidanceVal = document.getElementById('ssGuidanceVal');
const ssStepsInput = document.getElementById('ssStepsInput');
const ssStepsVal = document.getElementById('ssStepsVal');
const slatGuidanceInput = document.getElementById('slatGuidanceInput');
const slatGuidanceVal = document.getElementById('slatGuidanceVal');
const slatStepsInput = document.getElementById('slatStepsInput');
const slatStepsVal = document.getElementById('slatStepsVal');

// App State
let active2dImageBlob = null;
let active2dImageURL = null;
let currentGltfUrl = null;
let activeModelRelativeUrl = null;
localStorage.removeItem('hf_token');
let hfToken = '';
const apiBase = window.location.protocol === 'file:' ? 'http://localhost:8000' : '';

// Custom Alert Modal Setup
const alertModal = document.getElementById('alertModal');
const alertModalTitle = document.getElementById('alertModalTitle');
const alertModalMessage = document.getElementById('alertModalMessage');
const closeAlertBtn = document.getElementById('closeAlertBtn');
const goConfigBtn = document.getElementById('goConfigBtn');

const alertModalIconContainer = document.getElementById('alertModalIconContainer');
const alertModalIcon = document.getElementById('alertModalIcon');

function showCustomAlert(message, title = 'Atención', showConfigBtn = false, type = 'error') {
    alertModalTitle.textContent = title;
    alertModalMessage.textContent = message;

    if (showConfigBtn) {
        goConfigBtn.style.display = 'inline-flex';
    } else {
        goConfigBtn.style.display = 'none';
    }

    if (alertModalIconContainer && alertModalIcon) {
        if (type === 'success') {
            alertModalIconContainer.style.background = 'rgba(76, 175, 80, 0.1)';
            alertModalIconContainer.style.color = '#4caf50';
            alertModalIcon.setAttribute('data-lucide', 'check-circle');
        } else {
            alertModalIconContainer.style.background = 'rgba(244, 67, 54, 0.1)';
            alertModalIconContainer.style.color = '#f44336';
            alertModalIcon.setAttribute('data-lucide', 'alert-triangle');
        }
    }

    alertModal.classList.add('active');
    if (window.lucide) {
        window.lucide.createIcons();
    }
}

if (closeAlertBtn) {
    closeAlertBtn.addEventListener('click', () => {
        alertModal.classList.remove('active');
    });
}

if (goConfigBtn) {
    goConfigBtn.addEventListener('click', () => {
        alertModal.classList.remove('active');
        settingsModal.classList.add('active');
    });
}

// Slider live value update helper
function setupSliderValueUpdate(slider, labelEl) {
    slider.addEventListener('input', (e) => {
        labelEl.textContent = e.target.value;
    });
}
setupSliderValueUpdate(decimateInput, decimateVal);
setupSliderValueUpdate(ssGuidanceInput, ssGuidanceVal);
setupSliderValueUpdate(ssStepsInput, ssStepsVal);
setupSliderValueUpdate(slatGuidanceInput, slatGuidanceVal);
setupSliderValueUpdate(slatStepsInput, slatStepsVal);


// Settings modal functionality has been deprecated in favor of server-side .env configuration

// Tab Switching
tabBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        const targetTab = btn.getAttribute('data-tab');

        tabBtns.forEach(b => b.classList.remove('active'));
        tabContents.forEach(c => c.classList.remove('active'));

        btn.classList.add('active');
        document.getElementById(targetTab).classList.add('active');

        // Toggle visibility of the Main 3D Build Button at the bottom
        if (targetTab === 'upload-tab') {
            generate3dBtn.style.display = 'flex';
        } else {
            generate3dBtn.style.display = 'none';
        }
    });
});

// Image Source Selection Toggles
if (sourceUploadBtn && sourceLibraryBtn) {
    sourceUploadBtn.addEventListener('click', () => {
        sourceUploadBtn.classList.add('active');
        sourceLibraryBtn.classList.remove('active');
        uploadSourceContainer.style.display = 'block';
        librarySourceContainer.style.display = 'none';
        dropzone.style.display = active2dImageBlob ? 'none' : 'flex';
    });

    sourceLibraryBtn.addEventListener('click', () => {
        sourceUploadBtn.classList.remove('active');
        sourceLibraryBtn.classList.add('active');
        uploadSourceContainer.style.display = 'none';
        librarySourceContainer.style.display = 'block';
        refreshLibraryThumbnails();
    });
}

let cachedGalleryItems = [];

async function refreshLibraryThumbnails() {
    try {
        const response = await fetch(`${apiBase}/api/gallery`);
        if (!response.ok) throw new Error('Error al cargar la galería.');
        const data = await response.json();
        cachedGalleryItems = data.items || [];
        renderLibraryThumbnails(cachedGalleryItems);
        checkActiveUserJob();
    } catch (e) {
        console.error('Error loading library thumbnails:', e);
    }
}

let isPollingActiveJobPC = false;
let bgJobCheckTimerPC = null;

async function checkActiveUserJob() {
    if (isPollingActiveJobPC) return;
    try {
        const res = await fetch(`${apiBase}/api/user-active-job`);
        if (!res.ok) return;
        const data = await res.json();
        if (data.has_active && data.job_id) {
            isPollingActiveJobPC = true;
            resumeActiveJobPollingPC(data.job_id, data.type);
        }
    } catch (e) {
        console.warn('[PC] Error checking active job:', e);
    }
}

if (!bgJobCheckTimerPC) {
    bgJobCheckTimerPC = setInterval(() => {
        if (!isPollingActiveJobPC) {
            checkActiveUserJob();
        }
    }, 3000);
}

function resumeActiveJobPollingPC(jobId, jobType) {
    const bgTaskBanner = document.getElementById('bgTaskBanner');
    const bgTaskText = document.getElementById('bgTaskText');
    const typeLabel = jobType === '2d' ? '2D' : '3D';
    
    if (bgTaskBanner && bgTaskText) {
        bgTaskText.textContent = `Generando ${typeLabel}... 0%`;
        bgTaskBanner.style.display = 'flex';
    }

    if (jobType === '3d' && typeof statusOverlay !== 'undefined' && statusOverlay) {
        statusOverlay.classList.add('active');
        updateLoader(10, 'Procesando en segundo plano...', 'Generando modelo 3D desde tu dispositivo...');
    }

    const pollInterval = setInterval(async () => {
        try {
            const statusRes = await fetch(`${apiBase}/api/job-status?job_id=${jobId}`);
            if (!statusRes.ok) return;
            const job = await statusRes.json();
            
            if (job.status === 'processing' || job.status === 'pending') {
                const progress = job.progress || 10;
                if (bgTaskBanner && bgTaskText) {
                    bgTaskText.textContent = `Generando ${typeLabel}... ${progress}%`;
                    bgTaskBanner.style.display = 'flex';
                }
                if (jobType === '3d' && typeof updateLoader === 'function') {
                    updateLoader(progress, job.status === 'pending' ? 'En cola de espera...' : 'Procesando modelo 3D...', job.message || 'La IA está generando tu modelo 3D...');
                }
            } else if (job.status === 'completed') {
                clearInterval(pollInterval);
                isPollingActiveJobPC = false;
                if (bgTaskBanner) bgTaskBanner.style.display = 'none';
                if (jobType === '3d' && typeof statusOverlay !== 'undefined' && statusOverlay) {
                    statusOverlay.classList.remove('active');
                }
                try { refreshLibraryThumbnails(); } catch (e) {}
                try { fetchUserInfo(); } catch (e) {}
                const resData = job.result;
                if (jobType === '3d' && resData && (resData.gltfUrl || resData.glbUrl)) {
                    showCustomToast('¡Modelo 3D generado y cargado con éxito!', 'success');
                    load3DModel(resData.gltfUrl, resData.glbUrl, resData.fbxUrl, resData.detectedCategory);
                } else if (jobType === '2d' && resData && resData.image) {
                    showCustomToast('¡Imagen 2D generada con éxito!', 'success');
                    fetch(resData.image)
                        .then(r => r.blob())
                        .then(blob => {
                            const file = new File([blob], "generated.png", { type: "image/png" });
                            handleImageFile(file);
                            const uploadTabBtn = document.querySelector('[data-tab="upload-tab"]');
                            if (uploadTabBtn) uploadTabBtn.click();
                        }).catch(e => console.error("Error loading generated 2D image:", e));
                }
            } else if (job.status === 'failed') {
                clearInterval(pollInterval);
                isPollingActiveJobPC = false;
                if (bgTaskBanner) bgTaskBanner.style.display = 'none';
                if (jobType === '3d' && typeof statusOverlay !== 'undefined' && statusOverlay) {
                    statusOverlay.classList.remove('active');
                }
            }
        } catch (e) {
            console.warn('[PC] Active job poll warning:', e);
        }
    }, 2500);
}

function renderLibraryThumbnails(items) {
    if (!libraryThumbnailGrid) return;

    // Filter only 2D images
    const images = items.filter(item => item.type === 'image');

    if (images.length === 0) {
        libraryThumbnailGrid.innerHTML = `
            <div class="library-thumb-empty">
                No hay imágenes 2D en la biblioteca. Genera una primero en "Generar 2D AI".
            </div>
        `;
        return;
    }

    libraryThumbnailGrid.innerHTML = '';
    images.forEach(img => {
        const thumb = document.createElement('div');
        thumb.className = 'library-thumb-item';
        thumb.title = img.name;
        thumb.dataset.filename = img.name;
        thumb.dataset.url = img.url;

        // Determine if this is the active preview
        const isCurrentActive = active2dImageBlob && active2dImageBlob.name === img.name;
        if (isCurrentActive) {
            thumb.classList.add('active');
        }

        thumb.innerHTML = `<img src="${apiBase}${img.url}" alt="${img.name}">`;

        thumb.addEventListener('click', async () => {
            document.querySelectorAll('.library-thumb-item').forEach(el => el.classList.remove('active'));
            thumb.classList.add('active');

            try {
                const res = await fetch(`${apiBase}${img.url}`);
                const blob = await res.blob();
                const file = new File([blob], img.name, { type: blob.type });
                handleImageFile(file);
            } catch (error) {
                console.error('Error setting library image:', error);
            }
        });

        libraryThumbnailGrid.appendChild(thumb);
    });
}

// 2D Image Upload Handlers
function handleImageFile(file) {
    if (!file || !file.type.startsWith('image/')) return;

    active2dImageBlob = file;

    if (active2dImageURL) {
        URL.revokeObjectURL(active2dImageURL);
    }

    active2dImageURL = URL.createObjectURL(file);
    imagePreview.src = active2dImageURL;

    dropzone.style.display = 'none';
    previewContainer.style.display = 'block';
    generate3dBtn.disabled = false;
}

dropzone.addEventListener('click', () => fileInput.click());

fileInput.addEventListener('change', (e) => {
    if (e.target.files.length > 0) {
        handleImageFile(e.target.files[0]);
    }
});

// Drag and Drop
dropzone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropzone.classList.add('dragover');
});

dropzone.addEventListener('dragleave', () => {
    dropzone.classList.remove('dragover');
});

dropzone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropzone.classList.remove('dragover');
    if (e.dataTransfer.files.length > 0) {
        handleImageFile(e.dataTransfer.files[0]);
    }
});

removePreviewBtn.addEventListener('click', (e) => {
    e.stopPropagation();
    active2dImageBlob = null;
    if (active2dImageURL) {
        URL.revokeObjectURL(active2dImageURL);
        active2dImageURL = null;
    }
    imagePreview.src = '';
    previewContainer.style.display = 'none';
    dropzone.style.display = 'flex';
    fileInput.value = '';
    generate3dBtn.disabled = true;
});

// Cropper.js Integration for PC Mode
let pcCropper = null;

const btnOpenCropPC = document.getElementById('btnOpenCropPC');
const cropModalOverlay = document.getElementById('cropModalOverlay');
const cropImageTarget = document.getElementById('cropImageTarget');
const btnCancelCrop = document.getElementById('btnCancelCrop');
const btnApplyCrop = document.getElementById('btnApplyCrop');
const btnCropAspectFree = document.getElementById('btnCropAspectFree');
const btnCropAspectSquare = document.getElementById('btnCropAspectSquare');
const btnCropReset = document.getElementById('btnCropReset');

function initCropperPC(imageUrl) {
    if (!cropModalOverlay || !cropImageTarget) return;
    
    cropImageTarget.src = imageUrl;
    cropModalOverlay.style.display = 'flex';

    if (pcCropper) {
        pcCropper.destroy();
        pcCropper = null;
    }

    setTimeout(() => {
        pcCropper = new Cropper(cropImageTarget, {
            aspectRatio: 1,
            viewMode: 1,
            autoCropArea: 0.85,
            responsive: true,
            background: false
        });
    }, 150);
}

if (btnOpenCropPC) {
    btnOpenCropPC.addEventListener('click', () => {
        if (active2dImageURL) {
            initCropperPC(active2dImageURL);
        }
    });
}

if (btnCancelCrop) {
    btnCancelCrop.addEventListener('click', () => {
        if (cropModalOverlay) cropModalOverlay.style.display = 'none';
        if (pcCropper) {
            pcCropper.destroy();
            pcCropper = null;
        }
    });
}

if (btnCropAspectFree) {
    btnCropAspectFree.addEventListener('click', () => {
        if (pcCropper) pcCropper.setAspectRatio(NaN);
    });
}

if (btnCropAspectSquare) {
    btnCropAspectSquare.addEventListener('click', () => {
        if (pcCropper) pcCropper.setAspectRatio(1);
    });
}

if (btnCropReset) {
    btnCropReset.addEventListener('click', () => {
        if (pcCropper) pcCropper.reset();
    });
}

if (btnApplyCrop) {
    btnApplyCrop.addEventListener('click', () => {
        if (!pcCropper) return;

        const croppedCanvas = pcCropper.getCroppedCanvas({
            width: 1024,
            height: 1024,
            imageSmoothingEnabled: true,
            imageSmoothingQuality: 'high'
        });

        if (croppedCanvas) {
            croppedCanvas.toBlob((blob) => {
                if (blob) {
                    const croppedFile = new File([blob], 'cropped_image.png', { type: 'image/png' });
                    handleImageFile(croppedFile);
                    showCustomToast('Imagen recortada con éxito.');
                }
                if (cropModalOverlay) cropModalOverlay.style.display = 'none';
                if (pcCropper) {
                    pcCropper.destroy();
                    pcCropper = null;
                }
            }, 'image/png');
        }
    });
}

// 2D Image Generation
generate2dBtn.addEventListener('click', async () => {
    const prompt = promptInput.value.trim();
    if (!prompt) {
        alert('Por favor introduce un prompt para la imagen.');
        return;
    }

    generate2dBtn.disabled = true;
    const originalText = generate2dBtn.querySelector('span').textContent;
    generate2dBtn.querySelector('span').textContent = 'Generando 2D...';

    const selectedModel = generatorModelSelect.value;

    // Create or get inline feedback element
    let feedbackEl = document.getElementById('generate2dFeedback');
    if (!feedbackEl) {
        feedbackEl = document.createElement('div');
        feedbackEl.id = 'generate2dFeedback';
        feedbackEl.style.fontSize = '0.75rem';
        feedbackEl.style.marginTop = '0.75rem';
        feedbackEl.style.padding = '0.6rem';
        feedbackEl.style.borderRadius = '6px';
        feedbackEl.style.background = 'rgba(255, 255, 255, 0.04)';
        feedbackEl.style.border = '1px solid var(--border)';
        feedbackEl.style.color = 'var(--text-muted)';
        feedbackEl.style.lineHeight = '1.4';
        generate2dBtn.parentNode.appendChild(feedbackEl);
    }

    feedbackEl.style.display = 'block';
    feedbackEl.style.background = 'rgba(255, 255, 255, 0.04)';
    feedbackEl.style.borderColor = 'var(--border)';
    feedbackEl.style.color = 'var(--text-muted)';
    feedbackEl.innerHTML = `
        <div style="display: flex; align-items: center; gap: 8px;">
            <div class="spinner-small" style="width: 12px; height: 12px; border: 2px solid rgba(255,255,255,0.2); border-top-color: var(--primary-light); border-radius: 50%; animation: spin 1s linear infinite;"></div>
            <span>Generando imagen. Esto puede tardar 1-2 minutos si el modelo de Hugging Face está inactivo...</span>
        </div>
    `;

    try {
        const response = await fetch(`${apiBase}/api/generate-2d`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                prompt: prompt,
                model: selectedModel,
                negative_prompt: negativePromptInput.value,
                token: hfToken
            })
        });

        if (response.status === 402) {
            const errJson = await response.json().catch(() => ({}));
            feedbackEl.style.display = 'none';
            openCreditsModal(errJson.error || 'Créditos insuficientes. Por favor, compra más créditos.');
            return;
        }

        if (response.status === 202) {
            const initJson = await response.json();
            const jobId = initJson.job_id;
            
            if (initJson.credits !== undefined) {
                updateUserCreditsDisplay(initJson.credits);
            }
            
            // Show background task banner in header
            const bgTaskBanner = document.getElementById('bgTaskBanner');
            const bgTaskText = document.getElementById('bgTaskText');
            if (bgTaskBanner && bgTaskText) {
                bgTaskText.textContent = `Generando 2D... 0%`;
                bgTaskBanner.style.display = 'flex';
            }

            // Start Polling for 2D job status
            const pollInterval = setInterval(async () => {
                try {
                    const statusRes = await fetch(`${apiBase}/api/job-status?job_id=${jobId}`);
                    if (!statusRes.ok) {
                        throw new Error('Error al verificar el estado del trabajo.');
                    }
                    const job = await statusRes.json();
                    
                    if (job.status === 'processing' || job.status === 'pending') {
                        const progress = job.progress || 10;
                        feedbackEl.innerHTML = `
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <div class="spinner-small" style="width: 12px; height: 12px; border: 2px solid rgba(255,255,255,0.2); border-top-color: var(--primary-light); border-radius: 50%; animation: spin 1s linear infinite;"></div>
                                <span>${job.message || 'Generando imagen...'} (${progress}%)</span>
                            </div>
                        `;
                        if (bgTaskBanner && bgTaskText) {
                            bgTaskText.textContent = `Generando 2D... ${progress}%`;
                            bgTaskBanner.style.display = 'flex';
                        }
                    } else if (job.status === 'completed') {
                        clearInterval(pollInterval);
                        if (bgTaskBanner) bgTaskBanner.style.display = 'none';
                        
                        const resJson = job.result;
                        const base64Data = resJson.image;
                        const modelUsed = resJson.model_used || selectedModel;
                        
                        const imgFetchRes = await fetch(base64Data);
                        const imageBlob = await imgFetchRes.blob();
                        const generatedFile = new File([imageBlob], "generated.png", { type: "image/png" });
                        
                        handleImageFile(generatedFile);
                        
                        feedbackEl.style.background = 'rgba(76, 175, 80, 0.1)';
                        feedbackEl.style.borderColor = 'rgba(76, 175, 80, 0.3)';
                        feedbackEl.style.color = '#81c784';
                        feedbackEl.innerHTML = `¡Éxito usando: <strong>${modelUsed.split('/').pop()}</strong>!`;
                        
                        document.querySelector('[data-tab="upload-tab"]').click();
                        refreshGallery();
                        showCustomToast('¡Imagen 2D generada en segundo plano con éxito!', 'success');
                        
                        setTimeout(() => {
                            feedbackEl.style.display = 'none';
                        }, 5000);
                        
                        generate2dBtn.disabled = false;
                        generate2dBtn.querySelector('span').textContent = originalText;
                    } else if (job.status === 'failed') {
                        clearInterval(pollInterval);
                        if (bgTaskBanner) bgTaskBanner.style.display = 'none';
                        throw new Error(job.message || 'Fallo en la generación de imagen.');
                    }
                } catch (pollErr) {
                    clearInterval(pollInterval);
                    if (bgTaskBanner) bgTaskBanner.style.display = 'none';
                    console.error(pollErr);
                    feedbackEl.style.background = 'rgba(244, 67, 54, 0.1)';
                    feedbackEl.style.borderColor = 'rgba(244, 67, 54, 0.3)';
                    feedbackEl.style.color = '#e57373';
                    feedbackEl.innerHTML = `Error: ${pollErr.message}`;
                    showCustomAlert(pollErr.message, 'Error al generar imagen 2D');
                    generate2dBtn.disabled = false;
                    generate2dBtn.querySelector('span').textContent = originalText;
                }
            }, 2000);
            return;
        }

        if (!response.ok) {
            const errJson = await response.json().catch(() => ({}));
            throw new Error(errJson.error || 'Error en la respuesta del servidor de generación de imágenes.');
        }

    } catch (error) {
        console.error(error);
        feedbackEl.style.background = 'rgba(244, 67, 54, 0.1)';
        feedbackEl.style.borderColor = 'rgba(244, 67, 54, 0.3)';
        feedbackEl.style.color = '#e57373';
        feedbackEl.innerHTML = `Error: ${error.message}`;
        showCustomAlert(error.message, 'Error al generar imagen 2D');
    } finally {
        generate2dBtn.disabled = false;
        generate2dBtn.querySelector('span').textContent = originalText;
    }
});

// 3D Generation (Trellis)
generate3dBtn.addEventListener('click', async () => {
    if (!active2dImageBlob) return;

    const version = 'v2';

    // Show Loading state
    statusOverlay.classList.add('active');
    updateLoader(10, 'Preparando imagen...', 'Convirtiendo la imagen 2D para enviar al servidor.');

    // Convert image blob to base64
    const reader = new FileReader();
    reader.readAsDataURL(active2dImageBlob);
    reader.onloadend = async () => {
        const base64Image = reader.result;

        try {
            // Check Hugging Face Space status first
            updateLoader(15, 'Verificando estado del servidor de IA...', 'Consultando disponibilidad del servidor Hugging Face...');
            let spaceSleeping = false;
            try {
                const statusRes = await fetch(`${apiBase}/api/space-status?type=3d&token=${encodeURIComponent(hfToken)}`);
                if (statusRes.ok) {
                    const statusData = await statusRes.json();
                    if (statusData.stage === 'SLEEPING') {
                        spaceSleeping = true;
                    }
                }
            } catch (statusErr) {
                console.warn('Failed to check space status, continuing anyway:', statusErr);
            }

            if (spaceSleeping) {
                updateLoader(20, 'Encendiendo servidor de IA...', 'El servidor en Hugging Face está hibernando por inactividad. Lo estamos encendiendo, esto puede tardar de 2 a 3 minutos en iniciar...');
            } else {
                updateLoader(25, 'Conectando con el servidor...', 'Enviando datos al motor Trellis a través de tu servidor local. Esto evita problemas de CORS.');
            }
            let seedValNum = parseInt(seedInput.value) || 0;
            if (randomSeedCheck.checked) {
                seedValNum = Math.floor(Math.random() * 2147483647);
                seedInput.value = seedValNum; // display the seed used
            }

            const resolution = resolutionSelect.value;
            const decimate = parseInt(decimateInput.value) || 300000;
            const textureSize = parseInt(textureSizeSelect.value) || 2048;
            const ssGuidanceNum = parseFloat(ssGuidanceInput.value);
            const ssStepsNum = parseInt(ssStepsInput.value);
            const slatGuidanceNum = parseFloat(slatGuidanceInput.value);
            const slatStepsNum = parseInt(slatStepsInput.value);
            const autoOptimize = false;
            const quadTargetFaces = 60000;
            const remeshMethod = 'cleanup';

            const response = await fetch(`${apiBase}/api/generate-3d`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    version: version,
                    image: base64Image,
                    token: hfToken,
                    seed: seedValNum,
                    resolution: resolution,
                    decimation_target: decimate,
                    texture_size: textureSize,
                    ss_guidance: ssGuidanceNum,
                    ss_steps: ssStepsNum,
                    slat_guidance: slatGuidanceNum,
                    slat_steps: slatStepsNum,
                    auto_optimize: autoOptimize,
                    quad_target_faces: quadTargetFaces,
                    remeshMethod: remeshMethod,
                    prompt: promptInput ? promptInput.value.trim() : ''
                })
            });

            if (response.status === 402) {
                const errData = await response.json().catch(() => ({}));
                statusOverlay.classList.remove('active');
                openCreditsModal(errData.error || 'Créditos insuficientes. La generación 3D cuesta 5 créditos.');
                return;
            }

            if (response.status === 202) {
                const initData = await response.json();
                const jobId = initData.job_id;
                
                if (initData.credits !== undefined) {
                    updateUserCreditsDisplay(initData.credits);
                }
                
                let consecutiveFailures = 0;
                const maxAllowedFailures = 12;

                const bgTaskBanner = document.getElementById('bgTaskBanner');
                const bgTaskText = document.getElementById('bgTaskText');

                // Start Polling for 3D job status
                const pollInterval = setInterval(async () => {
                    try {
                        const statusRes = await fetch(`${apiBase}/api/job-status?job_id=${jobId}`);
                        if (!statusRes.ok) {
                            consecutiveFailures++;
                            if (consecutiveFailures < maxAllowedFailures) return;
                            throw new Error('Error al verificar el estado de la tarea 3D tras varios intentos.');
                        }
                        consecutiveFailures = 0;
                        const job = await statusRes.json();
                        
                        if (job.status === 'processing' || job.status === 'pending') {
                            const progress = job.progress || 10;
                            updateLoader(progress, job.status === 'pending' ? 'En cola de espera...' : 'Procesando en segundo plano...', job.message || 'Generando modelo 3D...');
                            if (bgTaskBanner && bgTaskText) {
                                bgTaskText.textContent = `Generando 3D... ${progress}%`;
                                bgTaskBanner.style.display = 'flex';
                            }
                        } else if (job.status === 'completed') {
                            clearInterval(pollInterval);
                            statusOverlay.classList.remove('active');
                            if (bgTaskBanner) bgTaskBanner.style.display = 'none';
                            
                            const data = job.result;
                            if (data.gltfUrl && data.glbUrl) {
                                refreshGallery();
                                showCustomToast('¡Modelo 3D generado y cargado con éxito!', 'success');
                                load3DModel(data.gltfUrl, data.glbUrl, data.fbxUrl, data.detectedCategory);
                            } else {
                                throw new Error('El resultado de la tarea no contiene las URLs de modelo esperadas.');
                            }
                        } else if (job.status === 'failed') {
                            clearInterval(pollInterval);
                            if (bgTaskBanner) bgTaskBanner.style.display = 'none';
                            throw new Error(job.message || 'Error durante la generación de la malla 3D.');
                        }
                    } catch (pollErr) {
                        if (pollErr.name === 'TypeError' || pollErr.message.includes('Failed to fetch') || pollErr.message.includes('NetworkError')) {
                            consecutiveFailures++;
                            if (consecutiveFailures < maxAllowedFailures) {
                                console.warn(`[Network Retry ${consecutiveFailures}/${maxAllowedFailures}] Reconectando a la tarea 3D...`);
                                return;
                            }
                        }
                        clearInterval(pollInterval);
                        if (bgTaskBanner) bgTaskBanner.style.display = 'none';
                        console.error(pollErr);
                        showCustomAlert(pollErr.message, 'Error al generar modelo 3D');
                        statusOverlay.classList.remove('active');
                    }
                }, 2500);
                return;
            }

            if (!response.ok) {
                const errData = await response.json().catch(() => ({ error: 'Error de red o timeout del servidor.' }));
                throw new Error(errData.error || 'Error interno en el servidor local.');
            }

        } catch (error) {
            console.error(error);
            showCustomAlert(error.message, 'Error al generar modelo 3D');
            statusOverlay.classList.remove('active');
        }
    };
});

function updateLoader(percent, title, desc) {
    loaderPercentage.textContent = `${percent}%`;
    statusTitle.textContent = title;
    statusDesc.textContent = desc;
}

// Three.js State for Skeletal Animations
let threeScene = null;
let threeCamera = null;
let threeRenderer = null;
let threeControls = null;
let threeModel = null;
let threeBones = {};
let threeAnimationFrameId = null;
let threeClock = new THREE.Clock();

function cleanupThreeViewer() {
    if (threeAnimationFrameId) {
        cancelAnimationFrame(threeAnimationFrameId);
        threeAnimationFrameId = null;
    }
    if (threeSkeletonHelper && threeScene) {
        try {
            threeScene.remove(threeSkeletonHelper);
        } catch (e) { }
    }
    threeSkeletonHelper = null;

    if (jointSpheres && jointSpheres.length > 0) {
        jointSpheres.forEach(item => {
            if (threeScene) {
                try {
                    threeScene.remove(item.mesh);
                } catch (e) { }
            }
        });
        jointSpheres = [];
    }

    showSkeletonHelper = false;
    if (toggleBonesHelperBtn) {
        toggleBonesHelperBtn.classList.remove('active');
        const span = toggleBonesHelperBtn.querySelector('span');
        if (span) span.textContent = "Ver Esqueleto (Rayos X)";
    }
    if (threeRenderer) {
        try {
            threeRenderer.dispose();
        } catch (e) { }
        threeRenderer = null;
    }
    threeScene = null;
    threeCamera = null;
    threeControls = null;
    threeModel = null;
    threeBones = {};
}

// Show toast feedback for actions (e.g. bone clicking)
function showCustomToast(msg) {
    let toast = document.getElementById('customToast');
    if (!toast) {
        toast = document.createElement('div');
        toast.id = 'customToast';
        toast.style.position = 'absolute';
        toast.style.bottom = '100px';
        toast.style.left = '50%';
        toast.style.transform = 'translateX(-50%)';
        toast.style.background = 'rgba(18, 18, 24, 0.95)';
        toast.style.border = '1px solid var(--primary)';
        toast.style.color = '#fff';
        toast.style.padding = '8px 16px';
        toast.style.borderRadius = '20px';
        toast.style.fontSize = '0.85rem';
        toast.style.zIndex = '1000';
        toast.style.transition = 'opacity 0.3s ease';
        toast.style.pointerEvents = 'none';
        viewerDisplay.appendChild(toast);
    }
    toast.textContent = msg;
    toast.style.opacity = '1';
    clearTimeout(toast.timeoutId);
    toast.timeoutId = setTimeout(() => {
        toast.style.opacity = '0';
    }, 2000);
}

function setupCanvasClickRaycaster(canvas) {
    let pointerDownX = 0;
    let pointerDownY = 0;

    canvas.addEventListener('pointerdown', (event) => {
        pointerDownX = event.clientX;
        pointerDownY = event.clientY;
    });

    canvas.addEventListener('pointerup', (event) => {
        if (!showSkeletonHelper || !threeCamera || !threeModel) return;

        // Calculate drag distance in screen pixels
        const moveX = event.clientX - pointerDownX;
        const moveY = event.clientY - pointerDownY;
        const dragDistance = Math.sqrt(moveX * moveX + moveY * moveY);

        // If the user dragged more than 5 pixels, they are rotating the camera - discard the click!
        if (dragDistance > 5) return;

        const rect = canvas.getBoundingClientRect();
        const mouse = new THREE.Vector2(
            ((event.clientX - rect.left) / rect.width) * 2 - 1,
            -((event.clientY - rect.top) / rect.height) * 2 + 1
        );

        const raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(mouse, threeCamera);

        // Intersect only the joint sphere meshes to guarantee the user specifically clicks the sphere
        const meshesToIntersect = jointSpheres.map(item => item.mesh).filter(Boolean);
        const intersects = raycaster.intersectObjects(meshesToIntersect);

        if (intersects.length > 0) {
            const hitMesh = intersects[0].object;
            const jointInfo = jointSpheres.find(item => item.mesh === hitMesh);
            if (jointInfo) {
                const closestBone = jointInfo.bone;
                console.log("[Raycast Click] Selected bone:", closestBone.name);

                selectedBone = closestBone;
                if (manualBoneNameInput) {
                    manualBoneNameInput.value = selectedBone.name;
                }
                if (applyBoneRenameBtn) {
                    applyBoneRenameBtn.style.display = 'none';
                }
                loadSelectedBoneRotations();
                updateWeightVisualizerBone();
                updateSelectedBoneMarker();
                showCustomToast(`Hueso seleccionado: ${closestBone.name}`);
            }
        }
    });

    let hoveredJoint = null;
    const originalColor = 0x00ffcc;

    canvas.addEventListener('pointermove', (event) => {
        if (!showSkeletonHelper || !threeCamera || !threeModel) {
            if (hoveredJoint) {
                hoveredJoint.material.color.setHex(originalColor);
                hoveredJoint.scale.setScalar(1.0);
                hoveredJoint = null;
            }
            return;
        }

        // Skip hover highlight if we are dragging/orbiting the camera
        if (event.buttons !== 0) {
            if (hoveredJoint) {
                hoveredJoint.material.color.setHex(originalColor);
                hoveredJoint.scale.setScalar(1.0);
                hoveredJoint = null;
            }
            return;
        }

        const rect = canvas.getBoundingClientRect();
        const mouse = new THREE.Vector2(
            ((event.clientX - rect.left) / rect.width) * 2 - 1,
            -((event.clientY - rect.top) / rect.height) * 2 + 1
        );

        const raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(mouse, threeCamera);

        const meshesToIntersect = jointSpheres.map(item => item.mesh).filter(Boolean);
        const intersects = raycaster.intersectObjects(meshesToIntersect);

        if (intersects.length > 0) {
            const hitMesh = intersects[0].object;
            if (hoveredJoint !== hitMesh) {
                // Restore old one
                if (hoveredJoint) {
                    hoveredJoint.material.color.setHex(originalColor);
                    hoveredJoint.scale.setScalar(1.0);
                }
                // Highlight new one
                hoveredJoint = hitMesh;
                hoveredJoint.material.color.setHex(0xffff00); // Yellow highlight
                hoveredJoint.scale.setScalar(1.3); // Scale up slightly for feedback
            }
        } else {
            // Restore old one if no hit
            if (hoveredJoint) {
                hoveredJoint.material.color.setHex(originalColor);
                hoveredJoint.scale.setScalar(1.0);
                hoveredJoint = null;
            }
        }
    });
}

function initThreeViewer(gltfUrl) {
    cleanupThreeViewer();
    activeGltfUrl = gltfUrl;

    // Clear display
    viewerDisplay.innerHTML = '';

    // Create canvas
    const canvas = document.createElement('canvas');
    canvas.style.width = '100%';
    canvas.style.height = '100%';
    viewerDisplay.appendChild(canvas);

    // Setup click selection for bones raycasting
    setupCanvasClickRaycaster(canvas);
    setupWeightPaintingCanvasEvents(canvas);

    // Setup Scene
    threeScene = new THREE.Scene();
    threeScene.background = new THREE.Color(0x0a0a0c);

    // Add custom styled grid helper
    const gridHelper = new THREE.GridHelper(10, 20, 0x9c27b0, 0x222230); // purple matching UI
    gridHelper.position.y = -0.5;
    threeScene.add(gridHelper);

    // Setup Camera
    const rect = viewerDisplay.getBoundingClientRect();
    threeCamera = new THREE.PerspectiveCamera(45, rect.width / rect.height, 0.1, 100);
    threeCamera.position.set(0, 0.3, 2.5);

    // Setup Renderer
    threeRenderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
    threeRenderer.setSize(rect.width, rect.height);
    threeRenderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    threeRenderer.shadowMap.enabled = true;
    threeRenderer.outputEncoding = THREE.sRGBEncoding;
    threeRenderer.physicallyCorrectLights = true;

    // Setup Controls
    threeControls = new THREE.OrbitControls(threeCamera, threeRenderer.domElement);
    threeControls.enableDamping = true;
    threeControls.dampingFactor = 0.05;
    threeControls.target.set(0, 0.3, 0);
    threeControls.autoRotate = isAutoRotating;
    threeControls.autoRotateSpeed = 1.2;

    // Setup Lighting - Brightened and balanced
    const ambientLight = new THREE.AmbientLight(0xffffff, 2.5);
    threeScene.add(ambientLight);

    const dirLight = new THREE.DirectionalLight(0xffffff, 3.5);
    dirLight.position.set(2, 5, 3);
    dirLight.castShadow = true;
    threeScene.add(dirLight);

    const fillLight = new THREE.DirectionalLight(0xffffff, 2.0);
    fillLight.position.set(-2, 1, -2);
    threeScene.add(fillLight);

    const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444, 2.0);
    hemiLight.position.set(0, 20, 0);
    threeScene.add(hemiLight);

    // Load Model
    const loader = new THREE.GLTFLoader();

    updateLoader(60, 'Cargando esqueleto...', 'Inicializando componentes 3D e interpretando sistema de huesos.');
    statusOverlay.classList.add('active');

    const absoluteUrl = gltfUrl.startsWith('http') ? gltfUrl : `${apiBase}${gltfUrl}`;

    loader.load(
        absoluteUrl,
        (gltf) => {
            threeModel = gltf.scene;

            // Adjust scaling and positions to fit the screen nicely
            const box = new THREE.Box3().setFromObject(threeModel);
            const size = box.getSize(new THREE.Vector3());
            const center = box.getCenter(new THREE.Vector3());

            // Normalize size if it's too big or small
            const maxDim = Math.max(size.x, size.y, size.z);
            if (maxDim > 0) {
                const scale = 1.6 / maxDim;
                threeModel.scale.set(scale, scale, scale);
            }

            // Stand model on the grid floor
            const updatedBox = new THREE.Box3().setFromObject(threeModel);
            const updatedCenter = updatedBox.getCenter(new THREE.Vector3());
            threeModel.position.x = -updatedCenter.x;
            threeModel.position.y = -updatedBox.min.y - 0.5;
            threeModel.position.z = -updatedCenter.z;

            threeScene.add(threeModel);

            // Find and map bones using a coordinate-based spatial classifier (works with bone_0, bone_1, etc.)
            threeBones = {};
            const allBonesList = [];
            threeModel.traverse((child) => {
                if (child.isSkinnedMesh) {
                    child.castShadow = true;
                    child.receiveShadow = true;
                    if (child.material) {
                        child.material.side = THREE.DoubleSide;
                    }
                }
                if (child.isBone) {
                    allBonesList.push(child);
                    // Map raw bone names directly as keys in threeBones
                    threeBones[child.name] = child;
                }
            });

            // Apply wireframe, nodes, and texture view if active
            applyWireframeState(threeModel, showWireframe);
            applyNodesState(threeModel, showNodes);
            applyTextureVisibility(threeModel, showTextures);

            // Ensure world matrices are fully computed in the initial T-pose
            threeModel.updateMatrixWorld(true);

            // Fetch absolute world positions
            const boneData = allBonesList.map(bone => {
                const pos = new THREE.Vector3();
                bone.getWorldPosition(pos);
                return { bone, pos, name: bone.name };
            });

            if (boneData.length > 0) {
                // Find Hips (usually closest to center X=0, Z=0 and roughly halfway up Y=0.8)
                let rootBoneData = boneData.find(d => !d.bone.parent || !d.bone.parent.isBone);
                if (!rootBoneData) {
                    rootBoneData = boneData.reduce((prev, curr) => {
                        const prevDist = Math.abs(prev.pos.x) + Math.abs(prev.pos.z);
                        const currDist = Math.abs(curr.pos.x) + Math.abs(curr.pos.z);
                        return prevDist < currDist ? prev : curr;
                    });
                }

                threeBones.hips = rootBoneData.bone;
                const hipsY = rootBoneData.pos.y;

                // Group other bones relative to Hips coordinate framework
                const leftBones = [];
                const rightBones = [];
                const spineBones = [];

                boneData.forEach(d => {
                    if (d.bone === threeBones.hips) return;

                    const relX = d.pos.x - rootBoneData.pos.x;
                    const relY = d.pos.y;

                    // Leg bones (below hips)
                    if (relY < hipsY - 0.1) {
                        if (relX < -0.04) leftBones.push(d);
                        else if (relX > 0.04) rightBones.push(d);
                    } else {
                        // Spine or Arms (at or above hips)
                        if (Math.abs(relX) < 0.08) {
                            spineBones.push(d);
                        } else {
                            if (relX < -0.08) leftBones.push(d);
                            else if (relX > 0.08) rightBones.push(d);
                        }
                    }
                });

                // Classify legs: sort top-to-bottom
                const leftLegBones = leftBones.filter(d => d.pos.y < hipsY - 0.1).sort((a, b) => b.pos.y - a.pos.y);
                const rightLegBones = rightBones.filter(d => d.pos.y < hipsY - 0.1).sort((a, b) => b.pos.y - a.pos.y);

                if (leftLegBones.length >= 1) threeBones.leftUpLeg = leftLegBones[0].bone;
                if (leftLegBones.length >= 2) threeBones.leftLeg = leftLegBones[1].bone;
                if (leftLegBones.length >= 3) threeBones.leftFoot = leftLegBones[2].bone;

                if (rightLegBones.length >= 1) threeBones.rightUpLeg = rightLegBones[0].bone;
                if (rightLegBones.length >= 2) threeBones.rightLeg = rightLegBones[1].bone;
                if (rightLegBones.length >= 3) threeBones.rightFoot = rightLegBones[2].bone;

                // Classify arms: sort closest to center axis to furthest (shoulder -> upper arm -> forearm -> hand)
                const leftArmBones = leftBones.filter(d => d.pos.y >= hipsY - 0.1).sort((a, b) => Math.abs(a.pos.x - rootBoneData.pos.x) - Math.abs(b.pos.x - rootBoneData.pos.x));
                const rightArmBones = rightBones.filter(d => d.pos.y >= hipsY - 0.1).sort((a, b) => Math.abs(a.pos.x - rootBoneData.pos.x) - Math.abs(b.pos.x - rootBoneData.pos.x));

                let leftArmStart = 0;
                if (leftArmBones.length >= 4) {
                    leftArmStart = 1;
                }
                let rightArmStart = 0;
                if (rightArmBones.length >= 4) {
                    rightArmStart = 1;
                }

                if (leftArmBones.length > leftArmStart) threeBones.leftArm = leftArmBones[leftArmStart].bone;
                if (leftArmBones.length > leftArmStart + 1) threeBones.leftForearm = leftArmBones[leftArmStart + 1].bone;
                if (leftArmBones.length > leftArmStart + 2) threeBones.leftHand = leftArmBones[leftArmStart + 2].bone;

                if (rightArmBones.length > rightArmStart) threeBones.rightArm = rightArmBones[rightArmStart].bone;
                if (rightArmBones.length > rightArmStart + 1) threeBones.rightForearm = rightArmBones[rightArmStart + 1].bone;
                if (rightArmBones.length > rightArmStart + 2) threeBones.rightHand = rightArmBones[rightArmStart + 2].bone;

                // Spine and neck (center bones above hips sorted bottom-to-top)
                const sortedSpine = spineBones.sort((a, b) => a.pos.y - b.pos.y);
                if (sortedSpine.length >= 1) threeBones.spine = sortedSpine[0].bone;
                if (sortedSpine.length >= 2) threeBones.neck = sortedSpine[sortedSpine.length - 1].bone;
            }

            console.log("[ThreeViewer] Bones mapped successfully:", Object.keys(threeBones));
            window.threeBones = threeBones;
            window.threeModel = threeModel;

            // Populate the dropdown options now that the model is loaded in Three.js
            setupManualBoneSelectOptions();

            // Disable bones toggle buttons if the model has no bones
            const hasBones = allBonesList.length > 0;
            if (toggleBonesBtn) {
                if (!hasBones) {
                    toggleBonesBtn.classList.add('disabled-btn');
                    toggleBonesBtn.style.opacity = '0.35';
                    toggleBonesBtn.style.cursor = 'not-allowed';
                    toggleBonesBtn.title = "Este modelo no posee huesos. Genéralo usando Rigging Automático en el panel lateral.";
                } else {
                    toggleBonesBtn.classList.remove('disabled-btn');
                    toggleBonesBtn.style.opacity = '';
                    toggleBonesBtn.style.cursor = '';
                    toggleBonesBtn.title = "Ver/Ocultar Huesos (Esqueleto)";
                }
            }
            if (toggleBonesHelperBtn) {
                if (!hasBones) {
                    toggleBonesHelperBtn.classList.add('disabled-btn');
                    toggleBonesHelperBtn.style.opacity = '0.35';
                    toggleBonesHelperBtn.style.cursor = 'not-allowed';
                    toggleBonesHelperBtn.title = "Este modelo no posee huesos. Genéralo usando Rigging Automático en el panel lateral.";
                } else {
                    toggleBonesHelperBtn.classList.remove('disabled-btn');
                    toggleBonesHelperBtn.style.opacity = '';
                    toggleBonesHelperBtn.style.cursor = '';
                    toggleBonesHelperBtn.title = "Ver Esqueleto (Rayos X)";
                }
            }

            statusOverlay.classList.remove('active');

            threeClock.start(); // Explicitly start clock
            threeClock.getDelta(); // reset clock
            threeAnimate();
        },
        (xhr) => {
            if (xhr.total) {
                const percent = Math.round((xhr.loaded / xhr.total) * 100);
                updateLoader(60 + Math.round(percent * 0.3), 'Cargando esqueleto...', `Descargando componentes: ${percent}%`);
            }
        },
        (error) => {
            console.error('[ThreeViewer] Error loading model:', error);
            statusOverlay.classList.remove('active');
            showCustomAlert('No se pudo inicializar la animación en Three.js.', 'Error de visualización');
        }
    );

    window.addEventListener('resize', onThreeResize);
}

function onThreeResize() {
    if (!threeCamera || !threeRenderer || !viewerDisplay) return;
    const rect = viewerDisplay.getBoundingClientRect();
    threeCamera.aspect = rect.width / rect.height;
    threeCamera.updateProjectionMatrix();
    threeRenderer.setSize(rect.width, rect.height);

    // Update all wireframe passes screenSize dynamically
    if (threeModel) {
        threeModel.traverse(child => {
            if (child.name.endsWith("_wireframe_helper")) {
                child.traverse(subChild => {
                    if (subChild.material && subChild.material.uniforms && subChild.material.uniforms.screenSize) {
                        subChild.material.uniforms.screenSize.value.set(rect.width, rect.height);
                    }
                });
            }
        });
    }
}

function threeAnimate() {
    threeAnimationFrameId = requestAnimationFrame(threeAnimate);

    if (threeControls) threeControls.update();

    // Apply bones rotation
    updateSkeletalAnimation();

    // Update glowing joint spheres positions in real-time
    if (showSkeletonHelper && jointSpheres && jointSpheres.length > 0) {
        jointSpheres.forEach(item => {
            const pos = new THREE.Vector3();
            item.bone.getWorldPosition(pos);
            item.mesh.position.copy(pos);
        });
    }

    // Update selected bone marker position in real-time if weight painting is active
    if (isWeightPaintingActive && selectedBoneMarker) {
        if (selectedBone) {
            const pos = new THREE.Vector3();
            selectedBone.getWorldPosition(pos);
            selectedBoneMarker.position.copy(pos);
            selectedBoneMarker.visible = true;
        } else {
            selectedBoneMarker.visible = false;
        }
    } else if (selectedBoneMarker) {
        selectedBoneMarker.visible = false;
    }

    if (isWeightPaintingActive && brushHelper && threeCamera) {
        brushHelper.lookAt(threeCamera.position);
    }

    if (threeRenderer && threeScene && threeCamera) {
        threeRenderer.render(threeScene, threeCamera);
    }
}



function updateSkeletalAnimation() {
    // Only manual adjustment is supported; bypass all procedural ticks.
}

// 3D Model Render and Viewer Interactions
function load3DModel(gltfUrl, downloadUrl, fbxUrl, detectedCategory = 'unknown') {
    currentModelCategory = detectedCategory;
    let categoryName = "Desconocido";
    const cat = String(detectedCategory).toLowerCase();
    if (cat === 'ai' || cat === 'humanoid') {
        categoryName = "Humanoide (Bípedo)";
    } else if (cat === 'local_quadruped' || cat === 'quadruped') {
        categoryName = "Cuadrúpedo (4 patas)";
    } else if (cat === 'unsupported' || cat === 'spider') {
        categoryName = "Arácnido / Insecto / Objeto";
    } else if (cat === 'object') {
        categoryName = "Objeto Estático";
    } else if (detectedCategory && detectedCategory !== 'unknown') {
        categoryName = detectedCategory;
    }

    if (aiClassificationText && aiClassificationBadge) {
        aiClassificationText.textContent = categoryName;
        aiClassificationBadge.style.display = 'flex';
    } else if (aiClassificationBadge) {
        aiClassificationBadge.style.display = 'none';
    }

    const rigTextEl = document.getElementById('rigDetectedCategoryText');
    if (rigTextEl) {
        rigTextEl.textContent = categoryName;
    }
    // Resolve URLs using apiBase for file:// compatibility
    const absoluteGltfUrl = gltfUrl.startsWith('http') ? gltfUrl : `${apiBase}${gltfUrl}`;
    const absoluteDownloadUrl = downloadUrl ? (downloadUrl.startsWith('http') ? downloadUrl : `${apiBase}${downloadUrl}`) : absoluteGltfUrl;

    currentGltfUrl = absoluteDownloadUrl; // Store the high-quality GLB download url
    activeModelRelativeUrl = gltfUrl; // Store relative path for rigging

    // Check if the loaded model is a rigged model
    const isRigged = gltfUrl.includes('_rigged.glb') || gltfUrl.includes('_rigged.fbx');
    const isClean = gltfUrl.includes('_clean.glb');

    if (animationControlGroup) animationControlGroup.style.display = 'none';
    viewerOverlay.classList.add('active');

    // FBX button is always visible as the main download action
    downloadFbxBtn.style.display = 'inline-flex';
    downloadFbxBtn.onclick = async () => {
        if (fbxUrl) {
            const absoluteFbxUrl = fbxUrl.startsWith('http') ? fbxUrl : `${apiBase}${fbxUrl}`;
            const link = document.createElement('a');
            link.href = absoluteFbxUrl;
            link.download = absoluteFbxUrl.split('/').pop();
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } else {
            // Raw model needs conversion/optimization first
            statusOverlay.classList.add('active');
            updateLoader(50, 'Convirtiendo a FBX...', 'Blender está optimizando la malla y exportando el archivo FBX...');
            
            try {
                const response = await fetch(`${apiBase}/api/optimize-3d`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        modelUrl: activeModelRelativeUrl,
                        quad_target_faces: 60000,
                        remeshMethod: 'cleanup'
                    })
                });

                if (!response.ok) {
                    const errData = await response.json().catch(() => ({ error: 'Error al convertir.' }));
                    throw new Error(errData.error || 'Error interno del servidor.');
                }

                const data = await response.json();
                if (data.fbxUrl) {
                    // Download the generated FBX
                    const absoluteFbxUrl = data.fbxUrl.startsWith('http') ? data.fbxUrl : `${apiBase}${data.fbxUrl}`;
                    const link = document.createElement('a');
                    link.href = absoluteFbxUrl;
                    link.download = absoluteFbxUrl.split('/').pop();
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);

                    // Save model info to reload the viewer with the cleaned model
                    sessionStorage.setItem('pendingModelToLoad', JSON.stringify({
                        gltfUrl: data.gltfUrl,
                        downloadUrl: data.glbUrl,
                        fbxUrl: data.fbxUrl,
                        detectedCategory: currentModelCategory
                    }));
                    window.location.reload();
                } else {
                    throw new Error('No se generó la URL del archivo FBX.');
                }
            } catch (error) {
                statusOverlay.classList.remove('active');
                showCustomAlert(error.message, 'Error al descargar FBX');
            }
        }
    };

    // Show vertical toolbar
    const toolbar = document.getElementById('rightVerticalToolbar');
    if (toolbar) toolbar.style.display = 'flex';

    // Set buttons and panels visibility based on model state
    const btnClean = document.getElementById('btnCleanPanel');
    const btnRigTrigger = document.getElementById('btnRigTriggerPanel');
    const btnRig = document.getElementById('btnRigPanel');
    const btnWeightPaint = document.getElementById('btnWeightPaintPanel');

    // Clean Panel / Button
    if (manualCleanPanel) {
        manualCleanPanel.classList.add('collapsed');
        if (!isClean) {
            manualCleanPanel.style.display = 'block';
            if (btnClean) btnClean.style.display = 'flex';
        } else {
            manualCleanPanel.style.display = 'none';
            if (btnClean) btnClean.style.display = 'none';
        }
    }

    // Rig Trigger Panel / Button (AI Rigging)
    if (rigTriggerPanel) {
        rigTriggerPanel.classList.add('collapsed');
        if (gltfUrl && !isRigged) {
            rigTriggerPanel.style.display = 'block';
            if (btnRigTrigger) btnRigTrigger.style.display = 'flex';
        } else {
            rigTriggerPanel.style.display = 'none';
            if (btnRigTrigger) btnRigTrigger.style.display = 'none';
        }
    }

    // Always use Three.js viewer for consistency and custom tools support
    initThreeViewer(absoluteDownloadUrl);

    // Manual Rig & Weight Paint (Rigged models only)
    if (isRigged) {
        if (manualRigPanel) {
            manualRigPanel.style.display = 'block';
            manualRigPanel.classList.add('collapsed');
            setupManualBoneSelectOptions();
        }
        if (manualWeightPaintPanel) {
            manualWeightPaintPanel.style.display = 'block';
            manualWeightPaintPanel.classList.add('collapsed');
        }
        if (btnRig) btnRig.style.display = 'flex';
        if (btnWeightPaint) btnWeightPaint.style.display = 'flex';
    } else {
        if (manualRigPanel) manualRigPanel.style.display = 'none';
        if (manualWeightPaintPanel) manualWeightPaintPanel.style.display = 'none';
        if (btnRig) btnRig.style.display = 'none';
        if (btnWeightPaint) btnWeightPaint.style.display = 'none';
    }

    // Reset toolbar button active states on load
    const toolbarButtons = [btnClean, btnRigTrigger, btnRig, btnWeightPaint];
    toolbarButtons.forEach(btn => {
        if (btn) btn.classList.remove('active');
    });

    // Reset weight painting state on load
    isWeightPaintingActive = false;
    if (activeWeightPaintCheck) {
        activeWeightPaintCheck.checked = false;
        const card = document.getElementById('paintInstructionCard');
        if (card) card.style.display = 'none';
    }
    updateSelectedBoneMarker();
    originalMaterialsMap.clear();
    if (brushHelper && threeScene) {
        threeScene.remove(brushHelper);
        brushHelper = null;
    }
}

// Toolbar actions
if (toggleAutoRotateBtn) {
    // Sync UI indicator with state on load
    if (isAutoRotating) {
        toggleAutoRotateBtn.classList.add('active');
    } else {
        toggleAutoRotateBtn.classList.remove('active');
    }

    toggleAutoRotateBtn.addEventListener('click', () => {
        isAutoRotating = !isAutoRotating;

        if (isAutoRotating) {
            toggleAutoRotateBtn.classList.add('active');
        } else {
            toggleAutoRotateBtn.classList.remove('active');
        }

        if (threeControls) {
            threeControls.autoRotate = isAutoRotating;
        }
    });
}

if (resetCameraBtn) {
    resetCameraBtn.addEventListener('click', () => {
        if (threeCamera && threeControls) {
            threeCamera.position.set(0, 0.3, 2.5);
            threeControls.target.set(0, 0.3, 0);
            threeControls.update();
        }

        // Temporary flash class on button for visual feedback
        resetCameraBtn.style.color = 'var(--primary-light)';
        setTimeout(() => {
            resetCameraBtn.style.color = '';
        }, 300);
    });
}

class SkinnedPoints extends THREE.Points {
    constructor(geometry, material) {
        super(geometry, material);
        this.isSkinnedMesh = true;
        this.bindMatrix = new THREE.Matrix4();
        this.bindMatrixInverse = new THREE.Matrix4();
    }
    bind(skeleton, bindMatrix) {
        this.skeleton = skeleton;
        this.bindMatrix.copy(bindMatrix || this.matrixWorld);
        this.bindMatrixInverse.copy(this.bindMatrix).invert();
    }
}

const skinnedLineVertexShader = `
    uniform vec2 offset;
    uniform vec2 screenSize;
    #include <common>
    #include <skinning_pars_vertex>
    void main() {
        #include <begin_vertex>
        #include <skinbase_vertex>
        #include <skinning_vertex>
        vec4 mvPosition = modelViewMatrix * vec4(transformed, 1.0);
        gl_Position = projectionMatrix * mvPosition;
        gl_Position.xy += (offset / screenSize) * gl_Position.w * 2.0;
    }
`;

const staticLineVertexShader = `
    uniform vec2 offset;
    uniform vec2 screenSize;
    void main() {
        vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
        gl_Position = projectionMatrix * mvPosition;
        gl_Position.xy += (offset / screenSize) * gl_Position.w * 2.0;
    }
`;

const staticLineFragmentShader = `
    uniform vec3 color;
    void main() {
        gl_FragColor = vec4(color, 0.95);
    }
`;

const skinnedLineFragmentShader = `
    uniform vec3 color;
    void main() {
        gl_FragColor = vec4(color, 0.95);
    }
`;

function createQuadWireframeGeometry(sourceGeometry) {
    const indices = sourceGeometry.index ? sourceGeometry.index.array : null;
    if (!indices) {
        return new THREE.EdgesGeometry(sourceGeometry, 10);
    }

    const quadEdges = [];
    const addedEdges = new Set();

    function addEdge(i1, i2) {
        const key = i1 < i2 ? `${i1}-${i2}` : `${i2}-${i1}`;
        if (!addedEdges.has(key)) {
            addedEdges.add(key);
            quadEdges.push(i1, i2);
        }
    }

    const numIndices = indices.length;
    let i = 0;

    while (i < numIndices) {
        if (i + 5 < numIndices) {
            const a = indices[i];
            const b = indices[i+1];
            const c = indices[i+2];

            const d = indices[i+3];
            const e = indices[i+4];
            const f = indices[i+5];

            const t1 = [a, b, c];
            const t2 = [d, e, f];
            const shared = t1.filter(v => t2.includes(v));

            if (shared.length === 2) {
                const s1 = shared[0];
                const s2 = shared[1];
                const o1 = t1.find(v => v !== s1 && v !== s2);
                const o2 = t2.find(v => v !== s1 && v !== s2);

                addEdge(s1, o1);
                addEdge(o1, s2);
                addEdge(s2, o2);
                addEdge(o2, s1);

                i += 6;
                continue;
            }
        }

        const a = indices[i];
        const b = indices[i+1];
        const c = indices[i+2];
        addEdge(a, b);
        addEdge(b, c);
        addEdge(c, a);
        i += 3;
    }

    const lineGeometry = new THREE.BufferGeometry();
    lineGeometry.setAttribute('position', sourceGeometry.attributes.position.clone());

    if (sourceGeometry.attributes.skinIndex) {
        lineGeometry.setAttribute('skinIndex', sourceGeometry.attributes.skinIndex.clone());
    }
    if (sourceGeometry.attributes.skinWeight) {
        lineGeometry.setAttribute('skinWeight', sourceGeometry.attributes.skinWeight.clone());
    }

    lineGeometry.setIndex(new THREE.BufferAttribute(new Uint32Array(quadEdges), 1));
    return lineGeometry;
}

class SkinnedLineSegments extends THREE.LineSegments {
    constructor(geometry, material) {
        super(geometry, material);
        this.isSkinnedMesh = true;
        this.bindMatrix = new THREE.Matrix4();
        this.bindMatrixInverse = new THREE.Matrix4();
    }
    bind(skeleton, bindMatrix) {
        this.skeleton = skeleton;
        this.bindMatrix.copy(bindMatrix || this.matrixWorld);
        this.bindMatrixInverse.copy(this.bindMatrix).invert();
    }
}

const skinnedPointsVertexShader = `
    uniform float size;
    #include <common>
    #include <skinning_pars_vertex>
    void main() {
        #include <begin_vertex>
        #include <skinbase_vertex>
        #include <skinning_vertex>
        vec4 mvPosition = modelViewMatrix * vec4(transformed, 1.0);
        gl_Position = projectionMatrix * mvPosition;
        gl_PointSize = size;
    }
`;

const staticPointsVertexShader = `
    uniform float size;
    void main() {
        vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
        gl_Position = projectionMatrix * mvPosition;
        gl_PointSize = size;
    }
`;

const skinnedPointsFragmentShader = `
    uniform vec3 color;
    void main() {
        // Draw round circular dots
        vec2 coord = gl_PointCoord - vec2(0.5);
        if (length(coord) > 0.5) discard;
        gl_FragColor = vec4(color, 1.0);
    }
`;

function applyWireframeState(model, active) {
    if (!model) return;

    const rect = viewerDisplay ? viewerDisplay.getBoundingClientRect() : null;
    const w = rect ? rect.width : window.innerWidth;
    const h = rect ? rect.height : window.innerHeight;

    model.traverse((child) => {
        if (child.name && (child.name.includes("_wireframe_helper") || child.name.includes("_points_helper"))) return;

        if (child.isMesh) {
            let wfGroup = child.getObjectByName(child.name + "_wireframe_helper");

            if (active) {
                if (!wfGroup) {
                    wfGroup = new THREE.Group();
                    wfGroup.name = child.name + "_wireframe_helper";
                    child.add(wfGroup);

                    if (child.isSkinnedMesh) {
                        // Render natively as a wireframe SkinnedMesh to align perfectly with bone deformations
                        const wfMat = new THREE.MeshBasicMaterial({
                            color: 0xffeb3b,
                            wireframe: true,
                            transparent: true,
                            opacity: 0.85,
                            depthWrite: false,
                            skinning: true
                        });
                        const lineMesh = new THREE.SkinnedMesh(child.geometry, wfMat);
                        lineMesh.name = child.name + "_wireframe_helper_skinned";
                        wfGroup.add(lineMesh);
                        lineMesh.bind(child.skeleton, child.bindMatrix);
                    } else {
                        // Static mesh helper - thick line segment passes
                        const edgesGeo = createQuadWireframeGeometry(child.geometry);
                        const offsets = [
                            new THREE.Vector2(0, 0),
                            new THREE.Vector2(-0.6, 0.6),
                            new THREE.Vector2(0.6, -0.6),
                            new THREE.Vector2(0.6, 0.6),
                            new THREE.Vector2(-0.6, -0.6)
                        ];
                        offsets.forEach((offsetVal, index) => {
                            const wfMat = new THREE.ShaderMaterial({
                                vertexShader: staticLineVertexShader,
                                fragmentShader: staticLineFragmentShader,
                                uniforms: {
                                    color: { value: new THREE.Color(0xffeb3b) },
                                    offset: { value: offsetVal },
                                    screenSize: { value: new THREE.Vector2(w, h) }
                                },
                                transparent: true,
                                depthWrite: false
                            });
                            const lineMesh = new THREE.LineSegments(edgesGeo, wfMat);
                            lineMesh.name = child.name + "_wireframe_helper_pass_" + index;
                            wfGroup.add(lineMesh);
                        });
                    }
                }
                wfGroup.visible = true;
            } else {
                if (wfGroup) {
                    wfGroup.visible = false;
                }
            }
        }
    });
}

function applyNodesState(model, active) {
    if (!model) return;

    model.traverse((child) => {
        if (child.name && (child.name.includes("_wireframe_helper") || child.name.includes("_points_helper"))) return;

        if (child.isMesh) {
            let ptsMesh = child.getObjectByName(child.name + "_points_helper");

            if (active) {
                if (!ptsMesh) {
                    if (child.isSkinnedMesh) {
                        const ptsMat = new THREE.ShaderMaterial({
                            vertexShader: skinnedPointsVertexShader,
                            fragmentShader: skinnedPointsFragmentShader,
                            uniforms: THREE.UniformsUtils.merge([
                                THREE.ShaderLib.standard.uniforms,
                                {
                                    size: { value: 9.0 }, // large 9px dots
                                    color: { value: new THREE.Color(0x00ff88) }
                                }
                            ]),
                            transparent: true,
                            depthWrite: false,
                            polygonOffset: true,
                            polygonOffsetFactor: -2,
                            polygonOffsetUnits: -4,
                            skinning: true
                        });
                        ptsMesh = new SkinnedPoints(child.geometry, ptsMat);
                        child.add(ptsMesh);
                        ptsMesh.bind(child.skeleton, child.bindMatrix);
                    } else {
                        const ptsMat = new THREE.ShaderMaterial({
                            vertexShader: staticPointsVertexShader,
                            fragmentShader: skinnedPointsFragmentShader,
                            uniforms: {
                                size: { value: 9.0 },
                                color: { value: new THREE.Color(0x00ff88) }
                            },
                            transparent: true,
                            depthWrite: false,
                            polygonOffset: true,
                            polygonOffsetFactor: -2,
                            polygonOffsetUnits: -4
                        });
                        ptsMesh = new THREE.Points(child.geometry, ptsMat);
                        child.add(ptsMesh);
                    }
                    ptsMesh.name = child.name + "_points_helper";
                }
                ptsMesh.visible = true;
            } else {
                if (ptsMesh) {
                    ptsMesh.visible = false;
                }
            }
        }
    });
}

if (toggleWireframeBtn) {
    toggleWireframeBtn.addEventListener('click', () => {
        showWireframe = !showWireframe;

        if (showWireframe) {
            toggleWireframeBtn.classList.add('active');
        } else {
            toggleWireframeBtn.classList.remove('active');
        }

        applyWireframeState(threeModel, showWireframe);
    });
}

if (toggleNodesBtn) {
    if (showNodes) {
        toggleNodesBtn.classList.add('active');
    } else {
        toggleNodesBtn.classList.remove('active');
    }

    toggleNodesBtn.addEventListener('click', () => {
        showNodes = !showNodes;

        if (showNodes) {
            toggleNodesBtn.classList.add('active');
        } else {
            toggleNodesBtn.classList.remove('active');
        }

        applyNodesState(threeModel, showNodes);
    });
}

function applyTextureVisibility(model, visible) {
    if (!model) return;

    model.traverse((child) => {
        if (child.name && (child.name.includes("_wireframe_helper") || child.name.includes("_points_helper"))) return;

        if (child.isMesh && child.material) {
            const mats = Array.isArray(child.material) ? child.material : [child.material];
            mats.forEach(mat => {
                // Ensure mesh material is always visible
                mat.visible = true;

                if (!visible) {
                    // Backup original map and color if not already backed up
                    if (mat._originalMap === undefined) {
                        mat._originalMap = mat.map;
                    }
                    if (mat._originalColor === undefined) {
                        mat._originalColor = mat.color ? mat.color.clone() : new THREE.Color(0xffffff);
                    }

                    // Swap to grey clay style
                    mat.map = null;
                    if (mat.color) mat.color.setHex(0x1a1a1c); // Dark charcoal grey
                    mat.needsUpdate = true;
                } else {
                    // Restore original texture and color
                    if (mat._originalMap !== undefined) {
                        mat.map = mat._originalMap;
                    }
                    if (mat._originalColor !== undefined) {
                        if (mat.color) mat.color.copy(mat._originalColor);
                    }
                    mat.needsUpdate = true;
                }
            });
        }
    });
}

if (toggleTextureBtn) {
    toggleTextureBtn.addEventListener('click', () => {
        showTextures = !showTextures;

        if (showTextures) {
            toggleTextureBtn.classList.add('active');
        } else {
            toggleTextureBtn.classList.remove('active');
        }

        applyTextureVisibility(threeModel, showTextures);
    });
}


// Rigging action from main viewer
const rigMethodSelect = document.getElementById('rigMethodSelect');
const rigDescriptionText = null;

if (runTriggerRigBtn) {
    runTriggerRigBtn.addEventListener('click', async () => {
        if (!activeModelRelativeUrl) return;

        const method = 'ai';

        statusOverlay.classList.add('active');
        const loaderTitle = 'Rigging por IA (Nube)...';
        const loaderDesc = 'Conectando con la IA de Hugging Face para calcular los pesos y el esqueleto...';
            

        try {
            if (method === 'ai') {
                updateLoader(15, 'Verificando estado del servidor de Rigging...', 'Consultando disponibilidad de UniRig en Hugging Face...');
                let spaceSleeping = false;
                try {
                    const statusRes = await fetch(`${apiBase}/api/space-status?type=rig&token=${encodeURIComponent(hfToken)}`);
                    if (statusRes.ok) {
                        const statusData = await statusRes.json();
                        if (statusData.stage === 'SLEEPING') {
                            spaceSleeping = true;
                        }
                    }
                } catch (statusErr) {
                    console.warn('Failed to check rig space status, continuing anyway:', statusErr);
                }

                if (spaceSleeping) {
                    updateLoader(20, 'Encendiendo servidor de Rigging...', 'El servidor UniRig en Hugging Face está hibernando por inactividad. Lo estamos encendiendo, esto puede tardar de 2 a 3 minutos en iniciar...');
                } else {
                    updateLoader(40, loaderTitle, loaderDesc);
                }
            } else {
                updateLoader(40, loaderTitle, loaderDesc);
            }
            const response = await fetch(`${apiBase}/api/rig-3d`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    modelUrl: activeModelRelativeUrl,
                    rigMethod: method,
                    token: hfToken
                })
            });

            if (!response.ok) {
                const errData = await response.json().catch(() => ({ error: 'Error al riggear.' }));
                throw new Error(errData.error || 'Error interno del servidor.');
            }

            const data = await response.json();
            if (data.riggedFbxUrl) {
                // Load the newly rigged model directly in the viewer
                load3DModel(data.riggedFbxUrl, data.riggedFbxUrl, null, currentModelCategory);

                // Refresh gallery to show the rigged file in the library list
                refreshGallery();

                showCustomAlert('¡Esqueleto y pesos de influencia generados con éxito! Tu modelo ahora está listo para ser animado. Usa el selector de animación que apareció en la barra inferior.', 'Rigging Completado', false, 'success');
            } else {
                throw new Error('No se devolvió la URL del modelo riggeado.');
            }
        } catch (error) {
            console.error(error);
            showCustomAlert(error.message, 'Error al riggear el modelo', false);
        } finally {
            statusOverlay.classList.remove('active');
        }
    });
}

// Gallery / Library Management
const galleryList = document.getElementById('galleryList');
const galleryTabBtn = document.getElementById('galleryTabBtn');

let cachedGalleryJSON = "";

async function refreshGallery() {
    try {
        const response = await fetch(`${apiBase}/api/gallery`);
        if (!response.ok) throw new Error('Error al cargar la galería.');

        const data = await response.json();
        const newItems = data.items || [];
        const newJSON = JSON.stringify(newItems);
        
        // Render control: avoid flickering if items didn't change
        if (newJSON !== cachedGalleryJSON) {
            cachedGalleryJSON = newJSON;
            cachedGalleryItems = newItems;
            renderGallery(cachedGalleryItems);
        }
    } catch (error) {
        console.error('Error refreshing gallery:', error);
    }
}

let currentFilter = 'all';

function renderGallery(items) {
    if (!galleryList) return;

    if (items.length === 0) {
        galleryList.innerHTML = `
            <div class="gallery-empty-state">
                <i data-lucide="inbox" style="opacity: 0.5; margin-bottom: 0.5rem; display: block; margin: 0 auto; text-align: center;"></i>
                <p style="font-size: 0.8rem; color: var(--text-dark); text-align: center;">Biblioteca vacía</p>
            </div>
        `;
        lucide.createIcons();
        return;
    }

    // Filter items based on active filter state
    const filteredItems = items.filter(item => {
        if (currentFilter === 'all') return true;
        return item.type === currentFilter;
    });

    if (filteredItems.length === 0) {
        galleryList.innerHTML = `
            <div class="gallery-empty-state">
                <i data-lucide="inbox" style="opacity: 0.5; margin-bottom: 0.5rem; display: block; margin: 0 auto; text-align: center;"></i>
                <p style="font-size: 0.8rem; color: var(--text-dark); text-align: center;">No hay elementos que coincidan con el filtro</p>
            </div>
        `;
        lucide.createIcons();
        return;
    }

    galleryList.innerHTML = '';

    filteredItems.forEach((item, index) => {
        const itemEl = document.createElement('div');
        itemEl.className = 'gallery-item';
        itemEl.style.animationDelay = `${index * 0.03}s`;

        const isImage = item.type === 'image';
        const formattedTime = new Date(item.mtime * 1000).toLocaleString('es-ES', {
            day: '2-digit',
            month: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });

        const thumbnailHtml = isImage
            ? `<img src="${apiBase}${item.url}" alt="${item.name}">`
            : `<i data-lucide="box" style="width: 24px; height: 24px;"></i>`;

        const actionButtonHtml = isImage
            ? `<button class="gallery-btn load-img-btn" title="Visualizar Imagen 2D">
                 <i data-lucide="eye" style="width: 14px; height: 14px;"></i>
               </button>`
            : `<button class="gallery-btn load-model-btn" title="Visualizar modelo 3D">
                 <i data-lucide="eye" style="width: 14px; height: 14px;"></i>
               </button>`;

        itemEl.innerHTML = `
            <div class="gallery-thumbnail">${thumbnailHtml}</div>
            <div class="gallery-info">
                <span class="gallery-name" title="${item.name}">${item.name}</span>
                <span class="gallery-meta">
                    <i data-lucide="calendar" style="width: 10px; height: 10px;"></i>
                    <span>${formattedTime}</span>
                </span>
            </div>
            <div class="gallery-actions">
                ${actionButtonHtml}
                ${!isImage ? `
                ${item.fbxUrl ? `
                <a href="${apiBase}${item.fbxUrl}" download="${item.name.replace('.glb', '.fbx')}" class="gallery-btn" title="Descargar archivo FBX (Quads)" style="text-decoration: none; background: rgba(0, 150, 136, 0.15); color: #009688; border-color: rgba(0, 150, 136, 0.3);">
                    <i data-lucide="download" style="width: 14px; height: 14px;"></i>
                </a>` : `
                <button class="gallery-btn download-raw-fbx-btn" data-url="${item.url}" title="Optimizar y descargar como FBX (Quads)" style="background: rgba(0, 150, 136, 0.15); color: #009688; border-color: rgba(0, 150, 136, 0.3);">
                    <i data-lucide="download" style="width: 14px; height: 14px;"></i>
                </button>
                `}
                ` : ''}
                <button class="gallery-btn delete-btn" title="Eliminar del disco">
                    <i data-lucide="trash-2" style="width: 14px; height: 14px;"></i>
                </button>
            </div>
        `;

        // Event listeners for actions
        if (isImage) {
            itemEl.querySelector('.load-img-btn').addEventListener('click', () => {
                const imgViewer = document.getElementById('image-viewer-container');
                const fullImg = document.getElementById('full2DImageViewPC');
                if (fullImg) fullImg.src = `${apiBase}${item.url}`;
                if (imgViewer) imgViewer.style.display = 'flex';
                window.current2DViewerItem = item;
            });
        } else {
            itemEl.querySelector('.load-model-btn').addEventListener('click', () => {
                load3DModel(`${apiBase}${item.url}`, `${apiBase}${item.url}`, item.fbxUrl, item.detectedCategory);
            });



            const downloadRawFbxBtn = itemEl.querySelector('.download-raw-fbx-btn');
            if (downloadRawFbxBtn) {
                downloadRawFbxBtn.addEventListener('click', async () => {
                    statusOverlay.classList.add('active');
                    updateLoader(50, 'Convirtiendo a FBX...', 'Blender está optimizando la malla y exportando el archivo FBX...');
                    
                    try {
                        const response = await fetch(`${apiBase}/api/optimize-3d`, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                modelUrl: item.url,
                                quad_target_faces: 60000,
                                remeshMethod: 'cleanup'
                            })
                        });

                        if (!response.ok) {
                            const errData = await response.json().catch(() => ({ error: 'Error al convertir.' }));
                            throw new Error(errData.error || 'Error interno del servidor.');
                        }

                        const data = await response.json();
                        if (data.fbxUrl) {
                            // Download FBX
                            const absoluteFbxUrl = data.fbxUrl.startsWith('http') ? data.fbxUrl : `${apiBase}${data.fbxUrl}`;
                            const link = document.createElement('a');
                            link.href = absoluteFbxUrl;
                            link.download = absoluteFbxUrl.split('/').pop();
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);

                            // Load clean model in viewer
                            sessionStorage.setItem('pendingModelToLoad', JSON.stringify({
                                gltfUrl: data.gltfUrl,
                                downloadUrl: data.glbUrl,
                                fbxUrl: data.fbxUrl,
                                detectedCategory: currentModelCategory
                            }));
                            window.location.reload();
                        } else {
                            throw new Error('No se generó el archivo FBX.');
                        }
                    } catch (error) {
                        console.error(error);
                        alert(`Error al descargar FBX: ${error.message}`);
                    } finally {
                        statusOverlay.classList.remove('active');
                    }
                });
            }


        }

        itemEl.querySelector('.delete-btn').addEventListener('click', async () => {
            if (confirm(`¿Estás seguro de que quieres eliminar ${item.name} de forma permanente del disco?`)) {
                try {
                    const response = await fetch(`${apiBase}/api/delete-gallery`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ name: item.name, type: item.type })
                    });

                    if (!response.ok) {
                        const errData = await response.json().catch(() => ({ error: 'Error al eliminar el archivo.' }));
                        throw new Error(errData.error || 'Error al eliminar el archivo.');
                    }
                    refreshGallery();
                } catch (e) {
                    alert('Error al eliminar item: ' + e.message);
                }
            }
        });

        galleryList.appendChild(itemEl);
    });

    lucide.createIcons();
}

// Bind gallery filter toggles
const filterBtns = document.querySelectorAll('.filter-group .toggle-btn');
filterBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        filterBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        currentFilter = btn.getAttribute('data-filter');
        renderGallery(cachedGalleryItems);
    });
});

// Bind navigation click to refresh gallery
if (galleryTabBtn) {
    galleryTabBtn.addEventListener('click', refreshGallery);
}

// 2D Image Viewer Overlay Handlers for PC Mode
const btnBackFrom2DViewerPC = document.getElementById('btnBackFrom2DViewerPC');
const btnCreate3DFrom2DViewerPC = document.getElementById('btnCreate3DFrom2DViewerPC');

if (btnBackFrom2DViewerPC) {
    btnBackFrom2DViewerPC.addEventListener('click', () => {
        const imgViewer = document.getElementById('image-viewer-container');
        if (imgViewer) imgViewer.style.display = 'none';
    });
}

if (btnCreate3DFrom2DViewerPC) {
    btnCreate3DFrom2DViewerPC.addEventListener('click', async () => {
        const imgViewer = document.getElementById('image-viewer-container');
        if (imgViewer) imgViewer.style.display = 'none';

        if (window.current2DViewerItem) {
            try {
                const item = window.current2DViewerItem;
                const fileUrl = `${apiBase}${item.url}`;
                const res = await fetch(fileUrl);
                const blob = await res.blob();
                const file = new File([blob], item.name, { type: blob.type });
                handleImageFile(file);

                // Activate upload-tab
                const uploadTabBtn = document.querySelector('[data-tab="upload-tab"]');
                if (uploadTabBtn) uploadTabBtn.click();
            } catch (e) {
                console.error("Error setting 3D source image:", e);
            }
        }
    });
}

// Bind animation selection changes to toggle between model-viewer and Three.js viewer
if (animationSelect) {
    animationSelect.addEventListener('change', () => {
        const val = animationSelect.value;
        if (!threeScene) {
            initThreeViewer(currentGltfUrl);
        }

        if (val === 'manual') {
            if (manualRigPanel) {
                manualRigPanel.style.display = 'block';
                setupManualBoneSelectOptions();
            }
        } else {
            if (manualRigPanel) manualRigPanel.style.display = 'none';
        }
    });
}

// Manual Bone Rigging Controller Logic
const boneFriendlyNames = {
    hips: "Pelvis / Cadera",
    spine: "Columna Vertebral",
    neck: "Cuello",
    leftShoulder: "Hombro Izquierdo",
    leftArm: "Brazo Izquierdo",
    leftForearm: "Antebrazo Izquierdo",
    leftHand: "Mano Izquierda",
    rightShoulder: "Hombro Derecho",
    rightArm: "Brazo Derecho",
    rightForearm: "Antebrazo Derecho",
    rightHand: "Mano Derecha",
    leftUpLeg: "Muslo Izquierdo",
    leftLeg: "Pierna Izquierda",
    leftFoot: "Pie Izquierdo",
    rightUpLeg: "Muslo Derecho",
    rightLeg: "Pierna Derecha",
    rightFoot: "Pie Derecho"
};

const extendedBoneFriendlyNames = {
    // Quadruped bone names
    Pelvis: "Pelvis / Cadera (Cuadrúpedo)",
    Spine: "Columna Vertebral (Cuadrúpedo)",
    Neck: "Cuello (Cuadrúpedo)",
    Head: "Cabeza (Cuadrúpedo)",
    Tail: "Cola",
    LeftUpLegRear: "Pata Trasera Sup. Izquierda",
    LeftLegRear: "Pata Trasera Inf. Izquierda",
    LeftFootRear: "Pie Trasero Izquierdo",
    RightUpLegRear: "Pata Trasera Sup. Derecha",
    RightLegRear: "Pata Trasera Inf. Derecha",
    RightFootRear: "Pie Trasero Derecho",
    LeftUpLegFront: "Pata Delantera Sup. Izquierda",
    LeftLegFront: "Pata Delantera Inf. Izquierda",
    LeftFootFront: "Pie Delantero Izquierdo",
    RightUpLegFront: "Pata Delantera Sup. Derecha",
    RightLegFront: "Pata Delantera Inf. Derecha",
    RightFootFront: "Pie Delantero Derecho",
};

function getFriendlyBoneName(name) {
    if (boneFriendlyNames[name]) return boneFriendlyNames[name];
    if (extendedBoneFriendlyNames[name]) return extendedBoneFriendlyNames[name];
    
    const lower = name.toLowerCase();
    
    // Friendly translation heuristics for custom rig systems (like spider, etc.)
    if (lower.includes("hips") || lower.includes("pelvis")) return `Pelvis / Cadera (${name})`;
    if (lower.includes("spine")) return `Columna Vertebral (${name})`;
    if (lower.includes("neck")) return `Cuello (${name})`;
    if (lower.includes("head")) return `Cabeza (${name})`;
    if (lower.includes("tail")) return `Cola (${name})`;
    
    if (lower.startsWith("left") || lower.includes("_l") || lower.includes(".l") || lower.includes("l_") || lower.includes("left")) {
        if (lower.includes("shoulder")) return `Hombro Izquierdo (${name})`;
        if (lower.includes("arm") || lower.includes("forearm")) return `Brazo/Antebrazo Izquierdo (${name})`;
        if (lower.includes("hand") || lower.includes("wrist")) return `Mano/Muñeca Izquierda (${name})`;
        if (lower.includes("leg") || lower.includes("thigh")) return `Pata/Pierna Izquierda (${name})`;
        if (lower.includes("foot") || lower.includes("toe")) return `Pie Izquierdo (${name})`;
        return `${name} (Izquierda)`;
    }
    
    if (lower.startsWith("right") || lower.includes("_r") || lower.includes(".r") || lower.includes("r_") || lower.includes("right")) {
        if (lower.includes("shoulder")) return `Hombro Derecho (${name})`;
        if (lower.includes("arm") || lower.includes("forearm")) return `Brazo/Antebrazo Derecho (${name})`;
        if (lower.includes("hand") || lower.includes("wrist")) return `Mano/Muñeca Derecha (${name})`;
        if (lower.includes("leg") || lower.includes("thigh")) return `Pata/Pierna Derecha (${name})`;
        if (lower.includes("foot") || lower.includes("toe")) return `Pie Derecho (${name})`;
        return `${name} (Derecha)`;
    }

    return name;
}

function setupManualBoneSelectOptions() {
    if (!manualBoneSelect) return;

    manualBoneSelect.innerHTML = '';

    const allBones = [];
    if (threeModel) {
        threeModel.traverse(c => {
            if (c.isBone) allBones.push(c);
        });
    }

    if (allBones.length > 0) {
        // Sort bones alphabetically by name
        allBones.sort((a, b) => a.name.localeCompare(b.name)).forEach(bone => {
            const opt = document.createElement('option');
            opt.value = bone.name;
            opt.textContent = getFriendlyBoneName(bone.name);
            manualBoneSelect.appendChild(opt);
        });
    } else {
        // Fallback to static roles if no model loaded
        Object.keys(boneFriendlyNames).forEach(key => {
            const opt = document.createElement('option');
            opt.value = key;
            opt.textContent = boneFriendlyNames[key];
            manualBoneSelect.appendChild(opt);
        });
    }

    // Populate the 3D bone mapping selector with all bones in GLB
    if (manualBoneMappingSelect && threeModel) {
        manualBoneMappingSelect.innerHTML = '';

        const noneOpt = document.createElement('option');
        noneOpt.value = '';
        noneOpt.textContent = '(Sin Asignar)';
        manualBoneMappingSelect.appendChild(noneOpt);

        const allBones = [];
        threeModel.traverse(c => {
            if (c.isBone) allBones.push(c.name);
        });

        allBones.sort().forEach(bName => {
            const opt = document.createElement('option');
            opt.value = bName;
            opt.textContent = bName;
            manualBoneMappingSelect.appendChild(opt);
        });
    }

    // Trigger initial load of sliders
    loadSelectedBoneRotations();
}

function loadSelectedBoneRotations() {
    const bone = selectedBone;
    updateWeightPaintSelectedBoneDisplay();

    if (!bone) {
        // Reset sliders if bone not assigned
        boneRotX.value = 0;
        boneRotY.value = 0;
        boneRotZ.value = 0;
        boneRotXVal.textContent = '0°';
        boneRotYVal.textContent = '0°';
        boneRotZVal.textContent = '0°';
        if (manualBoneNameInput) manualBoneNameInput.value = '';
        if (applyBoneRenameBtn) applyBoneRenameBtn.style.display = 'none';
        return;
    }

    // Convert radians to degrees
    const degX = Math.round(THREE.MathUtils.radToDeg(bone.rotation.x));
    const degY = Math.round(THREE.MathUtils.radToDeg(bone.rotation.y));
    const degZ = Math.round(THREE.MathUtils.radToDeg(bone.rotation.z));

    boneRotX.value = degX;
    boneRotY.value = degY;
    boneRotZ.value = degZ;

    boneRotXVal.textContent = degX + '°';
    boneRotYVal.textContent = degY + '°';
    boneRotZVal.textContent = degZ + '°';
}

// Renaming bone logic
if (manualBoneNameInput && applyBoneRenameBtn) {
    manualBoneNameInput.addEventListener('input', () => {
        if (selectedBone) {
            const currentVal = manualBoneNameInput.value.trim();
            if (currentVal && currentVal !== selectedBone.name) {
                applyBoneRenameBtn.style.display = 'inline-block';
            } else {
                applyBoneRenameBtn.style.display = 'none';
            }
        }
    });

    applyBoneRenameBtn.addEventListener('click', () => {
        if (selectedBone) {
            const oldName = selectedBone.name;
            const newName = manualBoneNameInput.value.trim();
            if (!newName) {
                showCustomAlert("El nombre del hueso no puede estar vacío.", "Error al renombrar");
                return;
            }
            // Rename bone in Three.js
            selectedBone.name = newName;
            
            // Update threeBones mapping if it exists
            if (threeBones[oldName]) {
                threeBones[newName] = selectedBone;
                delete threeBones[oldName];
            }
            
            applyBoneRenameBtn.style.display = 'none';
            showCustomToast(`Hueso renombrado de ${oldName} a ${newName}`);
        }
    });
}

function updateBoneRotationFromSliders() {
    const bone = selectedBone;
    if (!bone) return;

    const degX = parseFloat(boneRotX.value);
    const degY = parseFloat(boneRotY.value);
    const degZ = parseFloat(boneRotZ.value);

    bone.rotation.x = THREE.MathUtils.degToRad(degX);
    bone.rotation.y = THREE.MathUtils.degToRad(degY);
    bone.rotation.z = THREE.MathUtils.degToRad(degZ);

    boneRotXVal.textContent = degX + '°';
    boneRotYVal.textContent = degY + '°';
    boneRotZVal.textContent = degZ + '°';
}

if (boneRotX) boneRotX.addEventListener('input', updateBoneRotationFromSliders);
if (boneRotY) boneRotY.addEventListener('input', updateBoneRotationFromSliders);
if (boneRotZ) boneRotZ.addEventListener('input', updateBoneRotationFromSliders);

if (resetBoneRotBtn) {
    resetBoneRotBtn.addEventListener('click', () => {
        const bone = selectedBone;
        if (!bone) return;

        bone.rotation.set(0, 0, 0);

        boneRotX.value = 0;
        boneRotY.value = 0;
        boneRotZ.value = 0;

        boneRotXVal.textContent = '0°';
        boneRotYVal.textContent = '0°';
        boneRotZVal.textContent = '0°';
    });
}

// Handle Skeleton Ray-X visualizer helper logic
function setSkeletonHelperActive(active) {
    showSkeletonHelper = active;
    if (showSkeletonHelper) {
        if (threeModel && threeScene) {
            if (threeSkeletonHelper) {
                threeScene.remove(threeSkeletonHelper);
            }
            threeSkeletonHelper = new THREE.SkeletonHelper(threeModel);
            threeScene.add(threeSkeletonHelper);

            // Clear any existing spheres first
            jointSpheres.forEach(item => {
                try { threeScene.remove(item.mesh); } catch (e) { }
            });
            jointSpheres = [];

            // Create glowing joint spheres at each bone
            threeModel.traverse(c => {
                if (c.isBone) {
                    // Create a larger, glowing cyan sphere for easy click and visibility
                    const sphereGeo = new THREE.SphereGeometry(0.015, 16, 16);
                    const sphereMat = new THREE.MeshBasicMaterial({
                        color: 0x00ffcc,
                        depthTest: false,
                        transparent: true,
                        opacity: 0.85
                    });
                    const sphere = new THREE.Mesh(sphereGeo, sphereMat);
                    sphere.renderOrder = 999; // draw on top of everything
                    threeScene.add(sphere);
                    jointSpheres.push({ bone: c, mesh: sphere });
                }
            });

            if (toggleBonesHelperBtn) {
                toggleBonesHelperBtn.classList.add('active');
                const span = toggleBonesHelperBtn.querySelector('span');
                if (span) span.textContent = "Ocultar Esqueleto (Rayos X)";
            }
            if (toggleBonesBtn) {
                toggleBonesBtn.classList.add('active');
            }
            showCustomToast("Haz clic en las esferas del cuerpo para seleccionar el hueso");
        }
    } else {
        if (threeSkeletonHelper && threeScene) {
            threeScene.remove(threeSkeletonHelper);
        }
        threeSkeletonHelper = null;

        jointSpheres.forEach(item => {
            if (threeScene) {
                try { threeScene.remove(item.mesh); } catch (e) { }
            }
        });
        jointSpheres = [];

        if (toggleBonesHelperBtn) {
            toggleBonesHelperBtn.classList.remove('active');
            const span = toggleBonesHelperBtn.querySelector('span');
            if (span) span.textContent = "Ver Esqueleto (Rayos X)";
        }
        if (toggleBonesBtn) {
            toggleBonesBtn.classList.remove('active');
        }
    }
}

if (toggleBonesHelperBtn) {
    toggleBonesHelperBtn.addEventListener('click', () => {
        if (toggleBonesHelperBtn.classList.contains('disabled-btn')) {
            showCustomToast("Este modelo no posee huesos. Genéralos usando Rigging Automático.");
            return;
        }
        setSkeletonHelperActive(!showSkeletonHelper);
    });
}

if (toggleBonesBtn) {
    toggleBonesBtn.addEventListener('click', () => {
        if (toggleBonesBtn.classList.contains('disabled-btn')) {
            showCustomToast("Este modelo no posee huesos. Genéralos usando Rigging Automático.");
            return;
        }
        setSkeletonHelperActive(!showSkeletonHelper);
    });
}

// Authentication & User Session Management
const authOverlay = document.getElementById('authOverlay');
const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
const tabLogin = document.getElementById('tabLogin');
const tabRegister = document.getElementById('tabRegister');
const logoutBtn = document.getElementById('logoutBtn');
const userHeaderActions = document.getElementById('userHeaderActions');
const headerUsernameText = document.getElementById('headerUsernameText');

// 3D Floating Shapes Background for Auth Screen
function initAuthBackground3D() {
    const canvas = document.getElementById('authBgCanvas');
    if (!canvas) return;

    const scene = new THREE.Scene();
    
    const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.z = 25;

    const renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

    // Lights
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.75);
    scene.add(ambientLight);

    const pointLight1 = new THREE.PointLight(0x9c27b0, 4.5, 60); // Purple light
    pointLight1.position.set(15, 15, 12);
    scene.add(pointLight1);

    const pointLight2 = new THREE.PointLight(0x00bcd4, 4.5, 60); // Cyan light
    pointLight2.position.set(-15, -15, 12);
    scene.add(pointLight2);

    const pointLight3 = new THREE.PointLight(0xffffff, 2.5, 45); // Center bright white light
    pointLight3.position.set(0, 0, 15);
    scene.add(pointLight3);

    // Floating geometries
    const geometries = [
        new THREE.TorusKnotGeometry(1.5, 0.45, 100, 16),
        new THREE.DodecahedronGeometry(1.8),
        new THREE.OctahedronGeometry(1.5),
        new THREE.IcosahedronGeometry(1.6, 1),
        new THREE.TorusGeometry(1.6, 0.35, 16, 100),
        new THREE.ConeGeometry(1.2, 2.2, 4),
        new THREE.TetrahedronGeometry(1.7),
        new THREE.CylinderGeometry(0.8, 0.8, 2.2, 6),
        new THREE.BoxGeometry(1.5, 1.5, 1.5),
        new THREE.RingGeometry(0.5, 1.6, 32),
        new THREE.SphereGeometry(1.4, 16, 16),
        new THREE.OctahedronGeometry(1.6, 1)
    ];

    const meshes = [];
    const colors = [0x9c27b0, 0x00bcd4, 0xe040fb, 0x00e5ff, 0xff4081, 0xffeb3b, 0x4caf50];

    geometries.forEach((geom, idx) => {
        const material = new THREE.MeshPhysicalMaterial({
            color: colors[idx % colors.length],
            roughness: 0.15,
            metalness: 0.85,
            clearcoat: 1.0,
            clearcoatRoughness: 0.1,
            wireframe: idx % 2 === 0
        });

        const mesh = new THREE.Mesh(geom, material);
        
        // Random positions
        mesh.position.set(
            (Math.random() - 0.5) * 35,
            (Math.random() - 0.5) * 20,
            (Math.random() - 0.5) * 10
        );

        // Rotation speeds
        mesh.userData = {
            rotX: (Math.random() - 0.5) * 0.008,
            rotY: (Math.random() - 0.5) * 0.008,
            floatSpeed: 0.001 + Math.random() * 0.002,
            floatOffset: Math.random() * Math.PI * 2,
            initialY: mesh.position.y
        };

        scene.add(mesh);
        meshes.push(mesh);
    });

    // Particle starfield
    const particlesCount = 250;
    const particlesGeometry = new THREE.BufferGeometry();
    const positions = new Float32Array(particlesCount * 3);

    for (let i = 0; i < particlesCount * 3; i += 3) {
        positions[i] = (Math.random() - 0.5) * 60;
        positions[i + 1] = (Math.random() - 0.5) * 40;
        positions[i + 2] = (Math.random() - 0.5) * 20;
    }

    particlesGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
    const particlesMaterial = new THREE.PointsMaterial({
        size: 0.12,
        color: 0xffffff,
        transparent: true,
        opacity: 0.5
    });

    const starfield = new THREE.Points(particlesGeometry, particlesMaterial);
    scene.add(starfield);

    // Mouse Parallax movement
    let mouseX = 0;
    let mouseY = 0;
    let targetX = 0;
    let targetY = 0;

    window.addEventListener('mousemove', (e) => {
        mouseX = (e.clientX - window.innerWidth / 2) / 150;
        mouseY = (e.clientY - window.innerHeight / 2) / 150;
    });

    // Resize handler
    window.addEventListener('resize', () => {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    });

    // Animation Loop
    let clock = new THREE.Clock();

    function animate() {
        const overlayActive = document.getElementById('authOverlay')?.classList.contains('active');
        if (!overlayActive) {
            requestAnimationFrame(animate);
            return;
        }

        const elapsedTime = clock.getElapsedTime();

        // Parallax camera lerp
        targetX += (mouseX - targetX) * 0.05;
        targetY += (mouseY - targetY) * 0.05;
        camera.position.x = targetX;
        camera.position.y = -targetY;
        camera.lookAt(scene.position);

        // Rotate and float meshes
        meshes.forEach(mesh => {
            mesh.rotation.x += mesh.userData.rotX;
            mesh.rotation.y += mesh.userData.rotY;
            mesh.position.y = mesh.userData.initialY + Math.sin(elapsedTime * 1.5 + mesh.userData.floatOffset) * 0.4;
        });

        // Rotate background starfield slightly
        starfield.rotation.y = elapsedTime * 0.015;

        renderer.render(scene, camera);
        requestAnimationFrame(animate);
    }

    animate();
}

// Initialize Auth 3D background immediately
initAuthBackground3D();

// User Credits State & Display Snycronization
let userCredits = 0;
function updateUserCreditsDisplay(credits) {
    userCredits = credits;
    const creditsText = document.getElementById('headerCreditsText');
    if (creditsText) creditsText.textContent = credits;
}

function updateUserHeaderAvatar(username, nick, avatar) {
    const dropdownUsernameText = document.getElementById('dropdownUsernameText');
    if (dropdownUsernameText) dropdownUsernameText.textContent = nick || username;
    if (headerUsernameText) headerUsernameText.textContent = nick || username;

    const avatarImg = document.getElementById('userHeaderAvatarImg');
    const avatarInitial = document.getElementById('userHeaderAvatarInitial');

    if (avatar && (avatar.startsWith('data:image') || avatar.startsWith('http') || avatar.startsWith('/'))) {
        if (avatarImg) {
            avatarImg.src = avatar;
            avatarImg.style.display = 'block';
        }
        if (avatarInitial) avatarInitial.style.display = 'none';
    } else {
        if (avatarImg) avatarImg.style.display = 'none';
        if (avatarInitial) {
            avatarInitial.textContent = (nick || username || 'P').charAt(0).toUpperCase();
            avatarInitial.style.display = 'block';
        }
    }
}

// Check Session on Start
async function checkAuthSession() {
    const mainAppContainer = document.querySelector('.app-container');
    try {
        const response = await fetch(`${apiBase}/api/me`);
        if (response.ok) {
            const data = await response.json();
            if (data.username) {
                // User is authenticated
                if (authOverlay) authOverlay.classList.remove('active');
                if (mainAppContainer) mainAppContainer.style.display = '';
                if (userHeaderActions) userHeaderActions.style.display = 'flex';
                
                updateUserHeaderAvatar(data.username, data.nick, data.avatar);
                // Update credits display
                updateUserCreditsDisplay(data.credits || 0);
                
                // Load gallery
                refreshGallery();
                checkMobileRedirect();
                return;
            }
        }
    } catch (e) {
        console.error("Error verifying session:", e);
    }
    // Show login overlay if not logged in
    if (authOverlay) authOverlay.classList.add('active');
    if (mainAppContainer) mainAppContainer.style.display = 'none';
    if (userHeaderActions) userHeaderActions.style.display = 'none';
}

function fetchUserInfo() {
    return checkAuthSession();
}

// Bind Authentication Event Listeners
const loginErrorMsg = document.getElementById('loginErrorMsg');
const registerErrorMsg = document.getElementById('registerErrorMsg');

function showRegisterError(msg) {
    if (registerErrorMsg) {
        registerErrorMsg.textContent = msg;
        registerErrorMsg.style.display = 'block';
    } else {
        showCustomAlert(msg, 'Error de Registro');
    }
}

function animateAuthBoxSwitch(showForm, hideForm) {
    const authBox = document.querySelector('.auth-box');
    if (!authBox) {
        hideForm.classList.remove('active');
        showForm.classList.add('active');
        return;
    }

    const startHeight = authBox.offsetHeight;
    authBox.style.height = `${startHeight}px`;

    hideForm.classList.remove('active');
    showForm.classList.add('active');

    // Calculate target height
    authBox.style.height = 'auto';
    const targetHeight = authBox.offsetHeight;
    authBox.style.height = `${startHeight}px`;

    // Force browser reflow to register height transition start
    void authBox.offsetHeight;

    authBox.style.height = `${targetHeight}px`;

    setTimeout(() => {
        authBox.style.height = 'auto';
    }, 360);
}

if (tabLogin && tabRegister && loginForm && registerForm) {
    tabLogin.addEventListener('click', () => {
        tabLogin.classList.add('active');
        tabRegister.classList.remove('active');
        animateAuthBoxSwitch(loginForm, registerForm);
        if (loginErrorMsg) loginErrorMsg.style.display = 'none';
        if (registerErrorMsg) registerErrorMsg.style.display = 'none';
    });

    tabRegister.addEventListener('click', () => {
        tabRegister.classList.add('active');
        tabLogin.classList.remove('active');
        animateAuthBoxSwitch(registerForm, loginForm);
        if (loginErrorMsg) loginErrorMsg.style.display = 'none';
        if (registerErrorMsg) registerErrorMsg.style.display = 'none';
    });
}

if (loginForm) {
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        if (loginErrorMsg) loginErrorMsg.style.display = 'none';
        const username = document.getElementById('loginUser').value.trim();
        const password = document.getElementById('loginPass').value;

        try {
            const response = await fetch(`${apiBase}/api/login`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password })
            });

            if (!response.ok) {
                const err = await response.json().catch(() => ({}));
                throw new Error(err.error || 'Credenciales inválidas.');
            }

            const data = await response.json();
            showCustomToast(`¡Bienvenido de nuevo, ${data.username}!`);
            
            // Hide overlay, update header, load gallery
            if (authOverlay) authOverlay.classList.remove('active');
            const mainAppContainer = document.querySelector('.app-container');
            if (mainAppContainer) mainAppContainer.style.display = '';
            if (userHeaderActions) userHeaderActions.style.display = 'flex';
            if (headerUsernameText) {
                const span = headerUsernameText.querySelector('span');
                if (span) span.textContent = data.username;
                else headerUsernameText.textContent = data.username;
            }
            // Update credits
            updateUserCreditsDisplay(data.credits || 0);

            // Clear inputs
            document.getElementById('loginUser').value = '';
            document.getElementById('loginPass').value = '';

            refreshGallery();
            checkMobileRedirect();

        } catch (err) {
            if (loginErrorMsg) {
                loginErrorMsg.textContent = err.message;
                loginErrorMsg.style.display = 'block';
            } else {
                showCustomAlert(err.message, 'Error de Inicio de Sesión');
            }
        }
    });
}

if (registerForm) {
    registerForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        if (registerErrorMsg) registerErrorMsg.style.display = 'none';
        const username = document.getElementById('registerUser').value.trim();
        const password = document.getElementById('registerPass').value;
        const confirmPass = document.getElementById('registerPassConfirm').value;

        if (password !== confirmPass) {
            showRegisterError('Las contraseñas no coinciden.');
            return;
        }

        if (password.length < 4) {
            showRegisterError('La contraseña debe tener al menos 4 caracteres.');
            return;
        }

        try {
            const response = await fetch(`${apiBase}/api/register`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password })
            });

            if (!response.ok) {
                const err = await response.json().catch(() => ({}));
                throw new Error(err.error || 'No se pudo registrar el usuario.');
            }

            showCustomAlert('Registro exitoso. Ahora puedes iniciar sesión con tu cuenta.', 'Registro Completado', false, 'success');
            
            // Switch to login tab
            tabLogin.click();
            
            // Clear inputs
            document.getElementById('registerUser').value = '';
            document.getElementById('registerPass').value = '';
            document.getElementById('registerPassConfirm').value = '';

        } catch (err) {
            showRegisterError(err.message);
        }
    });
}

if (logoutBtn) {
    logoutBtn.addEventListener('click', async () => {
        try {
            await fetch(`${apiBase}/api/logout`, { method: 'POST' });
            showCustomToast('Has cerrado sesión correctamente.');
            
            // Show overlay, update header, reset model visualizer
            if (authOverlay) authOverlay.classList.add('active');
            const mainAppContainer = document.querySelector('.app-container');
            if (mainAppContainer) mainAppContainer.style.display = 'none';
            if (userHeaderActions) userHeaderActions.style.display = 'none';
            
            // Clear current canvas model to protect session visual separation
            if (threeModel && threeScene) {
                threeScene.remove(threeModel);
                threeModel = null;
            }
            if (threeSkeletonHelper && threeScene) {
                threeScene.remove(threeSkeletonHelper);
                threeSkeletonHelper = null;
            }
            if (jointSpheres) {
                jointSpheres.forEach(item => {
                    if (threeScene) {
                        try { threeScene.remove(item.mesh); } catch (e) {}
                    }
                });
                jointSpheres = [];
            }
            
            // Reset gallery items list
            const galleryList = document.getElementById('galleryList');
            if (galleryList) galleryList.innerHTML = '';

        } catch (e) {
            console.error("Logout failed:", e);
        }
    });
}

// Bind Credits Store Modal
const creditsModal = document.getElementById('creditsModal');
const headerCreditsBtn = document.getElementById('headerCreditsBtn');
const closeCreditsModalBtn = document.getElementById('closeCreditsModalBtn');

function openCreditsModal(alertMessage = '') {
    if (creditsModal) {
        creditsModal.classList.add('active');
        if (alertMessage) {
            showCustomToast(alertMessage, 'warning');
        }
    }
}

if (headerCreditsBtn) {
    headerCreditsBtn.addEventListener('click', () => openCreditsModal());
}

if (closeCreditsModalBtn) {
    closeCreditsModalBtn.addEventListener('click', () => {
        if (creditsModal) creditsModal.classList.remove('active');
    });
}

if (creditsModal) {
    creditsModal.addEventListener('click', (e) => {
        if (e.target === creditsModal) {
            creditsModal.classList.remove('active');
        }
    });
}

// User Profile Menu Dropdown Toggle
const userMenuBtn = document.getElementById('userMenuBtn');
const userDropdownMenu = document.getElementById('userDropdownMenu');

if (userMenuBtn && userDropdownMenu) {
    userMenuBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        userDropdownMenu.classList.toggle('active');
    });

    document.addEventListener('click', (e) => {
        if (!userMenuBtn.contains(e.target) && !userDropdownMenu.contains(e.target)) {
            userDropdownMenu.classList.remove('active');
        }
    });
}

// Bind Profile and Privacy Modals in Header Menu
const profileMenuBtn = document.getElementById('profileMenuBtn');
const privacyMenuBtn = document.getElementById('privacyMenuBtn');
const profileModal = document.getElementById('profileModal');
const privacyModal = document.getElementById('privacyModal');
const closeProfileModalBtn = document.getElementById('closeProfileModalBtn');
const cancelProfileBtn = document.getElementById('cancelProfileBtn');
const closePrivacyModalBtn = document.getElementById('closePrivacyModalBtn');
const cancelPrivacyBtn = document.getElementById('cancelPrivacyBtn');
const profileForm = document.getElementById('profileForm');
const privacyForm = document.getElementById('privacyForm');

if (profileMenuBtn) {
    profileMenuBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        if (userDropdownMenu) userDropdownMenu.classList.remove('active');
        fetch(`${apiBase}/api/me`).then(res => res.json()).then(data => {
            const profileNickInput = document.getElementById('profileNickInput');
            const profileFullNameInput = document.getElementById('profileFullNameInput');
            const profileAvatarPreview = document.getElementById('profileAvatarPreview');
            if (profileNickInput) profileNickInput.value = data.nick || data.username || '';
            if (profileFullNameInput) profileFullNameInput.value = data.full_name || '';
            if (profileAvatarPreview && data.avatar) profileAvatarPreview.src = data.avatar;
            if (profileModal) profileModal.classList.add('active');
        }).catch(() => {
            if (profileModal) profileModal.classList.add('active');
        });
    });
}

if (privacyMenuBtn) {
    privacyMenuBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        if (userDropdownMenu) userDropdownMenu.classList.remove('active');
        fetch(`${apiBase}/api/me`).then(res => res.json()).then(data => {
            const privacyEmailInput = document.getElementById('privacyEmailInput');
            if (privacyEmailInput) privacyEmailInput.value = data.email || '';
            if (privacyModal) privacyModal.classList.add('active');
        }).catch(() => {
            if (privacyModal) privacyModal.classList.add('active');
        });
    });
}

const profileAvatarInput = document.getElementById('profileAvatarInput');
const profileAvatarPreview = document.getElementById('profileAvatarPreview');

if (profileAvatarInput && profileAvatarPreview) {
    profileAvatarInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (evt) => {
                profileAvatarPreview.src = evt.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
}

[closeProfileModalBtn, cancelProfileBtn].forEach(btn => {
    if (btn) btn.addEventListener('click', () => profileModal?.classList.remove('active'));
});

[closePrivacyModalBtn, cancelPrivacyBtn].forEach(btn => {
    if (btn) btn.addEventListener('click', () => privacyModal?.classList.remove('active'));
});

// Profile Form Submit
if (profileForm) {
    profileForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const nick = document.getElementById('profileNickInput')?.value.trim();
        const full_name = document.getElementById('profileFullNameInput')?.value.trim();
        const avatar = document.getElementById('profileAvatarPreview')?.src;
        try {
            const res = await fetch(`${apiBase}/api/update-profile`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ nick, full_name, avatar })
            });
            if (res.ok) {
                showCustomToast('¡Perfil actualizado con éxito!', 'success');
                if (profileModal) profileModal.classList.remove('active');
                fetchUserInfo();
            } else {
                showCustomToast('Error al actualizar el perfil.', 'error');
            }
        } catch (err) {
            showCustomToast('Error de conexión al actualizar perfil.', 'error');
        }
    });
}

// Privacy Form Submit
if (privacyForm) {
    privacyForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const email = document.getElementById('privacyEmailInput')?.value.trim();
        const current_password = document.getElementById('privacyCurrentPasswordInput')?.value;
        const new_password = document.getElementById('privacyNewPasswordInput')?.value;
        const confirm_password = document.getElementById('privacyConfirmPasswordInput')?.value;

        if (new_password && new_password !== confirm_password) {
            showCustomToast('Las contraseñas no coinciden.', 'warning');
            return;
        }

        try {
            const res = await fetch(`${apiBase}/api/update-privacy`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email, current_password, new_password })
            });
            const data = await res.json();
            if (res.ok && data.success) {
                showCustomToast('¡Configuración de privacidad guardada!', 'success');
                if (privacyModal) privacyModal.classList.remove('active');
            } else {
                showCustomToast(data.error || 'Error al guardar privacidad.', 'error');
            }
        } catch (err) {
            showCustomToast('Error de conexión al guardar privacidad.', 'error');
        }
    });
}

// Mobile QR Viewer Modal handlers
if (viewOnMobileBtn) {
    viewOnMobileBtn.addEventListener('click', () => {
        if (!activeGltfUrl) {
            showCustomToast('No hay ningún modelo 3D activo para visualizar en el celular.', 'warning');
            return;
        }
        
        // Resolve absolute GLTF URL
        const absoluteModelUrl = activeGltfUrl.startsWith('http') ? activeGltfUrl : `${window.location.origin}${activeGltfUrl}`;
        const viewerUrl = `${window.location.origin}/viewer.html?v=123&model=${encodeURIComponent(absoluteModelUrl)}`;
        
        // Generate QR code image url using public API
        const qrApiUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(viewerUrl)}`;
        
        mobileQrImage.src = qrApiUrl;
        mobileQrLink.href = viewerUrl;
        mobileQrLink.textContent = viewerUrl;
        
        mobileQrModal.classList.add('active');
    });
}

if (closeMobileQrModalBtn) {
    closeMobileQrModalBtn.addEventListener('click', () => {
        mobileQrModal.classList.remove('active');
    });
}

if (mobileQrModal) {
    mobileQrModal.addEventListener('click', (e) => {
        if (e.target === mobileQrModal) {
            mobileQrModal.classList.remove('active');
        }
    });
}

document.querySelectorAll('.buy-pack-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
        const amount = btn.getAttribute('data-amount') || '25';
        const originalText = btn.textContent;
        btn.disabled = true;
        btn.textContent = 'Redirigiendo a Stripe...';
        
        try {
            const response = await fetch(`${apiBase}/api/create-checkout-session`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ pack_type: amount })
            });
            
            if (response.ok) {
                const resData = await response.json();
                if (resData.url) {
                    window.location.href = resData.url;
                } else {
                    throw new Error('La respuesta de Stripe no contiene la URL de Checkout.');
                }
            } else {
                const errData = await response.json().catch(() => ({}));
                throw new Error(errData.error || 'Error al iniciar Checkout de Stripe.');
            }
        } catch (err) {
            showCustomAlert(err.message, 'Error de Pago');
            btn.disabled = false;
            btn.textContent = originalText;
        }
    });
});

// Dynamic 3D Credit Cost Calculator
function update3dCreditCostDisplay() {
    if (!generate3dBtn) return;
    let cost = 5; // Base cost
    
    if (resolutionSelect && resolutionSelect.value === '1536') {
        cost += 2; // Extra for 1536 High Resolution
    }
    
    if (textureSizeSelect && textureSizeSelect.value === '4096') {
        cost += 3; // Extra for 4096 4K texture
    }
    
    const span = generate3dBtn.querySelector('span');
    if (span) {
        span.textContent = `Construir Malla 3D (Cuesta ${cost} créditos)`;
    }
}

if (resolutionSelect) resolutionSelect.addEventListener('change', update3dCreditCostDisplay);
if (textureSizeSelect) textureSizeSelect.addEventListener('change', update3dCreditCostDisplay);

// Call initially
update3dCreditCostDisplay();

// Initial session check
checkAuthSession();

// Check for payment success callback parameter in URL query
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('payment') === 'success') {
    showCustomToast('¡Pago completado! Tus nuevos créditos se acreditarán en segundos.', 'success');
    const cleanUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
    window.history.replaceState({ path: cleanUrl }, '', cleanUrl);
}

// Check if there is a pending model to load after page reload (F5)
const pendingModel = sessionStorage.getItem('pendingModelToLoad');
if (pendingModel) {
    try {
        const { gltfUrl, downloadUrl, fbxUrl, detectedCategory } = JSON.parse(pendingModel);
        sessionStorage.removeItem('pendingModelToLoad');
        
        // Load model directly using the stored category
        
        load3DModel(gltfUrl, downloadUrl, fbxUrl, detectedCategory);
    } catch (e) {
        console.error('Error loading pending model after reload:', e);
    }
}

// Manual Mesh Clean / Optimization Panel handlers
const manualQuadFacesInput = document.getElementById('manualQuadFacesInput');
const manualQuadFacesVal = document.getElementById('manualQuadFacesVal');
const manualRemeshMethodSelect = document.getElementById('manualRemeshMethodSelect');
const runManualCleanBtn = document.getElementById('runManualCleanBtn');

if (manualQuadFacesInput && manualQuadFacesVal) {
    manualQuadFacesInput.addEventListener('input', () => {
        manualQuadFacesVal.textContent = manualQuadFacesInput.value;
    });
}

if (runManualCleanBtn) {
    runManualCleanBtn.addEventListener('click', async () => {
        if (!activeModelRelativeUrl) {
            showCustomAlert('Por favor, selecciona un modelo de la biblioteca primero.', 'Modelo no seleccionado');
            return;
        }
        statusOverlay.classList.add('active');

        const quadTargetFaces = manualQuadFacesInput ? parseInt(manualQuadFacesInput.value) : 60000;
        const remeshMethod = manualRemeshMethodSelect ? manualRemeshMethodSelect.value : 'tris_to_quads';

        if (remeshMethod === 'cleanup') {
            updateLoader(50, 'Limpieza rápida de malla...', 'Blender está fusionando vértices duplicados y eliminando componentes flotantes aislados...');
        } else {
            updateLoader(50, 'Optimización local...', 'Blender está limpiando la malla, remallando a quads y proyectando texturas...');
        }

        try {
            const response = await fetch(`${apiBase}/api/optimize-3d`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    modelUrl: activeModelRelativeUrl,
                    quad_target_faces: quadTargetFaces,
                    remeshMethod: remeshMethod
                })
            });

            if (!response.ok) {
                const errData = await response.json().catch(() => ({ error: 'Error al optimizar.' }));
                throw new Error(errData.error || 'Error interno del servidor.');
            }

            const data = await response.json();
            if (data.gltfUrl && data.glbUrl) {
                sessionStorage.setItem('pendingModelToLoad', JSON.stringify({
                    gltfUrl: data.gltfUrl,
                    downloadUrl: data.glbUrl,
                    fbxUrl: data.fbxUrl,
                    detectedCategory: currentModelCategory
                }));
                location.reload();
            } else {
                throw new Error('No se recibieron los URLs del modelo optimizado.');
            }
        } catch (error) {
            statusOverlay.classList.remove('active');
            showCustomAlert(error.message, 'Error de Optimización');
        }
    });
}

// ==================== WEIGHT PAINTING PROTOTYPE ====================

function getWeightVisualizerMaterial(boneIndex) {
    return new THREE.ShaderMaterial({
        vertexShader: `
            #include <common>
            #include <skinning_pars_vertex>
            
            uniform int selectedBoneIndex;
            varying float vWeight;
            
            void main() {
                vWeight = 0.0;
                if (skinWeight.x > 0.0 && int(skinIndex.x) == selectedBoneIndex) vWeight = skinWeight.x;
                else if (skinWeight.y > 0.0 && int(skinIndex.y) == selectedBoneIndex) vWeight = skinWeight.y;
                else if (skinWeight.z > 0.0 && int(skinIndex.z) == selectedBoneIndex) vWeight = skinWeight.z;
                else if (skinWeight.w > 0.0 && int(skinIndex.w) == selectedBoneIndex) vWeight = skinWeight.w;

                #include <begin_vertex>
                #include <skinbase_vertex>
                #include <skinning_vertex>
                #include <project_vertex>
            }
        `,
        fragmentShader: `
            varying float vWeight;
            void main() {
                // Color map: 0.0 is blue, 0.5 is green, 1.0 is red
                vec3 blue = vec3(0.0, 0.0, 0.8);
                vec3 green = vec3(0.0, 0.8, 0.0);
                vec3 red = vec3(1.0, 0.0, 0.0);
                vec3 color;
                if (vWeight < 0.5) {
                    color = mix(blue, green, vWeight * 2.0);
                } else {
                    color = mix(green, red, (vWeight - 0.5) * 2.0);
                }
                gl_FragColor = vec4(color, 1.0);
            }
        `,
        uniforms: THREE.UniformsUtils.merge([
            THREE.ShaderLib.standard.uniforms,
            {
                selectedBoneIndex: { value: boneIndex }
            }
        ]),
        skinning: true,
        wireframe: false,
        depthTest: true,
        depthWrite: true
    });
}

// Enable/Disable Weight Visualizer Shader
function toggleWeightVisualizer(enable) {
    if (!threeModel) return;

    activeSkinnedMeshes = [];
    spatialGrid = null;

    // Get selected bone index
    let boneIdx = -1;
    const activeBone = selectedBone;
    if (activeBone && threeModel) {
        // Find bone's index in the skeleton
        let allBones = [];
        threeModel.traverse(c => {
            if (c.isBone) allBones.push(c);
        });
        boneIdx = allBones.indexOf(activeBone);
    }
    targetBoneIdx = boneIdx;

    threeModel.traverse(child => {
        if (child.name && (child.name.includes("_wireframe_helper") || child.name.includes("_points_helper"))) return;
        if (child.isSkinnedMesh) {
            if (enable) {
                activeSkinnedMeshes.push(child);
                
                // Override raycast method to bypass expensive CPU skinning calculations
                if (!child.originalRaycast) {
                    child.originalRaycast = child.raycast;
                }
                child.raycast = THREE.Mesh.prototype.raycast;

                // Save original material if not already saved
                if (!originalMaterialsMap.has(child)) {
                    originalMaterialsMap.set(child, child.material);
                }
                child.material = getWeightVisualizerMaterial(boneIdx);
            } else {
                // Restore original raycast
                if (child.originalRaycast) {
                    child.raycast = child.originalRaycast;
                }
                // Restore original material
                if (originalMaterialsMap.has(child)) {
                    child.material = originalMaterialsMap.get(child);
                }
            }
        }
    });
}

// Update Uniform on active material when selected bone changes
function updateWeightVisualizerBone() {
    if (!isWeightPaintingActive || !threeModel) return;
    
    let boneIdx = -1;
    const activeBone = selectedBone;
    if (activeBone) {
        let allBones = [];
        threeModel.traverse(c => {
            if (c.isBone) allBones.push(c);
        });
        boneIdx = allBones.indexOf(activeBone);
    }

    targetBoneIdx = boneIdx;

    threeModel.traverse(child => {
        if (child.isSkinnedMesh && child.material && child.material.uniforms && child.material.uniforms.selectedBoneIndex) {
            child.material.uniforms.selectedBoneIndex.value = boneIdx;
            child.material.needsUpdate = true;
        }
    });
}

// UI Handlers for Weight Paint settings
if (activeWeightPaintCheck) {
    activeWeightPaintCheck.addEventListener('change', () => {
        isWeightPaintingActive = activeWeightPaintCheck.checked;
        toggleWeightVisualizer(isWeightPaintingActive);
        
        const card = document.getElementById('paintInstructionCard');
        if (card) {
            card.style.display = isWeightPaintingActive ? 'block' : 'none';
        }
        
        // Hide auto-rotation by default to avoid conflicts while painting
        if (isWeightPaintingActive) {
            isAutoRotating = false;
            if (threeControls) threeControls.autoRotate = false;
            if (toggleAutoRotateBtn) toggleAutoRotateBtn.classList.remove('active');
            
            // Automatically enable skeleton helper/bones visualization for selection
            setSkeletonHelperActive(true);
            
            // Collapse other panels to make room
            const rigPanel = document.getElementById('manualRigPanel');
            if (rigPanel) rigPanel.classList.add('collapsed');
            const cleanPanel = document.getElementById('manualCleanPanel');
            if (cleanPanel) cleanPanel.classList.add('collapsed');
            
            // Deactivate their toolbar buttons
            const btnRig = document.getElementById('btnRigPanel');
            if (btnRig) btnRig.classList.remove('active');
            const btnClean = document.getElementById('btnCleanPanel');
            if (btnClean) btnClean.classList.remove('active');
            
            // Show/Create selected bone marker sphere on the mesh
            updateSelectedBoneMarker();
            
            // Add brush helper mesh to scene
            if (!brushHelper && threeScene) {
                const geom = new THREE.RingGeometry(0.095, 0.10, 32);
                const mat = new THREE.MeshBasicMaterial({
                    color: 0xffaa00,
                    side: THREE.DoubleSide,
                    transparent: true,
                    opacity: 0.8,
                    depthTest: false
                });
                brushHelper = new THREE.Mesh(geom, mat);
                brushHelper.renderOrder = 1001;
                threeScene.add(brushHelper);
            }
        } else {
            if (brushHelper && threeScene) {
                threeScene.remove(brushHelper);
                brushHelper = null;
            }
            
            // Clean up selected bone marker when deactivated
            updateSelectedBoneMarker();
        }
    });
}

if (weightPaintRadiusInput && weightPaintRadiusVal) {
    setupSliderValueUpdate(weightPaintRadiusInput, weightPaintRadiusVal);
    weightPaintRadiusInput.addEventListener('input', (e) => {
        weightPaintRadius = parseFloat(e.target.value);
        if (brushHelper) {
            brushHelper.scale.setScalar(weightPaintRadius / 0.10); // Scale relative to default 0.1
        }
    });
}

if (weightPaintStrengthInput && weightPaintStrengthVal) {
    setupSliderValueUpdate(weightPaintStrengthInput, weightPaintStrengthVal);
    weightPaintStrengthInput.addEventListener('input', (e) => {
        weightPaintStrength = parseFloat(e.target.value);
    });
}

if (weightPaintModeSelect) {
    weightPaintModeSelect.addEventListener('change', () => {
        weightPaintMode = weightPaintModeSelect.value;
    });
}

// Mouse events on canvas for painting weights
let isMouseDown = false;
const paintRaycaster = new THREE.Raycaster();
const paintMouse = new THREE.Vector2();

function setupWeightPaintingCanvasEvents(canvas) {
    // Prevent right-click browser menu on canvas when weight painting is active
    canvas.addEventListener('contextmenu', (e) => {
        if (isWeightPaintingActive) {
            e.preventDefault();
        }
    }, true);

    canvas.addEventListener('pointerdown', (e) => {
        if (!isWeightPaintingActive) return;
        
        // Paint actions require holding the Ctrl key
        if (e.ctrlKey) {
            // Prevent OrbitControls from receiving this click and rotating the camera
            e.stopImmediatePropagation();
            e.preventDefault();

            if (e.button === 0) { // Left Click + Ctrl -> Add weight
                weightPaintMode = 'add';
                if (weightPaintModeSelect) weightPaintModeSelect.value = 'add';
                isMouseDown = true;
                if (brushHelper) brushHelper.material.color.setHex(0x00ff66); // GREEN
                if (threeControls) threeControls.enabled = false;
                paintWeightsAtMouse(e, canvas);
            } else if (e.button === 2) { // Right Click + Ctrl -> Sub weight
                weightPaintMode = 'sub';
                if (weightPaintModeSelect) weightPaintModeSelect.value = 'sub';
                isMouseDown = true;
                if (brushHelper) brushHelper.material.color.setHex(0xff3333); // RED
                if (threeControls) threeControls.enabled = false;
                paintWeightsAtMouse(e, canvas);
            }
        } else {
            // Normal click (no Ctrl) -> Ensure camera controls are active
            if (threeControls) threeControls.enabled = true;
        }
    }, true);

    canvas.addEventListener('pointermove', (e) => {
        if (!isWeightPaintingActive) return;

        // Skip brush raycasting when actively rotating/panning the camera
        if (e.buttons !== 0 && !e.ctrlKey) {
            if (brushHelper) brushHelper.visible = false;
            lastBrushHit = null;
            return;
        }

        // Only show/update brush helper if Ctrl key is held!
        if (!e.ctrlKey) {
            if (brushHelper) brushHelper.visible = false;
            lastBrushHit = null;
            return;
        }

        // Set hover color if not active drawing
        if (brushHelper && !isMouseDown) {
            brushHelper.material.color.setHex(0xffaa00); // ORANGE/YELLOW
        }

        // Skip raycast/paint on micro-movements of less than 4 pixels in screen coordinates
        const dx = e.clientX - lastMouseScreenX;
        const dy = e.clientY - lastMouseScreenY;
        if (Math.abs(dx) < 4 && Math.abs(dy) < 4) {
            return;
        }
        lastMouseScreenX = e.clientX;
        lastMouseScreenY = e.clientY;

        // Position brush helper (throttled inside updateBrushHelperPosition)
        updateBrushHelperPosition(e, canvas);
        
        // Continue painting if mouse is down and Ctrl is held
        if (isMouseDown && e.ctrlKey) {
            const now = performance.now();
            if (now - lastPaintTime < 80) return; // Throttle paint loops to ~12 FPS on heavy meshes to prevent UI freeze
            lastPaintTime = now;

            e.stopImmediatePropagation();
            e.preventDefault();

            if (e.buttons === 1) { // Left button held
                weightPaintMode = 'add';
                if (weightPaintModeSelect) weightPaintModeSelect.value = 'add';
                if (brushHelper) brushHelper.material.color.setHex(0x00ff66); // GREEN
                paintWeightsAtMouse(e, canvas);
            } else if (e.buttons === 2) { // Right button held
                weightPaintMode = 'sub';
                if (weightPaintModeSelect) weightPaintModeSelect.value = 'sub';
                if (brushHelper) brushHelper.material.color.setHex(0xff3333); // RED
                paintWeightsAtMouse(e, canvas);
            }
        }
    }, true);

    window.addEventListener('pointerup', (e) => {
        if (isWeightPaintingActive) {
            if (isMouseDown) {
                isMouseDown = false;
                e.stopImmediatePropagation();
                e.preventDefault();
            }
            if (brushHelper) brushHelper.material.color.setHex(0xffaa00); // ORANGE/YELLOW
            // Always restore camera controls on pointerup
            if (threeControls) {
                threeControls.enabled = true;
            }
        }
    }, true);
}

function updateBrushHelperPosition(event, canvas) {
    if (!brushHelper || !threeCamera || !threeModel || activeSkinnedMeshes.length === 0) {
        lastBrushHit = null;
        if (brushHelper) brushHelper.visible = false;
        return;
    }

    // Limit hover updates to ~40fps
    const now = performance.now();
    if (now - lastRaycastTime < 25) return;
    lastRaycastTime = now;

    const rect = canvas.getBoundingClientRect();
    paintMouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
    paintMouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;

    paintRaycaster.setFromCamera(paintMouse, threeCamera);
    
    // Fast Bounding Sphere colision check (takes 0.001ms) for hover placement
    const mesh = activeSkinnedMeshes[0];
    if (!mesh.geometry.boundingSphere) {
        mesh.geometry.computeBoundingSphere();
    }

    const sphere = new THREE.Sphere();
    sphere.copy(mesh.geometry.boundingSphere).applyMatrix4(mesh.matrixWorld);

    const intersectPoint = new THREE.Vector3();
    if (paintRaycaster.ray.intersectSphere(sphere, intersectPoint)) {
        brushHelper.position.copy(intersectPoint);
        brushHelper.visible = true;
        
        // Cache a basic reference for start of paint
        lastBrushHit = {
            object: mesh,
            point: intersectPoint
        };
    } else {
        brushHelper.visible = false;
        lastBrushHit = null;
    }
}

function buildSpatialGrid(mesh) {
    const geometry = mesh.geometry;
    const positionAttr = geometry.attributes.position;
    if (!positionAttr) return null;

    const posArray = positionAttr.array;
    const vCount = positionAttr.count;

    // Get bounding box of the geometry
    if (!geometry.boundingBox) {
        geometry.computeBoundingBox();
    }
    const bbox = geometry.boundingBox;
    
    // We will use a grid of 25x25x25 cells for higher search density
    const gridSize = 25;
    const min = bbox.min;
    const max = bbox.max;
    const sizeX = (max.x - min.x) || 0.01;
    const sizeY = (max.y - min.y) || 0.01;
    const sizeZ = (max.z - min.z) || 0.01;

    const cellWidth = sizeX / gridSize;
    const cellHeight = sizeY / gridSize;
    const cellDepth = sizeZ / gridSize;

    // Initialize grid cells map
    const cells = new Map();

    for (let idx = 0; idx < vCount; idx++) {
        const idx3 = idx * 3;
        const vx = posArray[idx3];
        const vy = posArray[idx3 + 1];
        const vz = posArray[idx3 + 2];

        // Compute cell coordinates (clamped to 0..gridSize-1)
        const cx = Math.min(gridSize - 1, Math.max(0, Math.floor((vx - min.x) / cellWidth)));
        const cy = Math.min(gridSize - 1, Math.max(0, Math.floor((vy - min.y) / cellHeight)));
        const cz = Math.min(gridSize - 1, Math.max(0, Math.floor((vz - min.z) / cellDepth)));

        // Create cell key
        const key = (cx << 16) | (cy << 8) | cz;
        let cellList = cells.get(key);
        if (!cellList) {
            cellList = [];
            cells.set(key, cellList);
        }
        cellList.push(idx);
    }

    return {
        cells: cells,
        min: min,
        cellWidth: cellWidth,
        cellHeight: cellHeight,
        cellDepth: cellDepth,
        gridSize: gridSize
    };
}

function paintWeightsAtMouse(event, canvas) {
    if (!threeCamera || !threeModel || activeSkinnedMeshes.length === 0) return;

    // Reuse the cached bounding sphere hit from updateBrushHelperPosition
    // This avoids the extremely expensive triangle-level raycast (which was the #1 bottleneck)
    if (!lastBrushHit) return;
    const mesh = lastBrushHit.object;
    const point = lastBrushHit.point;

    // Transform bounding sphere intersection point to local geometry space
    const approxLocal = mesh.worldToLocal(point.clone());

    if (targetBoneIdx === -1) {
        const now = performance.now();
        if (now - lastNoBoneToastTime > 3000) {
            showCustomToast("Por favor, selecciona un hueso haciendo clic en una articulación celeste primero.");
            lastNoBoneToastTime = now;
        }
        return;
    }

    const geometry = mesh.geometry;
    const positionAttr = geometry.attributes.position;
    const skinIndexAttr = geometry.attributes.skinIndex;
    const skinWeightAttr = geometry.attributes.skinWeight;

    if (!positionAttr || !skinIndexAttr || !skinWeightAttr) return;

    // Build spatial grid on demand if not already built
    if (!spatialGrid) {
        spatialGrid = buildSpatialGrid(mesh);
    }

    // Retrieve underlying Float32/Int arrays for raw access
    const posArray = positionAttr.array;
    const idxArray = skinIndexAttr.array;
    const wtArray = skinWeightAttr.array;

    // Compute camera ray in local mesh space for accurate vertex targeting
    const rect = canvas.getBoundingClientRect();
    const mx = ((event.clientX - rect.left) / rect.width) * 2 - 1;
    const my = -((event.clientY - rect.top) / rect.height) * 2 + 1;
    paintRaycaster.setFromCamera({x: mx, y: my}, threeCamera);

    // Transform ray origin & direction into mesh local space
    const invMatrix = new THREE.Matrix4().copy(mesh.matrixWorld).invert();
    const localRayOrigin = paintRaycaster.ray.origin.clone().applyMatrix4(invMatrix);
    const localRayDir = paintRaycaster.ray.direction.clone().transformDirection(invMatrix).normalize();

    // Search cells around the approximate sphere hit point to find the vertex
    // closest to the camera ray (perpendicular distance), not to the sphere surface point
    const searchRadius = Math.max(weightPaintRadius * 5, 1.0);
    const srMinX = approxLocal.x - searchRadius;
    const srMaxX = approxLocal.x + searchRadius;
    const srMinY = approxLocal.y - searchRadius;
    const srMaxY = approxLocal.y + searchRadius;
    const srMinZ = approxLocal.z - searchRadius;
    const srMaxZ = approxLocal.z + searchRadius;

    const srMinCx = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((srMinX - spatialGrid.min.x) / spatialGrid.cellWidth)));
    const srMaxCx = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((srMaxX - spatialGrid.min.x) / spatialGrid.cellWidth)));
    const srMinCy = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((srMinY - spatialGrid.min.y) / spatialGrid.cellHeight)));
    const srMaxCy = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((srMaxY - spatialGrid.min.y) / spatialGrid.cellHeight)));
    const srMinCz = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((srMinZ - spatialGrid.min.z) / spatialGrid.cellDepth)));
    const srMaxCz = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((srMaxZ - spatialGrid.min.z) / spatialGrid.cellDepth)));

    let nearestRayDistSq = Infinity;
    let nearestVx = approxLocal.x, nearestVy = approxLocal.y, nearestVz = approxLocal.z;
    const rox = localRayOrigin.x, roy = localRayOrigin.y, roz = localRayOrigin.z;
    const rdx = localRayDir.x, rdy = localRayDir.y, rdz = localRayDir.z;

    for (let cx = srMinCx; cx <= srMaxCx; cx++) {
        for (let cy = srMinCy; cy <= srMaxCy; cy++) {
            for (let cz = srMinCz; cz <= srMaxCz; cz++) {
                const key = (cx << 16) | (cy << 8) | cz;
                const cellList = spatialGrid.cells.get(key);
                if (!cellList) continue;
                for (let i = 0; i < cellList.length; i++) {
                    const vi = cellList[i];
                    const vi3 = vi * 3;
                    // Vector from ray origin to vertex
                    const vx = posArray[vi3] - rox;
                    const vy = posArray[vi3 + 1] - roy;
                    const vz = posArray[vi3 + 2] - roz;
                    // Projection of vertex onto ray direction (t parameter)
                    const t = vx * rdx + vy * rdy + vz * rdz;
                    if (t < 0) continue; // behind camera
                    // Perpendicular distance² = |V|² - t²
                    const perpDistSq = (vx * vx + vy * vy + vz * vz) - t * t;
                    if (perpDistSq < nearestRayDistSq) {
                        nearestRayDistSq = perpDistSq;
                        nearestVx = posArray[vi3];
                        nearestVy = posArray[vi3 + 1];
                        nearestVz = posArray[vi3 + 2];
                    }
                }
            }
        }
    }

    // Use the nearest vertex position as the paint center (snapped to mesh surface)
    const lx = nearestVx;
    const ly = nearestVy;
    const lz = nearestVz;
    const radius = weightPaintRadius;
    const radiusSq = radius * radius;

    // Query spatial grid for cells overlapping the brush bounding box around the snapped center
    const minX = lx - radius;
    const maxX = lx + radius;
    const minY = ly - radius;
    const maxY = ly + radius;
    const minZ = lz - radius;
    const maxZ = lz + radius;

    const minCx = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((minX - spatialGrid.min.x) / spatialGrid.cellWidth)));
    const maxCx = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((maxX - spatialGrid.min.x) / spatialGrid.cellWidth)));
    const minCy = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((minY - spatialGrid.min.y) / spatialGrid.cellHeight)));
    const maxCy = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((maxY - spatialGrid.min.y) / spatialGrid.cellHeight)));
    const minCz = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((minZ - spatialGrid.min.z) / spatialGrid.cellDepth)));
    const maxCz = Math.min(spatialGrid.gridSize - 1, Math.max(0, Math.floor((maxZ - spatialGrid.min.z) / spatialGrid.cellDepth)));

    let modified = false;
    let minModifiedIdx = Infinity;
    let maxModifiedIdx = -Infinity;

    // Loop through only the overlapping cells!
    for (let cx = minCx; cx <= maxCx; cx++) {
        for (let cy = minCy; cy <= maxCy; cy++) {
            for (let cz = minCz; cz <= maxCz; cz++) {
                const key = (cx << 16) | (cy << 8) | cz;
                const cellList = spatialGrid.cells.get(key);
                if (!cellList) continue;

                const cCount = cellList.length;
                for (let i = 0; i < cCount; i++) {
                    const idx = cellList[i];
                    const idx3 = idx * 3;
                    const vx = posArray[idx3];
                    const vy = posArray[idx3 + 1];
                    const vz = posArray[idx3 + 2];

                    const dx = vx - lx;
                    const dy = vy - ly;
                    const dz = vz - lz;
                    
                    // Fast squared distance check to avoid Math.sqrt for 99% of vertices
                    const distSq = dx * dx + dy * dy + dz * dz;

                    if (distSq < radiusSq) {
                        // Calculate actual distance only for vertices inside the brush radius
                        const dist = Math.sqrt(distSq);
                        const falloff = 1.0 - (dist / radius);
                        const deltaWeight = falloff * weightPaintStrength * 0.15; // Scaled down for smooth paint

                        // Get current bones indices and weights directly using local variables (zero garbage collection)
                        const idx4 = idx * 4;
                        let idx0 = idxArray[idx4];
                        let idx1 = idxArray[idx4 + 1];
                        let idx2 = idxArray[idx4 + 2];
                        let idx3Val = idxArray[idx4 + 3];

                        let wt0 = wtArray[idx4];
                        let wt1 = wtArray[idx4 + 1];
                        let wt2 = wtArray[idx4 + 2];
                        let wt3 = wtArray[idx4 + 3];

                        // Find if target bone is already affecting this vertex (flat conditional check)
                        let boneSlot = -1;
                        if (wt0 > 0.0 && idx0 === targetBoneIdx) boneSlot = 0;
                        else if (wt1 > 0.0 && idx1 === targetBoneIdx) boneSlot = 1;
                        else if (wt2 > 0.0 && idx2 === targetBoneIdx) boneSlot = 2;
                        else if (wt3 > 0.0 && idx3Val === targetBoneIdx) boneSlot = 3;

                        // If not affecting, replace slot with lowest weight
                        if (boneSlot === -1) {
                            let minSlot = 0;
                            let minWt = wt0;
                            if (wt1 < minWt) { minWt = wt1; minSlot = 1; }
                            if (wt2 < minWt) { minWt = wt2; minSlot = 2; }
                            if (wt3 < minWt) { minWt = wt3; minSlot = 3; }
                            
                            boneSlot = minSlot;
                            if (boneSlot === 0) { idx0 = targetBoneIdx; wt0 = 0.0; }
                            else if (boneSlot === 1) { idx1 = targetBoneIdx; wt1 = 0.0; }
                            else if (boneSlot === 2) { idx2 = targetBoneIdx; wt2 = 0.0; }
                            else if (boneSlot === 3) { idx3Val = targetBoneIdx; wt3 = 0.0; }
                        }

                        // Get current weight of the targeted slot
                        let oldWt = 0.0;
                        if (boneSlot === 0) oldWt = wt0;
                        else if (boneSlot === 1) oldWt = wt1;
                        else if (boneSlot === 2) oldWt = wt2;
                        else if (boneSlot === 3) oldWt = wt3;

                        let newWt = oldWt;
                        if (weightPaintMode === 'add') {
                            newWt = Math.min(1.0, oldWt + deltaWeight);
                        } else {
                            newWt = Math.max(0.0, oldWt - deltaWeight);
                        }

                        if (newWt !== oldWt) {
                            if (boneSlot === 0) wt0 = newWt;
                            else if (boneSlot === 1) wt1 = newWt;
                            else if (boneSlot === 2) wt2 = newWt;
                            else if (boneSlot === 3) wt3 = newWt;

                            // Normalize remaining slots
                            let otherSum = 0.0;
                            if (boneSlot !== 0) otherSum += wt0;
                            if (boneSlot !== 1) otherSum += wt1;
                            if (boneSlot !== 2) otherSum += wt2;
                            if (boneSlot !== 3) otherSum += wt3;

                            if (otherSum > 0.0) {
                                const scale = (1.0 - newWt) / otherSum;
                                if (boneSlot !== 0) wt0 *= scale;
                                if (boneSlot !== 1) wt1 *= scale;
                                if (boneSlot !== 2) wt2 *= scale;
                                if (boneSlot !== 3) wt3 *= scale;
                            } else {
                                const remaining = (1.0 - newWt) / 3.0;
                                if (boneSlot !== 0) wt0 = remaining;
                                if (boneSlot !== 1) wt1 = remaining;
                                if (boneSlot !== 2) wt2 = remaining;
                                if (boneSlot !== 3) wt3 = remaining;
                            }

                            // Write back directly to typed arrays
                            idxArray[idx4] = idx0;
                            idxArray[idx4 + 1] = idx1;
                            idxArray[idx4 + 2] = idx2;
                            idxArray[idx4 + 3] = idx3Val;

                            wtArray[idx4] = wt0;
                            wtArray[idx4 + 1] = wt1;
                            wtArray[idx4 + 2] = wt2;
                            wtArray[idx4 + 3] = wt3;

                            if (idx < minModifiedIdx) minModifiedIdx = idx;
                            if (idx > maxModifiedIdx) maxModifiedIdx = idx;
                            modified = true;
                        }
                    }
                }
            }
        }
    }

    if (modified) {
        // GPU Upload Optimization: upload only the slice of the array that was modified
        const start = minModifiedIdx * 4;
        const count = (maxModifiedIdx - minModifiedIdx + 1) * 4;
        
        skinIndexAttr.updateRange.offset = start;
        skinIndexAttr.updateRange.count = count;
        skinIndexAttr.needsUpdate = true;

        skinWeightAttr.updateRange.offset = start;
        skinWeightAttr.updateRange.count = count;
        skinWeightAttr.needsUpdate = true;
    }
}

// Save Weight Painting Changes Handler
if (saveWeightPaintBtn) {
    saveWeightPaintBtn.addEventListener('click', () => {
        if (!threeModel || !activeModelRelativeUrl) return;

        // Turn off painting shader first so we export original materials
        const originalPaintingState = isWeightPaintingActive;
        if (originalPaintingState) {
            activeWeightPaintCheck.checked = false;
            const card = document.getElementById('paintInstructionCard');
            if (card) card.style.display = 'none';
            isWeightPaintingActive = false;
            toggleWeightVisualizer(false);
            if (brushHelper && threeScene) {
                threeScene.remove(brushHelper);
                brushHelper = null;
            }
        }

        statusOverlay.classList.add('active');
        updateLoader(40, 'Guardando Influencias...', 'Exportando el modelo tridimensional y recalculando pesos...');

        // Use THREE.GLTFExporter to export GLB
        const exporter = new THREE.GLTFExporter();
        
        // Export options
        const exportOptions = {
            binary: true,
            animations: [],
            truncateDrawRange: false
        };

        exporter.parse(threeModel, async (gltfBuffer) => {
            try {
                // Convert buffer array to base64
                const blob = new Blob([gltfBuffer], { type: 'application/octet-stream' });
                const reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onloadend = async () => {
                    const glbBase64 = reader.result;

                    updateLoader(70, 'Regenerando FBX...', 'Blender está compilando las nuevas influencias de huesos y texturas en el archivo FBX...');
                    
                    const response = await fetch(`${apiBase}/api/save-weights`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            modelUrl: activeModelRelativeUrl,
                            glbBase64: glbBase64
                        })
                    });

                    if (!response.ok) {
                        const errData = await response.json().catch(() => ({ error: 'Error al actualizar pesos.' }));
                        throw new Error(errData.error || 'Error interno del servidor.');
                    }

                    const data = await response.json();
                    
                    // Reload model with updated files
                    sessionStorage.setItem('pendingModelToLoad', JSON.stringify({
                        gltfUrl: activeModelRelativeUrl,
                        downloadUrl: activeModelRelativeUrl,
                        fbxUrl: data.fbxUrl,
                        detectedCategory: currentModelCategory
                    }));
                    window.location.reload();
                };
            } catch (error) {
                console.error(error);
                statusOverlay.classList.remove('active');
                alert(`Error al guardar pesos: ${error.message}`);
                
                // Restore painting state on failure
                if (originalPaintingState) {
                    activeWeightPaintCheck.checked = true;
                    const card = document.getElementById('paintInstructionCard');
                    if (card) card.style.display = 'block';
                    isWeightPaintingActive = true;
                    toggleWeightVisualizer(true);
                }
            }
        }, (error) => {
            console.error('Error during GLTF export:', error);
            statusOverlay.classList.remove('active');
            alert('Error al exportar la malla para guardar.');
        }, exportOptions);
    });
}

// Generic function to toggle collapsible panels from the vertical toolbar buttons
function toggleToolbarPanel(panelId, buttonId) {
    const panel = document.getElementById(panelId);
    const button = document.getElementById(buttonId);
    if (!panel) return;

    const isCurrentlyCollapsed = panel.classList.contains('collapsed');

    // 1. Collapse all panels
    const allPanels = ['manualRigPanel', 'manualCleanPanel', 'rigTriggerPanel', 'manualWeightPaintPanel'];
    allPanels.forEach(id => {
        const p = document.getElementById(id);
        if (p) p.classList.add('collapsed');
    });

    // 2. Deactivate all buttons
    const allBtns = ['btnRigPanel', 'btnCleanPanel', 'btnRigTriggerPanel', 'btnWeightPaintPanel'];
    allBtns.forEach(id => {
        const b = document.getElementById(id);
        if (b) b.classList.remove('active');
    });

    // 3. If it was collapsed, expand it and set button active
    if (isCurrentlyCollapsed) {
        panel.classList.remove('collapsed');
        if (button) button.classList.add('active');
    }
}

// Attach event listeners for the vertical toolbar buttons
const btnRigPanel = document.getElementById('btnRigPanel');
const btnCleanPanel = document.getElementById('btnCleanPanel');
const btnRigTriggerPanel = document.getElementById('btnRigTriggerPanel');
const btnWeightPaintPanel = document.getElementById('btnWeightPaintPanel');

if (btnRigPanel) {
    btnRigPanel.addEventListener('click', () => toggleToolbarPanel('manualRigPanel', 'btnRigPanel'));
}
if (btnCleanPanel) {
    btnCleanPanel.addEventListener('click', () => toggleToolbarPanel('manualCleanPanel', 'btnCleanPanel'));
}
if (btnRigTriggerPanel) {
    btnRigTriggerPanel.addEventListener('click', () => toggleToolbarPanel('rigTriggerPanel', 'btnRigTriggerPanel'));
}
if (btnWeightPaintPanel) {
    btnWeightPaintPanel.addEventListener('click', () => toggleToolbarPanel('manualWeightPaintPanel', 'btnWeightPaintPanel'));
}

function updateWeightPaintSelectedBoneDisplay() {
    const textEl = document.getElementById('weightPaintSelectedBoneText');
    if (textEl) {
        textEl.textContent = selectedBone ? getFriendlyBoneName(selectedBone.name) : 'Ninguno';
    }
}

function updateSelectedBoneMarker() {
    if (!threeScene) return;

    if (isWeightPaintingActive) {
        if (selectedBone) {
            if (!selectedBoneMarker) {
                // Create a beautiful, glowing hot-orange/magenta pulsing sphere
                const group = new THREE.Group();

                const innerGeo = new THREE.SphereGeometry(0.025, 16, 16);
                const innerMat = new THREE.MeshBasicMaterial({
                    color: 0xff0055, // Hot magenta/red to stand out against weight map blue
                    depthTest: false,
                    transparent: true,
                    opacity: 0.95
                });
                const innerMesh = new THREE.Mesh(innerGeo, innerMat);
                innerMesh.renderOrder = 1000;
                group.add(innerMesh);

                selectedBoneMarker = group;
                threeScene.add(selectedBoneMarker);
            }
            const pos = new THREE.Vector3();
            selectedBone.getWorldPosition(pos);
            selectedBoneMarker.position.copy(pos);
            selectedBoneMarker.visible = true;
        } else {
            if (selectedBoneMarker) selectedBoneMarker.visible = false;
        }
    } else {
        if (selectedBoneMarker) {
            threeScene.remove(selectedBoneMarker);
            selectedBoneMarker = null;
        }
    }
}

// Check mobile viewport and show interactive redirect dialog
function checkMobileRedirect() {
    if (window.innerWidth < 768) {
        if (sessionStorage.getItem('dismissedMobileWarning') === 'true') {
            return;
        }

        const overlay = document.createElement('div');
        overlay.style.position = 'fixed';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.width = '100vw';
        overlay.style.height = '100vh';
        overlay.style.backgroundColor = 'rgba(10, 10, 12, 0.96)';
        overlay.style.zIndex = '999999';
        overlay.style.display = 'flex';
        overlay.style.alignItems = 'center';
        overlay.style.justifyContent = 'center';
        overlay.style.padding = '24px';
        overlay.style.boxSizing = 'border-box';
        overlay.style.backdropFilter = 'blur(10px)';
        overlay.style.webkitBackdropFilter = 'blur(10px)';
        
        overlay.innerHTML = `
            <div style="background: #18181c; border: 1px solid #7c3aed; border-radius: 16px; padding: 24px; text-align: center; max-width: 400px; width: 100%; box-shadow: 0 20px 45px rgba(0,0,0,0.5); font-family: sans-serif;">
                <div style="font-size: 3.5rem; margin-bottom: 16px; animation: bounce 2s infinite;">📱</div>
                <h3 style="color: #ffffff; margin-top: 0; font-size: 1.35rem; font-weight: 700; margin-bottom: 12px; letter-spacing: -0.5px;">¿Estás en un Celular?</h3>
                <p style="color: #a1a1aa; font-size: 0.9rem; line-height: 1.5; margin-bottom: 24px;">
                    La creación, edición y limpieza de mallas está diseñada para pantallas de PC/Laptops. En celulares, te recomendamos usar el visor 3D táctil optimizado y proyectar en Realidad Aumentada (AR).
                </p>
                <div style="display: flex; flex-direction: column; gap: 12px; width: 100%;">
                    <a href="/viewer.html?v=123" style="background: #7c3aed; color: #ffffff; padding: 14px; border-radius: 10px; text-decoration: none; font-weight: 700; font-size: 0.95rem; display: block; box-shadow: 0 4px 12px rgba(124, 58, 237, 0.3);">
                        Abrir Visor Móvil (AR)
                    </a>
                    <button id="btnStayOnPCWeb" style="background: transparent; border: 1px solid rgba(255,255,255,0.15); color: #a1a1aa; padding: 12px; border-radius: 10px; font-weight: 600; font-size: 0.9rem; cursor: pointer; transition: all 0.2s;">
                        Seguir en Web de PC (No recomendado)
                    </button>
                </div>
            </div>
            <style>
                @keyframes bounce {
                    0%, 100% { transform: translateY(0); }
                    50% { transform: translateY(-10px); }
                }
                #btnStayOnPCWeb:hover {
                    background: rgba(255,255,255,0.05);
                    color: #ffffff;
                }
            </style>
        `;
        document.body.appendChild(overlay);
        
        overlay.querySelector('#btnStayOnPCWeb').addEventListener('click', () => {
            sessionStorage.setItem('dismissedMobileWarning', 'true');
            sessionStorage.setItem('forceDesktop', 'true');
            document.body.removeChild(overlay);
        });
    }
}

// Execute check on page load - only via auth functions