File size: 71,045 Bytes
e2ca502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ╔══════════════════════════════════════════════════════════╗
// ║           PixelAI Studio — Core Engine (JS)              ║
// ║           Alinhado com schema Supabase real              ║
// ╚══════════════════════════════════════════════════════════╝

let supabaseClient = null;
try {
    supabaseClient = window.supabase.createClient(CONFIG.SUPABASE_URL, CONFIG.SUPABASE_ANON_KEY);
} catch (e) {
    console.error("Supabase Client Error:", e);
    // Fallback if needed, but functions will show an error toast if it's null
}

// ─── STATE ───
let currentUser = null;
let currentCredits = 0;
let selectedFile = null;

// ─── TRANSLATIONS ───
const translations = {
    pt: {
        nav_login: "Entrar",
        nav_register: "Criar Conta",
        auth_title: "Portal de Acesso",
        auth_subtitle: "Inicie sua jornada criativa com PixelAI.",
        auth_google: "Conta Google",
        auth_phantom: "Phantom Wallet",
        auth_or: "ou email",
        auth_login_btn: "Entrar",
        auth_register_btn: "Registrar",
        stat_credits: "Créditos Ativos",
        stat_history: "Arquivos Processados",
        tools_title: "Laboratório de IA",
        tool_bg_removal: "Remover Fundo",
        tool_desc: "Algoritmo de alta precisão v2.4 rodando em GPU Cloud.",
        upload_title: "Enviar Imagem",
        upload_subtitle: "Arraste ou clique para selecionar",
        btn_execute: "Executar Remoção",
        msg_processing: "Processando...",
        btn_download: "Download",
        btn_new_file: "Novo Arquivo",
        history_title: "Histórico de Criações",
        msg_fill_login: "Preencha email e senha",
        msg_login_error: "Erro ao entrar: ",
        msg_register_error: "Erro ao registrar: ",
        msg_register_ok: "Conta criada! Verifique seu email se necessário, ou faça login.",
        msg_no_credits: "Créditos insuficientes!",
        msg_server_error: "Falha ao processar. O servidor de IA pode estar inicializando — aguarde 30s e tente novamente.",
        msg_history_empty: "Nenhuma imagem processada ainda.",
        msg_phantom_missing: "Instale a Phantom Wallet para continuar.",
        msg_processing_long: "Processando (pode levar 30s no primeiro uso)..."
    },
    en: {
        nav_login: "Login",
        nav_register: "Create Account",
        auth_title: "Access Portal",
        auth_subtitle: "Start your creative journey with PixelAI.",
        auth_google: "Google Account",
        auth_phantom: "Phantom Wallet",
        auth_or: "or email",
        auth_login_btn: "Login",
        auth_register_btn: "Register",
        stat_credits: "Active Credits",
        stat_history: "Files Processed",
        tools_title: "AI Laboratory",
        tool_bg_removal: "Remove Background",
        tool_desc: "High precision algorithm v2.4 running on GPU Cloud.",
        upload_title: "Upload Image",
        upload_subtitle: "Drag or click to select",
        btn_execute: "Execute Removal",
        msg_processing: "Processing...",
        btn_download: "Download",
        btn_new_file: "New File",
        history_title: "Creation History",
        msg_fill_login: "Fill email and password",
        msg_login_error: "Login error: ",
        msg_register_error: "Register error: ",
        msg_register_ok: "Account created! Check your email if needed, or log in.",
        msg_no_credits: "Insufficient credits!",
        msg_server_error: "Failed to process. The AI server may be warming up — wait 30s and retry.",
        msg_history_empty: "No images processed yet.",
        msg_phantom_missing: "Install Phantom Wallet to continue.",
        msg_processing_long: "Processing (first use may take 30s)..."
    }
};

Object.assign(translations.pt, {
    btn_remove_bg: "Remover Fundo (1 Crédito)",
    msg_invalid_file: "Selecione um arquivo de imagem válido.",
    msg_backend_offline: "O backend não respondeu. Se o frontend está no Netlify, confirme se o servidor local e o túnel estão abertos."
});

Object.assign(translations.pt, {
    msg_manual_pay_cancelled: "Pagamento manual cancelado."
});

Object.assign(translations.en, {
    btn_remove_bg: "Remove Background (1 Credit)",
    msg_invalid_file: "Select a valid image file.",
    msg_backend_offline: "The backend did not respond. If the frontend is on Netlify, keep the local server and tunnel running."
});

Object.assign(translations.pt, {
    msg_result_ready: "Resultado pronto. Se o fundo original era quadriculado, ele deve sair transparente no download."
});

Object.assign(translations.en, {
    msg_result_ready: "Result ready. If the original background was checkerboard, it should now be transparent in the download."
});

Object.assign(translations.pt, {
    page_title: "PixelAI Studio — Ferramentas de Imagem Elite",
    nav_plans: "Planos",
    auth_email_placeholder: "Seu email",
    auth_password_placeholder: "Sua senha",
    home_title: "Remoção de Fundo Profissional para Logos, textos e imagens",
    home_subtitle: "Escolha seu plano e comece em segundos. Alta qualidade, fluxo simples e edição manual integrada.",
    home_cta_start: "Começar Grátis",
    home_cta_login: "Entrar",
    plan_free_label: "Plano Gratuito",
    plan_free_name: "Starter",
    plan_free_meta: "10 créditos iniciais",
    plan_free_f1: "Remoção de fundo por IA",
    plan_free_f2: "Editor manual com pincel",
    plan_free_f3: "Histórico de imagens",
    plan_free_btn: "Usar Grátis",
    plan_pro_label: "Plano Pago (Crypto)",
    plan_pro_name: "Pro Crypto",
    plan_pro_meta_suffix: "por pacote",
    plan_pro_f1: "Volume alto de processamento",
    plan_pro_f2: "Prioridade no fluxo de produção",
    plan_pro_f3: "Compra com Phantom Wallet",
    plan_pro_btn: "Ativar Plano Pro",
    credit_empty_title: "Seus créditos acabaram",
    credit_empty_subtitle: "Ative o plano Pro com crypto para continuar processando sem parar.",
    credit_buy_btn: "Comprar",
    credit_claim_btn: "Claim NFT",
    credit_view_plans_btn: "Ver Planos",
    model_ultra_pro: "IA Ultra Pro (BiRefNet) - Especialista (SOTA)",
    model_high: "IA Alta (Bria RMBG 1.4) - Ótima Qualidade",
    model_standard: "IA Padrão (ISNet) - Rápido",
    model_logo_specialist: "Modo Especialista (Textos e Logos) - Novo Algoritmo",
    crop_hint: "Opcional: Arraste os cantos para selecionar a área do objeto principal e ajudar a IA.",
    btn_cancel: "Cancelar",
    tool_erase: "Apagar",
    tool_restore: "Restaurar",
    tool_undo: "Desfazer",
    tool_ai_again: "IA Novamente",
    zoom_out: "Zoom -",
    zoom_in: "Zoom +",
    zoom_reset: "100%",
    msg_supabase_not_loaded: "Erro de conexão com servidor. Desative adblocks.",
    msg_result_invalid_image: "Imagem retornada pelo servidor é inválida.",
    msg_bg_timeout: "Tempo esgotado ({seconds}s). O servidor de IA pode estar baixando/inicializando o modelo. Aguarde e tente novamente.",
    msg_bg_connection_failed: "Falha de conexão com o servidor. Verifique sua internet.",
    msg_bg_temp_fail: "Falha temporária ao carregar modelo de IA no servidor. Tente novamente em 20 segundos."
});

