Bin
2025-12-17 d616898802dfe7e5dd648bcf53c6d1f86b6d3642
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
import type Konva from "konva";
import { useState, useRef, forwardRef, useImperativeHandle, useEffect, useMemo, useCallback } from "react";
import { Group, Shape } from "react-konva";
import {
  ControlPoints,
  GhostLine,
  GhostPoint,
  type GhostPointRef,
  VectorPoints,
  VectorShape,
  VectorTransformer,
  ProxyNodes,
} from "./components";
import { createEventHandlers } from "./eventHandlers";
import { convertPoint } from "./pointManagement";
import { normalizePoints, convertBezierToSimplePoints, isPointInPolygon } from "./utils";
import { findClosestPointOnPath, getDistance, snapToPixel } from "./eventHandlers/utils";
import { constrainAnchorPointsToBounds, constrainPointToBounds } from "./utils/boundsChecking";
import { stageToImageCoordinates } from "./eventHandlers/utils";
import { PointCreationManager } from "./pointCreationManager";
import { VectorSelectionTracker, type VectorInstance } from "./VectorSelectionTracker";
import { calculateShapeBoundingBox } from "./utils/bezierBoundingBox";
import {
  shouldClosePathOnPointClick,
  isActivePointEligibleForClosing,
  handlePointDeselection,
  handlePointSelection,
} from "./eventHandlers/pointSelection";
import { handlePointSelectionFromIndex } from "./eventHandlers/mouseHandlers";
import { handleShiftClickPointConversion } from "./eventHandlers/drawing";
import { deletePoint } from "./pointManagement";
import type { BezierPoint, GhostPoint as GhostPointType, KonvaVectorProps, KonvaVectorRef } from "./types";
import { ShapeType, ExportFormat, PathType } from "./types";
import {
  INSTANCE_ID_PREFIX,
  INSTANCE_ID_LENGTH,
  DEFAULT_TRANSFORM,
  DEFAULT_FIT_SCALE,
  DEFAULT_TRANSFORMER_STATE,
  DEFAULT_STROKE_COLOR,
  DEFAULT_FILL_COLOR,
  DEFAULT_POINT_FILL,
  DEFAULT_POINT_STROKE,
  DEFAULT_POINT_STROKE_SELECTED,
  DEFAULT_POINT_STROKE_WIDTH,
  HIT_RADIUS,
  TRANSFORMER_SETUP_DELAY,
  TRANSFORMER_CLEAR_DELAY,
  MIN_POINTS_FOR_CLOSING,
  MIN_POINTS_FOR_BEZIER_CLOSING,
  INVISIBLE_SHAPE_OPACITY,
  DEGREES_TO_RADIANS,
  DEFAULT_SCALE,
  DEFAULT_OFFSET,
  DEFAULT_CALLBACK_TIME,
  ARRAY_INDEX,
  SELECTION_SIZE,
  CENTER_CALCULATION_DIVISOR,
} from "./constants";
 
/**
 * **KonvaVector Component** - Advanced vector graphics editor with bezier curve support
 *
 * A comprehensive React component for creating and editing polylines and polygons with support for:
 * - **Dual Point Formats**: Simple `[[x,y],...]` or complex `{x,y,isBezier,...}` formats
 * - **Bezier Curves**: Create smooth curves with control points and conversion between regular/bezier points
 * - **Interactive Editing**: Point selection, dragging, multi-selection with transformer
 * - **Drawing Modes**: Click-to-add points, drag-to-create bezier curves, ghost point insertion
 * - **Path Management**: Open polylines or closed polygons with configurable constraints
 * - **Export Formats**: Export as simple coordinates or detailed format with bezier information
 *
 * ## Key Features
 *
 * ### Point Management
 * - **Add Points**: Click in drawing mode, Shift+click on path segments
 * - **Edit Points**: Drag to reposition, Alt+click to convert regular ↔ bezier
 * - **Delete Points**: Alt+click on existing points
 * - **Multi-Selection**: Select multiple points for batch transformations
 * - **Break Closed Path**: Alt+click on any segment of a closed path to break it at that specific segment (array is shifted so breaking point becomes first, point before breaking becomes active)
 *
 * ### Bezier Curves
 * - **Create**: Drag while adding points or convert existing points
 * - **Edit**: Drag control points, disconnect/reconnect control handles
 * - **Control**: `allowBezier` prop to enable/disable bezier functionality
 *
 * ### Interaction Modes
 * - **Drawing Mode**: `isDrawingMode={true}` - Click to add points, drag for bezier curves
 * - **Edit Mode**: `isDrawingMode={false}` - Select, drag, and transform existing points
 * - **Skeleton Mode**: `skeletonEnabled={true}` - Connect points to active point instead of last point
 * - **Disabled Mode**: Point selection still works for keypoint annotation - click to select points, Cmd/Ctrl+click for multi-selection
 *
 * ### Export & Import
 * - **Simple Format**: `[[x,y], [x,y], ...]` - Easy to work with
 * - **Complex Format**: `[{x,y,isBezier,controlPoint1,controlPoint2}, ...]` - Full feature support
 * - **Auto Type Detection**: Exports include `type: ShapeType.POLYGON | ShapeType.POLYLINE` based on `allowClose`
 *
 * ## Usage Examples
 *
 * ### Basic Vector Path
 * ```tsx
 * <KonvaVector
 *   initialPoints={EXAMPLE_COORDINATES.BASIC_PATH}
 *   onPointsChange={setPoints}
 *   isDrawingMode={true}
 *   allowClose={false}
 * />
 * ```
 *
 * ### Polygon with Bezier Support
 * ```tsx
 * <KonvaVector
 *   initialPoints={complexPoints}
 *   onPointsChange={setPoints}
 *   allowClose={true}
 *   allowBezier={true}
 *   minPoints={EXAMPLE_POINT_CONSTRAINTS.MIN_POINTS}
 *   maxPoints={EXAMPLE_POINT_CONSTRAINTS.MAX_POINTS}
 * />
 * ```
 *
 * ### With Export Handling
 * ```tsx
 * <KonvaVector
 *   initialPoints={points}
 *   onPointsChange={setPoints}
 *   format={ExportFormat.SIMPLE}
 *   onTransformationComplete={(data) => {
 
 *   }}
 * />
 * ```
 *
 * ### With Path Breaking
 * ```tsx
 * <KonvaVector
 *   initialPoints={closedPolygonPoints}
 *   onPointsChange={setPoints}
 *   allowClose={true}
 *   closed={true}
 *   // Alt+click on any segment to break the closed path at that specific segment
 *   // The points array is shifted so the breaking point becomes the first element, point before breaking becomes active
 *   onPathClosedChange={(isClosed) => {
 *     console.log('Path closed state:', isClosed);
 *   }}
 * />
 * ```
 *
 * ### With Custom Point Styling
 * ```tsx
 * <KonvaVector
 *   initialPoints={points}
 *   onPointsChange={setPoints}
 *   // Customize point appearance
 *   pointRadius={DEFAULT_POINT_RADIUS}
 *   pointFill={DEFAULT_POINT_FILL}
 *   pointStroke={DEFAULT_POINT_STROKE}
 *   pointStrokeSelected={DEFAULT_POINT_STROKE_SELECTED}
 *   pointStrokeWidth={DEFAULT_POINT_STROKE_WIDTH}
 * />
 * ```
 *
 * ### As Keypoint Annotation Tool
 * ```tsx
 * <KonvaVector
 *   initialPoints={keypoints}
 *   onPointsChange={setKeypoints}
 *   selected={false} // Disable editing but allow selection
 *   allowClose={false} // Keypoints don't form closed paths
 *   allowBezier={false} // Keypoints are simple points
 *   pointRadius={KEYPOINT_POINT_RADIUS}
 *   onPointSelected={(pointIndex) => {
 *     console.log('Selected keypoint:', pointIndex);
 *   }}
 * />
 * ```
 *
 * ## Keyboard Shortcuts
 * - **Alt + Click**: Convert point between regular ↔ bezier
 * - **Alt + Click on segment**: Break closed path at segment (when path is closed)
 * - **Click on first/last point**: Close path bidirectionally (first→last or last→first)
 * - **Shift + Click**: Add point on path segment
 * - **Shift + Drag**: Create bezier point with control handles
 *
 * ## Props Overview
 * - `initialPoints`: Points in simple or complex format
 * - `allowBezier`: Enable/disable bezier curve functionality
 * - `allowClose`: Allow path to be closed into polygon
 * - `isDrawingMode`: Enable point addition mode
 * - `skeletonEnabled`: Connect new points to active point
 * - `format`: Export format (`ExportFormat.SIMPLE` | `ExportFormat.REGULAR`)
 * - `minPoints`/`maxPoints`: Point count constraints
 * - `stroke`/`fill`: Path styling colors
 * - `pointRadius`: Configurable point sizes for enabled/disabled states
 * - `pointFill`/`pointStroke`/`pointStrokeSelected`: Point styling colors
 * - `pointStrokeWidth`: Point stroke width
 * - Event handlers for all point operations
 *
 * @component
 * @example
 * ```tsx
 * // Simple usage
 * <KonvaVector
 *   initialPoints={EXAMPLE_COORDINATES.SIMPLE_PATH}
 *   onPointsChange={handlePointsChange}
 *   allowBezier={true}
 *   allowClose={false}
 * />
 * ```
 */