Object.assign(translations.en, {
    page_title: "PixelAI Studio — Elite Image Tools",
    nav_plans: "Plans",
    auth_email_placeholder: "Your email",
    auth_password_placeholder: "Your password",
    home_title: "Professional Background Removal for Logos, Text and Images",
    home_subtitle: "Choose your plan and start in seconds. High quality, simple workflow, and built-in manual editing.",
    home_cta_start: "Start Free",
    home_cta_login: "Login",
    plan_free_label: "Free Plan",
    plan_free_name: "Starter",
    plan_free_meta: "10 initial credits",
    plan_free_f1: "AI background removal",
    plan_free_f2: "Manual brush editor",
    plan_free_f3: "Image history",
    plan_free_btn: "Use Free",
    plan_pro_label: "Paid Plan (Crypto)",
    plan_pro_name: "Pro Crypto",
    plan_pro_meta_suffix: "per package",
    plan_pro_f1: "High processing volume",
    plan_pro_f2: "Priority in production flow",
    plan_pro_f3: "Purchase with Phantom Wallet",
    plan_pro_btn: "Activate Pro Plan",
    credit_empty_title: "Your credits are over",
    credit_empty_subtitle: "Activate Pro with crypto to keep processing without stopping.",
    credit_buy_btn: "Buy",
    credit_claim_btn: "Claim NFT",
    credit_view_plans_btn: "View Plans",
    model_ultra_pro: "Ultra Pro AI (BiRefNet) - Specialist (SOTA)",
    model_high: "High AI (Bria RMBG 1.4) - Great Quality",
    model_standard: "Standard AI (ISNet) - Fast",
    model_logo_specialist: "Specialist Mode (Text & Logos) - New Algorithm",
    crop_hint: "Optional: Drag corners to select the main subject area and help the AI.",
    btn_cancel: "Cancel",
    tool_erase: "Erase",
    tool_restore: "Restore",
    tool_undo: "Undo",
    tool_ai_again: "Run AI Again",
    zoom_out: "Zoom -",
    zoom_in: "Zoom +",
    zoom_reset: "100%",
    msg_supabase_not_loaded: "Server connection error. Disable ad blockers.",
    msg_result_invalid_image: "The image returned by the server is invalid.",
    msg_bg_timeout: "Request timed out ({seconds}s). The AI server may be downloading/initializing the model. Please wait and try again.",
    msg_bg_connection_failed: "Connection to server failed. Check your internet.",
    msg_bg_temp_fail: "Temporary failure while loading AI model on server. Try again in 20 seconds."
});

Object.assign(translations.pt, {
    msg_buy_login_first: "Entre na sua conta para comprar créditos.",
    msg_buy_connect_wallet: "Conecte a Phantom Wallet para continuar.",
    msg_buy_confirm: "Você autoriza o pagamento de {price} SOL por {credits} créditos?",
    msg_buy_success: "Compra confirmada! Créditos adicionados na conta.",
    msg_buy_cancelled: "Compra cancelada na carteira.",
    msg_buy_network_fee: "A rede Solana sempre cobra taxa (estimada: ~{fee} SOL). Total estimado: {total} SOL.",
    msg_buy_insufficient_sol: "Saldo insuficiente. Necessario ~{needed} SOL (pagamento + taxa), disponivel: {balance} SOL.",
    msg_buy_invalid_transfer: "Pagamento nao validado para a carteira de destino.",
    msg_buy_failed: "Falha ao processar compra em crypto: "
});

Object.assign(translations.en, {
    msg_buy_login_first: "Log in to buy credits.",
    msg_buy_connect_wallet: "Connect Phantom Wallet to continue.",
    msg_buy_confirm: "Confirm payment of {price} SOL for {credits} credits?",
    msg_buy_success: "Purchase confirmed! Credits were added to your account.",
    msg_buy_cancelled: "Purchase canceled in wallet.",
    msg_buy_network_fee: "Solana always charges a network fee (estimated: ~{fee} SOL). Estimated total: {total} SOL.",
    msg_buy_insufficient_sol: "Insufficient balance. Required ~{needed} SOL (payment + fee), available: {balance} SOL.",
    msg_buy_invalid_transfer: "Payment was not validated to the destination wallet.",
    msg_buy_failed: "Failed to process crypto purchase: "
});

Object.assign(translations.pt, {
    msg_nft_claim_disabled: "Claim por NFT está desativado no config.js.",
    msg_nft_claim_no_list: "Adicione os mint IDs em NFT_CLAIM_MINT_IDS no config.js.",
    msg_nft_claim_none: "Nenhum NFT elegível encontrado na sua carteira.",
    msg_nft_claim_no_new: "Você já resgatou créditos para todos os NFTs elegíveis desta carteira.",
    msg_nft_claim_success: "Claim concluído: +{credits} créditos para {count} NFT(s).",
    msg_nft_claim_error: "Erro no claim de NFT: "
});

Object.assign(translations.en, {
    msg_nft_claim_disabled: "NFT claim is disabled in config.js.",
    msg_nft_claim_no_list: "Add mint IDs to NFT_CLAIM_MINT_IDS in config.js.",
    msg_nft_claim_none: "No eligible NFTs were found in your wallet.",
    msg_nft_claim_no_new: "You already claimed credits for all eligible NFTs in this wallet.",
    msg_nft_claim_success: "Claim completed: +{credits} credits for {count} NFT(s).",
    msg_nft_claim_error: "NFT claim error: "
});

Object.assign(translations.pt, {
    msg_login_invalid_credentials: "Email ou senha inválidos.",
    msg_login_email_unconfirmed: "Confirme seu email antes de entrar.",
    msg_login_session_failed: "Não foi possível confirmar sua sessão. Tente novamente.",
    msg_login_cancelled: "Login cancelado.",
    msg_phantom_blocked: "A Phantom bloqueou esta dApp neste domínio. Use o fallback de pagamento manual para liberar créditos.",
    msg_manual_pay_prompt: "Envie {price} SOL para {wallet} na Phantom e cole aqui a assinatura (hash) da transação:",
    msg_manual_pay_invalid: "Transação inválida ou sem pagamento correto para a carteira de destino.",
    msg_manual_pay_already: "Essa assinatura já foi usada para claim de créditos.",
    msg_manual_pay_success: "Pagamento confirmado on-chain. Créditos liberados!"
});

Object.assign(translations.en, {
    msg_login_invalid_credentials: "Invalid email or password.",
    msg_login_email_unconfirmed: "Confirm your email before signing in.",
    msg_login_session_failed: "Unable to confirm your session. Try again.",
    msg_login_cancelled: "Login canceled.",
    msg_phantom_blocked: "Phantom blocked this dApp on this domain. Use manual payment fallback to unlock credits.",
    msg_manual_pay_prompt: "Send {price} SOL to {wallet} in Phantom and paste the transaction signature (hash):",
    msg_manual_pay_invalid: "Invalid transaction or payment not sent correctly to destination wallet.",
    msg_manual_pay_already: "This signature was already used to claim credits.",
    msg_manual_pay_cancelled: "Manual payment canceled.",
    msg_manual_pay_success: "On-chain payment confirmed. Credits unlocked!"
});

let currentLang = localStorage.getItem('lang') || 'pt';
let activeApiUrl = localStorage.getItem('last-working-api-url') || CONFIG.API_URL;
const API_PROBE_TIMEOUT_MS = 8000;
const SOLANA_BASE_FEE_BUFFER_LAMPORTS = 5000;

if (activeApiUrl && !/^(https?:)?\/\//i.test(activeApiUrl)) {
    activeApiUrl = CONFIG.API_URL;
}
if (window.location.hostname.includes('hf.space') && activeApiUrl.includes('loca.lt')) {
    activeApiUrl = CONFIG.API_URL;
}

function t(key) {
    return translations[currentLang][key] || key;
}

function formatT(key, vars = {}) {
    let text = t(key);
    for (const [name, value] of Object.entries(vars)) {
        text = text.replace(`{${name}}`, String(value));
    }
    return text;
}

function formatSol(value) {
    return Number(value).toFixed(3).replace(/\.?0+$/, '');
}

function setPlanPriceLabels() {
    const priceText = `${formatSol(CONFIG.CRYPTO_PLAN_PRICE_SOL)} SOL`;
    const creditsText = `${CONFIG.CRYPTO_PLAN_CREDITS} créditos`;
    const homePrice = document.getElementById('home-plan-price');
    const homeCredits = document.getElementById('home-plan-credits');
    const workspacePrice = document.getElementById('workspace-plan-price');
    if (homePrice) homePrice.innerText = priceText;
    if (homeCredits) homeCredits.innerText = creditsText;
    if (workspacePrice) workspacePrice.innerText = priceText;
}

function setupHomeParallax() {
    const home = document.getElementById('page-home');
    if (!home) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    const nodes = Array.from(home.querySelectorAll('[data-parallax]'));
    if (!nodes.length) return;

    home.addEventListener('mousemove', (event) => {
        const rect = home.getBoundingClientRect();
        const nx = ((event.clientX - rect.left) / rect.width - 0.5) * 2;
        const ny = ((event.clientY - rect.top) / rect.height - 0.5) * 2;
        nodes.forEach((el) => {
            const speed = Number(el.getAttribute('data-parallax') || 10);
            el.style.setProperty('--px', `${(-nx * speed).toFixed(2)}px`);
            el.style.setProperty('--py', `${(-ny * speed).toFixed(2)}px`);
        });
    });

    home.addEventListener('mouseleave', () => {
        nodes.forEach((el) => {
            el.style.setProperty('--px', '0px');
            el.style.setProperty('--py', '0px');
        });
    });
}

function normalizeMintList() {
    const list = Array.isArray(CONFIG.NFT_CLAIM_MINT_IDS) ? CONFIG.NFT_CLAIM_MINT_IDS : [];
    return [...new Set(list.map(v => String(v || '').trim()).filter(Boolean))];
}

function getClaimStorageKey() {
    const userId = currentUser?.id || 'anon';
    return `pixelai-nft-claims:${userId}`;
}

function getClaimedMints() {
    try {
        const raw = localStorage.getItem(getClaimStorageKey());
        const arr = raw ? JSON.parse(raw) : [];
        return Array.isArray(arr) ? arr : [];
    } catch (_) {
        return [];
    }
}

function setClaimedMints(mints) {
    try {
        localStorage.setItem(getClaimStorageKey(), JSON.stringify([...new Set(mints)]));
    } catch (_) {}
}

function getPaymentStorageKey() {
    const userId = currentUser?.id || 'anon';
    return `pixelai-sol-payments:${userId}`;
}

function getUsedPaymentSignatures() {
    try {
        const raw = localStorage.getItem(getPaymentStorageKey());
        const arr = raw ? JSON.parse(raw) : [];
        return Array.isArray(arr) ? arr : [];
    } catch (_) {
        return [];
    }
}

function setUsedPaymentSignatures(signatures) {
    try {
        localStorage.setItem(getPaymentStorageKey(), JSON.stringify([...new Set(signatures)]));
    } catch (_) {}
}

function markPaymentSignatureUsed(signature) {
    const clean = String(signature || '').trim();
    if (!clean) return;
    const used = new Set(getUsedPaymentSignatures());
    used.add(clean);
    setUsedPaymentSignatures([...used]);
}

function getErrorMessage(err) {
    return String(err?.message || err || '').trim();
}

function isUserRejectedError(err) {
    const msg = getErrorMessage(err).toLowerCase();
    return msg.includes('reject') || msg.includes('cancel') || msg.includes('denied');
}

function isPhantomBlockedError(err) {
    const msg = getErrorMessage(err).toLowerCase();
    return msg.includes('malicious')
        || msg.includes('pedido bloqueado')
        || msg.includes('phantom blocked')
        || msg.includes('not secure');
}

function isInsufficientFundsError(err) {
    const msg = getErrorMessage(err).toLowerCase();
    return msg.includes('insufficient funds')
        || msg.includes('insufficient lamports')
        || msg.includes('sol insuficiente')
        || msg.includes('nao tem sol suficientes')
        || msg.includes('não tem sol suficientes');
}

function isCredentialAuthError(err) {
    const msg = getErrorMessage(err).toLowerCase();
    return msg.includes('invalid login credentials')
        || msg.includes('invalid_credentials')
        || msg.includes('authentication failed')
        || msg.includes('wrong email or password');
}

function isEmailUnconfirmedError(err) {
    const msg = getErrorMessage(err).toLowerCase();
    return msg.includes('email not confirmed')
        || msg.includes('email_not_confirmed')
        || msg.includes('email confirmation required')
        || msg.includes('confirm your email');
}

function isSessionMissingError(err) {
    const msg = getErrorMessage(err).toLowerCase();
    return msg.includes('session')
        && (msg.includes('missing') || msg.includes('invalid') || msg.includes('unable'));
}

function getLoginErrorMessage(err, channel = 'email') {
    if (isEmailUnconfirmedError(err)) {
        return t('msg_login_email_unconfirmed');
    }
    if (isCredentialAuthError(err)) {
        return t('msg_login_invalid_credentials');
    }
    if (isSessionMissingError(err)) {
        return t('msg_login_session_failed');
    }
    if (channel === 'phantom' && isPhantomBlockedError(err)) {
        return t('msg_phantom_blocked');
    }
    if (channel === 'phantom' && isUserRejectedError(err)) {
        return t('msg_login_cancelled');
    }
    return getErrorMessage(err) || t('msg_login_session_failed');
}

function normalizePubkey(value) {
    if (!value) return '';
    if (typeof value === 'string') return value;
    if (typeof value.toBase58 === 'function') return value.toBase58();
    if (value.pubkey) return normalizePubkey(value.pubkey);
    return String(value);
}

async function validateSolTransferSignature({
    signature,
    expectedFrom,
    expectedTo,
    minLamports,
    connection
}) {
    const parsedTx = await connection.getParsedTransaction(signature, {
        commitment: 'confirmed',
        maxSupportedTransactionVersion: 0
    });
    if (!parsedTx) return false;

    const instructions = parsedTx?.transaction?.message?.instructions || [];
    let paidLamports = 0;

    for (const instruction of instructions) {
        if (instruction?.program !== 'system') continue;
        if (instruction?.parsed?.type !== 'transfer') continue;
        const info = instruction?.parsed?.info || {};
        const source = normalizePubkey(info.source);
        const destination = normalizePubkey(info.destination);
        const lamports = Number(info.lamports || 0);
        if (source === expectedFrom && destination === expectedTo && Number.isFinite(lamports)) {
            paidLamports += lamports;
        }
    }

    return paidLamports >= minLamports;
}

async function creditCurrentUserCryptoPlan(signature) {
    const newCredits = Number(currentCredits || 0) + Number(CONFIG.CRYPTO_PLAN_CREDITS || 0);
    const { error } = await supabaseClient
        .from('profiles')
        .update({ creditos: newCredits })
        .eq('id', currentUser.id);
    if (error) throw error;

    currentCredits = newCredits;
    markPaymentSignatureUsed(signature);
    renderCredits();
}

async function manualPaymentFallbackClaim(fromAddress) {
    const promptMsg = formatT('msg_manual_pay_prompt', {
        price: formatSol(CONFIG.CRYPTO_PLAN_PRICE_SOL),
        wallet: CONFIG.DEV_SOLANA_WALLET
    });
    const typedSignature = window.prompt(promptMsg);
    if (typedSignature === null) {
        showToast(t('msg_manual_pay_cancelled'), 'error');
        return false;
    }

    const signature = String(typedSignature || '').trim();
    if (!signature) {
        showToast(t('msg_manual_pay_invalid'), 'error');
        return false;
    }

    const used = new Set(getUsedPaymentSignatures());
    if (used.has(signature)) {
        showToast(t('msg_manual_pay_already'), 'error');
        return false;
    }

    const connection = await getSolanaReadConnection();
    const expectedTo = new window.solanaWeb3.PublicKey(CONFIG.DEV_SOLANA_WALLET).toString();
    const minLamports = Math.round(Number(CONFIG.CRYPTO_PLAN_PRICE_SOL) * window.solanaWeb3.LAMPORTS_PER_SOL);

    const isValid = await validateSolTransferSignature({
        signature,
        expectedFrom: fromAddress,
        expectedTo,
        minLamports,
        connection
    });
    if (!isValid) {
        showToast(t('msg_manual_pay_invalid'), 'error');
        return false;
    }

    await creditCurrentUserCryptoPlan(signature);
    showToast(t('msg_manual_pay_success'), 'success', 7000);
    return true;
}

async function getSolanaReadConnection() {
    const urls = Array.isArray(CONFIG.SOLANA_RPC_URLS) && CONFIG.SOLANA_RPC_URLS.length
        ? CONFIG.SOLANA_RPC_URLS
        : ['https://api.mainnet-beta.solana.com'];

    let lastError = null;
    for (const url of urls) {
        try {
            const connection = new window.solanaWeb3.Connection(url, 'confirmed');
            await connection.getLatestBlockhash('confirmed');
            return connection;
        } catch (err) {
            lastError = err;
            console.warn('[NFT] RPC indisponível:', url, err);
        }
    }
    throw lastError || new Error('Nenhum RPC Solana disponível.');
}

function setLanguage(lang) {
    currentLang = lang;
    localStorage.setItem('lang', lang);
    if (translations[lang]?.page_title) {
        document.title = translations[lang].page_title;
    }

    document.querySelectorAll('.btn-lang').forEach(btn => btn.classList.remove('active'));
    const btn = document.getElementById(`lang-${lang}`);
    if (btn) btn.classList.add('active');

    document.querySelectorAll('[data-i18n]').forEach(el => {
        const key = el.getAttribute('data-i18n');
        if (translations[lang][key]) {
            if (el.tagName === 'INPUT' && el.type !== 'submit') {
                el.placeholder = translations[lang][key];
            } else {
                el.innerText = translations[lang][key];
            }
        }
    });
}

// ─── TOAST ───
function showToast(msg, type = 'info', timeout = 4000) {
    const container = document.getElementById('toast-container');
    if (!container) { alert(msg); return; }
    const el = document.createElement('div');
    el.className = `toast toast-${type}`;
    el.innerText = msg;
    container.appendChild(el);
    setTimeout(() => el.classList.add('show'), 10);
    setTimeout(() => {
        el.classList.remove('show');
        setTimeout(() => el.remove(), 300);
    }, timeout);
}