export const KonvaVector = forwardRef<KonvaVectorRef, KonvaVectorProps>((props, ref) => {
  // Generate unique instance ID
  const instanceId = useMemo(
    () => `${INSTANCE_ID_PREFIX}${Math.random().toString(36).substr(2, INSTANCE_ID_LENGTH)}`,
    [],
  );
 
  // Flag to track programmatic selection to prevent infinite loops
  const isProgrammaticSelection = useRef(false);
 
  const {
    initialPoints: rawInitialPoints = [],
    onPointsChange,
    onPointAdded,
    onPointRemoved,
    onPointEdited,
    onPointRepositioned,
    onPointConverted,
    onPathShapeChanged,
    onPathClosedChange,
    onTransformationComplete,
    onPointSelected,
    onFinish,
    onGhostPointClick,
    scaleX,
    scaleY,
    x,
    y,
    imageSmoothingEnabled = false,
    transform = DEFAULT_TRANSFORM,
    fitScale = DEFAULT_FIT_SCALE,
    width,
    height,
    onMouseDown,
    onMouseMove,
    onMouseUp,
    onClick,
    onDblClick,
    onTransformStart,
    onTransformEnd,
    onMouseEnter,
    onMouseLeave,
    allowClose = false,
    closed,
    allowBezier = true,
    minPoints,
    maxPoints,
    skeletonEnabled = false,
    format = ExportFormat.REGULAR,
    stroke = DEFAULT_STROKE_COLOR,
    fill = DEFAULT_FILL_COLOR,
    pixelSnapping = false,
    selected = true,
    disabled = false,
    transformMode = false,
    isMultiRegionSelected = false,
    disableInternalPointAddition = false,
    disableGhostLine = false,
    pointRadius,
    pointFill = DEFAULT_POINT_FILL,
    pointStroke = DEFAULT_POINT_STROKE,
    pointStrokeSelected = DEFAULT_POINT_STROKE_SELECTED,
    pointStrokeWidth = DEFAULT_POINT_STROKE_WIDTH,
  } = props;
 
  // Normalize input points to BezierPoint format
  const [initialPoints, setInitialPoints] = useState(() => normalizePoints(rawInitialPoints));
 
  // Ref to track current points for immediate access during transformation
  // This ensures applyTransformationToPoints always uses the latest points
  const currentPointsRef = useRef<BezierPoint[]>(initialPoints);
 
  // Ref to store updatePoints function to ensure it's accessible in closures
  const updatePointsRef = useRef<((points: BezierPoint[]) => void) | null>(null);
 
  // Update ref whenever initialPoints state changes
  useEffect(() => {
    currentPointsRef.current = initialPoints;
  }, [initialPoints]);
 
  // Ref to track if we're updating points internally to prevent infinite loops
  const isInternalUpdateRef = useRef(false);
  // Ref to track the last normalized points to prevent unnecessary updates
  const lastNormalizedPointsRef = useRef<BezierPoint[]>(initialPoints);
  // Ref to track the last points we sent to parent to detect circular updates
  const lastSentToParentRef = useRef<BezierPoint[] | null>(null);
 
  // Helper function to compare points by their actual data (ignoring IDs)
  const arePointsEqual = useCallback((points1: BezierPoint[], points2: BezierPoint[]): boolean => {
    if (points1.length !== points2.length) return false;
 
    for (let i = 0; i < points1.length; i++) {
      const p1 = points1[i];
      const p2 = points2[i];
 
      if (
        p1.x !== p2.x ||
        p1.y !== p2.y ||
        p1.isBezier !== p2.isBezier ||
        p1.disconnected !== p2.disconnected ||
        p1.isBranching !== p2.isBranching
      ) {
        return false;
      }
 
      // Compare control points if bezier
      if (p1.isBezier) {
        if (!!p1.controlPoint1 !== !!p2.controlPoint1) return false;
        if (!!p1.controlPoint2 !== !!p2.controlPoint2) return false;
 
        if (p1.controlPoint1 && p2.controlPoint1) {
          if (p1.controlPoint1.x !== p2.controlPoint1.x || p1.controlPoint1.y !== p2.controlPoint1.y) {
            return false;
          }
        }
 
        if (p1.controlPoint2 && p2.controlPoint2) {
          if (p1.controlPoint2.x !== p2.controlPoint2.x || p1.controlPoint2.y !== p2.controlPoint2.y) {
            return false;
          }
        }
      }
    }
 
    return true;
  }, []);
 
  // Update initialPoints when rawInitialPoints changes (only if different)
  useEffect(() => {
    // Skip if this is an internal update
    if (isInternalUpdateRef.current) {
      return;
    }
 
    const normalized = normalizePoints(rawInitialPoints);
 
    // Skip if this matches what we just sent to parent (circular update prevention)
    if (lastSentToParentRef.current && arePointsEqual(lastSentToParentRef.current, normalized)) {
      lastSentToParentRef.current = null; // Clear after handling
      return;
    }
 
    // Only update if points actually changed (compare by data, not IDs)
    if (!arePointsEqual(lastNormalizedPointsRef.current, normalized)) {
      lastNormalizedPointsRef.current = normalized;
      setInitialPoints(normalized);
    }
  }, [rawInitialPoints, arePointsEqual]);
 
  // Initialize lastAddedPointId and activePointId when component loads with existing points
  useEffect(() => {
    if (initialPoints.length > 0) {
      const lastPoint = initialPoints[initialPoints.length - 1];
      setLastAddedPointId(lastPoint.id);
      // Only set activePointId if skeleton mode is enabled
      if (skeletonEnabled) {
        setActivePointId(lastPoint.id);
      }
    }
  }, [initialPoints.length, skeletonEnabled]); // Only run when the number of points changes or skeleton mode changes
 
  // Use initialPoints directly - this will update when the parent re-renders
  const [selectedPointIndex, setSelectedPointIndex] = useState<number | null>(null);
  const [selectedPoints, setSelectedPoints] = useState<Set<number>>(new Set());
 
  // Compute effective selected points - when transformMode is true, all points are selected
  const effectiveSelectedPoints = useMemo(() => {
    if (transformMode && initialPoints.length > 0) {
      return new Set(Array.from({ length: initialPoints.length }, (_, i) => i));
    }
    return selectedPoints;
  }, [transformMode, initialPoints.length, selectedPoints]);
  const [lastAddedPointId, setLastAddedPointId] = useState<string | null>(null);
 
  const transformerRef = useRef<Konva.Transformer>(null);
  const stageRef = useRef<Konva.Layer>(null);
  const pointRefs = useRef<{ [key: number]: Konva.Circle | null }>({});
  const proxyRefs = useRef<{ [key: number]: Konva.Circle | null }>({});
  // Store transformer state to preserve rotation, scale, and center when updating selection
  const transformerStateRef = useRef<{
    rotation: number;
    scaleX: number;
    scaleY: number;
    centerX: number;
    centerY: number;
  }>(DEFAULT_TRANSFORMER_STATE);
 
  // Handle Shift key state
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.shiftKey) {
        setIsShiftKeyHeld(true);
        setIsDisconnectedMode(true);
        // Recalculate ghost point when Shift is pressed
        // Use a small delay to ensure state is updated
        setTimeout(() => {
          if (calculateGhostPointRef.current) {
            // Pass true for shiftKeyState since Shift is being pressed
            calculateGhostPointRef.current(true);
          }
        }, 0);
      }
    };
 
    const handleKeyUp = (e: KeyboardEvent) => {
      if (!e.shiftKey) {
        setIsShiftKeyHeld(false);
        setIsDisconnectedMode(false);
        // Clear ghost point when Shift is released
        setGhostPoint(null);
      }
    };
 
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);
 
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("keyup", handleKeyUp);
    };
  }, []);
 
  const [draggedPointIndex, setDraggedPointIndex] = useState<number | null>(null);
  const [isShiftKeyHeld, setIsShiftKeyHeld] = useState(false);
  const [draggedControlPoint, setDraggedControlPoint] = useState<{
    pointIndex: number;
    controlIndex: number;
  } | null>(null);
  const [isDraggingShape, setIsDraggingShape] = useState(false);
  const shapeDragStartPos = useRef<{ x: number; y: number; imageX: number; imageY: number } | null>(null);
  const originalPointsPositions = useRef<
    Array<{ x: number; y: number; controlPoint1?: { x: number; y: number }; controlPoint2?: { x: number; y: number } }>
  >([]);
  const justFinishedShapeDrag = useRef(false);
  const shapeDragDistance = useRef(0);
  const [isDisconnectedMode, setIsDisconnectedMode] = useState(false);
  const [ghostPoint, setGhostPoint] = useState<GhostPointType | null>(null);
 
  // Clear ghost point when conditions change that should hide it
  useEffect(() => {
    // Clear ghost point when:
    // - Shape is disabled
    // - Shape is not selected
    // - Max points reached
    // Note: Shift key release is handled in handleKeyUp, not here
    if (disabled || !selected || (maxPoints !== undefined && initialPoints.length >= maxPoints)) {
      setGhostPoint(null);
    }
  }, [disabled, selected, maxPoints, initialPoints.length]);
 
  const [_newPointDragIndex, setNewPointDragIndex] = useState<number | null>(null);
  const [isDraggingNewBezier, setIsDraggingNewBezier] = useState(false);
  const [ghostPointDragInfo, setGhostPointDragInfo] = useState<{
    ghostPoint: GhostPointType;
    isDragging: boolean;
    dragDistance: number;
  } | null>(null);
 
  const cursorPositionRef = useRef<{
    x: number;
    y: number;
  } | null>(null);
  const ghostLineRafRef = useRef<number | null>(null);
  const lastCallbackTime = useRef<number>(DEFAULT_CALLBACK_TIME);
  const [visibleControlPoints, setVisibleControlPoints] = useState<Set<number>>(new Set());
  const [activePointId, setActivePointId] = useState<string | null>(null);
  const [isTransforming, setIsTransforming] = useState(false);
 
  // Flag to track if point selection was handled in VectorPoints onClick
  const pointSelectionHandled = useRef(false);
 
  // Ref to track the _transformable group for applying transformations
  const transformableGroupRef = useRef<Konva.Group>(null);
 
  // Ref to track click timeout for click/double-click debouncing
  const clickTimeoutRef = useRef<number | null>(null);
 
  // Flag to track if we've handled a double-click through debouncing
  const doubleClickHandledRef = useRef(false);
 
  // Track if we're currently transforming to avoid duplicate onTransformStart calls
  const isTransformingRef = useRef(false);
 
  // Helper function to call onTransformStart (only if not already transforming)
  const handleTransformStart = useCallback(() => {
    if (!isTransformingRef.current) {
      isTransformingRef.current = true;
      // Always call onTransformStart if provided, even if called multiple times
      // The flag prevents duplicate calls, but we ensure it's called at least once
      onTransformStart?.();
    }
  }, [onTransformStart]);
 
  // Helper function to call onTransformEnd (only if currently transforming)
  const handleTransformEnd = useCallback(
    (e?: Konva.KonvaEventObject<MouseEvent>) => {
      // Always reset the flag if we were transforming
      // This ensures we don't get stuck in a transforming state
      if (isTransformingRef.current) {
        isTransformingRef.current = false;
        // Always call onTransformEnd if provided to ensure history is unfrozen
        onTransformEnd?.(e);
      }
    },
    [onTransformEnd],
  );
 
  // Track initial transform state for delta calculation
  const initialTransformRef = useRef<{
    x: number;
    y: number;
    scaleX: number;
    scaleY: number;
    rotation: number;
  } | null>(null);
 
  // Define commitMultiRegionTransform as a useCallback so we can use it in both useImperativeHandle and onDragEnd
  const commitMultiRegionTransform = useCallback(() => {
    if (!isMultiRegionSelected || !transformableGroupRef.current || !initialTransformRef.current) {
      return;
    }
 
    // Get the _transformable group
    const transformableGroup = transformableGroupRef.current;
 
    // Get the group's current transform values
    const currentX = transformableGroup.x();
    const currentY = transformableGroup.y();
    const currentScaleX = transformableGroup.scaleX();
    const currentScaleY = transformableGroup.scaleY();
    const currentRotation = transformableGroup.rotation();
 
    // Calculate deltas from initial state
    const initial = initialTransformRef.current;
    const dx = currentX - initial.x;
    const dy = currentY - initial.y;
    const scaleX = currentScaleX / initial.scaleX;
    const scaleY = currentScaleY / initial.scaleY;
    const rotation = currentRotation - initial.rotation;
 
    // Apply constraints to the transform before committing
    const imageWidth = width || 0;
    const imageHeight = height || 0;
 
    let constrainedDx = dx;
    let constrainedDy = dy;
    const constrainedScaleX = scaleX;
    const constrainedScaleY = scaleY;
 
    if (imageWidth > 0 && imageHeight > 0) {
      // Calculate bounding box of current points after transform
      const xs = initialPoints.map((p) => p.x);
      const ys = initialPoints.map((p) => p.y);
      const minX = Math.min(...xs);
      const maxX = Math.max(...xs);
      const minY = Math.min(...ys);
      const maxY = Math.max(...ys);
 
      // Apply scale and position to get new bounds
      const scaledMinX = minX * scaleX + dx;
      const scaledMaxX = maxX * scaleX + dx;
      const scaledMinY = minY * scaleY + dy;
      const scaledMaxY = maxY * scaleY + dy;
 
      // Apply constraints
      if (scaledMinX < 0) constrainedDx = dx - scaledMinX;
      if (scaledMaxX > imageWidth) constrainedDx = dx - (scaledMaxX - imageWidth);
      if (scaledMinY < 0) constrainedDy = dy - scaledMinY;
      if (scaledMaxY > imageHeight) constrainedDy = dy - (scaledMaxY - imageHeight);
    }
 
    // Apply the transformation exactly as the single-region onTransformEnd handler does:
    // 1. Scale around origin (0,0)
    // 2. Rotate around origin (0,0)
    // 3. Translate by (constrainedDx, constrainedDy)
    const radians = rotation * (Math.PI / 180);
    const cos = Math.cos(radians);
    const sin = Math.sin(radians);
 
    const transformedVertices = initialPoints.map((point) => {
      // Step 1: Scale
      const x = point.x * constrainedScaleX;
      const y = point.y * constrainedScaleY;
 
      // Step 2: Rotate
      const rx = x * cos - y * sin;
      const ry = x * sin + y * cos;
 
      // Step 3: Translate and clamp to image bounds
      const translatedPos = {
        x: Math.max(0, Math.min(imageWidth, rx + constrainedDx)),
        y: Math.max(0, Math.min(imageHeight, ry + constrainedDy)),
      };
      // Apply pixel snapping if enabled
      const snappedPos = snapToPixel(translatedPos, pixelSnapping);
      const result = {
        ...point,
        x: snappedPos.x,
        y: snappedPos.y,
      };
 
      // Transform control points if bezier
      if (point.isBezier) {
        if (point.controlPoint1) {
          const cp1x = point.controlPoint1.x * constrainedScaleX;
          const cp1y = point.controlPoint1.y * constrainedScaleY;
          const cp1rx = cp1x * cos - cp1y * sin;
          const cp1ry = cp1x * sin + cp1y * cos;
          const cp1Translated = {
            x: Math.max(0, Math.min(imageWidth, cp1rx + constrainedDx)),
            y: Math.max(0, Math.min(imageHeight, cp1ry + constrainedDy)),
          };
          result.controlPoint1 = snapToPixel(cp1Translated, pixelSnapping);
        }
        if (point.controlPoint2) {
          const cp2x = point.controlPoint2.x * constrainedScaleX;
          const cp2y = point.controlPoint2.y * constrainedScaleY;
          const cp2rx = cp2x * cos - cp2y * sin;
          const cp2ry = cp2x * sin + cp2y * cos;
          const cp2Translated = {
            x: Math.max(0, Math.min(imageWidth, cp2rx + constrainedDx)),
            y: Math.max(0, Math.min(imageHeight, cp2ry + constrainedDy)),
          };
          result.controlPoint2 = snapToPixel(cp2Translated, pixelSnapping);
        }
      }
 
      return result;
    });
 
    // Update the points
    onPointsChange?.(transformedVertices);
 
    // Reset the _transformable group transform to identity
    // This ensures the visual representation matches the committed data
    transformableGroup.x(0);
    transformableGroup.y(0);
    transformableGroup.scaleX(1);
    transformableGroup.scaleY(1);
    transformableGroup.rotation(0);
 
    // Update the initial transform state to reflect the reset
    initialTransformRef.current = {
      x: 0,
      y: 0,
      scaleX: 1,
      scaleY: 1,
      rotation: 0,
    };
 
    // Detach and reattach the transformer to prevent resizing issues
    // BUT: Delay this when multiple regions are selected to allow other regions'
    // onTransformEnd handlers to fire first (e.g., PolygonRegion's Line onTransformEnd)
    const stage = transformableGroup.getStage();
    if (stage) {
      const transformer = stage.findOne("Transformer") as Konva.Transformer | undefined;
      if (transformer) {
        // Check if there are multiple nodes attached (multiple regions selected)
        const nodes = transformer.nodes();
        const hasMultipleRegions = nodes.length > 1;
 
        // If multiple regions, delay the detach/reattach to allow other onTransformEnd handlers to fire
        const delay = hasMultipleRegions ? 50 : 0;
 
        setTimeout(() => {
          // Temporarily detach the transformer
          transformer.nodes([]);
 
          // Force a redraw
          stage.batchDraw();
 
          // Reattach the transformer after a brief delay
          setTimeout(() => {
            transformer.nodes(nodes);
            stage.batchDraw();
          }, 0);
        }, delay);
      }
    }
  }, [isMultiRegionSelected, initialPoints, width, height, onPointsChange]);
 
  // Capture initial transform state when group is created
  useEffect(() => {
    if (isMultiRegionSelected && transformableGroupRef.current && !initialTransformRef.current) {
      const group = transformableGroupRef.current;
      initialTransformRef.current = {
        x: group.x(),
        y: group.y(),
        scaleX: group.scaleX(),
        scaleY: group.scaleY(),
        rotation: group.rotation(),
      };
    } else if (!isMultiRegionSelected) {
      // Reset when not in multi-region mode
      initialTransformRef.current = null;
    }
  }, [isMultiRegionSelected]);
 
  // Initialize PointCreationManager instance
  const pointCreationManager = useMemo(() => new PointCreationManager(), []);
 
  // Initialize VectorSelectionTracker
  const tracker = useMemo(() => VectorSelectionTracker.getInstance(), []);
 
  // Compute if path is closed based on point references
  // A path is closed if the first point's prevPointId points to the last point
  const isPathClosed = useMemo(() => {
    if (!allowClose || initialPoints.length < 2) {
      return false;
    }
 
    const firstPoint = initialPoints[0];
    const lastPoint = initialPoints[initialPoints.length - 1];
 
    // Path is closed if the first point's prevPointId points to the last point
    return firstPoint.prevPointId === lastPoint.id;
  }, [allowClose, initialPoints]);
 
  // Use external closed prop when provided, otherwise use computed value
  const finalIsPathClosed = allowClose && closed !== undefined ? closed : isPathClosed;
 
  // Debug logging for path closure state
  useEffect(() => {
    if (allowClose && initialPoints.length >= 2) {
      const firstPoint = initialPoints[0];
      const lastPoint = initialPoints[initialPoints.length - 1];
    }
  }, [allowClose, initialPoints, isPathClosed, finalIsPathClosed]);
 
  // Setter for path closed state - used when path is closed/opened programmatically
  const setIsPathClosed = useCallback(
    (closed: boolean) => {
      if (allowClose) {
        // Always notify parent when path closure state changes programmatically
        onPathClosedChange?.(closed);
      }
    },
    [allowClose, onPathClosedChange],
  );
 
  const isDragging = useRef(false);
  const [stageReadyRetry, setStageReadyRetry] = useState(0);
  const calculateGhostPointRef = useRef<
    ((shiftKeyState?: boolean, eventPos?: { x: number; y: number }) => void) | null
  >(null);
  const ghostPointRef = useRef<GhostPointRef | null>(null);
 
  // Ref to prevent effect from running multiple times
  const handlersAttachedRef = useRef(false);
 
  // Refs to access current values in event handlers without recreating them
  const currentValuesRef = useRef({
    initialPoints,
    effectiveSelectedPoints,
    allowClose,
    finalIsPathClosed,
    pixelSnapping,
    isDraggingNewBezier,
    ghostPointDragInfo,
    draggedPointIndex,
    draggedControlPoint,
    isDraggingShape,
    instanceId,
    transform,
    fitScale,
    x,
    y,
    width,
    height,
    skeletonEnabled,
    activePointId,
    lastAddedPointId,
    selected,
    disabled,
    onFinish,
    isShiftKeyHeld,
  });
 
  // Update refs on every render
  currentValuesRef.current = {
    initialPoints,
    effectiveSelectedPoints,
    allowClose,
    finalIsPathClosed,
    pixelSnapping,
    isDraggingNewBezier,
    ghostPointDragInfo,
    draggedPointIndex,
    draggedControlPoint,
    isDraggingShape,
    instanceId,
    transform,
    fitScale,
    x,
    y,
    width,
    height,
    skeletonEnabled,
    activePointId,
    lastAddedPointId,
    selected,
    disabled,
    onFinish,
    isShiftKeyHeld,
  };
 
  // Determine if drawing should be disabled based on current interaction context
  const isDrawingDisabled = () => {
    // Disable all interactions when disabled prop is true
    // Disable all interactions when selected prop is false
    // Disable drawing when Shift is held (for Shift+click functionality)
    // Disable drawing when multiple points are selected or when in transform mode
    if (
      disabled ||
      !selected ||
      isShiftKeyHeld ||
      effectiveSelectedPoints.size > SELECTION_SIZE.MULTI_SELECTION_MIN ||
      transformMode
    ) {
      return true;
    }
 
    // Dynamically check control point hover
    if (cursorPositionRef.current && initialPoints.length > 0) {
      const scale = transform.zoom * fitScale;
      const controlPointHitRadius = HIT_RADIUS.CONTROL_POINT / scale;
 
      for (let i = 0; i < initialPoints.length; i++) {
        const point = initialPoints[i];
        if (point.isBezier) {
          // Check control point 1
          if (point.controlPoint1) {
            const distance = Math.sqrt(
              (cursorPositionRef.current.x - point.controlPoint1.x) ** 2 +
                (cursorPositionRef.current.y - point.controlPoint1.y) ** 2,
            );
            if (distance <= controlPointHitRadius) {
              return true; // Disable drawing when hovering over control points
            }
          }
          // Check control point 2
          if (point.controlPoint2) {
            const distance = Math.sqrt(
              (cursorPositionRef.current.x - point.controlPoint2.x) ** 2 +
                (cursorPositionRef.current.y - point.controlPoint2.y) ** 2,
            );
            if (distance <= controlPointHitRadius) {
              return true; // Disable drawing when hovering over control points
            }
          }
        }
      }
    }
 
    // Dynamically check point hover
    if (cursorPositionRef.current && initialPoints.length > 0) {
      const scale = transform.zoom * fitScale;
      const selectionHitRadius = HIT_RADIUS.SELECTION / scale;
 
      for (let i = 0; i < initialPoints.length; i++) {
        const point = initialPoints[i];
        const distance = Math.sqrt(
          (cursorPositionRef.current.x - point.x) ** 2 + (cursorPositionRef.current.y - point.y) ** 2,
        );
        if (distance <= selectionHitRadius) {
          // If exactly one point is selected and this is that point, allow drawing
          if (selectedPoints.size === SELECTION_SIZE.MULTI_SELECTION_MIN && selectedPoints.has(i)) {
            continue; // Don't disable drawing for the selected point
          }
 
          // Don't disable drawing when hovering over the last point in the path
          // (so you can continue drawing from it)
          if (i === initialPoints.length - ARRAY_INDEX.LAST_OFFSET) {
            continue; // Don't disable drawing for the last point
          }
 
          // Don't disable drawing when hovering over the first point if path closing is possible
          // (so you can see the closing indicator)
          if (i === ARRAY_INDEX.FIRST && allowClose && !finalIsPathClosed) {
            continue; // Don't disable drawing for the first point when closing is possible
          }
 
          return true; // Disable drawing when hovering over other points
        }
      }
    }
 
    // Dynamically check segment hover (to hide ghost line when hovering over path segments)
    if (cursorPositionRef.current && initialPoints.length >= 2) {
      const scale = transform.zoom * fitScale;
      const segmentHitRadius = HIT_RADIUS.SEGMENT / scale; // Slightly larger than point hit radius
 
      // Use the same logic as findClosestPointOnPath for consistent Bezier curve detection
      const closestPathPoint = findClosestPointOnPath(
        cursorPositionRef.current,
        initialPoints,
        allowClose,
        finalIsPathClosed,
      );
 
      if (closestPathPoint && getDistance(cursorPositionRef.current, closestPathPoint.point) <= segmentHitRadius) {
        return true; // Disable drawing when hovering over segments
      }
    }
 
    return false; // Drawing is enabled
  };
 
  const drawingDisabled = isDrawingDisabled();
 
  // Notify parent when path closure state changes (only when not using external state)
  useEffect(() => {
    if (!(allowClose && closed !== undefined)) {
      onPathClosedChange?.(finalIsPathClosed);
    }
  }, [finalIsPathClosed, closed, allowClose, onPathClosedChange]);
 
  // Handle drawing mode changes
  useEffect(() => {
    if (!drawingDisabled) {
      setVisibleControlPoints(new Set());
    }
  }, [drawingDisabled]);
 
  // Initialize cursor position when points are available or component becomes active
  // This ensures ghost line can render immediately
  useEffect(() => {
    const group = stageRef.current;
    if (!group) return;
 
    const stage = group.getStage();
    if (!stage) return;
 
    // Try to get current mouse position and set cursor position
    const initializeCursorPosition = () => {
      const pos = stage.getPointerPosition();
      if (pos) {
        const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
        // Always update cursor position when points are available (not just when null)
        // This ensures ghost line can render immediately after region selection
        cursorPositionRef.current = imagePos;
        // Trigger a redraw to show ghost line
        if (ghostLineRafRef.current) {
          cancelAnimationFrame(ghostLineRafRef.current);
        }
        ghostLineRafRef.current = requestAnimationFrame(() => {
          stage.batchDraw();
        });
        return true;
      }
      return false;
    };
 
    // Try immediately
    const gotPosition = initializeCursorPosition();
 
    // Only set fallback position if this instance is active/selected and selected
    // Check if this instance is the active one using the tracker
    const isActiveInstance = tracker.getActiveInstanceId() === instanceId;
    const hasSelection = selectedPoints.size > 0 || effectiveSelectedPoints.size > 0;
    const isInstanceSelected = tracker.isInstanceSelected(instanceId);
    // Show ghost line only if not disabled AND selected AND (active OR has selection)
    const shouldShowGhostLine = !disabled && selected && (isActiveInstance || hasSelection || isInstanceSelected);
 
    // If we couldn't get the position and we have points, set a fallback position
    // Use the last point or center of the region as a fallback until mouse moves
    // Only do this for the active/selected instance that is selected
    if (!gotPosition && initialPoints.length > 0 && !cursorPositionRef.current && shouldShowGhostLine) {
      const lastPoint = initialPoints[initialPoints.length - 1];
      // Set cursor position to a small offset from the last point so ghost line is visible
      cursorPositionRef.current = {
        x: lastPoint.x + 50,
        y: lastPoint.y + 50,
      };
      // Trigger a redraw to show ghost line
      if (ghostLineRafRef.current) {
        cancelAnimationFrame(ghostLineRafRef.current);
      }
      ghostLineRafRef.current = requestAnimationFrame(() => {
        stage.batchDraw();
      });
    } else if (!shouldShowGhostLine && cursorPositionRef.current) {
      // Clear cursor position if this instance shouldn't show ghost line
      cursorPositionRef.current = null;
    }
 
    // Also try after a short delay to ensure stage is ready
    const timeout = setTimeout(() => {
      if (!cursorPositionRef.current) {
        initializeCursorPosition();
      }
    }, 0);
 
    // Add a one-time mousemove listener to capture cursor position immediately when mouse moves
    // This ensures we get the position even if getPointerPosition() returns null initially
    const handleOneTimeMouseMove = (e: Konva.KonvaEventObject<MouseEvent>) => {
      const pos = e.target.getStage()?.getPointerPosition();
      if (pos) {
        const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
        cursorPositionRef.current = imagePos;
        // Trigger a redraw to show ghost line
        if (ghostLineRafRef.current) {
          cancelAnimationFrame(ghostLineRafRef.current);
        }
        ghostLineRafRef.current = requestAnimationFrame(() => {
          stage.batchDraw();
        });
        // Remove listener after first capture
        stage.off("mousemove", handleOneTimeMouseMove);
      }
    };
 
    // Add one-time listener
    stage.on("mousemove", handleOneTimeMouseMove);
 
    return () => {
      clearTimeout(timeout);
      stage.off("mousemove", handleOneTimeMouseMove);
    };
  }, [
    initialPoints.length,
    transform,
    fitScale,
    x,
    y,
    selected,
    instanceId,
    selectedPoints.size,
    effectiveSelectedPoints.size,
  ]); // Re-run when points change, transform changes, or selection changes
 
  // Stabilize functions for tracker registration
  const getPoints = useCallback(() => initialPoints, [initialPoints]);
  const updatePoints = useCallback(
    (points: BezierPoint[]) => {
      // Set flag to prevent useEffect from running when we update internally
      isInternalUpdateRef.current = true;
      // Update the ref to track the last normalized points
      lastNormalizedPointsRef.current = points;
      // Update current points ref immediately for transformation callbacks
      currentPointsRef.current = points;
      setInitialPoints(points);
      // Clear flag immediately - it only needs to prevent the current useEffect run
      isInternalUpdateRef.current = false;
      // Track what we're sending to parent to detect circular updates
      lastSentToParentRef.current = points;
      onPointsChange?.(points);
    },
    [onPointsChange],
  );
 
  // Store updatePoints in ref for access in closures
  useEffect(() => {
    updatePointsRef.current = updatePoints;
  }, [updatePoints]);
 
  // Function to update current points ref - used by VectorTransformer during transformation
  const updateCurrentPointsRef = useCallback((points: BezierPoint[]) => {
    currentPointsRef.current = points;
  }, []);
 
  // Function to get current points ref - used by VectorTransformer during transformation
  const getCurrentPointsRef = useCallback(() => {
    return currentPointsRef.current;
  }, []);
  const setSelectedPointsStable = useCallback((selectedPoints: Set<number>) => {
    setSelectedPoints(selectedPoints);
  }, []);
  const setSelectedPointIndexStable = useCallback((index: number | null) => {
    setSelectedPointIndex(index);
  }, []);
  const getTransformStable = useCallback(() => transform, [transform]);
  const getFitScaleStable = useCallback(() => fitScale, [fitScale]);
  const getBoundsStable = useCallback(() => ({ width, height }), [width, height]);
 
  // Wrapper for onPointSelected to prevent infinite loops during programmatic selection
  const onPointSelectedWrapper = useCallback(
    (index: number | null) => {
      if (!isProgrammaticSelection.current && onPointSelected) {
        onPointSelected(index);
      }
    },
    [onPointSelected],
  );
 
  // Register instance with tracker
  useEffect(() => {
    const vectorInstance: VectorInstance = {
      id: instanceId,
      getPoints,
      updatePoints,
      setSelectedPoints: setSelectedPointsStable,
      setSelectedPointIndex: setSelectedPointIndexStable,
      onPointSelected: onPointSelectedWrapper,
      onTransformationComplete,
      getTransform: getTransformStable,
      getFitScale: getFitScaleStable,
      getBounds: getBoundsStable,
    };
 
    tracker.registerInstance(vectorInstance);
 
    return () => {
      tracker.unregisterInstance(instanceId);
    };
  }, [
    instanceId,
    tracker,
    getPoints,
    updatePoints,
    setSelectedPointsStable,
    setSelectedPointIndexStable,
    onPointSelectedWrapper,
    onTransformationComplete,
    getTransformStable,
    getFitScaleStable,
    getBoundsStable,
  ]);
 
  // Clear selection when component is disabled or not selected
  useEffect(() => {
    if (disabled || !selected) {
      setSelectedPointIndex(null);
      setSelectedPoints(new Set());
      setVisibleControlPoints(new Set());
      setDraggedControlPoint(null);
      setGhostPoint(null);
      setGhostPointDragInfo(null);
      setIsDraggingNewBezier(false);
      setNewPointDragIndex(null);
      // Hide all Bezier control points when not selected
      setVisibleControlPoints(new Set());
    }
  }, [selected]);
  const lastPos = useRef<{
    x: number;
    y: number;
    originalX?: number;
    originalY?: number;
    originalControlPoint1?: { x: number; y: number };
    originalControlPoint2?: { x: number; y: number };
  } | null>(null);
 
  // Set up Transformer nodes once when selection changes
  useEffect(() => {
    if (transformerRef.current) {
      if (effectiveSelectedPoints.size > SELECTION_SIZE.MULTI_SELECTION_MIN) {
        // Use setTimeout to ensure proxy nodes are rendered first
        setTimeout(() => {
          if (transformerRef.current) {
            // Set up proxy nodes once - transformer will manage them independently
            // Use getAllPoints() to get the correct proxy nodes for all points
            const allPoints = getAllPoints();
            const nodes = Array.from(effectiveSelectedPoints)
              .map((index) => {
                // Ensure the index is within bounds of all points
                if (index < allPoints.length) {
                  return proxyRefs.current[index];
                }
                return null;
              })
              .filter((node) => node?.getAbsoluteTransform) as Konva.Node[];
 
            if (nodes.length > 0) {
              // Always set the complete set of nodes - transformer will handle positioning
              transformerRef.current.nodes(nodes);
              transformerRef.current.getLayer()?.batchDraw();
            }
          }
        }, TRANSFORMER_SETUP_DELAY);
      } else {
        // Clear transformer when selection is less than minimum points for transformer
        setTimeout(() => {
          if (transformerRef.current) {
            transformerRef.current.nodes([]);
            transformerRef.current.getLayer()?.batchDraw();
          }
        }, TRANSFORMER_CLEAR_DELAY);
      }
    }
  }, [effectiveSelectedPoints]); // Depend on effectiveSelectedPoints to include transform mode
 
  // Note: We don't update proxy node positions during transformation
  // The transformer handles positioning the proxy nodes itself
  // This prevents conflicts and maintains the transformer's rotation state
 
  // Helper function to generate shape data and call transformation complete callback
  const notifyTransformationComplete = () => {
    // Get all points
    const allPoints = getAllPoints();
 
    if (format === ExportFormat.SIMPLE) {
      // Export in simple format
      // For simple format, we need to call a different callback or handle differently
      // since onTransformationComplete expects the complex format
    } else {
      // Export in regular format
      const exportedPoints = allPoints.map((point) => {
        const controlPoints: Array<{ x: number; y: number }> = [];
 
        if (point.isBezier) {
          if (point.controlPoint1) {
            controlPoints.push({
              x: point.controlPoint1.x,
              y: point.controlPoint1.y,
            });
          }
          if (point.controlPoint2) {
            controlPoints.push({
              x: point.controlPoint2.x,
              y: point.controlPoint2.y,
            });
          }
        }
 
        return {
          x: point.x,
          y: point.y,
          bezier: point.isBezier || false,
          controlPoints,
        };
      });
 
      // Check if we have enough points based on minPoints constraint
      const incomplete = minPoints !== undefined && allPoints.length < minPoints;
 
      const shapeData = {
        type: allowClose ? ShapeType.POLYGON : ShapeType.POLYLINE,
        isClosed: finalIsPathClosed,
        points: exportedPoints,
        incomplete,
      };
 
      onTransformationComplete?.(shapeData);
    }
  };
 
  // Helper function to check if we can add more points
  const canAddMorePoints = () => {
    return maxPoints === undefined || initialPoints.length < maxPoints;
  };
 
  // Update PointCreationManager props when relevant props change
  useEffect(() => {
    pointCreationManager.setProps({
      initialPoints,
      allowBezier,
      pixelSnapping,
      width,
      height,
      transform,
      fitScale,
      onPointsChange,
      onPointAdded,
      onPointEdited,
      canAddMorePoints,
      skeletonEnabled,
      lastAddedPointId,
      activePointId,
      setLastAddedPointId,
      setActivePointId,
      setVisibleControlPoints,
      setNewPointDragIndex,
      setIsDraggingNewBezier,
      ghostPoint,
      selectedPoints: effectiveSelectedPoints,
      isShiftKeyHeld,
      setGhostPoint,
    });
  }, [
    pointCreationManager,
    initialPoints,
    effectiveSelectedPoints,
    allowBezier,
    pixelSnapping,
    width,
    height,
    transform,
    fitScale,
    onPointsChange,
    onPointAdded,
    onPointEdited,
    canAddMorePoints,
    skeletonEnabled,
    lastAddedPointId,
    activePointId,
    setLastAddedPointId,
    setActivePointId,
    setVisibleControlPoints,
    setNewPointDragIndex,
    setIsDraggingNewBezier,
    ghostPoint,
    isShiftKeyHeld,
    setGhostPoint,
  ]);
 
  // Helper function to get all points for rendering and interactions
  const getAllPoints = () => {
    return [...initialPoints];
  };
 
  // Helper function to get all line segments for rendering
  const getAllLineSegments = () => {
    const segments: Array<{ from: BezierPoint; to: BezierPoint }> = [];
    const allPoints = getAllPoints();
 
    // In skeleton mode, we need to handle segments differently
    if (skeletonEnabled) {
      // Create a map for quick point lookup
      const pointMap = new Map<string, BezierPoint>();
      for (const point of allPoints) {
        pointMap.set(point.id, point);
      }
 
      // First, add all segments that have explicit prevPointId relationships
      for (const point of allPoints) {
        if (point.prevPointId) {
          const prevPoint = pointMap.get(point.prevPointId);
          if (prevPoint) {
            segments.push({ from: prevPoint, to: point });
          }
        }
      }
 
      // Then, handle points that don't have prevPointId but should be connected
      // These are points that were added but not yet connected to the active point
      const connectedPointIds = new Set<string>();
      segments.forEach((segment) => {
        connectedPointIds.add(segment.from.id);
        connectedPointIds.add(segment.to.id);
      });
 
      // Find points that aren't connected yet
      const unconnectedPoints = allPoints.filter((point) => !connectedPointIds.has(point.id));
 
      if (unconnectedPoints.length > 0 && activePointId) {
        const activePoint = pointMap.get(activePointId);
        if (activePoint) {
          // Connect unconnected points to the active point
          for (const unconnectedPoint of unconnectedPoints) {
            segments.push({ from: activePoint, to: unconnectedPoint });
          }
        }
      }
    } else {
      // Non-skeleton mode: use the original prevPointId logic
      // Create a map for quick point lookup
      const pointMap = new Map<string, BezierPoint>();
      for (const point of allPoints) {
        pointMap.set(point.id, point);
      }
 
      // Find all id-prevPointId pairs and create line segments
      for (const point of allPoints) {
        if (point.prevPointId) {
          const prevPoint = pointMap.get(point.prevPointId);
          if (prevPoint) {
            segments.push({ from: prevPoint, to: point });
          }
        }
      }
    }
 
    // The path closure is now determined by point references
    // If the first point has a prevPointId that references the last point,
    // the closing segment will be created automatically through the prevPointId logic above
    // No need to add an additional closing segment
 
    return segments;
  };
 
  // Helper function to get point info
  const getPointInfo = (globalIndex: number) => {
    if (globalIndex < initialPoints.length) {
      return {
        pathType: PathType.MAIN,
        pathIndex: globalIndex,
        point: initialPoints[globalIndex],
      };
    }
    return null;
  };
 
  // Helper function to update a point by its global index
  const updatePointByGlobalIndex = (globalIndex: number, updatedPoint: BezierPoint) => {
    // Update main path point
    if (globalIndex >= 0 && globalIndex < initialPoints.length) {
      const newPoints = [...initialPoints];
      newPoints[globalIndex] = updatedPoint;
      setInitialPoints(newPoints); // Update internal state
      onPointsChange?.(newPoints);
      return;
    }
  };
 
  // Convert a point between regular and Bezier
  const convertPointHandler = (pointIndex: number) => {
    const pointInfo = getPointInfo(pointIndex);
    if (!pointInfo) {
      return;
    }
 
    const point = pointInfo.point;
 
    if (point.isBezier) {
      // Convert from Bezier to regular
      convertPoint(
        pointInfo.pathIndex,
        initialPoints,
        onPointConverted,
        onPointsChange,
        onPathShapeChanged,
        setVisibleControlPoints,
        visibleControlPoints,
      );
 
      // Hide control points for the converted point
      setVisibleControlPoints((prev) => {
        const newSet = new Set(prev);
        newSet.delete(pointIndex);
        return newSet;
      });
    } else {
      // Check if bezier is allowed
      if (!allowBezier) {
        return;
      }
 
      // Convert from regular to Bezier
      // Don't convert first or last points of main path
      if (pointInfo.pathIndex === 0 || pointInfo.pathIndex === initialPoints.length - 1) {
        return;
      }
 
      convertPoint(
        pointInfo.pathIndex,
        initialPoints,
        onPointConverted,
        onPointsChange,
        onPathShapeChanged,
        setVisibleControlPoints,
        visibleControlPoints,
      );
 
      // Make control points visible for the converted point
      setVisibleControlPoints((prev) => {
        const newSet = new Set(prev);
        newSet.add(pointIndex);
        return newSet;
      });
    }
 
    // Notify transformation complete after point conversion
    notifyTransformationComplete();
  };
 
  // Expose methods through ref
  useImperativeHandle(ref, () => ({
    convertPoint: convertPointHandler,
    close: () => {
      if (!allowClose || initialPoints.length < MIN_POINTS_FOR_CLOSING) {
        return false;
      }
 
      // Check if we can close the path based on point count or bezier points
      const canClosePath = () => {
        // Allow closing if we have more than 2 points
        if (initialPoints.length > MIN_POINTS_FOR_BEZIER_CLOSING) {
          return true;
        }
 
        // Allow closing if we have at least one bezier point
        const hasBezierPoint = initialPoints.some((point) => point.isBezier);
        if (hasBezierPoint) {
          return true;
        }
 
        return false;
      };
 
      if (!canClosePath()) {
        return false;
      }
 
      // Additional validation: ensure we meet the minimum points requirement
      if (minPoints && initialPoints.length < minPoints) {
        return false;
      }
 
      // Check if path is already closed
      if (finalIsPathClosed) {
        return true;
      }
 
      // Close the path by setting the first point's prevPointId to the last point's ID
      const firstPoint = initialPoints[0];
      const lastPoint = initialPoints[initialPoints.length - 1];
 
      const updatedPoints = [...initialPoints];
      updatedPoints[0] = {
        ...firstPoint,
        prevPointId: lastPoint.id,
      };
 
      // Update the points and notify parent
      onPointsChange?.(updatedPoints);
 
      // Update the internal path closed state and notify parent
      setIsPathClosed(true);
 
      return true;
    },
    selectPointsByIds: (pointIds: string[]) => {
      // Check if this instance can have selection
      if (!tracker.canInstanceHaveSelection(instanceId)) {
        return; // Block the selection
      }
 
      // Find the indices of the points with the given IDs
      const selectedIndices = new Set<number>();
      let primarySelectedIndex: number | null = null;
 
      for (let i = 0; i < initialPoints.length; i++) {
        if (pointIds.includes(initialPoints[i].id)) {
          selectedIndices.add(i);
          // Set the first found point as the primary selected point
          if (primarySelectedIndex === null) {
            primarySelectedIndex = i;
          }
        }
      }
 
      // Use tracker for global selection management
      isProgrammaticSelection.current = true;
      tracker.selectPoints(instanceId, selectedIndices);
      setTimeout(() => {
        isProgrammaticSelection.current = false;
      }, 0);
    },
    clearSelection: () => {
      // Use tracker for global selection management
      isProgrammaticSelection.current = true;
      tracker.selectPoints(instanceId, new Set());
      setTimeout(() => {
        isProgrammaticSelection.current = false;
      }, 0);
    },
    getSelectedPointIds: () => {
      const selectedIds: string[] = [];
      selectedPoints.forEach((index) => {
        if (index < initialPoints.length) {
          selectedIds.push(initialPoints[index].id);
        }
      });
      return selectedIds;
    },
    exportShape: () => {
      const exportedPoints = initialPoints.map((point) => {
        const controlPoints: Array<{ x: number; y: number }> = [];
 
        if (point.isBezier) {
          if (point.controlPoint1) {
            controlPoints.push({
              x: point.controlPoint1.x,
              y: point.controlPoint1.y,
            });
          }
          if (point.controlPoint2) {
            controlPoints.push({
              x: point.controlPoint2.x,
              y: point.controlPoint2.y,
            });
          }
        }
 
        return {
          x: point.x,
          y: point.y,
          bezier: point.isBezier || false,
          controlPoints,
        };
      });
 
      // Check if we have enough points based on minPoints constraint
      const incomplete = minPoints !== undefined && initialPoints.length < minPoints;
 
      return {
        type: allowClose ? ShapeType.POLYGON : ShapeType.POLYLINE,
        isClosed: finalIsPathClosed,
        points: exportedPoints,
        incomplete,
      };
    },
    exportSimpleShape: () => {
      const simplePoints = convertBezierToSimplePoints(initialPoints);
 
      // Check if we have enough points based on minPoints constraint
      const incomplete = minPoints !== undefined && initialPoints.length < minPoints;
 
      return {
        type: allowClose ? ShapeType.POLYGON : ShapeType.POLYLINE,
        isClosed: finalIsPathClosed,
        points: simplePoints,
        incomplete,
      };
    },
    // Programmatic point creation methods
    startPoint: (x: number, y: number) => pointCreationManager.startPoint(x, y),
    updatePoint: (x: number, y: number) => pointCreationManager.updatePoint(x, y),
    commitPoint: (x: number, y: number) => pointCreationManager.commitPoint(x, y),
    // Programmatic point transformation methods
    translatePoints: (dx: number, dy: number, pointIds?: string[]) => {
      const pointsToTransform = pointIds ? initialPoints.filter((p) => pointIds.includes(p.id)) : initialPoints;
 
      const updatedPoints = initialPoints.map((point) => {
        if (pointsToTransform.some((p) => p.id === point.id)) {
          const updatedPoint = { ...point };
 
          // Apply translation to main point
          updatedPoint.x += dx;
          updatedPoint.y += dy;
 
          // Apply translation to control points if it's a bezier point
          if (updatedPoint.isBezier) {
            if (updatedPoint.controlPoint1) {
              updatedPoint.controlPoint1 = {
                ...updatedPoint.controlPoint1,
                x: updatedPoint.controlPoint1.x + dx,
                y: updatedPoint.controlPoint1.y + dy,
              };
            }
            if (updatedPoint.controlPoint2) {
              updatedPoint.controlPoint2 = {
                ...updatedPoint.controlPoint2,
                x: updatedPoint.controlPoint2.x + dx,
                y: updatedPoint.controlPoint2.y + dy,
              };
            }
          }
 
          return updatedPoint;
        }
        return point;
      });
 
      onPointsChange?.(updatedPoints);
    },
    rotatePoints: (angle: number, centerX: number, centerY: number, pointIds?: string[]) => {
      const pointsToTransform = pointIds ? initialPoints.filter((p) => pointIds.includes(p.id)) : initialPoints;
 
      // If no point IDs provided, calculate center of the entire shape
      let actualCenterX = centerX;
      let actualCenterY = centerY;
 
      if (!pointIds) {
        // Use the accurate shape bounding box calculation
        const bbox = calculateShapeBoundingBox(initialPoints);
        actualCenterX = (bbox.left + bbox.right) / CENTER_CALCULATION_DIVISOR;
        actualCenterY = (bbox.top + bbox.bottom) / CENTER_CALCULATION_DIVISOR;
      }
 
      const radians = angle * DEGREES_TO_RADIANS;
      const cos = Math.cos(radians);
      const sin = Math.sin(radians);
 
      const updatedPoints = initialPoints.map((point) => {
        if (pointsToTransform.some((p) => p.id === point.id)) {
          const updatedPoint = { ...point };
 
          // Apply rotation to main point
          const dx = updatedPoint.x - actualCenterX;
          const dy = updatedPoint.y - actualCenterY;
          updatedPoint.x = actualCenterX + dx * cos - dy * sin;
          updatedPoint.y = actualCenterY + dx * sin + dy * cos;
 
          // Apply rotation to control points if it's a bezier point
          if (updatedPoint.isBezier) {
            if (updatedPoint.controlPoint1) {
              const cp1Dx = updatedPoint.controlPoint1.x - actualCenterX;
              const cp1Dy = updatedPoint.controlPoint1.y - actualCenterY;
              updatedPoint.controlPoint1 = {
                ...updatedPoint.controlPoint1,
                x: actualCenterX + cp1Dx * cos - cp1Dy * sin,
                y: actualCenterY + cp1Dx * sin + cp1Dy * cos,
              };
            }
            if (updatedPoint.controlPoint2) {
              const cp2Dx = updatedPoint.controlPoint2.x - actualCenterX;
              const cp2Dy = updatedPoint.controlPoint2.y - actualCenterY;
              updatedPoint.controlPoint2 = {
                ...updatedPoint.controlPoint2,
                x: actualCenterX + cp2Dx * cos - cp2Dy * sin,
                y: actualCenterY + cp2Dx * sin + cp2Dy * cos,
              };
            }
          }
 
          return updatedPoint;
        }
        return point;
      });
 
      onPointsChange?.(updatedPoints);
    },
    scalePoints: (scaleX: number, scaleY: number, centerX: number, centerY: number, pointIds?: string[]) => {
      const pointsToTransform = pointIds ? initialPoints.filter((p) => pointIds.includes(p.id)) : initialPoints;
 
      // If no point IDs provided, calculate center of the entire shape
      let actualCenterX = centerX;
      let actualCenterY = centerY;
 
      if (!pointIds) {
        // Use the accurate shape bounding box calculation
        const bbox = calculateShapeBoundingBox(initialPoints);
        actualCenterX = (bbox.left + bbox.right) / CENTER_CALCULATION_DIVISOR;
        actualCenterY = (bbox.top + bbox.bottom) / CENTER_CALCULATION_DIVISOR;
      }
 
      const updatedPoints = initialPoints.map((point) => {
        if (pointsToTransform.some((p) => p.id === point.id)) {
          const updatedPoint = { ...point };
 
          // Apply scaling to main point
          const dx = updatedPoint.x - actualCenterX;
          const dy = updatedPoint.y - actualCenterY;
          updatedPoint.x = actualCenterX + dx * scaleX;
          updatedPoint.y = actualCenterY + dy * scaleY;
 
          // Apply scaling to control points if it's a bezier point
          if (updatedPoint.isBezier) {
            if (updatedPoint.controlPoint1) {
              const cp1Dx = updatedPoint.controlPoint1.x - actualCenterX;
              const cp1Dy = updatedPoint.controlPoint1.y - actualCenterY;
              updatedPoint.controlPoint1 = {
                ...updatedPoint.controlPoint1,
                x: actualCenterX + cp1Dx * scaleX,
                y: actualCenterY + cp1Dy * scaleY,
              };
            }
            if (updatedPoint.controlPoint2) {
              const cp2Dx = updatedPoint.controlPoint2.x - actualCenterX;
              const cp2Dy = updatedPoint.controlPoint2.y - actualCenterY;
              updatedPoint.controlPoint2 = {
                ...updatedPoint.controlPoint2,
                x: actualCenterX + cp2Dx * scaleX,
                y: actualCenterY + cp2Dy * scaleY,
              };
            }
          }
 
          return updatedPoint;
        }
        return point;
      });
 
      onPointsChange?.(updatedPoints);
    },
    transformPoints: (
      transformation: {
        dx?: number;
        dy?: number;
        rotation?: number;
        scaleX?: number;
        scaleY?: number;
        centerX?: number;
        centerY?: number;
      },
      pointIds?: string[],
    ) => {
      const pointsToTransform = pointIds ? initialPoints.filter((p) => pointIds.includes(p.id)) : initialPoints;
 
      // If no point IDs provided and we need center point, calculate center of the entire shape
      let actualCenterX = transformation.centerX;
      let actualCenterY = transformation.centerY;
 
      if (
        !pointIds &&
        (transformation.rotation !== undefined ||
          transformation.scaleX !== undefined ||
          transformation.scaleY !== undefined)
      ) {
        // Use the accurate shape bounding box calculation
        const bbox = calculateShapeBoundingBox(initialPoints);
        actualCenterX = (bbox.left + bbox.right) / CENTER_CALCULATION_DIVISOR;
        actualCenterY = (bbox.top + bbox.bottom) / CENTER_CALCULATION_DIVISOR;
      }
 
      const updatedPoints = initialPoints.map((point) => {
        if (pointsToTransform.some((p) => p.id === point.id)) {
          const updatedPoint = { ...point };
 
          // Apply translation
          if (transformation.dx !== undefined) {
            updatedPoint.x += transformation.dx;
            updatedPoint.y += transformation.dy || DEFAULT_OFFSET;
          }
 
          // Apply rotation and scaling (need center point)
          if (
            (transformation.rotation !== undefined ||
              transformation.scaleX !== undefined ||
              transformation.scaleY !== undefined) &&
            actualCenterX !== undefined &&
            actualCenterY !== undefined
          ) {
            let finalX = updatedPoint.x;
            let finalY = updatedPoint.y;
 
            // Apply scaling
            if (transformation.scaleX !== undefined || transformation.scaleY !== undefined) {
              const scaleX = transformation.scaleX || DEFAULT_SCALE;
              const scaleY = transformation.scaleY || DEFAULT_SCALE;
              const dx = finalX - actualCenterX;
              const dy = finalY - actualCenterY;
              finalX = actualCenterX + dx * scaleX;
              finalY = actualCenterY + dy * scaleY;
            }
 
            // Apply rotation
            if (transformation.rotation !== undefined) {
              const radians = transformation.rotation * DEGREES_TO_RADIANS;
              const cos = Math.cos(radians);
              const sin = Math.sin(radians);
              const dx = finalX - actualCenterX;
              const dy = finalY - actualCenterY;
              finalX = actualCenterX + dx * cos - dy * sin;
              finalY = actualCenterY + dx * sin + dy * cos;
            }
 
            updatedPoint.x = finalX;
            updatedPoint.y = finalY;
          }
 
          // Apply transformations to control points if it's a bezier point
          if (updatedPoint.isBezier) {
            if (updatedPoint.controlPoint1) {
              const cp1 = { ...updatedPoint.controlPoint1 };
 
              // Apply translation
              if (transformation.dx !== undefined) {
                cp1.x += transformation.dx;
                cp1.y += transformation.dy || 0;
              }
 
              // Apply rotation and scaling
              if (
                (transformation.rotation !== undefined ||
                  transformation.scaleX !== undefined ||
                  transformation.scaleY !== undefined) &&
                actualCenterX !== undefined &&
                actualCenterY !== undefined
              ) {
                let finalCp1X = cp1.x;
                let finalCp1Y = cp1.y;
 
                // Apply scaling
                if (transformation.scaleX !== undefined || transformation.scaleY !== undefined) {
                  const scaleX = transformation.scaleX || 1;
                  const scaleY = transformation.scaleY || 1;
                  const dx = finalCp1X - actualCenterX;
                  const dy = finalCp1Y - actualCenterY;
                  finalCp1X = actualCenterX + dx * scaleX;
                  finalCp1Y = actualCenterY + dy * scaleY;
                }
 
                // Apply rotation
                if (transformation.rotation !== undefined) {
                  const radians = transformation.rotation * DEGREES_TO_RADIANS;
                  const cos = Math.cos(radians);
                  const sin = Math.sin(radians);
                  const dx = finalCp1X - actualCenterX;
                  const dy = finalCp1Y - actualCenterY;
                  finalCp1X = actualCenterX + dx * cos - dy * sin;
                  finalCp1Y = actualCenterY + dx * sin + dy * cos;
                }
 
                cp1.x = finalCp1X;
                cp1.y = finalCp1Y;
              }
 
              updatedPoint.controlPoint1 = cp1;
            }
 
            if (updatedPoint.controlPoint2) {
              const cp2 = { ...updatedPoint.controlPoint2 };
 
              // Apply translation
              if (transformation.dx !== undefined) {
                cp2.x += transformation.dx;
                cp2.y += transformation.dy || 0;
              }
 
              // Apply rotation and scaling
              if (
                (transformation.rotation !== undefined ||
                  transformation.scaleX !== undefined ||
                  transformation.scaleY !== undefined) &&
                actualCenterX !== undefined &&
                actualCenterY !== undefined
              ) {
                let finalCp2X = cp2.x;
                let finalCp2Y = cp2.y;
 
                // Apply scaling
                if (transformation.scaleX !== undefined || transformation.scaleY !== undefined) {
                  const scaleX = transformation.scaleX || 1;
                  const scaleY = transformation.scaleY || 1;
                  const dx = finalCp2X - actualCenterX;
                  const dy = finalCp2Y - actualCenterY;
                  finalCp2X = actualCenterX + dx * scaleX;
                  finalCp2Y = actualCenterY + dy * scaleY;
                }
 
                // Apply rotation
                if (transformation.rotation !== undefined) {
                  const radians = transformation.rotation * DEGREES_TO_RADIANS;
                  const cos = Math.cos(radians);
                  const sin = Math.sin(radians);
                  const dx = finalCp2X - actualCenterX;
                  const dy = finalCp2Y - actualCenterY;
                  finalCp2X = actualCenterX + dx * cos - dy * sin;
                  finalCp2Y = actualCenterY + dx * sin + dy * cos;
                }
 
                cp2.x = finalCp2X;
                cp2.y = finalCp2Y;
              }
 
              updatedPoint.controlPoint2 = cp2;
            }
          }
 
          return updatedPoint;
        }
        return point;
      });
 
      onPointsChange?.(updatedPoints);
    },
    // Shape analysis methods
    getShapeBoundingBox: () => {
      return calculateShapeBoundingBox(initialPoints);
    },
    // Hit testing method
    isPointOverShape: (x: number, y: number, hitRadius = 10) => {
      // Convert screen coordinates to image coordinates
      const imageX = (x - transform.offsetX) / (fitScale * transform.zoom);
      const imageY = (y - transform.offsetY) / (fitScale * transform.zoom);
      const point = { x: imageX, y: imageY };
 
      // If no points, return false
      if (initialPoints.length === 0) {
        return false;
      }
 
      // First check if hovering over any individual point (vertices)
      for (const vertex of initialPoints) {
        const distance = getDistance(point, vertex);
        if (distance <= hitRadius / (fitScale * transform.zoom)) {
          return true; // Hovering over a vertex
        }
      }
 
      // For single point, we already checked above, so return false if not hit
      if (initialPoints.length === 1) {
        return false;
      }
 
      // For polylines and polygons, check if point is close to any segment
      const closestPathPoint = findClosestPointOnPath(point, initialPoints, allowClose, finalIsPathClosed);
 
      if (closestPathPoint) {
        const distance = getDistance(point, closestPathPoint.point);
        return distance <= hitRadius / (fitScale * transform.zoom);
      }
 
      // For closed polygons, also check if point is inside the polygon
      if (finalIsPathClosed && initialPoints.length >= 3) {
        return isPointInPolygon(point, initialPoints);
      }
 
      return false;
    },
    // Multi-region transformation method - applies group transform to points
    commitMultiRegionTransform,
    // Delete multiple points by their IDs
    deletePointsByIds: (pointIds: string[]) => {
      if (!pointIds || pointIds.length === 0) return;
 
      // Find indices of points to delete (in reverse order to maintain correct indices)
      const indicesToDelete = pointIds
        .map((id) => initialPoints.findIndex((p) => p.id === id))
        .filter((idx) => idx >= 0)
        .sort((a, b) => b - a); // Sort descending to delete from end to start
 
      if (indicesToDelete.length === 0) return;
 
      // Create a set of deleted point IDs for quick lookup
      const deletedPointIds = new Set(pointIds);
 
      // Delete points one by one in reverse order (from highest index to lowest)
      // This ensures indices remain valid as we delete
      let updatedPoints = [...initialPoints];
      let updatedSelectedPointIndex = selectedPointIndex;
      let updatedLastAddedPointId = lastAddedPointId;
 
      for (const index of indicesToDelete) {
        if (index < 0 || index >= updatedPoints.length) continue;
 
        const deletedPoint = updatedPoints[index];
        const newPoints = [...updatedPoints];
        newPoints.splice(index, 1);
 
        // Reconnect points after deletion (same logic as deletePoint function)
        // For skeleton mode: use deleted point's prevPointId
        for (let i = 0; i < newPoints.length; i++) {
          const point = newPoints[i];
          if (point.prevPointId === deletedPoint.id) {
            let newPrevPointId: string | undefined = deletedPoint.prevPointId;
 
            // Edge cases:
            if (index === 0) {
              // If we deleted the first point, this point becomes the new first point
              newPrevPointId = undefined;
            } else if (!deletedPoint.prevPointId) {
              // If deleted point had no prevPointId (was a root point), this point becomes a root
              newPrevPointId = undefined;
            } else if (deletedPointIds.has(deletedPoint.prevPointId)) {
              // If the previous point is also being deleted, we need to find the next valid ancestor
              // This handles cascading deletions in skeleton mode
              let ancestorId = deletedPoint.prevPointId;
              while (ancestorId && deletedPointIds.has(ancestorId)) {
                const ancestorIndex = updatedPoints.findIndex((p) => p.id === ancestorId);
                if (ancestorIndex >= 0 && ancestorIndex < updatedPoints.length) {
                  ancestorId = updatedPoints[ancestorIndex].prevPointId;
                } else {
                  ancestorId = undefined;
                  break;
                }
              }
              newPrevPointId = ancestorId;
            }
            // Otherwise, use deletedPoint.prevPointId which is correct for both linear and skeleton modes
 
            newPoints[i] = {
              ...point,
              prevPointId: newPrevPointId,
            };
          }
        }
 
        // Update selection state
        if (updatedSelectedPointIndex === index) {
          updatedSelectedPointIndex = null;
          onPointSelected?.(null);
        } else if (updatedSelectedPointIndex !== null && updatedSelectedPointIndex > index) {
          updatedSelectedPointIndex = updatedSelectedPointIndex - 1;
        }
 
        // Handle active point
        if (updatedLastAddedPointId === deletedPoint.id) {
          if (newPoints.length > 0) {
            const newLastPoint = newPoints[newPoints.length - 1];
            updatedLastAddedPointId = newLastPoint.id;
          } else {
            updatedLastAddedPointId = null;
          }
        }
 
        // Update visible control points
        setVisibleControlPoints((prev) => {
          const newSet = new Set(prev);
          newSet.delete(index);
          const adjustedSet = new Set<number>();
          for (const pointIndex of Array.from(newSet)) {
            if (pointIndex > index) {
              adjustedSet.add(pointIndex - 1);
            } else {
              adjustedSet.add(pointIndex);
            }
          }
          return adjustedSet;
        });
 
        onPointRemoved?.(deletedPoint, index);
        updatedPoints = newPoints;
      }
 
      // Clear selection after deleting all selected points
      setSelectedPointIndex(updatedSelectedPointIndex);
      setLastAddedPointId(updatedLastAddedPointId);
      tracker.selectPoints(instanceId, new Set());
      onPointsChange?.(updatedPoints);
    },
  }));
 
  // Ensure commitMultiRegionTransform is called when ImageTransformer's onDragEnd fires
  // ImageTransformer will call applyTransform which calls commitMultiRegionTransform
  // But we also need to ensure the Group position is preserved when selection is cleared
  // by committing the transform before the selection is cleared
  useEffect(() => {
    if (!isMultiRegionSelected && transformableGroupRef.current) {
      // When selection is cleared, commit any pending transform first
      const group = transformableGroupRef.current;
      const currentX = group.x();
      const currentY = group.y();
 
      // If there's a pending transform, commit it before the Group is unmounted/reset
      if ((currentX !== 0 || currentY !== 0) && initialTransformRef.current) {
        commitMultiRegionTransform();
        handleTransformEnd();
      }
    }
  }, [isMultiRegionSelected, commitMultiRegionTransform, handleTransformEnd]);
 
  // Clean up click timeout on unmount
  useEffect(() => {
    return () => {
      if (clickTimeoutRef.current) {
        clearTimeout(clickTimeoutRef.current);
        clickTimeoutRef.current = null;
      }
    };
  }, []);
 
  // Set up stage-level event listeners for cursor position, ghost point, and point dragging
  // This allows these features to work even when the invisible shape is disabled
  useEffect(() => {
    // Prevent running if handlers are already attached
    // This stops the infinite loop caused by state updates triggering re-renders
    if (handlersAttachedRef.current) {
      return () => {}; // Return empty cleanup function
    }
 
    const group = stageRef.current;
    if (!group) {
      // If stageRef is not available yet, try again after a short delay
      const retryTimeout = setTimeout(() => {
        if (!handlersAttachedRef.current) {
          // Force re-run by incrementing retry counter
          setStageReadyRetry((prev) => prev + 1);
        }
      }, 100);
      return () => {
        clearTimeout(retryTimeout);
      };
    }
 
    const stage = group.getStage();
    if (!stage) {
      // If stage is not available yet, try again after a short delay
      const retryTimeout = setTimeout(() => {
        if (!handlersAttachedRef.current) {
          // Force re-run by incrementing retry counter
          setStageReadyRetry((prev) => prev + 1);
        }
      }, 100);
      return () => {
        clearTimeout(retryTimeout);
      };
    }
 
    handlersAttachedRef.current = true;
 
    // Helper function to calculate and set ghost point based on current cursor position
    const calculateGhostPoint = (shiftKeyState?: boolean, eventPos?: { x: number; y: number }) => {
      const group = stageRef.current;
      if (!group) return;
      const stage = group.getStage();
      if (!stage) return;
 
      // Use event position if provided, otherwise fall back to stage.getPointerPosition()
      const pos = eventPos || stage.getPointerPosition();
      if (!pos) return;
 
      const {
        transform,
        fitScale,
        x,
        y,
        width,
        height,
        initialPoints,
        allowClose,
        finalIsPathClosed,
        pixelSnapping,
        isDraggingNewBezier,
        ghostPointDragInfo,
        selected,
        disabled,
        isShiftKeyHeld: refShiftState,
      } = currentValuesRef.current;
 
      if (disabled || !selected || isDragging.current || isDraggingNewBezier || ghostPointDragInfo?.isDragging) {
        return;
      }
 
      const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
 
      // Only process ghost point logic if within bounds
      if (imagePos.x >= 0 && imagePos.x <= width && imagePos.y >= 0 && imagePos.y <= height) {
        // Use provided shiftKeyState or fall back to ref value
        const currentShiftState = shiftKeyState !== undefined ? shiftKeyState : (refShiftState ?? false);
 
        if (initialPoints.length >= 2 && currentShiftState) {
          const scale = transform.zoom * fitScale;
          const hitRadius = HIT_RADIUS.SELECTION / scale;
          let isOverPoint = false;
 
          for (let i = 0; i < initialPoints.length; i++) {
            const point = initialPoints[i];
            const distance = Math.sqrt((imagePos.x - point.x) ** 2 + (imagePos.y - point.y) ** 2);
 
            if (distance <= hitRadius) {
              isOverPoint = true;
              break;
            }
          }
 
          if (isOverPoint) {
            setGhostPoint(null);
          } else {
            const closestPathPoint = findClosestPointOnPath(imagePos, initialPoints, allowClose, finalIsPathClosed);
 
            if (closestPathPoint) {
              const snappedGhostPoint = snapToPixel(closestPathPoint.point, pixelSnapping);
 
              // Always create a new ghost point object to ensure React detects the change
              let newGhostPoint: { x: number; y: number; prevPointId: string; nextPointId: string };
 
              if (closestPathPoint.segmentIndex === initialPoints.length) {
                const lastPoint = initialPoints[initialPoints.length - 1];
                const firstPoint = initialPoints[0];
 
                newGhostPoint = {
                  x: snappedGhostPoint.x,
                  y: snappedGhostPoint.y,
                  prevPointId: lastPoint.id,
                  nextPointId: firstPoint.id,
                };
              } else {
                const currentPoint = initialPoints[closestPathPoint.segmentIndex];
                const prevPoint = currentPoint?.prevPointId
                  ? initialPoints.find((p) => p.id === currentPoint.prevPointId)
                  : null;
 
                if (currentPoint && prevPoint) {
                  newGhostPoint = {
                    x: snappedGhostPoint.x,
                    y: snappedGhostPoint.y,
                    prevPointId: prevPoint.id,
                    nextPointId: currentPoint.id,
                  };
                } else {
                  setGhostPoint(null);
                  return;
                }
              }
 
              // Always update the ghost point with a new object reference
              // This ensures React detects the change and re-renders
              setGhostPoint({ ...newGhostPoint });
 
              // Also update directly via ref for immediate visual update
              if (ghostPointRef.current) {
                ghostPointRef.current.updatePosition(newGhostPoint.x, newGhostPoint.y);
              }
            } else {
              setGhostPoint(null);
            }
          }
        } else {
          setGhostPoint(null);
        }
      } else {
        setGhostPoint(null);
      }
    };
 
    // Store the function in a ref so it can be accessed from handleKeyDown
    calculateGhostPointRef.current = calculateGhostPoint;
 
    // Only set up stage-level dragging when disableInternalPointAddition is true
    // Otherwise, let the layer handlers handle it
    if (!disableInternalPointAddition) {
      // Still handle cursor position and ghost point
      const handleStageMouseMove = (e: Konva.KonvaEventObject<MouseEvent>) => {
        // Use stage.getPointerPosition() directly for consistent coordinate space
        const pos = stage.getPointerPosition();
        if (!pos) return;
 
        // Get current values from ref to avoid stale closures
        const {
          transform,
          fitScale,
          x,
          y,
          width,
          height,
          initialPoints,
          allowClose,
          finalIsPathClosed,
          pixelSnapping,
          isDraggingNewBezier,
          ghostPointDragInfo,
          selected,
        } = currentValuesRef.current;
 
        // Update Shift key state from the event to keep it in sync
        if (e.evt.shiftKey !== isShiftKeyHeld) {
          setIsShiftKeyHeld(e.evt.shiftKey);
        }
 
        // Debug: Log coordinate conversion
        const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
 
        // Always update cursor position (even outside bounds) so ghost line can work
        cursorPositionRef.current = imagePos;
 
        // Use RAF to batch redraw calls for performance
        if (ghostLineRafRef.current) {
          cancelAnimationFrame(ghostLineRafRef.current);
        }
        ghostLineRafRef.current = requestAnimationFrame(() => {
          stage.batchDraw();
        });
 
        // Recalculate ghost point using the helper function
        // Pass the event's shiftKey state and position for real-time updates
        calculateGhostPoint(e.evt.shiftKey, pos);
      };
 
      const handleStageMouseEnter = (e: Konva.KonvaEventObject<MouseEvent>) => {
        // Capture cursor position when mouse enters stage so ghost line can render immediately
        const pos = e.target.getStage()?.getPointerPosition();
        if (pos) {
          const { transform, fitScale, x, y } = currentValuesRef.current;
          const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
          cursorPositionRef.current = imagePos;
          // Trigger a redraw to show ghost line
          if (ghostLineRafRef.current) {
            cancelAnimationFrame(ghostLineRafRef.current);
          }
          ghostLineRafRef.current = requestAnimationFrame(() => {
            stage.batchDraw();
          });
        }
      };
 
      const handleStageMouseLeave = () => {
        cursorPositionRef.current = null;
        setGhostPoint(null);
      };
 
      stage.on("mousemove", handleStageMouseMove);
      stage.on("mouseenter", handleStageMouseEnter);
      stage.on("mouseleave", handleStageMouseLeave);
 
      // Try to initialize cursor position if mouse is already over the stage
      // This ensures ghost line can render immediately even if mouseenter didn't fire
      const tryInitializeCursorPosition = () => {
        const pos = stage.getPointerPosition();
        if (pos) {
          const { transform, fitScale, x, y } = currentValuesRef.current;
          const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
          cursorPositionRef.current = imagePos;
          // Trigger a redraw to show ghost line
          if (ghostLineRafRef.current) {
            cancelAnimationFrame(ghostLineRafRef.current);
          }
          ghostLineRafRef.current = requestAnimationFrame(() => {
            stage.batchDraw();
          });
        }
      };
 
      // Try to initialize immediately
      tryInitializeCursorPosition();
 
      // Also try after a short delay in case the stage isn't ready yet
      const initTimeout = setTimeout(() => {
        tryInitializeCursorPosition();
      }, 0);
 
      return () => {
        clearTimeout(initTimeout);
        if (ghostLineRafRef.current) {
          cancelAnimationFrame(ghostLineRafRef.current);
        }
        stage.off("mousemove", handleStageMouseMove);
        stage.off("mouseenter", handleStageMouseEnter);
        stage.off("mouseleave", handleStageMouseLeave);
      };
    }
 
    // When disableInternalPointAddition is true, handle point dragging at stage level
    const handleStageMouseDown = (e: Konva.KonvaEventObject<MouseEvent>) => {
      // Get current values from ref to avoid stale closures
      const {
        initialPoints,
        effectiveSelectedPoints,
        instanceId,
        transform,
        fitScale,
        x,
        y,
        skeletonEnabled,
        activePointId,
        lastAddedPointId,
        allowClose,
        finalIsPathClosed,
        selected,
        disabled,
        onFinish,
      } = currentValuesRef.current;
 
      // Prevent all interactions when disabled
      if (disabled) {
        return;
      }
 
      // Check if event target belongs to this instance's group
      const target = e.target;
      let targetGroup: Konva.Node | null = target;
      while (targetGroup && targetGroup !== group) {
        targetGroup = targetGroup.getParent();
      }
      // If target is not within our group, ignore this event
      if (targetGroup !== group) return;
 
      // Use e.target.getStage() to match how layer handlers get pointer position
      const pos = e.target.getStage()?.getPointerPosition();
      if (!pos) return;
 
      const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
 
      // Check if clicking on a point (by checking if target is a Circle with name starting with "point-")
      const targetName = target.name();
      if (targetName && targetName.startsWith("point-")) {
        // Extract point index from name (format: "point-{index}")
        const match = targetName.match(/^point-(\d+)$/);
        if (match) {
          const pointIndex = Number.parseInt(match[1], 10);
          if (pointIndex >= 0 && pointIndex < initialPoints.length) {
            const point = initialPoints[pointIndex];
 
            // If cmd-click, don't handle it here - let the onClick handler on the Circle component handle it
            // The onClick handler has the correct pointIndex, while this handler would need to find it by distance
            // which could select the wrong point when multiple points are close together
            if (e.evt.ctrlKey || e.evt.metaKey) {
              // Just prevent event propagation and return - let onClick handle the selection
              e.evt.stopPropagation();
              return;
            }
 
            // Normal click - prevent event propagation to avoid region deselection
            e.evt.stopPropagation();
 
            // Store the potential drag target but don't start dragging yet
            // We'll start dragging only if the mouse moves beyond a threshold
            setDraggedPointIndex(pointIndex);
            lastPos.current = {
              x: e.evt.clientX,
              y: e.evt.clientY,
              originalX: point.x,
              originalY: point.y,
              originalControlPoint1: point.isBezier ? point.controlPoint1 : undefined,
              originalControlPoint2: point.isBezier ? point.controlPoint2 : undefined,
            };
            return;
          }
        }
      }
 
      // Check if clicking on a control point (by checking target name)
      if (targetName && targetName.startsWith("control-point-")) {
        const match = targetName.match(/^control-point-(\d+)-(\d+)$/);
        if (match) {
          const pointIndex = Number.parseInt(match[1], 10);
          const controlIndex = Number.parseInt(match[2], 10);
          if (pointIndex >= 0 && pointIndex < initialPoints.length) {
            const point = initialPoints[pointIndex];
            if (point.isBezier && controlIndex >= 1 && controlIndex <= 2) {
              const controlPoint = controlIndex === 1 ? point.controlPoint1 : point.controlPoint2;
              if (controlPoint) {
                setDraggedControlPoint({ pointIndex, controlIndex });
                isDragging.current = true;
                handleTransformStart();
                lastPos.current = {
                  x: e.evt.clientX,
                  y: e.evt.clientY,
                  originalX: controlPoint.x,
                  originalY: controlPoint.y,
                };
                return;
              }
            }
          }
        }
      }
 
      // Fallback: check by distance (in case names don't match)
      const scale = transform.zoom * fitScale;
      const hitRadius = HIT_RADIUS.SELECTION / scale;
 
      for (let i = 0; i < initialPoints.length; i++) {
        const point = initialPoints[i];
        const distance = Math.sqrt((imagePos.x - point.x) ** 2 + (imagePos.y - point.y) ** 2);
 
        if (distance <= hitRadius) {
          // If cmd-click, handle selection immediately and don't set up dragging
          if (e.evt.ctrlKey || e.evt.metaKey) {
            // Prevent event from propagating to avoid region deselection
            e.evt.stopPropagation();
 
            // Create a mock event object for the selection handlers
            const mockEvent = {
              ...e,
              target: e.target,
              evt: e.evt,
            } as Konva.KonvaEventObject<MouseEvent>;
 
            // Try deselection first
            if (
              handlePointDeselection(mockEvent, {
                instanceId,
                initialPoints,
                transform,
                fitScale,
                x,
                y,
                selectedPoints: effectiveSelectedPoints,
                setSelectedPoints,
                skeletonEnabled,
                setActivePointId,
                setLastAddedPointId,
                lastAddedPointId,
                activePointId,
              } as any)
            ) {
              return;
            }
            // If not deselection, try selection (adding to multi-selection)
            if (
              handlePointSelection(mockEvent, {
                instanceId,
                initialPoints,
                transform,
                fitScale,
                x,
                y,
                selectedPoints: effectiveSelectedPoints,
                setSelectedPoints,
                setSelectedPointIndex,
                skeletonEnabled,
                setActivePointId,
                setLastAddedPointId,
                lastAddedPointId,
                activePointId,
                allowClose,
                isPathClosed: finalIsPathClosed,
                selected,
                onFinish,
              } as any)
            ) {
              return;
            }
          } else {
            // Normal click - prevent event propagation to avoid region deselection
            e.evt.stopPropagation();
 
            // Store the potential drag target but don't start dragging yet
            // We'll start dragging only if the mouse moves beyond a threshold
            setDraggedPointIndex(i);
            lastPos.current = {
              x: e.evt.clientX,
              y: e.evt.clientY,
              originalX: point.x,
              originalY: point.y,
              originalControlPoint1: point.isBezier ? point.controlPoint1 : undefined,
              originalControlPoint2: point.isBezier ? point.controlPoint2 : undefined,
            };
          }
          return;
        }
      }
 
      // Check if clicking on a control point
      for (let i = 0; i < initialPoints.length; i++) {
        const point = initialPoints[i];
        if (point.isBezier) {
          if (point.controlPoint1) {
            const distance = Math.sqrt(
              (imagePos.x - point.controlPoint1.x) ** 2 + (imagePos.y - point.controlPoint1.y) ** 2,
            );
            if (distance <= hitRadius) {
              setDraggedControlPoint({ pointIndex: i, controlIndex: 1 });
              isDragging.current = true;
              handleTransformStart();
              lastPos.current = {
                x: e.evt.clientX,
                y: e.evt.clientY,
                originalX: point.controlPoint1.x,
                originalY: point.controlPoint1.y,
              };
              return;
            }
          }
 
          if (point.controlPoint2) {
            const distance = Math.sqrt(
              (imagePos.x - point.controlPoint2.x) ** 2 + (imagePos.y - point.controlPoint2.y) ** 2,
            );
            if (distance <= hitRadius) {
              setDraggedControlPoint({ pointIndex: i, controlIndex: 2 });
              isDragging.current = true;
              handleTransformStart();
              lastPos.current = {
                x: e.evt.clientX,
                y: e.evt.clientY,
                originalX: point.controlPoint2.x,
                originalY: point.controlPoint2.y,
              };
              return;
            }
          }
        }
      }
    };
 
    const handleStageMouseMove = (e: Konva.KonvaEventObject<MouseEvent>) => {
      // Get current values from ref to avoid stale closures
      const {
        initialPoints,
        allowClose,
        finalIsPathClosed,
        pixelSnapping,
        isDraggingNewBezier,
        ghostPointDragInfo,
        draggedPointIndex,
        draggedControlPoint,
        isDraggingShape,
        effectiveSelectedPoints,
        transform,
        fitScale,
        x,
        y,
        width,
        height,
        disabled,
      } = currentValuesRef.current;
 
      // Prevent all interactions when disabled (but allow cursor position updates for ghost line)
      // Only block dragging and point interactions
      if (disabled && (draggedPointIndex !== null || draggedControlPoint !== null || isDraggingShape)) {
        // Stop any ongoing drags when disabled
        setDraggedPointIndex(null);
        setDraggedControlPoint(null);
        setIsDraggingShape(false);
        return;
      }
 
      // Always update cursor position first (for ghost line to work everywhere)
      const pos = e.target.getStage()?.getPointerPosition();
      if (!pos) return;
 
      // Update Shift key state from the event to keep it in sync
      if (e.evt.shiftKey !== isShiftKeyHeld) {
        setIsShiftKeyHeld(e.evt.shiftKey);
      }
 
      const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
 
      // Always update cursor position (even outside bounds) so ghost line can work
      cursorPositionRef.current = imagePos;
 
      // Use RAF to batch redraw calls for performance
      if (ghostLineRafRef.current) {
        cancelAnimationFrame(ghostLineRafRef.current);
      }
      ghostLineRafRef.current = requestAnimationFrame(() => {
        stage.batchDraw();
      });
 
      // Recalculate ghost point using the helper function
      // Pass the event's shiftKey state and position for real-time updates
      if (calculateGhostPointRef.current) {
        calculateGhostPointRef.current(e.evt.shiftKey, pos);
      }
 
      // Handle shape dragging first (if active, allow dragging to continue even outside bounds)
      // Skip individual shape dragging if disabled or in multi-region mode (ImageTransformer handles it)
      if (isDraggingShape && shapeDragStartPos.current && !disabled && !isMultiRegionSelected) {
        // Calculate delta from start position
        const deltaX = imagePos.x - shapeDragStartPos.current.imageX;
        const deltaY = imagePos.y - shapeDragStartPos.current.imageY;
 
        // Track drag distance
        shapeDragDistance.current = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
 
        // Apply delta to all points
        // IMPORTANT: Do NOT apply pixel snapping during dragging - it causes points to collapse
        // Pixel snapping will be applied when dragging ends (in handleStageMouseUp)
        const newPoints = initialPoints.map((point, index) => {
          const original = originalPointsPositions.current[index];
          if (!original) return point;
 
          const newX = original.x + deltaX;
          const newY = original.y + deltaY;
 
          const updatedPoint = {
            ...point,
            x: newX,
            y: newY,
          };
 
          // Move control points with the anchor point
          if (point.isBezier) {
            if (original.controlPoint1) {
              const cp1X = original.controlPoint1.x + deltaX;
              const cp1Y = original.controlPoint1.y + deltaY;
              updatedPoint.controlPoint1 = { x: cp1X, y: cp1Y };
            }
            if (original.controlPoint2) {
              const cp2X = original.controlPoint2.x + deltaX;
              const cp2Y = original.controlPoint2.y + deltaY;
              updatedPoint.controlPoint2 = { x: cp2X, y: cp2Y };
            }
          }
 
          return updatedPoint;
        });
 
        // Apply bounds checking to preserve relative positions
        const constrainedPoints = constrainAnchorPointsToBounds(newPoints as BezierPoint[], { width, height });
 
        // Do NOT apply pixel snapping here - it will cause points to collapse
        // Pixel snapping will be applied once when dragging ends
        onPointsChange?.(constrainedPoints as BezierPoint[]);
        return; // Don't process other logic when dragging shape
      }
 
      // If we're dragging a point from this instance, allow dragging to continue
      // even if mouse moves outside our group (user might drag outside bounds)
      const isDraggingFromThisInstance = draggedPointIndex !== null || draggedControlPoint !== null;
 
      // Check if event target belongs to this instance's group
      // This prevents ghost point snapping from working for other regions
      // But we still update cursor position above so ghost line can work
      const target = e.target;
      let targetGroup: Konva.Node | null = target;
      while (targetGroup && targetGroup !== group && targetGroup.getParent()) {
        targetGroup = targetGroup.getParent();
      }
      const isTargetInGroup = targetGroup === group;
      // Also allow when hovering over empty space (stage or layer)
      const isStageOrLayer = target === stage || target.getParent() === stage;
 
      // Only process ghost point snapping and dragging if:
      // - Target is in our group, OR
      // - We're hovering over empty space (stage/layer), OR
      // - We're dragging from this instance
      if (!isDraggingFromThisInstance && !isTargetInGroup && !isStageOrLayer) {
        // Clear ghost point when hovering over other regions, but keep cursor position for ghost line
        setGhostPoint(null);
        return;
      }
 
      // Only process ghost point and other logic if within bounds
      if (imagePos.x >= 0 && imagePos.x <= width && imagePos.y >= 0 && imagePos.y <= height) {
        // Handle ghost point when Shift is held (check event directly for real-time updates)
        // Only show ghost point when region is selected and not disabled
        if (
          e.evt.shiftKey &&
          imagePos &&
          initialPoints.length >= 2 &&
          !isDragging.current &&
          !isDraggingNewBezier &&
          !ghostPointDragInfo?.isDragging &&
          selected &&
          !disabled
        ) {
          const scale = transform.zoom * fitScale;
          const hitRadius = HIT_RADIUS.SELECTION / scale;
          let isOverPoint = false;
 
          for (let i = 0; i < initialPoints.length; i++) {
            const point = initialPoints[i];
            const distance = Math.sqrt((imagePos.x - point.x) ** 2 + (imagePos.y - point.y) ** 2);
 
            if (distance <= hitRadius) {
              isOverPoint = true;
              break;
            }
          }
 
          if (isOverPoint) {
            setGhostPoint(null);
          } else {
            const closestPathPoint = findClosestPointOnPath(imagePos, initialPoints, allowClose, finalIsPathClosed);
 
            if (closestPathPoint) {
              const snappedGhostPoint = snapToPixel(closestPathPoint.point, pixelSnapping);
 
              if (closestPathPoint.segmentIndex === initialPoints.length) {
                const lastPoint = initialPoints[initialPoints.length - 1];
                const firstPoint = initialPoints[0];
 
                const ghostPointData = {
                  x: snappedGhostPoint.x,
                  y: snappedGhostPoint.y,
                  prevPointId: lastPoint.id,
                  nextPointId: firstPoint.id,
                };
                setGhostPoint(ghostPointData);
              } else {
                const currentPoint = initialPoints[closestPathPoint.segmentIndex];
                const prevPoint = currentPoint?.prevPointId
                  ? initialPoints.find((p) => p.id === currentPoint.prevPointId)
                  : null;
 
                if (currentPoint && prevPoint) {
                  const ghostPointData = {
                    x: snappedGhostPoint.x,
                    y: snappedGhostPoint.y,
                    prevPointId: prevPoint.id,
                    nextPointId: currentPoint.id,
                  };
                  setGhostPoint(ghostPointData);
                }
              }
            } else {
              setGhostPoint(null);
            }
          }
        } else if (!e.evt.shiftKey) {
          setGhostPoint(null);
        }
 
        // Handle point dragging
        if (draggedPointIndex !== null && lastPos.current && !disabled) {
          if (effectiveSelectedPoints.size > 1) {
            return; // Don't drag when transformer is active
          }
 
          // Check if we should start dragging
          const dragThreshold = 5;
          const mouseDeltaX = Math.abs(e.evt.clientX - lastPos.current.x);
          const mouseDeltaY = Math.abs(e.evt.clientY - lastPos.current.y);
 
          if (!isDragging.current && (mouseDeltaX > dragThreshold || mouseDeltaY > dragThreshold)) {
            isDragging.current = true;
            handleTransformStart();
          }
 
          if (!isDragging.current) {
            return;
          }
 
          const newPoints = [...initialPoints];
          const draggedPoint = newPoints[draggedPointIndex];
 
          const originalX = lastPos.current.originalX ?? draggedPoint.x;
          const originalY = lastPos.current.originalY ?? draggedPoint.y;
 
          const snappedPos = snapToPixel(imagePos, pixelSnapping);
          const finalPos = constrainAnchorPointsToBounds([snappedPos], { width, height })[0];
 
          newPoints[draggedPointIndex] = {
            ...draggedPoint,
            x: finalPos.x,
            y: finalPos.y,
          };
 
          // Handle bezier control points
          if (draggedPoint.isBezier) {
            const updatedPoint = newPoints[draggedPointIndex];
 
            if (updatedPoint.controlPoint1 && lastPos.current.originalControlPoint1) {
              const deltaX = finalPos.x - originalX;
              const deltaY = finalPos.y - originalY;
              const cp1Pos = {
                x: lastPos.current.originalControlPoint1.x + deltaX,
                y: lastPos.current.originalControlPoint1.y + deltaY,
              };
              updatedPoint.controlPoint1 = snapToPixel(cp1Pos, pixelSnapping);
            }
 
            if (updatedPoint.controlPoint2 && lastPos.current.originalControlPoint2) {
              const deltaX = finalPos.x - originalX;
              const deltaY = finalPos.y - originalY;
              const cp2Pos = {
                x: lastPos.current.originalControlPoint2.x + deltaX,
                y: lastPos.current.originalControlPoint2.y + deltaY,
              };
              updatedPoint.controlPoint2 = snapToPixel(cp2Pos, pixelSnapping);
            }
 
            const constrainedPoint = constrainAnchorPointsToBounds([updatedPoint], { width, height })[0];
            newPoints[draggedPointIndex] = constrainedPoint;
          }
 
          onPointsChange?.(newPoints);
          onPointRepositioned?.(newPoints[draggedPointIndex], draggedPointIndex);
        }
 
        // Handle control point dragging
        if (draggedControlPoint && lastPos.current && !disabled) {
          const newPoints = [...initialPoints];
          const point = newPoints[draggedControlPoint.pointIndex];
 
          if (point.isBezier) {
            const snappedPos = snapToPixel(imagePos, pixelSnapping);
            const finalPos = constrainPointToBounds(snappedPos, { width, height });
 
            if (draggedControlPoint.controlIndex === 1) {
              point.controlPoint1 = finalPos;
            } else if (draggedControlPoint.controlIndex === 2) {
              point.controlPoint2 = finalPos;
            }
 
            newPoints[draggedControlPoint.pointIndex] = point;
            onPointsChange?.(newPoints);
            onPointEdited?.(point, draggedControlPoint.pointIndex);
          }
        }
      } else {
        // When outside bounds, clear ghost point but keep cursor position for ghost line
        setGhostPoint(null);
      }
    };
 
    const handleStageMouseUp = (e: Konva.KonvaEventObject<MouseEvent>) => {
      // Get current values from ref to avoid stale closures
      const {
        isDraggingShape,
        draggedPointIndex,
        initialPoints,
        effectiveSelectedPoints,
        instanceId,
        skeletonEnabled,
        activePointId,
        disabled,
        onFinish,
        pixelSnapping,
        width,
        height,
      } = currentValuesRef.current;
 
      // Prevent all interactions when disabled
      if (disabled) {
        return;
      }
 
      // Handle shape dragging end
      if (isDraggingShape) {
        const dragThreshold = 5; // Only prevent clicks if we actually dragged
        const actuallyDragged = shapeDragDistance.current > dragThreshold;
 
        setIsDraggingShape(false);
        handleTransformEnd(e);
 
        // Apply pixel snapping when dragging ends (if enabled)
        // CRITICAL: Snap all points while preventing collapse by preserving relative positions
        if (pixelSnapping && currentPointsRef.current.length > 0) {
          // Get the current points (they were updated during dragging without snapping)
          // Use currentPointsRef to get the latest points immediately
          const currentPoints = currentPointsRef.current;
 
          // Snap the first point
          const firstPoint = currentPoints[0];
          const snappedFirstPos = snapToPixel({ x: firstPoint.x, y: firstPoint.y }, pixelSnapping);
 
          // For all points, snap individually but check for collisions
          const snappedPoints: BezierPoint[] = [];
          const snappedPositions = new Map<number, { x: number; y: number }>(); // Track snapped positions by index
 
          for (let i = 0; i < currentPoints.length; i++) {
            const point = currentPoints[i];
 
            if (i === 0) {
              // First point - use snapped position directly
              const snappedPoint: BezierPoint = {
                ...point,
                x: snappedFirstPos.x,
                y: snappedFirstPos.y,
              };
 
              // Snap control points if bezier
              if (point.isBezier) {
                if (point.controlPoint1) {
                  snappedPoint.controlPoint1 = snapToPixel(point.controlPoint1, pixelSnapping);
                }
                if (point.controlPoint2) {
                  snappedPoint.controlPoint2 = snapToPixel(point.controlPoint2, pixelSnapping);
                }
              }
 
              snappedPoints.push(snappedPoint);
              snappedPositions.set(i, { x: snappedFirstPos.x, y: snappedFirstPos.y });
            } else {
              // Subsequent points - snap individually first
              let snappedPos = snapToPixel({ x: point.x, y: point.y }, pixelSnapping);
 
              // Check if this snapped position would collide with any previously snapped point
              let wouldCollapse = false;
              for (let j = 0; j < i; j++) {
                const prevSnapped = snappedPositions.get(j);
                if (prevSnapped) {
                  const snappedDistance = Math.sqrt(
                    (snappedPos.x - prevSnapped.x) ** 2 + (snappedPos.y - prevSnapped.y) ** 2,
                  );
                  const originalDistance = Math.sqrt(
                    (point.x - currentPoints[j].x) ** 2 + (point.y - currentPoints[j].y) ** 2,
                  );
 
                  // If snapped positions would be the same but original positions were different,
                  // preserve relative offset to prevent collapse
                  if (snappedDistance < 0.1 && originalDistance > 0.1) {
                    wouldCollapse = true;
                    // Preserve relative offset from first point
                    const relativeX = point.x - firstPoint.x;
                    const relativeY = point.y - firstPoint.y;
                    snappedPos = {
                      x: snappedFirstPos.x + relativeX,
                      y: snappedFirstPos.y + relativeY,
                    };
                    break;
                  }
                }
              }
 
              const snappedPoint: BezierPoint = {
                ...point,
                x: snappedPos.x,
                y: snappedPos.y,
              };
 
              // Snap control points if bezier
              if (point.isBezier) {
                if (point.controlPoint1) {
                  snappedPoint.controlPoint1 = snapToPixel(point.controlPoint1, pixelSnapping);
                }
                if (point.controlPoint2) {
                  snappedPoint.controlPoint2 = snapToPixel(point.controlPoint2, pixelSnapping);
                }
              }
 
              snappedPoints.push(snappedPoint);
              snappedPositions.set(i, { x: snappedPos.x, y: snappedPos.y });
            }
          }
 
          const finalSnappedPoints = snappedPoints;
 
          // Apply bounds checking after snapping
          const constrainedSnappedPoints = constrainAnchorPointsToBounds(finalSnappedPoints as BezierPoint[], {
            width,
            height,
          });
 
          // Update points with snapped positions using updatePoints to ensure proper state management
          // Use ref to ensure we have the latest updatePoints function
          if (updatePointsRef.current) {
            updatePointsRef.current(constrainedSnappedPoints as BezierPoint[]);
          }
        }
 
        shapeDragStartPos.current = null;
        originalPointsPositions.current = [];
 
        // Only prevent click handler from adding a point if we actually dragged
        if (actuallyDragged) {
          justFinishedShapeDrag.current = true;
          // Prevent event propagation to avoid triggering click handlers
          e.evt.stopPropagation();
          e.evt.preventDefault();
          // Don't use setTimeout - let the click handlers clear the flag
        }
 
        shapeDragDistance.current = 0;
        return; // Don't process point selection when ending shape drag
      }
 
      // Handle point selection if we clicked but didn't drag
      if (draggedPointIndex !== null && !isDragging.current) {
        // Use handlePointSelectionFromIndex to properly handle selection through tracker
        handlePointSelectionFromIndex(
          draggedPointIndex,
          {
            instanceId,
            initialPoints,
            selectedPoints: effectiveSelectedPoints,
            setSelectedPoints,
            skeletonEnabled,
            setActivePointId,
            activePointId,
            onFinish,
          } as any,
          e,
        );
        onPointSelected?.(draggedPointIndex);
      }
 
      // Reset dragging state
      isDragging.current = false;
      handleTransformEnd(e);
      setDraggedPointIndex(null);
      setDraggedControlPoint(null);
    };
 
    const handleStageMouseEnter = (e: Konva.KonvaEventObject<MouseEvent>) => {
      // Capture cursor position when mouse enters stage so ghost line can render immediately
      const pos = e.target.getStage()?.getPointerPosition();
      if (pos) {
        const { transform, fitScale, x, y } = currentValuesRef.current;
        const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
        cursorPositionRef.current = imagePos;
        // Trigger a redraw to show ghost line
        if (ghostLineRafRef.current) {
          cancelAnimationFrame(ghostLineRafRef.current);
        }
        ghostLineRafRef.current = requestAnimationFrame(() => {
          stage.batchDraw();
        });
      }
    };
 
    const handleStageMouseLeave = () => {
      cursorPositionRef.current = null;
      setGhostPoint(null);
    };
 
    if (disableInternalPointAddition) {
      stage.on("mousedown", handleStageMouseDown);
      stage.on("mousemove", handleStageMouseMove);
      stage.on("mouseup", handleStageMouseUp);
      stage.on("mouseenter", handleStageMouseEnter);
      stage.on("mouseleave", handleStageMouseLeave);
 
      // Try to initialize cursor position if mouse is already over the stage
      // This ensures ghost line can render immediately even if mouseenter didn't fire
      const tryInitializeCursorPosition = () => {
        const pos = stage.getPointerPosition();
        if (pos) {
          const { transform, fitScale, x, y } = currentValuesRef.current;
          const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
          cursorPositionRef.current = imagePos;
          // Trigger a redraw to show ghost line
          if (ghostLineRafRef.current) {
            cancelAnimationFrame(ghostLineRafRef.current);
          }
          ghostLineRafRef.current = requestAnimationFrame(() => {
            stage.batchDraw();
          });
        }
      };
 
      // Try to initialize immediately
      tryInitializeCursorPosition();
 
      // Also try after a short delay in case the stage isn't ready yet
      const initTimeout = setTimeout(() => {
        tryInitializeCursorPosition();
      }, 0);
 
      return () => {
        clearTimeout(initTimeout);
        handlersAttachedRef.current = false;
        stage.off("mousedown", handleStageMouseDown);
        stage.off("mousemove", handleStageMouseMove);
        stage.off("mouseup", handleStageMouseUp);
        stage.off("mouseenter", handleStageMouseEnter);
        stage.off("mouseleave", handleStageMouseLeave);
      };
    }
    // Handle cursor position, ghost point, and shape dragging
    stage.on("mousemove", handleStageMouseMove);
    stage.on("mouseup", handleStageMouseUp);
    stage.on("mouseenter", handleStageMouseEnter);
    stage.on("mouseleave", handleStageMouseLeave);
 
    // Try to initialize cursor position if mouse is already over the stage
    // This ensures ghost line can render immediately even if mouseenter didn't fire
    const tryInitializeCursorPosition = () => {
      const pos = stage.getPointerPosition();
      if (pos) {
        const { transform, fitScale, x, y } = currentValuesRef.current;
        const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
        cursorPositionRef.current = imagePos;
        // Trigger a redraw to show ghost line
        if (ghostLineRafRef.current) {
          cancelAnimationFrame(ghostLineRafRef.current);
        }
        ghostLineRafRef.current = requestAnimationFrame(() => {
          stage.batchDraw();
        });
      }
    };
 
    // Try to initialize immediately
    tryInitializeCursorPosition();
 
    // Also try after a short delay in case the stage isn't ready yet
    const initTimeout = setTimeout(() => {
      tryInitializeCursorPosition();
    }, 0);
 
    return () => {
      clearTimeout(initTimeout);
      handlersAttachedRef.current = false;
      if (ghostLineRafRef.current) {
        cancelAnimationFrame(ghostLineRafRef.current);
      }
      stage.off("mousemove", handleStageMouseMove);
      stage.off("mouseup", handleStageMouseUp);
      stage.off("mouseenter", handleStageMouseEnter);
      stage.off("mouseleave", handleStageMouseLeave);
    };
  }, [disableInternalPointAddition, stageReadyRetry]); // Re-run when disableInternalPointAddition changes or when retrying
 
  // Handle Shift key for disconnected mode
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Shift") {
        setIsDisconnectedMode(true);
      }
    };
 
    const handleKeyUp = (e: KeyboardEvent) => {
      if (e.key === "Shift") {
        setIsDisconnectedMode(false);
      }
    };
 
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);
 
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("keyup", handleKeyUp);
    };
  }, []);
 
  // Click handler with debouncing for single/double-click detection
  const handleClickWithDebouncing = useCallback(
    (e: any, onClickHandler?: (e: any) => void, onDblClickHandler?: (e: any) => void) => {
      // If disabled or not selected, fire onClick immediately (no need to wait for double-click detection)
      if (disabled || !selected) {
        if (onClickHandler) {
          const newEvent = {
            ...e,
            evt: {
              ...e.evt,
              defaultPrevented: false,
              stopImmediatePropagation: e.evt.stopImmediatePropagation?.bind(e.evt) || (() => {}),
              stopPropagation: e.evt.stopPropagation?.bind(e.evt) || (() => {}),
              preventDefault: e.evt.preventDefault?.bind(e.evt) || (() => {}),
            },
          };
          onClickHandler(newEvent);
        }
        return;
      }
 
      // Clear any existing timeout
      if (clickTimeoutRef.current) {
        clearTimeout(clickTimeoutRef.current);
        clickTimeoutRef.current = null;
        // This is a double-click, handle it
        doubleClickHandledRef.current = true;
        if (onDblClickHandler) {
          // Create a new event object to avoid defaultPrevented issues
          // Preserve all event methods by copying the original evt object and only resetting defaultPrevented
          const newEvent = {
            ...e,
            evt: {
              ...e.evt,
              defaultPrevented: false,
              // Preserve all methods from the original event
              stopImmediatePropagation: e.evt.stopImmediatePropagation?.bind(e.evt) || (() => {}),
              stopPropagation: e.evt.stopPropagation?.bind(e.evt) || (() => {}),
              preventDefault: e.evt.preventDefault?.bind(e.evt) || (() => {}),
            },
          };
          onDblClickHandler(newEvent);
        }
        // Reset the flag after a short delay
        setTimeout(() => {
          doubleClickHandledRef.current = false;
        }, 100);
        return;
      }
 
      // Set a timeout for single-click handling (only when selected, to detect double-clicks)
      clickTimeoutRef.current = setTimeout(() => {
        clickTimeoutRef.current = null;
        if (onClickHandler) {
          // Create a new event object to avoid defaultPrevented issues
          // This ensures the onClick handler in VectorRegion.jsx can fire even if
          // the event was prevented elsewhere (e.g., by onFinish handler)
          // Preserve all event methods by copying the original evt object and only resetting defaultPrevented
          const newEvent = {
            ...e,
            evt: {
              ...e.evt,
              defaultPrevented: false,
              // Preserve all methods from the original event
              stopImmediatePropagation: e.evt.stopImmediatePropagation?.bind(e.evt) || (() => {}),
              stopPropagation: e.evt.stopPropagation?.bind(e.evt) || (() => {}),
              preventDefault: e.evt.preventDefault?.bind(e.evt) || (() => {}),
            },
          };
          onClickHandler(newEvent);
        }
      }, 200);
    },
    [selected, disabled],
  );
 
  // Create event handlers
  const eventHandlers = createEventHandlers({
    instanceId,
    initialPoints,
    width,
    height,
    pixelSnapping,
    selectedPoints: effectiveSelectedPoints,
    selectedPointIndex,
    setSelectedPointIndex,
    setSelectedPoints,
    setDraggedPointIndex,
    setDraggedControlPoint,
    setIsDisconnectedMode,
    setGhostPoint,
    setNewPointDragIndex,
    setIsDraggingNewBezier,
    setGhostPointDragInfo,
    setVisibleControlPoints,
    setIsPathClosed,
    isDragging,
    lastPos,
    lastCallbackTime,
    isDrawingMode: !drawingDisabled, // Use dynamic drawing detection
    allowClose,
    allowBezier,
    isPathClosed: finalIsPathClosed,
    transform,
    fitScale,
    x,
    y,
    ghostPoint,
    ghostPointDragInfo,
    draggedPointIndex,
    draggedControlPoint,
    isDraggingNewBezier,
    newPointDragIndex: _newPointDragIndex,
    visibleControlPoints,
    isDisconnectedMode,
    onPointsChange,
    onPointAdded,
    onPointRemoved,
    onPointEdited,
    onPointRepositioned,
    onPointConverted,
    onPathShapeChanged,
    onPointSelected,
    onFinish,
    onGhostPointClick,
    onMouseDown,
    onMouseMove,
    onMouseUp,
    onClick,
    notifyTransformationComplete,
    canAddMorePoints,
    maxPoints,
    minPoints, // Add minPoints to event handlers
    skeletonEnabled,
    getAllPoints,
    getPointInfo,
    updatePointByGlobalIndex,
    lastAddedPointId,
    setLastAddedPointId,
    activePointId,
    setActivePointId,
    isTransforming,
    selected,
    disabled,
    transformMode,
    disableInternalPointAddition,
    handleTransformStart,
    handleTransformEnd,
    pointCreationManager,
  });
 
  return (
    <Group
      ref={stageRef}
      scaleX={scaleX}
      scaleY={scaleY}
      x={x}
      y={y}
      imageSmoothingEnabled={imageSmoothingEnabled}
      onMouseDown={selected && !disabled ? eventHandlers.handleLayerMouseDown : undefined}
      onMouseMove={selected && !disabled ? eventHandlers.handleLayerMouseMove : undefined}
      onMouseUp={selected && !disabled ? eventHandlers.handleLayerMouseUp : undefined}
      onClick={
        !selected || transformMode
          ? undefined
          : (e) => {
              // Prevent editing when disabled, but allow selection clicks
              // Prevent all clicks when in transform mode (already checked above, but double-check)
              if (transformMode) {
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.evt.stopImmediatePropagation();
                e.cancelBubble = true;
                return;
              }
 
              // When disabled, only allow selection clicks - skip all editing logic
              if (disabled) {
                // Call handleClickWithDebouncing to trigger selection via onClick handler
                // This allows the shape to be selected even when disabled
                handleClickWithDebouncing(e, onClick, onDblClick);
                return;
              }
 
              // Don't add points if we just finished shape dragging
              if (justFinishedShapeDrag.current) {
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.cancelBubble = true; // Also set cancelBubble for Konva
                justFinishedShapeDrag.current = false; // Clear flag immediately
                return;
              }
 
              // Skip if point selection was already handled by VectorPoints onClick
              if (pointSelectionHandled.current) {
                pointSelectionHandled.current = false;
                // Don't prevent propagation - let the event bubble to VectorShape onClick
                return;
              }
 
              // For the first point in drawing mode, we need to ensure the click handler works
              // The issue is that the flag logic is interfering with first point creation
              // Let's try calling the drawing mode click handler directly for the first point
              // Skip if internal point addition is disabled
              if (initialPoints.length === 0 && !drawingDisabled && !disableInternalPointAddition) {
                // For the first point, call the drawing mode click handler directly
                const pos = e.target.getStage()?.getPointerPosition();
                if (pos) {
                  // Use the same coordinate transformation as the event handlers
                  const imagePos = {
                    x: (pos.x - x - transform.offsetX) / (scaleX * transform.zoom * fitScale),
                    y: (pos.y - y - transform.offsetY) / (scaleY * transform.zoom * fitScale),
                  };
 
                  // Check if we're within canvas bounds
                  if (imagePos.x >= 0 && imagePos.x <= width && imagePos.y >= 0 && imagePos.y <= height) {
                    // Create the first point directly
                    const newPoint = {
                      id: `point-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
                      x: imagePos.x,
                      y: imagePos.y,
                      isBezier: false,
                    };
 
                    const newPoints = [...initialPoints, newPoint];
                    onPointsChange?.(newPoints);
                    onPointAdded?.(newPoint, newPoints.length - 1);
 
                    // Set as the last added point
                    setLastAddedPointId(newPoint.id);
                    setActivePointId(newPoint.id);
 
                    return;
                  }
                }
              }
 
              // For subsequent points, use the normal event handler
              // But don't prevent propagation - let the event bubble to VectorShape onClick
              // so that shape selection/unselection can work when clicking on segments
              eventHandlers.handleLayerClick(e);
              // Don't call preventDefault or stopPropagation here - let the event bubble
            }
      }
      onDblClick={
        !selected || disabled
          ? undefined
          : (e) => {
              // If we've already handled this double-click through debouncing, ignore it
              if (doubleClickHandledRef.current) {
                return;
              }
              // Otherwise, call the original onDblClick handler
              onDblClick?.(e);
            }
      }
    >
      {/* Invisible rectangle - render to capture mouse events for cursor position updates */}
      {/* Disabled when disableInternalPointAddition is true, component is not selected, or disabled */}
      {selected && !disabled && !disableInternalPointAddition && (
        <Shape
          sceneFunc={(ctx, shape) => {
            ctx.beginPath();
            ctx.rect(0, 0, width, height);
            ctx.fillShape(shape);
          }}
          fill={INVISIBLE_SHAPE_OPACITY}
        />
      )}
 
      {/* Conditionally wrap content with _transformable group for ImageTransformer */}
      {isMultiRegionSelected ? (
        <Group
          name="_transformable"
          ref={transformableGroupRef}
          draggable={!disabled}
          onTransformEnd={(e) => {
            // Prevent transform when disabled
            if (disabled) return;
            // This is called when ImageTransformer finishes transforming the Group
            // Commit the transform immediately to prevent position reset
            if (e.target === e.currentTarget && transformableGroupRef.current && initialTransformRef.current) {
              commitMultiRegionTransform();
              handleTransformEnd(e);
            }
          }}
        >
          {/* Unified vector shape - renders all lines based on id-prevPointId relationships */}
          <VectorShape
            segments={getAllLineSegments()}
            allowClose={allowClose}
            isPathClosed={finalIsPathClosed}
            stroke={stroke}
            fill={fill}
            strokeWidth={props.strokeWidth}
            opacity={props.opacity}
            transform={transform}
            fitScale={fitScale}
            onClick={(e) => {
              // Prevent editing clicks when disabled, but allow selection clicks
              // Prevent all clicks when in transform mode
              if (transformMode) {
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.evt.stopImmediatePropagation();
                e.cancelBubble = true;
                return;
              }
 
              // When disabled, only allow selection clicks - skip all editing logic
              if (disabled) {
                // Allow the click to bubble for selection - don't prevent propagation
                // Use debouncing for click/double-click detection for selection
                if (!justFinishedShapeDrag.current && !e.evt.shiftKey) {
                  handleClickWithDebouncing(e, onClick, onDblClick);
                }
                return;
              }
 
              // CRITICAL: Handle Alt+click FIRST (for point deletion and segment breaking)
              // This must happen before any other click handling to ensure deletion works
              if (e.evt.altKey && !e.evt.shiftKey && selected) {
                // Let the event bubble to the Group onClick handler which has the Alt+click logic
                // Don't stop propagation or prevent default - let it reach createClickHandler
                return;
              }
 
              // Don't add points if we just finished shape dragging
              if (justFinishedShapeDrag.current) {
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.cancelBubble = true; // Also set cancelBubble for Konva
                justFinishedShapeDrag.current = false; // Clear flag immediately
                return;
              }
 
              // Check if click is on the last added point by checking cursor position
              if (cursorPositionRef.current && lastAddedPointId) {
                const lastAddedPoint = initialPoints.find((p) => p.id === lastAddedPointId);
                if (lastAddedPoint) {
                  const scale = transform.zoom * fitScale;
                  const hitRadius = HIT_RADIUS.SELECTION / scale; // Use constant for consistent hit detection
                  const distance = Math.sqrt(
                    (cursorPositionRef.current.x - lastAddedPoint.x) ** 2 +
                      (cursorPositionRef.current.y - lastAddedPoint.y) ** 2,
                  );
 
                  if (distance <= hitRadius) {
                    // Find the index of the last added point
                    const lastAddedPointIndex = initialPoints.findIndex((p) => p.id === lastAddedPointId);
 
                    // Only trigger onFinish if the last added point is already selected (second click)
                    // and no modifiers are pressed (ctrl, meta, shift, alt) and component is selected
                    // and not in transform mode
                    if (
                      lastAddedPointIndex !== -1 &&
                      effectiveSelectedPoints.has(lastAddedPointIndex) &&
                      selected &&
                      !transformMode
                    ) {
                      const hasModifiers = e.evt.ctrlKey || e.evt.metaKey || e.evt.shiftKey || e.evt.altKey;
                      if (!hasModifiers) {
                        e.evt.preventDefault();
                        onFinish?.(e);
                        return;
                      }
                      // If modifiers are held, skip onFinish entirely and let normal modifier handling take over
                      return;
                    }
                  }
                }
              }
 
              // Use debouncing for click/double-click detection
              // This will call the onClick handler from VectorRegion.jsx which handles shape selection/unselection
              // Only call if we didn't just finish dragging (to allow shape dragging to work)
              // Don't call if Shift is held (to allow shift-click for ghost point insertion without unselecting)
              if (!justFinishedShapeDrag.current && !e.evt.shiftKey) {
                // Stop propagation to prevent the Group onClick handler from also processing the click
                // This prevents the shape from being selected and then immediately unselected
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.cancelBubble = true;
                handleClickWithDebouncing(e, onClick, onDblClick);
              }
            }}
            onMouseDown={(e) => {
              // Don't start shape drag if disabled
              if (disabled) {
                return;
              }
              // Don't start shape drag if in multi-region selection mode
              // ImageTransformer will handle dragging in this case
              if (isMultiRegionSelected) {
                return;
              }
 
              // Don't start shape drag if we're already dragging a point or control point
              if (draggedPointIndex !== null || draggedControlPoint !== null) {
                return;
              }
 
              // Don't start shape drag if transformer is active
              if (effectiveSelectedPoints.size > 1) {
                return;
              }
 
              // Don't start shape drag if clicking on a point
              const pos = e.target.getStage()?.getPointerPosition();
              if (!pos) return;
 
              const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
              const scale = transform.zoom * fitScale;
              const hitRadius = HIT_RADIUS.SELECTION / scale;
 
              // Check if clicking on any point
              for (let i = 0; i < initialPoints.length; i++) {
                const point = initialPoints[i];
                const distance = Math.sqrt((imagePos.x - point.x) ** 2 + (imagePos.y - point.y) ** 2);
                if (distance <= hitRadius) {
                  return; // Let point dragging handle it
                }
              }
 
              // Check if clicking on any control point
              for (let i = 0; i < initialPoints.length; i++) {
                const point = initialPoints[i];
                if (point.isBezier) {
                  if (point.controlPoint1) {
                    const distance = Math.sqrt(
                      (imagePos.x - point.controlPoint1.x) ** 2 + (imagePos.y - point.controlPoint1.y) ** 2,
                    );
                    if (distance <= hitRadius) {
                      return; // Let control point dragging handle it
                    }
                  }
                  if (point.controlPoint2) {
                    const distance = Math.sqrt(
                      (imagePos.x - point.controlPoint2.x) ** 2 + (imagePos.y - point.controlPoint2.y) ** 2,
                    );
                    if (distance <= hitRadius) {
                      return; // Let control point dragging handle it
                    }
                  }
                }
              }
 
              // Start shape dragging (don't stop propagation yet - we'll do it on mouseup if we actually drag)
              setIsDraggingShape(true);
              handleTransformStart();
              shapeDragDistance.current = 0; // Reset drag distance
              shapeDragStartPos.current = {
                x: e.evt.clientX,
                y: e.evt.clientY,
                imageX: imagePos.x,
                imageY: imagePos.y,
              };
 
              // Store original positions of all points
              originalPointsPositions.current = initialPoints.map((point) => ({
                x: point.x,
                y: point.y,
                controlPoint1: point.controlPoint1 ? { x: point.controlPoint1.x, y: point.controlPoint1.y } : undefined,
                controlPoint2: point.controlPoint2 ? { x: point.controlPoint2.x, y: point.controlPoint2.y } : undefined,
              }));
            }}
            onMouseEnter={onMouseEnter}
            onMouseLeave={onMouseLeave}
            key={`vector-shape-${initialPoints.length}-${initialPoints.map((p) => p.id).join("-")}`}
          />
 
          {/* Ghost line - preview from last point to cursor */}
          {selected && !disabled && !disableGhostLine && (
            <GhostLine
              initialPoints={initialPoints}
              cursorPositionRef={cursorPositionRef}
              draggedControlPoint={draggedControlPoint}
              draggedPointIndex={draggedPointIndex}
              isDraggingNewBezier={isDraggingNewBezier}
              isPathClosed={finalIsPathClosed}
              allowClose={allowClose}
              transform={transform}
              fitScale={fitScale}
              maxPoints={maxPoints}
              minPoints={minPoints}
              skeletonEnabled={skeletonEnabled}
              selectedPointIndex={selectedPointIndex}
              lastAddedPointId={lastAddedPointId}
              activePointId={activePointId}
              stroke={stroke}
              pixelSnapping={pixelSnapping}
              drawingDisabled={drawingDisabled}
              isShiftKeyHeld={isShiftKeyHeld}
              transformMode={transformMode}
              effectiveSelectedPointsSize={effectiveSelectedPoints.size}
            />
          )}
 
          {/* Control points - render first so lines appear under main points */}
          {selected && !disabled && (
            <ControlPoints
              initialPoints={getAllPoints()}
              selectedPointIndex={selectedPointIndex}
              isDraggingNewBezier={isDraggingNewBezier}
              draggedControlPoint={draggedControlPoint}
              visibleControlPoints={visibleControlPoints}
              transform={transform}
              fitScale={fitScale}
              key={`control-points-${initialPoints.length}-${initialPoints.map((p, i) => `${i}-${p.x.toFixed(1)}-${p.y.toFixed(1)}-${p.controlPoint1?.x?.toFixed(1) || "null"}-${p.controlPoint1?.y?.toFixed(1) || "null"}-${p.controlPoint2?.x?.toFixed(1) || "null"}-${p.controlPoint2?.y?.toFixed(1) || "null"}`).join("-")}`}
            />
          )}
 
          {/* All vector points */}
          <VectorPoints
            initialPoints={getAllPoints()}
            selectedPointIndex={selectedPointIndex}
            selectedPoints={effectiveSelectedPoints}
            transform={transform}
            fitScale={fitScale}
            pointRefs={pointRefs}
            selected={selected}
            disabled={disabled}
            transformMode={transformMode}
            pointRadius={pointRadius}
            pointFill={pointFill}
            pointStroke={pointStroke}
            pointStrokeSelected={pointStrokeSelected}
            pointStrokeWidth={pointStrokeWidth}
            activePointId={activePointId}
            maxPoints={maxPoints}
            onPointClick={(e, pointIndex) => {
              // Prevent all clicks when disabled or in transform mode
              if (disabled || transformMode) {
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.evt.stopImmediatePropagation();
                e.cancelBubble = true;
                return;
              }
 
              // CRITICAL: For single-point regions, directly call onClick handler so the region can be selected
              // Single-point regions have no segments to click on, so clicking the point must trigger region selection
              // Check this FIRST before any other logic
              // BUT: Don't do this in transform mode - clicks must be completely disabled
              const isSinglePointRegion = initialPoints.length === 1;
              if (
                isSinglePointRegion &&
                !e.evt.altKey &&
                !e.evt.shiftKey &&
                !e.evt.ctrlKey &&
                !e.evt.metaKey &&
                !transformMode
              ) {
                // Select the point first
                tracker.selectPoints(instanceId, new Set([pointIndex]));
                // Directly call handleClickWithDebouncing to trigger region selection
                // This works even when selected=false (Group onClick is undefined)
                pointSelectionHandled.current = true;
                handleClickWithDebouncing(e, onClick, onDblClick);
                return;
              }
 
              // Handle point selection even when not selected (similar to shape clicks)
              // But never allow selection when disabled
              if (disabled) {
                return;
              }
              if (!selected) {
                // Check if this instance can have selection
                if (!tracker.canInstanceHaveSelection(instanceId)) {
                  return; // Block the selection
                }
 
                // Check if we're about to close the path - prevent point selection in this case
                if (
                  shouldClosePathOnPointClick(
                    pointIndex,
                    {
                      initialPoints,
                      allowClose,
                      isPathClosed: finalIsPathClosed,
                      skeletonEnabled,
                      activePointId,
                    } as any,
                    e,
                  ) &&
                  isActivePointEligibleForClosing({
                    initialPoints,
                    skeletonEnabled,
                    activePointId,
                  } as any)
                ) {
                  // Use the bidirectional closePath function
                  const success = (ref as React.MutableRefObject<KonvaVectorRef | null>)?.current?.close();
                  if (success) {
                    return; // Path was closed, don't select the point
                  }
                }
 
                // Handle cmd-click to select all points (only when not in transform mode)
                if (!transformMode && (e.evt.ctrlKey || e.evt.metaKey) && !e.evt.altKey && !e.evt.shiftKey) {
                  // Select all points in the path
                  const allPointIndices = Array.from({ length: initialPoints.length }, (_, i) => i);
                  tracker.selectPoints(instanceId, new Set(allPointIndices));
                  pointSelectionHandled.current = true; // Mark that we handled selection
                  e.evt.stopImmediatePropagation(); // Prevent all other handlers from running
                  return;
                }
 
                // Check if this is the last added point and already selected (second click)
                // Only check if the shape is selected - non-selected shapes should not trigger onFinish
                if (selected) {
                  const isLastAddedPoint = lastAddedPointId && initialPoints[pointIndex]?.id === lastAddedPointId;
                  const isAlreadySelected = effectiveSelectedPoints.has(pointIndex);
 
                  // Only fire onFinish if this is the last added point AND it was already selected (second click)
                  // and no modifiers are pressed (ctrl, meta, shift, alt) and we're in drawing mode
                  // and not in transform mode
                  if (isLastAddedPoint && isAlreadySelected && !drawingDisabled && !transformMode) {
                    const hasModifiers = e.evt.ctrlKey || e.evt.metaKey || e.evt.shiftKey || e.evt.altKey;
                    if (!hasModifiers) {
                      onFinish?.(e);
                      pointSelectionHandled.current = true; // Mark that we handled selection
                      e.evt.stopImmediatePropagation(); // Prevent all other handlers from running
                      return;
                    }
                    // If modifiers are held, skip onFinish entirely and let normal modifier handling take over
                    return;
                  }
                }
 
                // Handle regular point selection (only when not in transform mode)
                if (!transformMode) {
                  if (e.evt.ctrlKey || e.evt.metaKey) {
                    // Add to multi-selection
                    const newSelection = new Set(selectedPoints);
                    newSelection.add(pointIndex);
                    tracker.selectPoints(instanceId, newSelection);
                  } else {
                    // Select only this point
                    tracker.selectPoints(instanceId, new Set([pointIndex]));
                  }
                }
 
                // Don't call onClick here - clicking on points should NOT select/unselect the shape
                // Only clicking on segments should select/unselect the shape
                // EXCEPTION: Single-point regions (handled above)
 
                // Mark that we handled selection and prevent all other handlers from running
                // This prevents the VectorShape onClick handler from firing, which would call onFinish
                pointSelectionHandled.current = true;
                e.evt.stopImmediatePropagation();
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.cancelBubble = true;
                return;
              }
 
              // When selected, let the normal event handlers handle it
              // The point click will be detected by the layer-level handlers
              //
            }}
          />
 
          {/* Proxy nodes for Transformer (positioned at exact point centers) - only show when not in drawing mode */}
          {drawingDisabled && (
            <ProxyNodes selectedPoints={effectiveSelectedPoints} initialPoints={getAllPoints()} proxyRefs={proxyRefs} />
          )}
 
          {/* Transformer for multiselection - only show when not in drawing mode and not multi-region selected */}
          {drawingDisabled && !isMultiRegionSelected && (
            <VectorTransformer
              selectedPoints={selectedPoints}
              initialPoints={getAllPoints()}
              transformerRef={transformerRef}
              proxyRefs={proxyRefs}
              bounds={{
                x: 0,
                y: 0,
                width: width,
                height: height,
              }}
              scaleX={scaleX}
              scaleY={scaleY}
              transform={transform}
              fitScale={fitScale}
              getCurrentPointsRef={getCurrentPointsRef}
              updateCurrentPointsRef={updateCurrentPointsRef}
              pixelSnapping={pixelSnapping}
              onPointsChange={(newPoints) => {
                // Update main path points
                onPointsChange?.(newPoints);
              }}
              onTransformStateChange={(state) => {
                transformerStateRef.current = state;
              }}
              onTransformationStart={() => {
                setIsTransforming(true);
                handleTransformStart();
              }}
              onTransformationEnd={() => {
                setIsTransforming(false);
                handleTransformEnd();
              }}
            />
          )}
        </Group>
      ) : (
        <>
          {/* Unified vector shape - renders all lines based on id-prevPointId relationships */}
          <VectorShape
            segments={getAllLineSegments()}
            allowClose={allowClose}
            isPathClosed={finalIsPathClosed}
            stroke={stroke}
            fill={fill}
            strokeWidth={props.strokeWidth}
            opacity={props.opacity}
            transform={transform}
            fitScale={fitScale}
            onClick={(e) => {
              // Prevent editing clicks when disabled, but allow selection clicks
              // Prevent all clicks when in transform mode
              if (transformMode) {
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.evt.stopImmediatePropagation();
                e.cancelBubble = true;
                return;
              }
 
              // When disabled, only allow selection clicks - skip all editing logic
              if (disabled) {
                // Allow the click to bubble for selection - don't prevent propagation
                // Use debouncing for click/double-click detection for selection
                if (!justFinishedShapeDrag.current && !e.evt.shiftKey) {
                  handleClickWithDebouncing(e, onClick, onDblClick);
                }
                return;
              }
 
              // CRITICAL: Handle Alt+click FIRST (for point deletion and segment breaking)
              // This must happen before any other click handling to ensure deletion works
              if (e.evt.altKey && !e.evt.shiftKey && selected) {
                // Let the event bubble to the Group onClick handler which has the Alt+click logic
                // Don't stop propagation or prevent default - let it reach createClickHandler
                return;
              }
 
              // Don't add points if we just finished shape dragging
              if (justFinishedShapeDrag.current) {
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.cancelBubble = true; // Also set cancelBubble for Konva
                justFinishedShapeDrag.current = false; // Clear flag immediately
                return;
              }
 
              // Check if click is on the last added point by checking cursor position
              if (cursorPositionRef.current && lastAddedPointId) {
                const lastAddedPoint = initialPoints.find((p) => p.id === lastAddedPointId);
                if (lastAddedPoint) {
                  const scale = transform.zoom * fitScale;
                  const hitRadius = HIT_RADIUS.SELECTION / scale; // Use constant for consistent hit detection
                  const distance = Math.sqrt(
                    (cursorPositionRef.current.x - lastAddedPoint.x) ** 2 +
                      (cursorPositionRef.current.y - lastAddedPoint.y) ** 2,
                  );
 
                  if (distance <= hitRadius) {
                    // Find the index of the last added point
                    const lastAddedPointIndex = initialPoints.findIndex((p) => p.id === lastAddedPointId);
 
                    // Only trigger onFinish if the last added point is already selected (second click)
                    // and no modifiers are pressed (ctrl, meta, shift, alt) and component is selected
                    // and not in transform mode
                    if (
                      lastAddedPointIndex !== -1 &&
                      effectiveSelectedPoints.has(lastAddedPointIndex) &&
                      selected &&
                      !transformMode
                    ) {
                      const hasModifiers = e.evt.ctrlKey || e.evt.metaKey || e.evt.shiftKey || e.evt.altKey;
                      if (!hasModifiers) {
                        e.evt.preventDefault();
                        onFinish?.(e);
                        return;
                      }
                      // If modifiers are held, skip onFinish entirely and let normal modifier handling take over
                      return;
                    }
                  }
                }
              }
 
              // Use debouncing for click/double-click detection
              // This will call the onClick handler from VectorRegion.jsx which handles shape selection/unselection
              // Only call if we didn't just finish dragging (to allow shape dragging to work)
              // Don't call if Shift is held (to allow shift-click for ghost point insertion without unselecting)
              if (!justFinishedShapeDrag.current && !e.evt.shiftKey) {
                // Stop propagation to prevent the Group onClick handler from also processing the click
                // This prevents the shape from being selected and then immediately unselected
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.cancelBubble = true;
                handleClickWithDebouncing(e, onClick, onDblClick);
              }
            }}
            onMouseDown={(e) => {
              // Don't start shape drag if disabled
              if (disabled) {
                return;
              }
              // Don't start shape drag if in multi-region selection mode
              // ImageTransformer will handle dragging in this case
              if (isMultiRegionSelected) {
                return;
              }
 
              // Don't start shape drag if we're already dragging a point or control point
              if (draggedPointIndex !== null || draggedControlPoint !== null) {
                return;
              }
 
              // Don't start shape drag if transformer is active
              if (effectiveSelectedPoints.size > 1) {
                return;
              }
 
              // Don't start shape drag if clicking on a point
              const pos = e.target.getStage()?.getPointerPosition();
              if (!pos) return;
 
              const imagePos = stageToImageCoordinates(pos, transform, fitScale, x, y);
              const scale = transform.zoom * fitScale;
              const hitRadius = HIT_RADIUS.SELECTION / scale;
 
              // Check if clicking on any point
              for (let i = 0; i < initialPoints.length; i++) {
                const point = initialPoints[i];
                const distance = Math.sqrt((imagePos.x - point.x) ** 2 + (imagePos.y - point.y) ** 2);
                if (distance <= hitRadius) {
                  return; // Let point dragging handle it
                }
              }
 
              // Check if clicking on any control point
              for (let i = 0; i < initialPoints.length; i++) {
                const point = initialPoints[i];
                if (point.isBezier) {
                  if (point.controlPoint1) {
                    const distance = Math.sqrt(
                      (imagePos.x - point.controlPoint1.x) ** 2 + (imagePos.y - point.controlPoint1.y) ** 2,
                    );
                    if (distance <= hitRadius) {
                      return; // Let control point dragging handle it
                    }
                  }
                  if (point.controlPoint2) {
                    const distance = Math.sqrt(
                      (imagePos.x - point.controlPoint2.x) ** 2 + (imagePos.y - point.controlPoint2.y) ** 2,
                    );
                    if (distance <= hitRadius) {
                      return; // Let control point dragging handle it
                    }
                  }
                }
              }
 
              // Start shape dragging (don't stop propagation yet - we'll do it on mouseup if we actually drag)
              setIsDraggingShape(true);
              handleTransformStart();
              shapeDragDistance.current = 0; // Reset drag distance
              shapeDragStartPos.current = {
                x: e.evt.clientX,
                y: e.evt.clientY,
                imageX: imagePos.x,
                imageY: imagePos.y,
              };
 
              // Store original positions of all points
              originalPointsPositions.current = initialPoints.map((point) => ({
                x: point.x,
                y: point.y,
                controlPoint1: point.controlPoint1 ? { x: point.controlPoint1.x, y: point.controlPoint1.y } : undefined,
                controlPoint2: point.controlPoint2 ? { x: point.controlPoint2.x, y: point.controlPoint2.y } : undefined,
              }));
            }}
            onMouseEnter={onMouseEnter}
            onMouseLeave={onMouseLeave}
            key={`vector-shape-${initialPoints.length}-${initialPoints.map((p) => p.id).join("-")}`}
          />
 
          {/* Ghost line - preview from last point to cursor */}
          {selected && !disabled && !disableGhostLine && (
            <GhostLine
              initialPoints={initialPoints}
              cursorPositionRef={cursorPositionRef}
              draggedControlPoint={draggedControlPoint}
              draggedPointIndex={draggedPointIndex}
              isDraggingNewBezier={isDraggingNewBezier}
              isPathClosed={finalIsPathClosed}
              allowClose={allowClose}
              transform={transform}
              fitScale={fitScale}
              maxPoints={maxPoints}
              minPoints={minPoints}
              skeletonEnabled={skeletonEnabled}
              selectedPointIndex={selectedPointIndex}
              lastAddedPointId={lastAddedPointId}
              activePointId={activePointId}
              stroke={stroke}
              pixelSnapping={pixelSnapping}
              drawingDisabled={drawingDisabled}
              isShiftKeyHeld={isShiftKeyHeld}
              transformMode={transformMode}
              effectiveSelectedPointsSize={effectiveSelectedPoints.size}
            />
          )}
 
          {/* Control points - render first so lines appear under main points */}
          {selected && !disabled && (
            <ControlPoints
              initialPoints={getAllPoints()}
              selectedPointIndex={selectedPointIndex}
              isDraggingNewBezier={isDraggingNewBezier}
              draggedControlPoint={draggedControlPoint}
              visibleControlPoints={visibleControlPoints}
              transform={transform}
              fitScale={fitScale}
              key={`control-points-${initialPoints.length}-${initialPoints.map((p, i) => `${i}-${p.x.toFixed(1)}-${p.y.toFixed(1)}-${p.controlPoint1?.x?.toFixed(1) || "null"}-${p.controlPoint1?.y?.toFixed(1) || "null"}-${p.controlPoint2?.x?.toFixed(1) || "null"}-${p.controlPoint2?.y?.toFixed(1) || "null"}`).join("-")}`}
            />
          )}
 
          {/* All vector points */}
          <VectorPoints
            initialPoints={getAllPoints()}
            selectedPointIndex={selectedPointIndex}
            selectedPoints={effectiveSelectedPoints}
            transform={transform}
            fitScale={fitScale}
            pointRefs={pointRefs}
            selected={selected}
            disabled={disabled}
            transformMode={transformMode}
            pointRadius={pointRadius}
            pointFill={pointFill}
            pointStroke={pointStroke}
            pointStrokeSelected={pointStrokeSelected}
            pointStrokeWidth={pointStrokeWidth}
            activePointId={activePointId}
            maxPoints={maxPoints}
            onPointClick={(e, pointIndex) => {
              // Handle Alt+click point deletion FIRST (before other checks)
              if (e.evt.altKey && !e.evt.shiftKey && selected) {
                deletePoint(
                  pointIndex,
                  initialPoints,
                  selectedPointIndex,
                  setSelectedPointIndex,
                  setVisibleControlPoints,
                  onPointSelected,
                  onPointRemoved,
                  onPointsChange,
                  setLastAddedPointId,
                  lastAddedPointId,
                );
                pointSelectionHandled.current = true;
                // Stop event propagation to prevent point addition
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.cancelBubble = true;
                return; // Successfully deleted point
              }
 
              // Handle Shift+click point conversion (before other checks)
              if (e.evt.shiftKey && !e.evt.altKey && selected && !disabled) {
                if (
                  handleShiftClickPointConversion(e, {
                    initialPoints,
                    transform,
                    fitScale,
                    x,
                    y,
                    allowBezier,
                    pixelSnapping,
                    onPointsChange,
                    onPointEdited,
                    setVisibleControlPoints,
                  } as any)
                ) {
                  pointSelectionHandled.current = true;
                  return; // Successfully converted point
                }
              }
 
              // Handle cmd/ctrl-click for multi-selection (when selected and not disabled)
              if (selected && !disabled && (e.evt.ctrlKey || e.evt.metaKey) && !e.evt.altKey && !e.evt.shiftKey) {
                // Check if this instance can have selection
                if (!tracker.canInstanceHaveSelection(instanceId)) {
                  return; // Block the selection
                }
 
                // Check if this point is already selected - if so, deselect it
                if (effectiveSelectedPoints.has(pointIndex)) {
                  const newSelection = new Set(effectiveSelectedPoints);
                  newSelection.delete(pointIndex);
                  tracker.selectPoints(instanceId, newSelection);
                  pointSelectionHandled.current = true;
                  e.evt.stopImmediatePropagation();
                  return;
                }
 
                // If not deselection, add to multi-selection
                const newSelection = new Set(effectiveSelectedPoints);
                newSelection.add(pointIndex);
                tracker.selectPoints(instanceId, newSelection);
                pointSelectionHandled.current = true;
                e.evt.stopImmediatePropagation();
                return;
              }
 
              // Handle point selection even when not selected (similar to shape clicks)
              // But never allow selection when disabled
              if (disabled) {
                return;
              }
              if (!selected) {
                // Check if this instance can have selection
                if (!tracker.canInstanceHaveSelection(instanceId)) {
                  return; // Block the selection
                }
 
                // Check if we're about to close the path - prevent point selection in this case
                if (
                  shouldClosePathOnPointClick(
                    pointIndex,
                    {
                      initialPoints,
                      allowClose,
                      isPathClosed: finalIsPathClosed,
                      skeletonEnabled,
                      activePointId,
                    } as any,
                    e,
                  )
                ) {
                  return; // Block the selection
                }
 
                // For non-selected mode, still allow point selection
                tracker.selectPoints(instanceId, new Set([pointIndex]));
                pointSelectionHandled.current = true;
 
                // CRITICAL: For single-point regions, directly call onClick handler so the region can be selected
                // Single-point regions have no segments to click on, so clicking the point must trigger region selection
                const isSinglePointRegion = initialPoints.length === 1;
                if (isSinglePointRegion && !e.evt.altKey && !e.evt.shiftKey && !e.evt.ctrlKey && !e.evt.metaKey) {
                  // Directly call handleClickWithDebouncing to trigger region selection
                  // This works even when selected=false (Group onClick is undefined)
                  handleClickWithDebouncing(e, onClick, onDblClick);
                  return;
                }
 
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.cancelBubble = true;
                return;
              }
 
              // Handle regular point selection (when selected, not disabled, and not in transform mode)
              if (selected && !disabled && !transformMode) {
                // Check if this instance can have selection
                if (!tracker.canInstanceHaveSelection(instanceId)) {
                  return; // Block the selection
                }
 
                // Select only this point (single selection for regular click)
                tracker.selectPoints(instanceId, new Set([pointIndex]));
                pointSelectionHandled.current = true;
 
                // CRITICAL: For single-point regions, directly call onClick handler so the region can be selected
                // Single-point regions have no segments to click on, so clicking the point must trigger region selection
                const isSinglePointRegion = initialPoints.length === 1;
                if (isSinglePointRegion && !e.evt.altKey && !e.evt.shiftKey && !e.evt.ctrlKey && !e.evt.metaKey) {
                  // Directly call handleClickWithDebouncing to trigger region selection
                  // This works even when selected=false (Group onClick is undefined)
                  handleClickWithDebouncing(e, onClick, onDblClick);
                  return;
                }
 
                // Don't call onClick here - clicking on points should NOT select/unselect the shape
                // Only clicking on segments should select/unselect the shape
                // EXCEPTION: Single-point regions (handled above)
                // Always stop event propagation to prevent the VectorShape onClick handler from firing
                // This prevents the shape from being selected/unselected when clicking on points
                e.evt.stopImmediatePropagation();
                e.evt.stopPropagation();
                e.evt.preventDefault();
                e.cancelBubble = true;
                return;
              }
 
              // Mark that point selection was handled
              pointSelectionHandled.current = true;
            }}
            onPointDragStart={eventHandlers.handlePointDragStart}
            onPointDragMove={eventHandlers.handlePointDragMove}
            onPointDragEnd={eventHandlers.handlePointDragEnd}
            onPointConvert={eventHandlers.handlePointConvert}
            onControlPointDragStart={eventHandlers.handleControlPointDragStart}
            onControlPointDragMove={eventHandlers.handleControlPointDragMove}
            onControlPointDragEnd={eventHandlers.handleControlPointDragEnd}
            onControlPointConvert={eventHandlers.handleControlPointConvert}
            onSegmentClick={eventHandlers.handleSegmentClick}
            visibleControlPoints={visibleControlPoints}
            allowBezier={allowBezier}
            isTransforming={isTransforming}
            key={`vector-points-${initialPoints.length}-${initialPoints.map((p, i) => `${i}-${p.x.toFixed(1)}-${p.y.toFixed(1)}-${p.controlPoint1?.x?.toFixed(1) || "null"}-${p.controlPoint1?.y?.toFixed(1) || "null"}-${p.controlPoint2?.x?.toFixed(1) || "null"}-${p.controlPoint2?.y?.toFixed(1) || "null"}`).join("-")}`}
          />
 
          {/* Proxy nodes for Transformer (positioned at exact point centers) - only show when not in drawing mode and not multi-region selected */}
          {drawingDisabled && !isMultiRegionSelected && (
            <ProxyNodes selectedPoints={effectiveSelectedPoints} initialPoints={getAllPoints()} proxyRefs={proxyRefs} />
          )}
 
          {/* Transformer for multiselection - only show when not in drawing mode and not multi-region selected */}
          {drawingDisabled && !isMultiRegionSelected && (
            <VectorTransformer
              selectedPoints={effectiveSelectedPoints}
              initialPoints={getAllPoints()}
              transformerRef={transformerRef}
              proxyRefs={proxyRefs}
              getCurrentPointsRef={getCurrentPointsRef}
              updateCurrentPointsRef={updateCurrentPointsRef}
              pixelSnapping={pixelSnapping}
              onPointsChange={(newPoints) => {
                // Update main path points
                onPointsChange?.(newPoints);
              }}
              onTransformationComplete={notifyTransformationComplete}
              onTransformationStart={() => {
                handleTransformStart();
              }}
              onTransformationEnd={() => {
                handleTransformEnd();
              }}
              bounds={{ x: 0, y: 0, width, height }}
              transform={transform}
              fitScale={fitScale}
            />
          )}
        </>
      )}
 
      {/* Ghost point - ALWAYS render if ghostPoint exists, outside any conditionals */}
      <GhostPoint
        ref={ghostPointRef}
        ghostPoint={ghostPoint}
        transform={transform}
        fitScale={fitScale}
        isShiftKeyHeld={isShiftKeyHeld}
        maxPoints={maxPoints}
        initialPointsLength={initialPoints.length}
        isDragging={isDragging.current}
      />
    </Group>
  );
});