// ─── INIT ───
function getApiCandidates() {
    const candidates = [
        CONFIG.API_URL,
        ...(CONFIG.API_FALLBACK_URLS || []),
        activeApiUrl
    ].filter(Boolean);

    return [...new Set(candidates.map(url => url.replace(/\/+$/, '')))];
}

function buildApiUrl(path, baseUrl = activeApiUrl) {
    return `${baseUrl}${path}`;
}

function isLocalApiUrl(baseUrl) {
    return baseUrl.includes('127.0.0.1') || baseUrl.includes('localhost');
}

function getApiHeaders(baseUrl, extraHeaders = {}) {
    const headers = { ...extraHeaders };
    if (!isLocalApiUrl(baseUrl)) {
        headers['Bypass-Tunnel-Reminder'] = 'true';
    }
    return headers;
}

async function probeApiBase(baseUrl) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), API_PROBE_TIMEOUT_MS);
    let response;

    try {
        response = await fetch(buildApiUrl('/api/health', baseUrl), {
            method: 'GET',
            headers: getApiHeaders(baseUrl),
            signal: controller.signal
        });
    } finally {
        clearTimeout(timer);
    }

    if (!response.ok) {
        throw new Error(`Health check falhou em ${baseUrl} (${response.status})`);
    }

    activeApiUrl = baseUrl;
    CONFIG.API_URL = baseUrl;
    localStorage.setItem('last-working-api-url', baseUrl);
    console.log('[API] usando backend:', baseUrl);
    return true;
}

async function exchangePasswordForSession(email, password) {
    const response = await fetch(`${CONFIG.SUPABASE_URL}/auth/v1/token?grant_type=password`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            apikey: CONFIG.SUPABASE_ANON_KEY,
            Authorization: `Bearer ${CONFIG.SUPABASE_ANON_KEY}`
        },
        body: JSON.stringify({ email, password })
    });

    const payload = await response.json().catch(() => ({}));
    if (!response.ok) {
        throw new Error(payload?.msg || payload?.error_description || payload?.error || `HTTP ${response.status}`);
    }

    if (!payload?.access_token || !payload?.refresh_token) {
        throw new Error('Sessao invalida retornada pelo Supabase.');
    }

    const { error } = await supabaseClient.auth.setSession({
        access_token: payload.access_token,
        refresh_token: payload.refresh_token
    });
    if (error) throw error;

    return payload;
}

async function signInWithPasswordSmart(email, password) {
    if (!supabaseClient) {
        throw new Error(t('msg_supabase_not_loaded'));
    }

    try {
        const { data, error } = await supabaseClient.auth.signInWithPassword({ email, password });
        if (!error) return data;
        console.warn('[AUTH] signInWithPassword fallback acionado:', error.message);
    } catch (err) {
        console.warn('[AUTH] signInWithPassword lançou excecao, usando fallback:', err);
    }

    return exchangePasswordForSession(email, password);
}

async function signInWithPasswordSmart(email, password) {
    if (!supabaseClient) {
        throw new Error(t('msg_supabase_not_loaded'));
    }

    try {
        const { data, error } = await supabaseClient.auth.signInWithPassword({ email, password });
        if (!error) return data;
        if (isCredentialAuthError(error) || isEmailUnconfirmedError(error)) {
            throw error;
        }
        console.warn('[AUTH] signInWithPassword fallback acionado:', error?.message || error);
    } catch (err) {
        if (isCredentialAuthError(err) || isEmailUnconfirmedError(err)) {
            throw err;
        }
        console.warn('[AUTH] signInWithPassword fallback:', err);
    }

    return exchangePasswordForSession(email, password);
}

function setAuthNavigation(isAuthenticated) {
    const guestNav = document.getElementById('auth-nav-guest');
    const userNav = document.getElementById('auth-nav-user');
    if (!guestNav || !userNav) return;

    guestNav.classList.toggle('hidden', isAuthenticated);
    userNav.classList.toggle('hidden', !isAuthenticated);
}

async function ensureBackendReady() {
    const candidates = getApiCandidates();

    for (const baseUrl of candidates) {
        try {
            await probeApiBase(baseUrl);
            return true;
        } catch (error) {
            console.warn('Backend health check failed:', baseUrl, error);
        }
    }

    return false;
}

async function waitForSupabaseSession(timeoutMs = 3000) {
    const started = Date.now();
    let lastSession = null;

    while (Date.now() - started < timeoutMs) {
        const { data, error } = await supabaseClient.auth.getSession();
        if (!error) {
            lastSession = data?.session || null;
            if (lastSession) return lastSession;
        }
        await new Promise((resolve) => setTimeout(resolve, 120));
    }

    if (lastSession) return lastSession;
    throw new Error(t('msg_login_session_failed'));
}

function finalizeAuthenticatedSession(session, source = 'auth') {
    if (!session?.user) {
        throw new Error(t('msg_login_session_failed'));
    }

    currentUser = session.user;
    setAuthNavigation(true);
    showPage('workspace');

    void updateUI().catch((err) => {
        console.error(`[AUTH:${source}] updateUI failed:`, err);
    });
    void loadHistory().catch((err) => {
        console.error(`[AUTH:${source}] loadHistory failed:`, err);
    });
}

async function ensureSignedInState(source = 'auth') {
    const session = await waitForSupabaseSession();
    finalizeAuthenticatedSession(session, source);
    return session;
}

window.addEventListener('DOMContentLoaded', async () => {
    setLanguage(currentLang);
    setPlanPriceLabels();
    setupHomeParallax();

    const modelSelect = document.getElementById('ai-model-select');
    if (modelSelect) {
        // For logo/text workflows, start in specialist mode every new session.
        modelSelect.value = 'logo-specialist';
        localStorage.setItem('preferred-bg-model', modelSelect.value);
        modelSelect.addEventListener('change', () => {
            localStorage.setItem('preferred-bg-model', modelSelect.value);
        });
    }

    try {
        if (!supabaseClient) throw new Error("Supabase não carregou.");
        const { data: { session } } = await supabaseClient.auth.getSession();
        if (session) {
            finalizeAuthenticatedSession(session, 'init');
        } else {
            setAuthNavigation(false);
            showPage('home');
        }

        supabaseClient.auth.onAuthStateChange((event, session) => {
            if (event === 'SIGNED_IN' && session) {
                finalizeAuthenticatedSession(session, 'event');
            } else if (event === 'SIGNED_OUT') {
                currentUser = null;
                currentCredits = 0;
                setAuthNavigation(false);
                showPage('home');
            }
        });
    } catch (err) {
        console.error('Init error:', err);
        showPage('home');
    }
});

// ─── AUTH ───


async function loginPhantom() {
    try {
        if (!supabaseClient) {
            throw new Error('Supabase não carregou no navegador.');
        }

        const provider = window.phantom?.solana || window.solana;
        if (!provider?.isPhantom) {
            showToast(t('msg_phantom_missing'), 'error');
            window.open('https://phantom.app/', '_blank');
            return;
        }

        const backendReady = await ensureBackendReady();
        if (!backendReady) {
            throw new Error(t('msg_backend_offline'));
        }

        const resp = await provider.connect();
        const address = resp.publicKey.toString();

        // 1) Chama o backend para criar/confirmar o usuário da carteira
        const authResp = await fetch(buildApiUrl('/api/phantom-auth'), {
            method: 'POST',
            headers: getApiHeaders(activeApiUrl, {
                'Content-Type': 'application/json'
            }),
            body: JSON.stringify({ wallet_address: address })
        });

        if (!authResp.ok) {
            const errData = await authResp.json().catch(() => ({}));
            const backendError = String(errData.error || `HTTP ${authResp.status}`).trim();
            console.error('[AUTH:phantom] backend error:', backendError, errData);
            throw new Error(backendError);
        }

        const { email, password } = await authResp.json();

        // 2) Loga no Supabase com fallback REST se o SDK falhar no navegador
        await signInWithPasswordSmart(email, password);
        await ensureSignedInState('phantom');

    } catch (err) {
        console.error('[AUTH:phantom] login error:', err);
        showToast(getLoginErrorMessage(err, 'phantom'), 'error');
    }
}

async function logout() {
    await supabaseClient.auth.signOut();
}

async function login() {
    if (!supabaseClient) return showToast(t('msg_supabase_not_loaded'), "error");
    const email = document.getElementById('auth-email').value.trim();
    const password = document.getElementById('auth-password').value;
    if (!email || !password) return showToast(t('msg_fill_login'), 'error');

    try {
        await signInWithPasswordSmart(email, password);
        await ensureSignedInState('email');
    } catch (error) {
        console.error('[AUTH:email] login error:', error);
        showToast(getLoginErrorMessage(error, 'email'), 'error');
    }
}

async function register() {
    const email = document.getElementById('auth-email').value.trim();
    const password = document.getElementById('auth-password').value;
    if (!email || !password) return showToast(t('msg_fill_login'), 'error');

    const emailRedirectTo = (CONFIG.AUTH_EMAIL_REDIRECT_URL || `${window.location.origin}${window.location.pathname}`).trim();
    const { error } = await supabaseClient.auth.signUp({
        email,
        password,
        options: {
            emailRedirectTo
        }
    });
    if (error) {
        showToast(t('msg_register_error') + error.message, 'error');
    } else {
        showToast(t('msg_register_ok'), 'success', 6000);
    }
}



async function claimNftCredits() {
    try {
        if (!currentUser) {
            showToast(t('msg_buy_login_first'), 'error');
            showPage('auth');
            return;
        }
        if (!window.solanaWeb3) {
            throw new Error('SDK Solana não carregou no navegador.');
        }
        if (CONFIG.NFT_CLAIM_ENABLED === false) {
            showToast(t('msg_nft_claim_disabled'), 'error');
            return;
        }

        const eligibleMints = normalizeMintList();
        if (!eligibleMints.length) {
            showToast(t('msg_nft_claim_no_list'), 'error');
            return;
        }

        const provider = window.phantom?.solana || window.solana;
        if (!provider?.isPhantom) {
            showToast(t('msg_phantom_missing'), 'error');
            window.open('https://phantom.app/', '_blank');
            return;
        }

        const resp = await provider.connect();
        const owner = resp.publicKey;
        const connection = await getSolanaReadConnection();
        const tokenProgramId = new window.solanaWeb3.PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');

        const parsedAccounts = await connection.getParsedTokenAccountsByOwner(
            owner,
            { programId: tokenProgramId },
            'confirmed'
        );

        const ownedMints = new Set();
        for (const item of parsedAccounts.value || []) {
            const info = item?.account?.data?.parsed?.info;
            const mint = info?.mint;
            const tokenAmount = info?.tokenAmount;
            if (!mint || !tokenAmount) continue;
            const amount = Number(tokenAmount.amount || 0);
            const decimals = Number(tokenAmount.decimals || 0);
            if (amount > 0 && decimals === 0) {
                ownedMints.add(mint);
            }
        }

        const matchedMints = eligibleMints.filter(m => ownedMints.has(m));
        if (!matchedMints.length) {
            showToast(t('msg_nft_claim_none'), 'error');
            return;
        }

        const claimed = new Set(getClaimedMints());
        const claimableMints = matchedMints.filter(m => !claimed.has(m));
        if (!claimableMints.length) {
            showToast(t('msg_nft_claim_no_new'), 'error');
            return;
        }

        const creditsPerNft = Number(CONFIG.NFT_CLAIM_CREDITS_PER_NFT || 200);
        const creditsToAdd = claimableMints.length * creditsPerNft;
        const newCredits = Number(currentCredits || 0) + creditsToAdd;

        const { error } = await supabaseClient
            .from('profiles')
            .update({ creditos: newCredits })
            .eq('id', currentUser.id);
        if (error) throw error;

        currentCredits = newCredits;
        setClaimedMints([...claimed, ...claimableMints]);
        renderCredits();
        showToast(formatT('msg_nft_claim_success', {
            credits: creditsToAdd,
            count: claimableMints.length
        }), 'success', 7000);
    } catch (err) {
        console.error('claimNftCredits error:', err);
        showToast(t('msg_nft_claim_error') + (err?.message || String(err)), 'error', 7000);
    }
}

async function buyCryptoPlanLegacy() {
    let fromAddress = '';
    try {
        if (!currentUser) {
            showToast(t('msg_buy_login_first'), 'error');
            showPage('auth');
            return;
        }

        const provider = window.phantom?.solana || window.solana;
        if (!provider?.isPhantom) {
            showToast(t('msg_phantom_missing'), 'error');
            window.open('https://phantom.app/', '_blank');
            return;
        }

        if (!window.solanaWeb3) {
            throw new Error('SDK Solana não carregou no navegador.');
        }

        const confirmMsg = formatT('msg_buy_confirm', {
            price: formatSol(CONFIG.CRYPTO_PLAN_PRICE_SOL),
            credits: CONFIG.CRYPTO_PLAN_CREDITS
        });
        if (!window.confirm(confirmMsg)) return;

        const resp = await provider.connect();
        const fromPubkey = resp.publicKey;
        fromAddress = fromPubkey.toString();
        const toPubkey = new window.solanaWeb3.PublicKey(CONFIG.DEV_SOLANA_WALLET);
        const toAddress = toPubkey.toString();
        const paymentLamports = Math.round(Number(CONFIG.CRYPTO_PLAN_PRICE_SOL) * window.solanaWeb3.LAMPORTS_PER_SOL);
        const connection = await getSolanaReadConnection();
        const latestBlock = await connection.getLatestBlockhash('confirmed');

        // One transparent instruction only: user wallet -> dev wallet.
        const tx = new window.solanaWeb3.Transaction({
            feePayer: fromPubkey,
            blockhash: latestBlock.blockhash,
            lastValidBlockHeight: latestBlock.lastValidBlockHeight
        }).add(window.solanaWeb3.SystemProgram.transfer({
            fromPubkey,
            toPubkey,
            lamports: paymentLamports
        }));

        let estimatedFeeLamports = SOLANA_BASE_FEE_BUFFER_LAMPORTS;
        try {
            const fee = await tx.getEstimatedFee(connection);
            if (Number.isFinite(fee) && fee > 0) {
                estimatedFeeLamports = fee;
            }
        } catch (feeErr) {
            console.warn('[CRYPTO] fee estimate failed, fallback to base fee buffer.', feeErr);
        }

        const userBalanceLamports = await connection.getBalance(fromPubkey, 'confirmed');
        const requiredLamports = paymentLamports + estimatedFeeLamports;
        const requiredSol = requiredLamports / window.solanaWeb3.LAMPORTS_PER_SOL;
        const balanceSol = userBalanceLamports / window.solanaWeb3.LAMPORTS_PER_SOL;
        const feeSol = estimatedFeeLamports / window.solanaWeb3.LAMPORTS_PER_SOL;

        showToast(formatT('msg_buy_network_fee', {
            fee: formatSol(feeSol),
            total: formatSol(requiredSol)
        }), 'info', 6500);

        if (userBalanceLamports < requiredLamports) {
            throw new Error(formatT('msg_buy_insufficient_sol', {
                needed: formatSol(requiredSol),
                balance: formatSol(balanceSol)
            }));
        }

        const simulation = await connection.simulateTransaction(tx, {
            commitment: 'processed',
            sigVerify: false,
            replaceRecentBlockhash: true
        });
        if (simulation?.value?.err) {
            throw new Error(`Simulation failed before wallet request: ${JSON.stringify(simulation.value.err)}`);
        }

        const txResult = await provider.signAndSendTransaction(tx);
        signature = txResult?.signature;
        if (!signature) throw new Error('Transaction sent without signature.');

        if (!signature) {
            // Fallback final: deixa a própria carteira escolher o RPC e completar dados.
            const fallbackTx = new window.solanaWeb3.Transaction({ feePayer: fromPubkey }).add(transferIx);
            try {
                const txResult = await provider.signAndSendTransaction(fallbackTx);
                signature = txResult?.signature || null;
            } catch (fallbackErr) {
                lastError = fallbackErr;
            }
        }

        if (!signature) {
            throw new Error((lastError && lastError.message) || 'Não foi possível enviar a transação na carteira.');
        }

        const newCredits = Number(currentCredits || 0) + Number(CONFIG.CRYPTO_PLAN_CREDITS || 0);
        const { error } = await supabaseClient
            .from('profiles')
            .update({ creditos: newCredits })
            .eq('id', currentUser.id);
        if (error) throw error;

        currentCredits = newCredits;
        renderCredits();
        showToast(t('msg_buy_success'), 'success', 6000);
    } catch (err) {
        const msg = err?.message || '';
        const lower = msg.toLowerCase();
        if (lower.includes('reject') || lower.includes('cancel')) {
            showToast(t('msg_buy_cancelled'), 'error');
            return;
        }
        console.error('buyCryptoPlan error:', err);
        showToast(t('msg_buy_failed') + msg, 'error', 7000);
    }
}

// Override do fluxo antigo: pagamento SOL seguro e transparente (1 transfer instruction).
async function buyCryptoPlan() {
    let fromAddress = '';
    try {
        if (!currentUser) {
            showToast(t('msg_buy_login_first'), 'error');
            showPage('auth');
            return;
        }

        const provider = window.phantom?.solana || window.solana;
        if (!provider?.isPhantom) {
            showToast(t('msg_phantom_missing'), 'error');
            window.open('https://phantom.app/', '_blank');
            return;
        }

        if (!window.solanaWeb3) {
            throw new Error('SDK Solana nao carregou no navegador.');
        }

        const confirmMsg = formatT('msg_buy_confirm', {
            price: formatSol(CONFIG.CRYPTO_PLAN_PRICE_SOL),
            credits: CONFIG.CRYPTO_PLAN_CREDITS
        });
        if (!window.confirm(confirmMsg)) return;

        const resp = await provider.connect();
        const fromPubkey = resp.publicKey;
        fromAddress = fromPubkey.toString();
        const toPubkey = new window.solanaWeb3.PublicKey(CONFIG.DEV_SOLANA_WALLET);
        const toAddress = toPubkey.toString();
        const paymentLamports = Math.round(Number(CONFIG.CRYPTO_PLAN_PRICE_SOL) * window.solanaWeb3.LAMPORTS_PER_SOL);

        const connection = await getSolanaReadConnection();
        const latestBlock = await connection.getLatestBlockhash('confirmed');
        const tx = new window.solanaWeb3.Transaction({
            feePayer: fromPubkey,
            blockhash: latestBlock.blockhash,
            lastValidBlockHeight: latestBlock.lastValidBlockHeight
        }).add(window.solanaWeb3.SystemProgram.transfer({
            fromPubkey,
            toPubkey,
            lamports: paymentLamports
        }));

        let estimatedFeeLamports = SOLANA_BASE_FEE_BUFFER_LAMPORTS;
        try {
            const fee = await tx.getEstimatedFee(connection);
            if (Number.isFinite(fee) && fee > 0) {
                estimatedFeeLamports = fee;
            }
        } catch (feeErr) {
            console.warn('[CRYPTO] fee estimate failed, fallback to base fee buffer.', feeErr);
        }

        const userBalanceLamports = await connection.getBalance(fromPubkey, 'confirmed');
        const requiredLamports = paymentLamports + estimatedFeeLamports;
        const requiredSol = requiredLamports / window.solanaWeb3.LAMPORTS_PER_SOL;
        const balanceSol = userBalanceLamports / window.solanaWeb3.LAMPORTS_PER_SOL;
        const feeSol = estimatedFeeLamports / window.solanaWeb3.LAMPORTS_PER_SOL;

        showToast(formatT('msg_buy_network_fee', {
            fee: formatSol(feeSol),
            total: formatSol(requiredSol)
        }), 'info', 6500);

        if (userBalanceLamports < requiredLamports) {
            throw new Error(formatT('msg_buy_insufficient_sol', {
                needed: formatSol(requiredSol),
                balance: formatSol(balanceSol)
            }));
        }

        const simulation = await connection.simulateTransaction(tx, {
            commitment: 'processed',
            sigVerify: false,
            replaceRecentBlockhash: true
        });
        if (simulation?.value?.err) {
            throw new Error(`Simulation failed before wallet request: ${JSON.stringify(simulation.value.err)}`);
        }

        const txResult = await provider.signAndSendTransaction(tx);
        const signature = txResult?.signature;
        if (!signature) {
            throw new Error('Transaction sent without signature.');
        }

        const confirmation = await connection.confirmTransaction({
            signature,
            blockhash: latestBlock.blockhash,
            lastValidBlockHeight: latestBlock.lastValidBlockHeight
        }, 'confirmed');
        if (confirmation.value?.err) {
            throw new Error(`Network confirmation failed: ${JSON.stringify(confirmation.value.err)}`);
        }

        const isValidTransfer = await validateSolTransferSignature({
            signature,
            expectedFrom: fromAddress,
            expectedTo: toAddress,
            minLamports: paymentLamports,
            connection
        });
        if (!isValidTransfer) {
            throw new Error(t('msg_buy_invalid_transfer'));
        }

        await creditCurrentUserCryptoPlan(signature);
        showToast(t('msg_buy_success'), 'success', 6000);
    } catch (err) {
        if (isUserRejectedError(err)) {
            showToast(t('msg_buy_cancelled'), 'error');
            return;
        }
        if (isPhantomBlockedError(err)) {
            showToast(t('msg_phantom_blocked'), 'error', 9000);
            if (fromAddress) {
                try {
                    await manualPaymentFallbackClaim(fromAddress);
                } catch (manualErr) {
                    console.error('manualPaymentFallbackClaim error:', manualErr);
                }
            }
            return;
        }
        if (isInsufficientFundsError(err)) {
            showToast(getErrorMessage(err), 'error', 7000);
            return;
        }

        const msg = getErrorMessage(err);
        console.error('buyCryptoPlan error:', err);
        showToast(t('msg_buy_failed') + msg, 'error', 7000);
    }
}

function showPage(pageId) {
    document.querySelectorAll('.page').forEach(p => p.style.display = 'none');
    const target = document.getElementById(`page-${pageId}`);
    if (target) target.style.display = 'block';
}

// ─── UI ───
function renderCredits() {
    const userCreditsEl = document.getElementById('user-credits');
    const statCreditsEl = document.getElementById('stat-credits');
    if (userCreditsEl) userCreditsEl.innerText = currentCredits;
    if (statCreditsEl) statCreditsEl.innerText = currentCredits;

    const offer = document.getElementById('credit-empty-offer');
    if (offer) {
        const hasCredits = Number(currentCredits || 0) >= Number(CONFIG.CUSTO_REMOVER_FUNDO || 1);
        offer.classList.toggle('hidden', hasCredits);
    }
}

async function updateUI() {
    if (!currentUser) return;

    setAuthNavigation(true);

    try {
        const { data, error } = await supabaseClient
            .from('profiles')
            .select('creditos')
            .eq('id', currentUser.id)
            .maybeSingle();

        if (error) throw error;

        if (!data) {
            // Cria perfil se trigger não criou (fallback)
            await supabaseClient.from('profiles').insert({
                id: currentUser.id,
                email: currentUser.email,
                creditos: CONFIG.CREDITOS_GRATIS
            });
            currentCredits = CONFIG.CREDITOS_GRATIS;
        } else {
            currentCredits = data.creditos ?? 0;
        }
    } catch (e) {
        console.error('Erro ao buscar créditos:', e);
        currentCredits = 0;
    }

    renderCredits();
}

// ─── EDITOR CANVAS (Borracha/Restaurar) ───
let originalImageObj = null;
let currentResultObj = null;
let canvas, ctx;
let isDrawing = false;
let brushMode = 'erase'; 
let brushSize = 30;
let lastX = 0, lastY = 0;
const MIN_EDITOR_ZOOM = 0.5;
const MAX_EDITOR_ZOOM = 4;
const EDITOR_ZOOM_STEP = 0.1;
let editorZoom = 1;
let zoomControlsBound = false;

function getCanvasViewport() {
    return document.getElementById('canvas-viewport');
}

function clampEditorZoom(value) {
    const numeric = Number(value);
    if (!Number.isFinite(numeric)) return 1;
    return Math.min(MAX_EDITOR_ZOOM, Math.max(MIN_EDITOR_ZOOM, numeric));
}

function updateZoomUi() {
    const range = document.getElementById('zoom-range');
    const value = document.getElementById('zoom-value');
    const zoomPercent = Math.round(editorZoom * 100);
    if (range) range.value = String(zoomPercent);
    if (value) value.innerText = `${zoomPercent}%`;
}

function calculateCanvasFitScale(viewport) {
    if (!canvas || !canvas.width) return 1;
    if (!viewport) return 1;
    const viewportWidth = viewport.clientWidth;
    if (!viewportWidth) return 1;
    return viewportWidth / canvas.width;
}

function setEditorZoom(nextZoom, options = {}) {
    const { preserveCenter = true } = options;
    editorZoom = clampEditorZoom(nextZoom);
    updateZoomUi();

    if (!canvas || !canvas.width || !canvas.height) return;

    const viewport = getCanvasViewport();
    if (!viewport) return;

    const prevCenterX = viewport.scrollLeft + (viewport.clientWidth / 2);
    const prevCenterY = viewport.scrollTop + (viewport.clientHeight / 2);
    const prevScrollWidth = Math.max(viewport.scrollWidth, 1);
    const prevScrollHeight = Math.max(viewport.scrollHeight, 1);
    const centerRatioX = prevCenterX / prevScrollWidth;
    const centerRatioY = prevCenterY / prevScrollHeight;

    const fitScale = calculateCanvasFitScale(viewport);
    const displayScale = fitScale * editorZoom;
    canvas.style.width = `${Math.max(1, Math.round(canvas.width * displayScale))}px`;
    canvas.style.height = `${Math.max(1, Math.round(canvas.height * displayScale))}px`;

    requestAnimationFrame(() => {
        if (preserveCenter) {
            const targetCenterX = centerRatioX * viewport.scrollWidth;
            const targetCenterY = centerRatioY * viewport.scrollHeight;
            viewport.scrollLeft = Math.max(0, targetCenterX - (viewport.clientWidth / 2));
            viewport.scrollTop = Math.max(0, targetCenterY - (viewport.clientHeight / 2));
        } else {
            viewport.scrollLeft = 0;
            viewport.scrollTop = 0;
        }
        updateCursorSize();
    });
}

function setupZoomControls() {
    if (zoomControlsBound) return;
    zoomControlsBound = true;

    const zoomRange = document.getElementById('zoom-range');
    const zoomIn = document.getElementById('btn-zoom-in');
    const zoomOut = document.getElementById('btn-zoom-out');
    const zoomReset = document.getElementById('btn-zoom-reset');
    const viewport = getCanvasViewport();

    if (zoomRange) {
        zoomRange.addEventListener('input', () => {
            setEditorZoom(Number(zoomRange.value) / 100, { preserveCenter: true });
        });
    }

    if (zoomIn) {
        zoomIn.addEventListener('click', () => {
            setEditorZoom(editorZoom + EDITOR_ZOOM_STEP, { preserveCenter: true });
        });
    }

    if (zoomOut) {
        zoomOut.addEventListener('click', () => {
            setEditorZoom(editorZoom - EDITOR_ZOOM_STEP, { preserveCenter: true });
        });
    }

    if (zoomReset) {
        zoomReset.addEventListener('click', () => {
            setEditorZoom(1, { preserveCenter: false });
        });
    }

    if (viewport) {
        viewport.addEventListener('wheel', (event) => {
            if (!(event.ctrlKey || event.metaKey)) return;
            event.preventDefault();
            const direction = event.deltaY < 0 ? 1 : -1;
            setEditorZoom(editorZoom + (direction * EDITOR_ZOOM_STEP), { preserveCenter: true });
        }, { passive: false });
    }

    window.addEventListener('resize', () => {
        setEditorZoom(editorZoom, { preserveCenter: false });
    });
}

function setupCanvasEditor() {
    canvas = document.getElementById('result-canvas');
    if(!canvas) return;
    ctx = canvas.getContext('2d', { willReadFrequently: true });
    setupZoomControls();
    
    // Bind events
    canvas.addEventListener('mousedown', startDraw);
    canvas.addEventListener('mousemove', (e) => { updateCursor(e); drawing(e); });
    canvas.addEventListener('mouseup', stopDraw);
    canvas.addEventListener('mouseout', (e) => { stopDraw(); document.getElementById('brush-cursor').style.display = 'none'; });
    canvas.addEventListener('mouseenter', () => { document.getElementById('brush-cursor').style.display = 'block'; });
    
    // Touch support
    canvas.addEventListener('touchstart', (e) => startDraw(e.touches[0]), {passive: false});
    canvas.addEventListener('touchmove', (e) => { e.preventDefault(); drawing(e.touches[0]); }, {passive: false});
    canvas.addEventListener('touchend', stopDraw);
    
    document.getElementById('brush-size').addEventListener('input', (e) => {
        brushSize = parseInt(e.target.value);
        updateCursorSize();
    });
    updateCursorSize(); // inicializa tamanho
    updateZoomUi();
}

function updateCursorSize() {
    const cursor = document.getElementById('brush-cursor');
    if (!cursor || !canvas || !canvas.width) return;
    const rect = canvas.getBoundingClientRect();
    const displayScale = rect.width / canvas.width;
    const cursorPx = Math.max(4, brushSize * (Number.isFinite(displayScale) && displayScale > 0 ? displayScale : 1));
    cursor.style.width = `${cursorPx}px`;
    cursor.style.height = `${cursorPx}px`;
}

function updateCursor(e) {
    const cursor = document.getElementById('brush-cursor');
    const rect = canvas.getBoundingClientRect();
    // Pega a posicao do mouse relativa a DIV container (já que o canvas e o cursor estao no mesmo relative container)
    // Para simplificar, ajustamos direto com base no mouseX e mouseY dentro do bounds do canvas visivel.
    cursor.style.left = (e.clientX - rect.left) + 'px';
    cursor.style.top = (e.clientY - rect.top) + 'px';
}

function setBrushMode(mode) {
    brushMode = mode;
    document.getElementById('btn-tool-erase').classList.toggle('active', mode === 'erase');
    document.getElementById('btn-tool-erase').style.border = mode === 'erase' ? '1px solid var(--accent)' : 'none';
    document.getElementById('btn-tool-restore').classList.toggle('active', mode === 'restore');
    document.getElementById('btn-tool-restore').style.border = mode === 'restore' ? '1px solid var(--accent)' : 'none';
}

function startDraw(e) {
    isDrawing = true;
    const rect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    
    lastX = (e.clientX - rect.left) * scaleX;
    lastY = (e.clientY - rect.top) * scaleY;
    drawing(e);
}

function drawing(e) {
    if (!isDrawing) return;
    const rect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    
    const currentX = (e.clientX - rect.left) * scaleX;
    const currentY = (e.clientY - rect.top) * scaleY;
    
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    ctx.lineWidth = brushSize;
    
    if (brushMode === 'erase') {
        ctx.globalCompositeOperation = 'destination-out';
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(currentX, currentY);
        ctx.stroke();
    } else {
        // Restore mode: usa canvas temporário para extrair pixels exatos
        const tCanvas = document.createElement('canvas');
        tCanvas.width = canvas.width;
        tCanvas.height = canvas.height;
        const tCtx = tCanvas.getContext('2d');
        
        tCtx.lineJoin = 'round';
        tCtx.lineCap = 'round';
        tCtx.lineWidth = brushSize;
        tCtx.beginPath();
        tCtx.moveTo(lastX, lastY);
        tCtx.lineTo(currentX, currentY);
        tCtx.stroke();
        
        tCtx.globalCompositeOperation = 'source-in';
        tCtx.drawImage(originalImageObj, 0, 0, canvas.width, canvas.height);
        
        ctx.globalCompositeOperation = 'source-over';
        ctx.drawImage(tCanvas, 0, 0);
    }
    
    lastX = currentX;
    lastY = currentY;
}

function stopDraw() { isDrawing = false; }

function resetCanvas() {
    if(!canvas || !currentResultObj) return;
    ctx.globalCompositeOperation = 'source-over';
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(currentResultObj, 0, 0, canvas.width, canvas.height);
    updateCursorSize();
}

document.addEventListener('DOMContentLoaded', () => {
    setupCanvasEditor();
});

// ─── IMAGE HANDLING ───
let cropper = null;

function loadFile(file) {
    if (!file || !file.type.startsWith('image/')) {
        showToast(t('msg_invalid_file'), 'error');
        return;
    }
    
    // Cleanup previous cropper
    if (cropper) {
        cropper.destroy();
        cropper = null;
    }
    
    selectedFile = file;
    const reader = new FileReader();
    reader.onload = (e) => {
        const img = document.getElementById('preview-img');
        
        img.onload = () => {
            document.getElementById('preview-container').classList.remove('hidden');
            document.getElementById('drop-zone').classList.add('hidden');
            document.getElementById('result-panel').classList.add('hidden');
            
            setTimeout(() => {
                // Initialize Cropper
                cropper = new Cropper(img, {
                    viewMode: 1,
                    dragMode: 'crop',
                    autoCropArea: 0.95,
                    restore: false,
                    guides: true,
                    center: true,
                    highlight: false,
                    cropBoxMovable: true,
                    cropBoxResizable: true,
                    toggleDragModeOnDblclick: false,
                });
            }, 50);
        };
        
        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
}

function handleDrop(e) {
    e.preventDefault();
    e.currentTarget.style.borderColor = '';
    const file = e.dataTransfer.files[0];
    loadFile(file);
}

function resetEditor() {
    selectedFile = null;
    originalImageObj = null;
    currentResultObj = null;
    editorZoom = 1;
    updateZoomUi();
    document.getElementById('preview-container').classList.add('hidden');
    document.getElementById('drop-zone').classList.remove('hidden');
    document.getElementById('result-panel').classList.add('hidden');
    document.getElementById('fileInput').value = '';
}

// ─── CORE: BACKGROUND REMOVAL ───
async function runAIAgain() {
    if(!canvas) return;
    canvas.toBlob((blob) => {
        // Criamos um novo File a partir do canvas atual
        const file = new File([blob], "edited_canvas.png", { type: "image/png" });
        selectedFile = file;
        // Atualiza originalImageObj para o novo canvas para as proximas edicoes
        const tempUrl = URL.createObjectURL(blob);
        originalImageObj = new Image();
        originalImageObj.src = tempUrl;
        document.getElementById('preview-img').src = tempUrl;
        
        // Roda a remocao de fundo
        processBackgroundRemoval();
    }, 'image/png');
}

async function processBackgroundRemoval() {
    console.log('[BG] start');
    if (!selectedFile) { console.warn('[BG] sem arquivo'); return; }
    if (currentCredits < CONFIG.CUSTO_REMOVER_FUNDO) {
        showToast(t('msg_no_credits'), 'error');
        const offer = document.getElementById('credit-empty-offer');
        if (offer) {
            offer.classList.remove('hidden');
            offer.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
        return;
    }

    const backendReady = await ensureBackendReady();
    if (!backendReady) {
        showToast(t('msg_backend_offline'), 'error', 7000);
        return;
    }

    const btn = document.getElementById('btn-process');
    const status = document.getElementById('process-status');
    const fill = document.getElementById('progress-fill');
    const msg = document.getElementById('process-msg');

    btn.disabled = true;
    status.classList.remove('hidden');
    fill.style.width = '15%';
    msg.innerText = t('msg_processing');

    let pct = 15;
    const ramp = setInterval(() => {
        pct = Math.min(pct + 4, 90);
        fill.style.width = pct + '%';
        if (pct >= 50) msg.innerText = t('msg_processing_long');
    }, 1000);

    const modelSelect = document.getElementById('ai-model-select');
    const selectedModel = modelSelect && modelSelect.value ? modelSelect.value : 'bria-rmbg';
    const requestTimeoutMs = (selectedModel === 'logo-specialist' || selectedModel === 'birefnet-general') ? 240000 : 120000;

    const controller = new AbortController();
    const fetchTimeout = setTimeout(() => {
        console.warn(`[BG] timeout fetch ${Math.round(requestTimeoutMs / 1000)}s — abortando`);
        controller.abort();
    }, requestTimeoutMs);

    try {
        const formData = new FormData();
        if (selectedModel) {
            formData.append('model', selectedModel);
            console.log('[BG] modelo:', selectedModel);
        }

        let imageBlob = selectedFile;
        let imageName = selectedFile.name || 'image.png';
        const previewVisible = !document.getElementById('preview-container').classList.contains('hidden');

        if (typeof cropper !== 'undefined' && cropper && previewVisible) {
            try {
                console.log('[BG] tentando getCroppedCanvas');
                const canvasToExtract = cropper.getCroppedCanvas({ maxWidth: 1024, maxHeight: 1024 });
                if (!canvasToExtract) throw new Error('getCroppedCanvas retornou null');

                imageBlob = await Promise.race([
                    new Promise((resolve, reject) => {
                        try {
                            canvasToExtract.toBlob(b => b ? resolve(b) : reject(new Error('toBlob null')), 'image/png');
                        } catch (e) { reject(e); }
                    }),
                    new Promise((_, reject) => setTimeout(() => reject(new Error('toBlob timeout 10s')), 10000))
                ]);
                imageName = 'cropped.png';
                console.log('[BG] cropped blob:', imageBlob.size, 'bytes');
            } catch (cropErr) {
                console.warn('[BG] cropper falhou, usando arquivo original:', cropErr.message);
                imageBlob = selectedFile;
                imageName = selectedFile.name || 'image.png';
            }
        } else {
            console.log('[BG] usando arquivo original direto');
        }

        // SALVA A IMAGEM ORIGINAL PARA O PINCEL DE RESTAURAÇÃO FUNCIONAR
        originalImageObj = new Image();
        originalImageObj.src = URL.createObjectURL(imageBlob);

        formData.append('image_file', imageBlob, imageName);
        console.log('[BG] POST →', CONFIG.API_URL + '/remove-background');

        const response = await fetch(buildApiUrl('/api/remove-background'), {
            method: 'POST',
            headers: getApiHeaders(activeApiUrl),
            body: formData,
            signal: controller.signal
        });
        clearTimeout(fetchTimeout);
        console.log('[BG] HTTP', response.status);

        if (!response.ok) {
            let errMsg = t('msg_server_error');
            try {
                const j = await response.json();
                if (j.error) errMsg = j.error;
            } catch (_) {}
            throw new Error(errMsg + ' (HTTP ' + response.status + ')');
        }

        const blob = await response.blob();
        console.log('[BG] blob recebido:', blob.size, 'bytes,', blob.type);
        if (!blob.size) throw new Error('Servidor retornou imagem vazia');
        const url = URL.createObjectURL(blob);

        clearInterval(ramp);
        fill.style.width = '100%';

        currentResultObj = new Image();
        currentResultObj.onload = () => {
            canvas.width = currentResultObj.width;
            canvas.height = currentResultObj.height;
            resetCanvas();
            document.getElementById('result-panel').classList.remove('hidden');
            document.getElementById('preview-container').classList.add('hidden');
            setEditorZoom(1, { preserveCenter: false });
            showToast(t('msg_result_ready'), 'success', 5000);
            console.log('[BG] OK ✓');
        };
        currentResultObj.onerror = () => {
            console.error('[BG] imagem retornada inválida');
            showToast(t('msg_result_invalid_image'), 'error', 6000);
        };
        currentResultObj.src = url;

        saveToHistory(blob).catch(e => console.error('[BG] save history:', e));
        deductCredits().catch(e => console.error('[BG] deduct credits:', e));

    } catch (err) {
        clearTimeout(fetchTimeout);
        console.error('[BG] ERRO:', err);
        let userMsg = err.message || t('msg_server_error');
        if (err.name === 'AbortError') {
            userMsg = formatT('msg_bg_timeout', { seconds: Math.round(requestTimeoutMs / 1000) });
        } else if (err.message && err.message.includes('Failed to fetch')) {
            userMsg = t('msg_bg_connection_failed');
        } else if (err.message && (err.message.includes('BrokenPipeError') || err.message.includes('Connection broken'))) {
            userMsg = t('msg_bg_temp_fail');
        }
        showToast(userMsg, 'error', 7000);
    } finally {
        clearTimeout(fetchTimeout);
        clearInterval(ramp);
        btn.disabled = false;
        setTimeout(() => {
            status.classList.add('hidden');
            fill.style.width = '0%';
        }, 500);
    }
}

async function saveToHistory(blob) {
    if (!currentUser) return;
    const fileName = `${currentUser.id}/${Date.now()}.png`;

    const { error: upErr } = await supabaseClient.storage
        .from('imagens')
        .upload(fileName, blob, { contentType: 'image/png' });

    if (upErr) {
        console.error('Storage error:', upErr);
        return;
    }

    const { data: { publicUrl } } = supabaseClient.storage
        .from('imagens')
        .getPublicUrl(fileName);

    const { error: insErr } = await supabaseClient.from('historico').insert({
        user_id: currentUser.id,
        ferramenta: 'remove-background',
        resultado_url: publicUrl
    });

    if (insErr) console.error('Insert history error:', insErr);

    loadHistory();
}

async function deductCredits() {
    if (!currentUser) return;
    const newCredits = Math.max(0, currentCredits - CONFIG.CUSTO_REMOVER_FUNDO);
    const { error } = await supabaseClient
        .from('profiles')
        .update({ creditos: newCredits })
        .eq('id', currentUser.id);
    if (error) {
        console.error('Deduct error:', error);
        return;
    }
    currentCredits = newCredits;
    renderCredits();
}

async function loadHistory() {
    if (!currentUser) return;
    try {
        const { data, error } = await supabaseClient
            .from('historico')
            .select('*')
            .eq('user_id', currentUser.id)
            .order('criado_em', { ascending: false });

        if (error) throw error;

        const grid = document.getElementById('history-grid');
        const countEl = document.getElementById('stat-history-count');

        if (!data || data.length === 0) {
            grid.innerHTML = `<p style="color: var(--text-secondary); font-size: 14px;">${t('msg_history_empty')}</p>`;
            countEl.innerText = '0';
            return;
        }

        grid.innerHTML = data.map(item => `
            <div class="history-item">
                <img src="${item.resultado_url}" class="history-img" loading="lazy" alt="">
                <div style="padding: 10px;">
                    <p style="font-size: 11px; color: var(--text-secondary);">${new Date(item.criado_em).toLocaleDateString()}</p>
                </div>
            </div>
        `).join('');

        countEl.innerText = data.length;
    } catch (err) {
        console.error('History error:', err);
    }
}

function downloadResult() {
    if(!canvas) return;
    const link = document.createElement('a');
    link.href = canvas.toDataURL('image/png');
    link.download = 'pixelai-result-edited.png';
    document.body.appendChild(link);
    link.click();
    link.remove();
}