wintf 0.0.1

Windows Tategaki Framework - Rust UI library with Japanese vertical text support
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
//! Windowsメッセージハンドラ関数
//!
//! 各関数はWindowsメッセージ定数と同じ名前を持ち、
//! 統一されたシグネチャ `fn(HWND, u32, WPARAM, LPARAM) -> Option<LRESULT>` を使用する。
//!
//! - `Some(LRESULT)`: 処理完了、この値を返す
//! - `None`: DefWindowProcWに委譲

#![allow(non_snake_case)]

use bevy_ecs::change_detection::DetectChangesMut;
use tracing::{debug, info, trace, warn};
use windows::Win32::Foundation::*;
use windows::Win32::UI::WindowsAndMessaging::*;
// Note: SetCapture/ReleaseCapture might require additional features or might not be exposed
// For MVP, we'll implement drag without explicit capture (Windows provides implicit capture during drag)

/// メッセージハンドラの戻り値型
/// - Some(LRESULT): 処理完了、この値を返す
/// - None: DefWindowProcWに委譲
type HandlerResult = Option<LRESULT>;

/// WM_NCCREATE: ウィンドウ作成時の非クライアント領域初期化
///
/// Entity IDをGWLP_USERDATAに保存する
#[inline]
pub(super) fn WM_NCCREATE(
    hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    let cs = lparam.0 as *const CREATESTRUCTW;
    if !cs.is_null() {
        let entity_bits = unsafe { (*cs).lpCreateParams as isize };
        // Entity IDをGWLP_USERDATAに保存(ID 0も有効)
        unsafe { SetWindowLongPtrW(hwnd, GWLP_USERDATA, entity_bits) };
    }
    None // DefWindowProcWに委譲
}

/// WM_NCDESTROY: ウィンドウ破棄時のクリーンアップ
///
/// Entity IDを取得してエンティティを削除し、GWLP_USERDATAをクリアする
#[inline]
pub(super) fn WM_NCDESTROY(
    hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    // Entity IDを取得してエンティティを削除
    if let Some(entity) = super::get_entity_from_hwnd(hwnd) {
        if let Some(world) = super::try_get_ecs_world() {
            let mut world = world.borrow_mut();

            // エンティティを削除(関連する全コンポーネントも削除される)
            // on_window_handle_removedシステムが自動的にApp通知を行う
            world.world_mut().despawn(entity);
        }
    }

    // GWLP_USERDATAをクリア
    unsafe { SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0) };

    None // DefWindowProcWに委譲
}

/// WM_ERASEBKGND: 背景消去要求
///
/// DirectCompositionで描画するため、背景消去をスキップする
#[inline]
pub(super) fn WM_ERASEBKGND(
    _hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    Some(LRESULT(1)) // 背景消去をスキップ
}

/// WM_PAINT: 再描画要求
///
/// DirectCompositionで描画するため、領域を無効化解除するだけ
#[inline]
pub(super) fn WM_PAINT(
    hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    use windows::Win32::Graphics::Gdi::ValidateRect;
    let _ = unsafe { ValidateRect(Some(hwnd), None) };
    Some(LRESULT(0))
}

/// WM_CLOSE: ウィンドウクローズ要求
///
/// DestroyWindowを呼び出してウィンドウを破棄する
#[inline]
pub(super) fn WM_CLOSE(
    hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    let _ = unsafe { DestroyWindow(hwnd) };
    Some(LRESULT(0))
}

/// WM_WINDOWPOSCHANGED: ウィンドウ位置/サイズ変更通知
///
/// World借用区切り方式による処理(3ステッププロトコル):
/// ① World借用 → DPI更新, echo判定に基づきWindowPos更新, BoxStyle更新 → 借用解放
/// ② try_tick_on_vsync() (内部で借用→解放)
/// ③ flush_window_pos_commands() (SetWindowPos実行、ラッパー経由)
///
/// echo判定: `is_self_initiated()` TLS フラグが `true` の場合、
/// 自アプリの `guarded_set_window_pos()` 経由の呼び出しであり、
/// `bypass_change_detection()` で `Changed<WindowPos>` の発火を抑制する。
#[inline]
pub(super) fn WM_WINDOWPOSCHANGED(
    hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    // echo 判定: TLS フラグを参照(ステップ①冒頭で1回のみ)
    let is_echo = crate::ecs::window::is_self_initiated();

    // ------------------------------------------------------------------
    // ① 第1借用セクション: DPI更新, echo判定に基づきWindowPos更新, BoxStyle更新
    // ------------------------------------------------------------------
    if let Some(entity) = super::get_entity_from_hwnd(hwnd) {
        if let Some(world) = super::try_get_ecs_world() {
            // DpiChangeContextを先に取得(try_tick_on_vsync前に消費する必要がある)
            // is_echo にかかわらず常に実行
            let dpi_context = crate::ecs::window::DpiChangeContext::take();

            // RefCellが既に借用されている場合はスキップ(再入時)
            if let Ok(mut world_borrow) = world.try_borrow_mut() {
                let windowpos = lparam.0 as *const WINDOWPOS;
                if !windowpos.is_null() {
                    let wp = unsafe { &*windowpos };

                    if let Ok(mut entity_ref) = world_borrow.world_mut().get_entity_mut(entity) {
                        // DpiChangeContextが存在する場合、DPIコンポーネントを即時更新
                        // これにより、以降の物理→論理座標変換で新DPIが使用される
                        let dpi = if let Some(ref ctx) = dpi_context {
                            // 新DPIでDPIコンポーネントを更新
                            if let Some(mut dpi_comp) =
                                entity_ref.get_mut::<crate::ecs::window::DPI>()
                            {
                                let old_dpi = *dpi_comp;
                                *dpi_comp = ctx.new_dpi;
                                trace!(
                                    entity = ?entity,
                                    old_dpi_x = old_dpi.dpi_x,
                                    old_dpi_y = old_dpi.dpi_y,
                                    new_dpi_x = ctx.new_dpi.dpi_x,
                                    new_dpi_y = ctx.new_dpi.dpi_y,
                                    "DPI updated via DpiChangeContext"
                                );
                            }
                            ctx.new_dpi
                        } else {
                            // コンテキストがない場合は既存のDPIを使用
                            entity_ref
                                .get::<crate::ecs::window::DPI>()
                                .copied()
                                .unwrap_or_default()
                        };

                        // WindowHandleを取得してウィンドウ座標→クライアント座標に変換
                        let client_coords = entity_ref
                            .get::<crate::ecs::window::WindowHandle>()
                            .and_then(|handle| {
                                handle
                                    .window_to_client_coords(wp.x, wp.y, wp.cx, wp.cy)
                                    .ok()
                            });

                        // クライアント座標が取得できた場合のみ処理
                        if let Some((client_pos, client_size)) = client_coords {
                            debug!(
                                is_echo = is_echo,
                                entity = ?entity,
                                x = client_pos.x,
                                y = client_pos.y,
                                cx = client_size.cx,
                                cy = client_size.cy,
                                "[WM_WINDOWPOSCHANGED] Processing"
                            );

                            if let Some(mut window_pos) =
                                entity_ref.get_mut::<crate::ecs::window::WindowPos>()
                            {
                                if is_echo {
                                    // echo(自アプリ由来)→ bypass_change_detection で更新
                                    // Changed<WindowPos> を発火させない → apply_window_pos_changes 非トリガー
                                    let bypass = window_pos.bypass_change_detection();
                                    bypass.position = Some(client_pos);
                                    bypass.size = Some(client_size);

                                    trace!(
                                        entity = ?entity,
                                        client_x = client_pos.x,
                                        client_y = client_pos.y,
                                        "WindowPos updated via bypass (echo)"
                                    );
                                } else {
                                    // 外部由来 → DerefMut で更新(Changed 発火 → apply_window_pos_changes トリガー)
                                    window_pos.position = Some(client_pos);
                                    window_pos.size = Some(client_size);

                                    trace!(
                                        entity = ?entity,
                                        window_x = wp.x,
                                        window_y = wp.y,
                                        window_cx = wp.cx,
                                        window_cy = wp.cy,
                                        client_x = client_pos.x,
                                        client_y = client_pos.y,
                                        client_cx = client_size.cx,
                                        client_cy = client_size.cy,
                                        "WindowPos updated (external change)"
                                    );
                                }
                            }

                            // BoxStyle.size のサイズ変更判定と条件付き更新
                            // BoxStyle.inset への書き込みは行わない(Window位置はWindowPosが唯一のsource of truth)
                            // 注: BoxStyleは論理座標(DIP)を使用するため、物理ピクセルから変換が必要
                            {
                                use crate::ecs::layout::{BoxSize, Dimension};

                                let physical_width = client_size.cx as f32;
                                let physical_height = client_size.cy as f32;

                                // DPI スケールで割って論理サイズに変換
                                let scale_x = dpi.scale_x();
                                let scale_y = dpi.scale_y();
                                let logical_width = physical_width / scale_x;
                                let logical_height = physical_height / scale_y;

                                let new_size = Some(BoxSize {
                                    width: Some(Dimension::Px(logical_width)),
                                    height: Some(Dimension::Px(logical_height)),
                                });

                                // Step 1: 現在のサイズを読み取り(immutable borrow)
                                let current_size = entity_ref
                                    .get::<crate::ecs::layout::BoxStyle>()
                                    .map(|bs| bs.size);

                                // Step 2: サイズ変更がある場合のみ get_mut で更新(Changed<BoxStyle> 発火)
                                let size_changed =
                                    current_size.map(|cs| cs != new_size).unwrap_or(false);

                                if size_changed {
                                    if let Some(mut box_style) =
                                        entity_ref.get_mut::<crate::ecs::layout::BoxStyle>()
                                    {
                                        box_style.size = new_size;
                                    }

                                    trace!(
                                        entity = ?entity,
                                        physical_width = physical_width,
                                        physical_height = physical_height,
                                        logical_width = logical_width,
                                        logical_height = logical_height,
                                        scale_x = scale_x,
                                        scale_y = scale_y,
                                        "[WM_WINDOWPOSCHANGED] BoxStyle.size updated (size changed)"
                                    );
                                } else {
                                    trace!(
                                        entity = ?entity,
                                        "[WM_WINDOWPOSCHANGED] BoxStyle.size unchanged, skipping update"
                                    );
                                }
                            }
                        }
                    }
                }
            }
            // world_borrowスコープ終了: 借用解放

            // ------------------------------------------------------------------
            // ② try_tick_on_vsync() (内部で借用→解放)
            // ------------------------------------------------------------------
            {
                use crate::ecs::world::VsyncTick;
                let _ = world.try_tick_on_vsync();
            }

            // ------------------------------------------------------------------
            // ③ flush_window_pos_commands() (SetWindowPos実行、ラッパー経由)
            // World借用解放後なので安全
            // ------------------------------------------------------------------
            crate::ecs::window::flush_window_pos_commands();
        }
    }
    None // DefWindowProcWに委譲
}

/// WM_DISPLAYCHANGE: ディスプレイ構成変更通知
///
/// Appリソースのmark_display_changeを呼び出す
#[inline]
pub(super) fn WM_DISPLAYCHANGE(
    _hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    if let Some(world) = super::try_get_ecs_world() {
        if let Ok(mut world_borrow) = world.try_borrow_mut() {
            if let Some(mut app) = world_borrow
                .world_mut()
                .get_resource_mut::<crate::ecs::App>()
            {
                app.mark_display_change();
            }
        }
    }
    None // DefWindowProcWに委譲
}

/// WM_DPICHANGED: DPI変更通知(モニター間移動など)
///
/// Per-Monitor DPI Aware (v2)では、アプリケーションが明示的にSetWindowPosを呼ぶ必要がある
/// DpiChangeContextを設定し、SetWindowPosを呼び出す
#[inline]
pub(super) fn WM_DPICHANGED(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    let new_dpi = crate::ecs::window::DPI::from_WM_DPICHANGED(wparam, lparam);

    // lparam から suggested_rect を取得
    let suggested_rect_ptr = lparam.0 as *const RECT;
    let suggested_rect = if !suggested_rect_ptr.is_null() {
        unsafe { *suggested_rect_ptr }
    } else {
        RECT::default()
    };

    debug!(
        hwnd = ?hwnd,
        dpi_x = new_dpi.dpi_x,
        dpi_y = new_dpi.dpi_y,
        scale_x = format_args!("{:.2}", new_dpi.scale_x()),
        scale_y = format_args!("{:.2}", new_dpi.scale_y()),
        suggested_left = suggested_rect.left,
        suggested_top = suggested_rect.top,
        suggested_right = suggested_rect.right,
        suggested_bottom = suggested_rect.bottom,
        "WM_DPICHANGED"
    );

    // DpiChangeContextをスレッドローカルに保存
    // SetWindowPos → WM_WINDOWPOSCHANGED の流れで
    // WM_WINDOWPOSCHANGEDがこのコンテキストを消費する
    crate::ecs::window::DpiChangeContext::set(crate::ecs::window::DpiChangeContext::new(
        new_dpi,
        suggested_rect,
    ));

    // 明示的にSetWindowPosを呼び出してsuggested_rectを適用
    // guarded_set_window_pos ラッパー経由でフィードバック防止TLSフラグを管理
    // これによりWM_WINDOWPOSCHANGEDが同期的に発火し、DpiChangeContextを消費する
    let width = suggested_rect.right - suggested_rect.left;
    let height = suggested_rect.bottom - suggested_rect.top;
    trace!(
        hwnd = ?hwnd,
        x = suggested_rect.left,
        y = suggested_rect.top,
        width,
        height,
        "Calling guarded_set_window_pos with suggested_rect"
    );

    let result = unsafe {
        crate::ecs::window::guarded_set_window_pos(
            hwnd,
            None,
            suggested_rect.left,
            suggested_rect.top,
            width,
            height,
            SWP_NOZORDER | SWP_NOACTIVATE,
        )
    };
    if let Err(e) = result {
        warn!(hwnd = ?hwnd, error = ?e, "SetWindowPos failed in WM_DPICHANGED");
    }

    Some(LRESULT(0))
}

// ============================================================================
// マウスメッセージハンドラ (Task 3.1-3.4, 4.1)
// ============================================================================

/// WM_NCHITTEST: 非クライアント領域ヒットテスト
///
/// クライアント領域判定を実装し、キャッシュ付きhit_testを呼び出す。
/// HTCLIENT / HTTRANSPARENT を返す(クリックスルー対応)。
#[inline]
pub(super) fn WM_NCHITTEST(
    hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    use windows::Win32::UI::WindowsAndMessaging::GetClientRect;

    // スクリーン座標を取得(lparam から)
    let x = (lparam.0 & 0xFFFF) as i16 as i32;
    let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as i32;

    // クライアント領域判定用に座標変換(クライアント領域外はDefWindowProcWに委譲)
    unsafe {
        use windows::Win32::Graphics::Gdi::ScreenToClient;
        let mut pt = POINT { x, y };
        if !ScreenToClient(hwnd, &mut pt).as_bool() {
            return None; // DefWindowProcW に委譲
        }

        // クライアント領域外の場合は DefWindowProcW に委譲
        let mut rect = RECT::default();
        if GetClientRect(hwnd, &mut rect).is_err() {
            return None;
        }
        if pt.x < rect.left || pt.x >= rect.right || pt.y < rect.top || pt.y >= rect.bottom {
            return None; // DefWindowProcW に委譲(非クライアント領域処理)
        }
    }

    // Entity 取得
    let Some(entity) = super::get_entity_from_hwnd(hwnd) else {
        return None;
    };

    // World 取得
    let Some(world) = super::try_get_ecs_world() else {
        return None;
    };

    // キャッシュ付きヒットテスト実行
    crate::ecs::nchittest_cache::cached_nchittest(hwnd, (x, y), entity, &world)
}

/// 当該ウィンドウに属し、exclude と異なるエンティティの PointerState 保持者を収集する。
///
/// WM_MOUSEMOVE の leave 処理で使用するヘルパー関数。
/// `find_owner_window` でウィンドウスコーピングを行い、他ウィンドウの PointerState を保護する。
fn collect_entities_to_leave(
    world: &mut bevy_ecs::world::World,
    window_entity: bevy_ecs::prelude::Entity,
    exclude: bevy_ecs::prelude::Entity,
) -> Vec<bevy_ecs::prelude::Entity> {
    use crate::ecs::pointer::PointerState;
    use crate::ecs::window::find_owner_window;

    let mut result = Vec::new();
    let mut query = world.query::<(bevy_ecs::prelude::Entity, &PointerState)>();
    for (e, _) in query.iter(world) {
        if e != exclude && find_owner_window(world, e) == Some(window_entity) {
            result.push(e);
        }
    }
    result
}

/// WM_MOUSEMOVE: マウス移動メッセージ
///
/// 位置をPointerBufferに蓄積し、hit_testでヒットしたエンティティにPointerStateを付与。
/// 初回移動時にTrackMouseEventを設定。
#[inline]
pub(super) fn WM_MOUSEMOVE(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    use crate::ecs::layout::hit_test::{PhysicalPoint as HitTestPoint, hit_test_in_window};
    use crate::ecs::pointer::{
        PointerLeave, PointerState, WindowPointerTracking, push_pointer_sample, set_modifier_state,
    };
    use std::time::Instant;
    use windows::Win32::UI::Input::KeyboardAndMouse::{
        TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent,
    };

    let Some(window_entity) = super::get_entity_from_hwnd(hwnd) else {
        return None;
    };

    // 位置取得(物理ピクセル、クライアント座標)
    let x = (lparam.0 & 0xFFFF) as i16 as i32;
    let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as i32;

    tracing::trace!("[WM_MOUSEMOVE] Received: x={}, y={}", x, y);

    // 修飾キー状態を抽出
    let wparam_val = wparam.0 as u32;
    let shift = (wparam_val & 0x04) != 0; // MK_SHIFT
    let ctrl = (wparam_val & 0x08) != 0; // MK_CONTROL

    // World借用してhit_testとPointerState管理
    // ドラッグ中のSetWindowPosはWorld借用外で実行する(WM_WINDOWPOSCHANGED同期発火対策)
    let mut deferred_set_window_pos: Option<(HWND, i32, i32)> = None;

    if let Some(world) = super::try_get_ecs_world() {
        if let Ok(mut world_borrow) = world.try_borrow_mut() {
            // TrackMouseEvent 設定(ウィンドウに対して)
            if let Ok(mut entity_ref) = world_borrow.world_mut().get_entity_mut(window_entity) {
                let needs_tracking = entity_ref
                    .get::<WindowPointerTracking>()
                    .is_none_or(|t| !t.0);

                if needs_tracking {
                    let mut tme = TRACKMOUSEEVENT {
                        cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
                        dwFlags: TME_LEAVE,
                        hwndTrack: hwnd,
                        dwHoverTime: 0,
                    };
                    let _ = unsafe { TrackMouseEvent(&mut tme) };

                    if entity_ref.get::<WindowPointerTracking>().is_some() {
                        if let Some(mut tracking) = entity_ref.get_mut::<WindowPointerTracking>() {
                            tracking.0 = true;
                        }
                    } else {
                        drop(entity_ref);
                        world_borrow
                            .world_mut()
                            .entity_mut(window_entity)
                            .insert(WindowPointerTracking(true));
                    }

                    trace!(
                        entity = ?window_entity,
                        hwnd = ?hwnd,
                        "TrackMouseEvent(TME_LEAVE) set"
                    );
                }
            }

            // hit_test でヒットしたエンティティを取得
            let hit_entity = hit_test_in_window(
                world_borrow.world(),
                window_entity,
                HitTestPoint::new(x as f32, y as f32),
            );

            // WindowPosを取得してスクリーン座標を計算
            let window_pos = world_borrow
                .world()
                .get::<crate::ecs::window::WindowPos>(window_entity);
            let (screen_x, screen_y) = if let Some(wp) = window_pos {
                if let Some(pos) = wp.position {
                    (x + pos.x, y + pos.y)
                } else {
                    (x, y)
                }
            } else {
                (x, y)
            };

            // ドラッグ処理(thread_local DragState + DragAccumulatorResource)
            // ヒットテスト結果に関わらず、Preparing/Dragging状態なら処理を続ける
            let state_snapshot = crate::ecs::drag::read_drag_state(|state| state.clone());

            match state_snapshot {
                crate::ecs::drag::DragState::Preparing {
                    entity,
                    start_pos,
                    start_time,
                } => {
                    if let Some(drag_config) = world_borrow
                        .world()
                        .get::<crate::ecs::drag::DragConfig>(entity)
                    {
                        if drag_config.enabled {
                            let current_pos =
                                crate::ecs::pointer::PhysicalPoint::new(screen_x, screen_y);

                            // 閾値チェック
                            let dx = current_pos.x - start_pos.x;
                            let dy = current_pos.y - start_pos.y;
                            let distance_sq = dx * dx + dy * dy;
                            let threshold_sq = drag_config.threshold * drag_config.threshold;

                            if distance_sq >= threshold_sq {
                                // 閾値到達:Dragging状態に遷移
                                crate::ecs::drag::start_dragging(current_pos);

                                // DragAccumulatorResourceにStarted遷移を記録
                                if let Some(accumulator) = world_borrow
                                    .world()
                                    .get_resource::<crate::ecs::drag::DragAccumulatorResource>(
                                ) {
                                    accumulator.set_transition(
                                        crate::ecs::drag::DragTransition::Started {
                                            entity,
                                            start_pos,
                                            timestamp: start_time,
                                        },
                                    );
                                    accumulator.update_position(current_pos);
                                }
                            }
                        }
                    }
                }
                crate::ecs::drag::DragState::Dragging {
                    prev_pos,
                    start_pos,
                    hwnd: drag_hwnd,
                    initial_window_pos,
                    move_window,
                    constraint,
                    ..
                } => {
                    let current_pos = crate::ecs::pointer::PhysicalPoint::new(screen_x, screen_y);

                    // ドラッグ中:デルタを累積
                    let delta = crate::ecs::pointer::PhysicalPoint::new(
                        current_pos.x - prev_pos.x,
                        current_pos.y - prev_pos.y,
                    );

                    tracing::trace!(
                        "[WM_MOUSEMOVE] Dragging: delta=({}, {}), current=({}, {})",
                        delta.x,
                        delta.y,
                        current_pos.x,
                        current_pos.y
                    );

                    // DragAccumulatorResourceにデルタを累積
                    if let Some(accumulator) = world_borrow
                        .world()
                        .get_resource::<crate::ecs::drag::DragAccumulatorResource>(
                    ) {
                        accumulator.accumulate_delta(delta);
                        accumulator.update_position(current_pos);
                    }

                    // thread_local DragStateのprev_posを更新
                    let ctx_res = world_borrow
                        .world()
                        .get_resource::<crate::ecs::drag::WindowDragContextResource>();
                    crate::ecs::drag::update_dragging(current_pos, ctx_res);

                    // WndProcレベル直接SetWindowPos(ECSパイプラインバイパス)
                    // NOTE: SetWindowPosはWM_WINDOWPOSCHANGEDを同期発火し、そこで
                    // World borrowが必要になるため、借用スコープ外に遅延実行する
                    if move_window {
                        let mut new_x = initial_window_pos.x + (current_pos.x - start_pos.x);
                        let mut new_y = initial_window_pos.y + (current_pos.y - start_pos.y);

                        // DragConstraint 適用
                        if let Some(ref c) = constraint {
                            let (cx, cy) = c.apply(new_x, new_y);
                            new_x = cx;
                            new_y = cy;
                        }

                        deferred_set_window_pos = Some((drag_hwnd, new_x, new_y));
                    }
                }
                _ => {}
            }

            // ヒットしたエンティティが存在する場合
            if let Some(target_entity) = hit_entity {
                // 当該ウィンドウに属し、target_entity と異なるエンティティを Leave 対象として収集
                let entities_to_leave = collect_entities_to_leave(
                    world_borrow.world_mut(),
                    window_entity,
                    target_entity,
                );

                // 古いエンティティからPointerStateを削除し、PointerLeaveを付与
                for old_entity in entities_to_leave {
                    if let Ok(mut entity_ref) = world_borrow.world_mut().get_entity_mut(old_entity)
                    {
                        entity_ref.remove::<PointerState>();
                        entity_ref.insert(PointerLeave);
                        debug!(
                            old_entity = ?old_entity,
                            new_entity = ?target_entity,
                            "PointerState moved, Leave marker inserted"
                        );
                    }
                }

                // 新しいエンティティにPointerStateを挿入または維持
                if let Ok(entity_ref) = world_borrow.world_mut().get_entity_mut(target_entity) {
                    let needs_insert = entity_ref.get::<PointerState>().is_none();
                    tracing::trace!(
                        entity = ?target_entity,
                        needs_insert,
                        "[WM_MOUSEMOVE] PointerState check"
                    );
                    drop(entity_ref);

                    if needs_insert {
                        world_borrow
                            .world_mut()
                            .entity_mut(target_entity)
                            .insert(PointerState {
                                client_point: crate::ecs::pointer::PhysicalPoint::new(x, y),
                                local_point: crate::ecs::pointer::PhysicalPoint::new(x, y),
                                shift_down: shift,
                                ctrl_down: ctrl,
                                ..Default::default()
                            });
                        debug!(
                            entity = ?target_entity,
                            x, y,
                            "PointerState inserted (Enter)"
                        );
                    }
                } else {
                    tracing::warn!(
                        entity = ?target_entity,
                        "[WM_MOUSEMOVE] Failed to get entity_mut"
                    );
                }

                // PointerStateが存在することを保証した上で、バッファに蓄積
                push_pointer_sample(target_entity, x as f32, y as f32, Instant::now());
                set_modifier_state(target_entity, shift, ctrl);
            } else {
                // hit_test失敗(Windowの空白部分)
                // Windowエンティティに対して処理
                let target_entity = window_entity;

                // 当該ウィンドウに属し、target_entity と異なるエンティティを Leave 対象として収集
                let entities_to_leave = collect_entities_to_leave(
                    world_borrow.world_mut(),
                    window_entity,
                    target_entity,
                );

                // 古いエンティティからPointerStateを削除し、PointerLeaveを付与
                for old_entity in entities_to_leave {
                    if let Ok(mut entity_ref) = world_borrow.world_mut().get_entity_mut(old_entity)
                    {
                        entity_ref.remove::<PointerState>();
                        entity_ref.insert(PointerLeave);
                        debug!(
                            old_entity = ?old_entity,
                            new_entity = ?target_entity,
                            "PointerState moved to Window, Leave marker inserted"
                        );
                    }
                }

                // PointerStateを挿入または維持
                if let Ok(entity_ref) = world_borrow.world_mut().get_entity_mut(target_entity) {
                    let needs_insert = entity_ref.get::<PointerState>().is_none();
                    drop(entity_ref);

                    if needs_insert {
                        world_borrow
                            .world_mut()
                            .entity_mut(target_entity)
                            .insert(PointerState {
                                client_point: crate::ecs::pointer::PhysicalPoint::new(x, y),
                                local_point: crate::ecs::pointer::PhysicalPoint::new(x, y),
                                shift_down: shift,
                                ctrl_down: ctrl,
                                ..Default::default()
                            });
                        debug!(
                            entity = ?target_entity,
                            x, y,
                            "PointerState inserted on Window (no hit)"
                        );
                    }
                }

                // PointerStateが存在することを保証した上で、バッファに蓄積
                push_pointer_sample(target_entity, x as f32, y as f32, Instant::now());
                set_modifier_state(target_entity, shift, ctrl);
            }
        }
    }

    // World借用解放後にSetWindowPosを実行
    // これにより同期発火するWM_WINDOWPOSCHANGEDがWorldを借用でき、
    // WindowPos.positionが正しく更新される
    if let Some((drag_hwnd, new_x, new_y)) = deferred_set_window_pos {
        let _ = unsafe {
            crate::ecs::window::guarded_set_window_pos(
                drag_hwnd,
                None,
                new_x,
                new_y,
                0,
                0,
                SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE,
            )
        };
    }

    Some(LRESULT(0))
}

/// WM_MOUSELEAVE: マウス離脱メッセージ
///
/// 当該ウィンドウに属するエンティティのPointerStateのみを削除し、
/// PointerLeaveマーカーを付与する(他ウィンドウのPointerStateは保持)。
#[inline]
pub(super) fn WM_MOUSELEAVE(
    hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    use crate::ecs::pointer::{PointerLeave, PointerState, WindowPointerTracking};
    use crate::ecs::window::find_owner_window;

    let Some(window_entity) = super::get_entity_from_hwnd(hwnd) else {
        return None;
    };

    if let Some(world) = super::try_get_ecs_world() {
        if let Ok(mut world_borrow) = world.try_borrow_mut() {
            // PointerStateを持つ全エンティティを収集(当該ウィンドウに属するもののみ)
            let mut entities_with_pointer_state = Vec::new();
            {
                let world_mut = world_borrow.world_mut();
                let mut query = world_mut.query::<(bevy_ecs::prelude::Entity, &PointerState)>();
                for (e, _) in query.iter(world_mut) {
                    if find_owner_window(world_mut, e) == Some(window_entity) {
                        entities_with_pointer_state.push(e);
                    }
                }
            }

            // 当該ウィンドウのエンティティからPointerStateを削除し、PointerLeaveを付与
            for entity in entities_with_pointer_state {
                if let Ok(mut entity_ref) = world_borrow.world_mut().get_entity_mut(entity) {
                    entity_ref.remove::<PointerState>();
                    entity_ref.insert(PointerLeave);
                    debug!(
                        entity = ?entity,
                        hwnd = ?hwnd,
                        "PointerLeave marker inserted (scoped to window)"
                    );
                }
            }

            // WindowPointerTrackingを無効化
            if let Ok(mut entity_ref) = world_borrow.world_mut().get_entity_mut(window_entity) {
                if let Some(mut tracking) = entity_ref.get_mut::<WindowPointerTracking>() {
                    tracking.0 = false;
                }
            }
        }
    }

    Some(LRESULT(0))
}

/// ボタンメッセージハンドラ共通処理
///
/// hit_test でヒット対象エンティティを特定し、ButtonBuffer に記録する。
/// PointerState がない場合は付与する。
#[inline]
fn handle_button_message(
    hwnd: HWND,
    wparam: WPARAM,
    lparam: LPARAM,
    button: crate::ecs::pointer::PointerButton,
    is_down: bool,
) -> HandlerResult {
    use crate::ecs::layout::hit_test::{PhysicalPoint as HitTestPoint, hit_test_in_window};
    use crate::ecs::pointer::{PhysicalPoint, PointerState};

    let Some(window_entity) = super::get_entity_from_hwnd(hwnd) else {
        return None;
    };

    // クリック位置を取得
    let x = (lparam.0 & 0xFFFF) as i16 as i32;
    let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as i32;

    tracing::debug!(
        "[WM_BUTTON] button={:?}, is_down={}, x={}, y={}",
        button,
        is_down,
        x,
        y
    );

    // 修飾キー状態を抽出
    let wparam_val = wparam.0 as u32;
    let shift = (wparam_val & 0x04) != 0;
    let ctrl = (wparam_val & 0x08) != 0;

    // スクリーン座標を事前計算(フォールバック処理でも使用)
    let (screen_x, screen_y) = if let Some(world) = super::try_get_ecs_world() {
        if let Ok(world_borrow) = world.try_borrow() {
            let window_pos = world_borrow
                .world()
                .get::<crate::ecs::window::WindowPos>(window_entity);
            if let Some(wp) = window_pos {
                if let Some(pos) = wp.position {
                    (x + pos.x, y + pos.y)
                } else {
                    (x, y)
                }
            } else {
                (x, y)
            }
        } else {
            (x, y)
        }
    } else {
        (x, y)
    };

    // hit_test でターゲットエンティティを特定し、PointerState を確保
    if let Some(world) = super::try_get_ecs_world() {
        if let Ok(mut world_borrow) = world.try_borrow_mut() {
            if let Some(target_entity) = hit_test_in_window(
                world_borrow.world(),
                window_entity,
                HitTestPoint::new(x as f32, y as f32),
            ) {
                // ヒットしたエンティティの名前とGlobalArrangement.boundsをログ出力
                let entity_name = world_borrow
                    .world()
                    .get::<bevy_ecs::name::Name>(target_entity)
                    .map(|n| n.as_str().to_string())
                    .unwrap_or_else(|| format!("{:?}", target_entity));
                let bounds_info = world_borrow
                    .world()
                    .get::<crate::ecs::layout::GlobalArrangement>(target_entity)
                    .map(|g| {
                        format!(
                            "({:.0},{:.0})-({:.0},{:.0})",
                            g.bounds.left, g.bounds.top, g.bounds.right, g.bounds.bottom
                        )
                    })
                    .unwrap_or_else(|| "no bounds".to_string());
                info!(
                    target_entity = ?target_entity,
                    entity_name = %entity_name,
                    client_x = x,
                    client_y = y,
                    screen_x,
                    screen_y,
                    bounds = %bounds_info,
                    button = ?button,
                    is_down,
                    "[handle_button_message] hit_test result"
                );

                // PointerState がない場合は付与
                if world_borrow
                    .world()
                    .get::<PointerState>(target_entity)
                    .is_none()
                {
                    world_borrow
                        .world_mut()
                        .entity_mut(target_entity)
                        .insert(PointerState {
                            client_point: PhysicalPoint::new(x, y),
                            local_point: PhysicalPoint::new(x, y),
                            left_down: button == crate::ecs::pointer::PointerButton::Left
                                && is_down,
                            right_down: button == crate::ecs::pointer::PointerButton::Right
                                && is_down,
                            middle_down: button == crate::ecs::pointer::PointerButton::Middle
                                && is_down,
                            shift_down: shift,
                            ctrl_down: ctrl,
                            ..Default::default()
                        });
                    debug!(
                        entity = ?target_entity,
                        button = ?button,
                        is_down,
                        "PointerState inserted on button event"
                    );
                }

                // 修飾キー状態を記録
                crate::ecs::pointer::set_modifier_state(target_entity, shift, ctrl);

                // ボタン状態をバッファに記録
                if is_down {
                    crate::ecs::pointer::record_button_down(target_entity, button);

                    // ドラッグ準備開始(DragConfigがあり、有効な場合)
                    // target_entity自身または祖先からDragConfigを探索
                    if button == crate::ecs::pointer::PointerButton::Left {
                        let drag_entity = {
                            let w = world_borrow.world();
                            find_ancestor_with_drag_config(w, target_entity)
                        };
                        if let Some((entity_with_config, drag_config)) = drag_entity {
                            if drag_config.enabled && drag_config.left_button {
                                tracing::info!(
                                    hit_entity = ?target_entity,
                                    drag_entity = ?entity_with_config,
                                    x = screen_x,
                                    y = screen_y,
                                    "[handle_button_message] Calling start_preparing (ancestor search)"
                                );
                                crate::ecs::drag::start_preparing(
                                    entity_with_config,
                                    PhysicalPoint::new(screen_x, screen_y),
                                );
                                // TODO: SetCapture for proper mouse capture (not available in current windows crate version)
                                // let _ = unsafe { SetCapture(hwnd) };
                            }
                        }
                    }
                } else {
                    crate::ecs::pointer::record_button_up(target_entity, button);

                    // ドラッグ終了(HWND ガード付き: 当該ウィンドウのドラッグのみ終了)
                    if button == crate::ecs::pointer::PointerButton::Left {
                        // thread_local DragStateをクローンして取得
                        let state_snapshot =
                            crate::ecs::drag::read_drag_state(|state| state.clone());

                        let should_end = match &state_snapshot {
                            crate::ecs::drag::DragState::Dragging {
                                hwnd: drag_hwnd, ..
                            } => *drag_hwnd == hwnd,
                            crate::ecs::drag::DragState::Preparing { entity, .. }
                            | crate::ecs::drag::DragState::JustStarted { entity, .. } => {
                                crate::ecs::window::find_owner_window(world_borrow.world(), *entity)
                                    == Some(window_entity)
                            }
                            _ => false,
                        };

                        if should_end {
                            if let crate::ecs::drag::DragState::Dragging { entity, .. }
                            | crate::ecs::drag::DragState::Preparing { entity, .. }
                            | crate::ecs::drag::DragState::JustStarted { entity, .. } =
                                &state_snapshot
                            {
                                // DragAccumulatorResourceにEnded遷移を記録
                                if let Some(accumulator) = world_borrow
                                    .world()
                                    .get_resource::<crate::ecs::drag::DragAccumulatorResource>(
                                ) {
                                    accumulator.set_transition(
                                        crate::ecs::drag::DragTransition::Ended {
                                            entity: *entity,
                                            end_pos: PhysicalPoint::new(screen_x, screen_y),
                                            cancelled: false,
                                        },
                                    );
                                }
                            }

                            // thread_local DragStateをIdleに戻す
                            crate::ecs::drag::end_dragging(
                                PhysicalPoint::new(screen_x, screen_y),
                                false,
                            );
                        } else {
                            trace!(
                                hwnd = format!("0x{:X}", hwnd.0 as usize),
                                "[handle_button_message] Drag end skipped: HWND mismatch"
                            );
                        }
                        // TODO: ReleaseCapture (not available in current windows crate version)
                        // let _ = unsafe { ReleaseCapture() };
                    }
                }

                return Some(LRESULT(0));
            }
        }
    }

    // フォールバック: ウィンドウエンティティに記録
    if is_down {
        crate::ecs::pointer::record_button_down(window_entity, button);
    } else {
        crate::ecs::pointer::record_button_up(window_entity, button);

        // ドラッグ終了(hit_test失敗時でもドラッグ中なら終了処理、HWNDガード付き)
        if button == crate::ecs::pointer::PointerButton::Left {
            let state_snapshot = crate::ecs::drag::read_drag_state(|state| state.clone());

            let should_end = match &state_snapshot {
                crate::ecs::drag::DragState::Dragging {
                    hwnd: drag_hwnd, ..
                } => *drag_hwnd == hwnd,
                crate::ecs::drag::DragState::Preparing { entity, .. }
                | crate::ecs::drag::DragState::JustStarted { entity, .. } => {
                    if let Some(world) = super::try_get_ecs_world() {
                        if let Ok(world_borrow) = world.try_borrow() {
                            crate::ecs::window::find_owner_window(world_borrow.world(), *entity)
                                == Some(window_entity)
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                }
                _ => false,
            };

            if should_end {
                if let Some(world) = super::try_get_ecs_world() {
                    if let Ok(world_borrow) = world.try_borrow() {
                        if let crate::ecs::drag::DragState::Dragging { entity, .. }
                        | crate::ecs::drag::DragState::Preparing { entity, .. }
                        | crate::ecs::drag::DragState::JustStarted { entity, .. } =
                            &state_snapshot
                        {
                            // DragAccumulatorResourceにEnded遷移を記録
                            if let Some(accumulator) = world_borrow
                                .world()
                                .get_resource::<crate::ecs::drag::DragAccumulatorResource>(
                            ) {
                                accumulator.set_transition(
                                    crate::ecs::drag::DragTransition::Ended {
                                        entity: *entity,
                                        end_pos: PhysicalPoint::new(screen_x, screen_y),
                                        cancelled: false,
                                    },
                                );
                            }
                        }
                    }
                }

                // thread_local DragStateをIdleに戻す
                crate::ecs::drag::end_dragging(PhysicalPoint::new(screen_x, screen_y), false);
            } else {
                trace!(
                    hwnd = format!("0x{:X}", hwnd.0 as usize),
                    "[handle_button_message] Fallback drag end skipped: HWND mismatch"
                );
            }
            // TODO: ReleaseCapture (not available in current windows crate version)
            // let _ = unsafe { ReleaseCapture() };
        }
    }

    Some(LRESULT(0))
}

/// WM_LBUTTONDOWN: 左ボタン押下
#[inline]
pub(super) fn WM_LBUTTONDOWN(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    handle_button_message(
        hwnd,
        wparam,
        lparam,
        crate::ecs::pointer::PointerButton::Left,
        true,
    )
}

/// WM_LBUTTONUP: 左ボタン解放
#[inline]
pub(super) fn WM_LBUTTONUP(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    handle_button_message(
        hwnd,
        wparam,
        lparam,
        crate::ecs::pointer::PointerButton::Left,
        false,
    )
}

/// WM_RBUTTONDOWN: 右ボタン押下
#[inline]
pub(super) fn WM_RBUTTONDOWN(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    handle_button_message(
        hwnd,
        wparam,
        lparam,
        crate::ecs::pointer::PointerButton::Right,
        true,
    )
}

/// WM_RBUTTONUP: 右ボタン解放
#[inline]
pub(super) fn WM_RBUTTONUP(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    handle_button_message(
        hwnd,
        wparam,
        lparam,
        crate::ecs::pointer::PointerButton::Right,
        false,
    )
}

/// WM_MBUTTONDOWN: 中ボタン押下
#[inline]
pub(super) fn WM_MBUTTONDOWN(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    handle_button_message(
        hwnd,
        wparam,
        lparam,
        crate::ecs::pointer::PointerButton::Middle,
        true,
    )
}

/// WM_MBUTTONUP: 中ボタン解放
#[inline]
pub(super) fn WM_MBUTTONUP(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    handle_button_message(
        hwnd,
        wparam,
        lparam,
        crate::ecs::pointer::PointerButton::Middle,
        false,
    )
}

/// WM_XBUTTONDOWN: 拡張ボタン押下
#[inline]
pub(super) fn WM_XBUTTONDOWN(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    // GET_XBUTTON_WPARAM: HIWORD of wParam
    let xbutton = ((wparam.0 >> 16) & 0xFFFF) as u16;
    let button = if xbutton == 1 {
        crate::ecs::pointer::PointerButton::XButton1
    } else {
        crate::ecs::pointer::PointerButton::XButton2
    };
    handle_button_message(hwnd, wparam, lparam, button, true)
}

/// WM_XBUTTONUP: 拡張ボタン解放
#[inline]
pub(super) fn WM_XBUTTONUP(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    let xbutton = ((wparam.0 >> 16) & 0xFFFF) as u16;
    let button = if xbutton == 1 {
        crate::ecs::pointer::PointerButton::XButton1
    } else {
        crate::ecs::pointer::PointerButton::XButton2
    };
    handle_button_message(hwnd, wparam, lparam, button, false)
}

/// ダブルクリックメッセージハンドラ共通処理
#[inline]
/// WM_*BUTTONDBLCLK ハンドラ共通処理
///
/// ダブルクリックイベントを処理し、hit_testでターゲットエンティティを特定して
/// PointerStateを付与する。WM_LBUTTONDOWNの代わりにWM_LBUTTONDBLCLKが来るため、
/// ボタン押下記録も同時に行う。
///
/// # Arguments
/// - `hwnd`: ウィンドウハンドル
/// - `wparam`: 修飾キー状態とXBUTTON情報
/// - `lparam`: クリック座標(クライアント座標)
/// - `double_click`: ダブルクリック種別
fn handle_double_click_message(
    hwnd: HWND,
    wparam: WPARAM,
    lparam: LPARAM,
    double_click: crate::ecs::pointer::DoubleClick,
) -> HandlerResult {
    use crate::ecs::layout::hit_test::{PhysicalPoint as HitTestPoint, hit_test_in_window};
    use crate::ecs::pointer::{PhysicalPoint, PointerState};

    let Some(window_entity) = super::get_entity_from_hwnd(hwnd) else {
        return None;
    };

    // クリック位置を取得
    let x = (lparam.0 & 0xFFFF) as i16 as i32;
    let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as i32;

    // 修飾キー状態を抽出
    let wparam_val = wparam.0 as u32;
    let shift = (wparam_val & 0x04) != 0;
    let ctrl = (wparam_val & 0x08) != 0;

    // ダブルクリックに対応するボタンを取得
    let button = match double_click {
        crate::ecs::pointer::DoubleClick::Left => crate::ecs::pointer::PointerButton::Left,
        crate::ecs::pointer::DoubleClick::Right => crate::ecs::pointer::PointerButton::Right,
        crate::ecs::pointer::DoubleClick::Middle => crate::ecs::pointer::PointerButton::Middle,
        crate::ecs::pointer::DoubleClick::XButton1 => crate::ecs::pointer::PointerButton::XButton1,
        crate::ecs::pointer::DoubleClick::XButton2 => crate::ecs::pointer::PointerButton::XButton2,
        crate::ecs::pointer::DoubleClick::None => return Some(LRESULT(0)),
    };

    // hit_test でターゲットエンティティを特定し、PointerState を確保
    if let Some(world) = super::try_get_ecs_world() {
        if let Ok(mut world_borrow) = world.try_borrow_mut() {
            if let Some(target_entity) = hit_test_in_window(
                world_borrow.world(),
                window_entity,
                HitTestPoint::new(x as f32, y as f32),
            ) {
                tracing::info!(
                    window_entity = ?window_entity,
                    target_entity = ?target_entity,
                    double_click = ?double_click,
                    x, y,
                    "[handle_double_click_message] Double-click detected"
                );

                // PointerState がない場合は付与
                if world_borrow
                    .world()
                    .get::<PointerState>(target_entity)
                    .is_none()
                {
                    world_borrow
                        .world_mut()
                        .entity_mut(target_entity)
                        .insert(PointerState {
                            client_point: PhysicalPoint::new(x, y),
                            local_point: PhysicalPoint::new(x, y),
                            left_down: button == crate::ecs::pointer::PointerButton::Left,
                            right_down: button == crate::ecs::pointer::PointerButton::Right,
                            middle_down: button == crate::ecs::pointer::PointerButton::Middle,
                            xbutton1_down: button == crate::ecs::pointer::PointerButton::XButton1,
                            xbutton2_down: button == crate::ecs::pointer::PointerButton::XButton2,
                            shift_down: shift,
                            ctrl_down: ctrl,
                            double_click,
                            ..Default::default()
                        });
                    debug!(
                        entity = ?target_entity,
                        button = ?button,
                        double_click = ?double_click,
                        "PointerState inserted on double-click event"
                    );
                } else {
                    // 既存の PointerState に double_click を設定
                    if let Some(mut ps) = world_borrow
                        .world_mut()
                        .get_mut::<PointerState>(target_entity)
                    {
                        ps.double_click = double_click;
                        ps.shift_down = shift;
                        ps.ctrl_down = ctrl;
                    }
                }

                // 修飾キー状態を記録
                crate::ecs::pointer::set_modifier_state(target_entity, shift, ctrl);

                // ボタン状態をバッファに記録
                crate::ecs::pointer::record_button_down(target_entity, button);
            }
        }
    }

    Some(LRESULT(0))
}

/// WM_LBUTTONDBLCLK: 左ボタンダブルクリック
#[inline]
pub(super) fn WM_LBUTTONDBLCLK(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    handle_double_click_message(hwnd, wparam, lparam, crate::ecs::pointer::DoubleClick::Left)
}

/// WM_RBUTTONDBLCLK: 右ボタンダブルクリック
#[inline]
pub(super) fn WM_RBUTTONDBLCLK(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    handle_double_click_message(
        hwnd,
        wparam,
        lparam,
        crate::ecs::pointer::DoubleClick::Right,
    )
}

/// WM_MBUTTONDBLCLK: 中ボタンダブルクリック
#[inline]
pub(super) fn WM_MBUTTONDBLCLK(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    handle_double_click_message(
        hwnd,
        wparam,
        lparam,
        crate::ecs::pointer::DoubleClick::Middle,
    )
}

/// WM_XBUTTONDBLCLK: 拡張ボタンダブルクリック
#[inline]
pub(super) fn WM_XBUTTONDBLCLK(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> HandlerResult {
    let xbutton = ((wparam.0 >> 16) & 0xFFFF) as u16;
    let double_click = if xbutton == 1 {
        crate::ecs::pointer::DoubleClick::XButton1
    } else {
        crate::ecs::pointer::DoubleClick::XButton2
    };
    handle_double_click_message(hwnd, wparam, lparam, double_click)
}

/// WM_MOUSEWHEEL: 垂直ホイール回転
#[inline]
pub(super) fn WM_MOUSEWHEEL(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    let Some(entity) = super::get_entity_from_hwnd(hwnd) else {
        return None;
    };

    // GET_WHEEL_DELTA_WPARAM: HIWORD of wParam (signed)
    let delta = ((wparam.0 >> 16) & 0xFFFF) as i16;
    crate::ecs::pointer::add_wheel_vertical(entity, delta);

    Some(LRESULT(0))
}

/// WM_MOUSEHWHEEL: 水平ホイール回転
#[inline]
pub(super) fn WM_MOUSEHWHEEL(
    hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    let Some(entity) = super::get_entity_from_hwnd(hwnd) else {
        return None;
    };

    let delta = ((wparam.0 >> 16) & 0xFFFF) as i16;
    crate::ecs::pointer::add_wheel_horizontal(entity, delta);

    Some(LRESULT(0))
}

/// WM_KEYDOWN: キー押下
#[inline]
pub(super) fn WM_KEYDOWN(
    _hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    use windows::Win32::UI::Input::KeyboardAndMouse::VK_ESCAPE;

    // ESCキーでドラッグキャンセル
    if wparam.0 == VK_ESCAPE.0 as usize {
        // thread_local DragStateをクローンして取得
        let state_snapshot = crate::ecs::drag::read_drag_state(|state| state.clone());

        if let crate::ecs::drag::DragState::Dragging {
            entity, start_pos, ..
        }
        | crate::ecs::drag::DragState::Preparing {
            entity, start_pos, ..
        }
        | crate::ecs::drag::DragState::JustStarted {
            entity, start_pos, ..
        } = state_snapshot
        {
            // DragAccumulatorResourceにEnded遷移を記録
            if let Some(world) = super::try_get_ecs_world() {
                if let Ok(world_borrow) = world.try_borrow() {
                    if let Some(accumulator) = world_borrow
                        .world()
                        .get_resource::<crate::ecs::drag::DragAccumulatorResource>(
                    ) {
                        accumulator.set_transition(crate::ecs::drag::DragTransition::Ended {
                            entity,
                            end_pos: start_pos,
                            cancelled: true,
                        });
                    }
                }
            }
        }

        crate::ecs::drag::cancel_dragging();
        // ReleaseCapture
        // TODO: ReleaseCapture (not available in current windows crate version)
        // let _ = unsafe { ReleaseCapture() };

        tracing::debug!("[WM_KEYDOWN] ESC key pressed, drag cancelled");
    }

    None // DefWindowProcWに委譲
}

/// WM_CANCELMODE: システムキャンセル
#[inline]
pub(super) fn WM_CANCELMODE(
    _hwnd: HWND,
    _message: u32,
    _wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    // thread_local DragStateをクローンして取得
    let state_snapshot = crate::ecs::drag::read_drag_state(|state| state.clone());

    if let crate::ecs::drag::DragState::Dragging {
        entity, start_pos, ..
    }
    | crate::ecs::drag::DragState::Preparing {
        entity, start_pos, ..
    }
    | crate::ecs::drag::DragState::JustStarted {
        entity, start_pos, ..
    } = state_snapshot
    {
        // DragAccumulatorResourceにEnded遷移を記録
        if let Some(world) = super::try_get_ecs_world() {
            if let Ok(world_borrow) = world.try_borrow() {
                if let Some(accumulator) = world_borrow
                    .world()
                    .get_resource::<crate::ecs::drag::DragAccumulatorResource>(
                ) {
                    accumulator.set_transition(crate::ecs::drag::DragTransition::Ended {
                        entity,
                        end_pos: start_pos,
                        cancelled: true,
                    });
                }
            }
        }
    }

    // ドラッグキャンセル
    crate::ecs::drag::cancel_dragging();

    tracing::debug!("[WM_CANCELMODE] System cancel, drag cancelled");

    None // DefWindowProcWに委譲(ReleaseCapture自動実行)
}

/// WM_ACTIVATE: ウィンドウ非アクティブ化時のドラッグキャンセル
///
/// Alt+Tabなどでウィンドウが非アクティブになった場合、ドラッグ中であればキャンセルする。
/// WM_CANCELMODEはモーダルダイアログやメニュー表示時にのみ送られ、
/// Alt+Tabでは送られないため、WM_ACTIVATEで補完する必要がある。
pub(super) fn WM_ACTIVATE(
    _hwnd: HWND,
    _message: u32,
    wparam: WPARAM,
    _lparam: LPARAM,
) -> HandlerResult {
    let activation_state = (wparam.0 & 0xFFFF) as u32;

    // 非アクティブ化時のみ処理 (WA_INACTIVE = 0)
    if activation_state != 0 {
        return None;
    }

    // ドラッグ中なら状態を確認してキャンセル
    let state_snapshot = crate::ecs::drag::read_drag_state(|state| state.clone());
    match state_snapshot {
        crate::ecs::drag::DragState::Dragging {
            entity, start_pos, ..
        } => {
            tracing::info!(
                entity = ?entity,
                "[WM_ACTIVATE] Window deactivated during drag, cancelling"
            );

            // DragAccumulatorResourceにEnded(cancelled)遷移を記録
            if let Some(world) = super::try_get_ecs_world() {
                if let Ok(world_borrow) = world.try_borrow() {
                    if let Some(accumulator) = world_borrow
                        .world()
                        .get_resource::<crate::ecs::drag::DragAccumulatorResource>(
                    ) {
                        accumulator.set_transition(crate::ecs::drag::DragTransition::Ended {
                            entity,
                            end_pos: start_pos,
                            cancelled: true,
                        });
                    }
                }
            }

            crate::ecs::drag::cancel_dragging();
        }
        crate::ecs::drag::DragState::Preparing { .. } => {
            tracing::debug!("[WM_ACTIVATE] Window deactivated during drag prepare, resetting");
            crate::ecs::drag::reset_to_idle();
        }
        _ => {}
    }

    None // DefWindowProcWに委譲
}

/// target_entity自身または祖先(ChildOf辿り)からDragConfigを持つエンティティを探す。
/// 見つかった場合は (entity, DragConfig clone) を返す。
fn find_ancestor_with_drag_config(
    world: &bevy_ecs::world::World,
    start: bevy_ecs::entity::Entity,
) -> Option<(bevy_ecs::entity::Entity, crate::ecs::drag::DragConfig)> {
    let mut current = start;
    loop {
        if let Some(config) = world.get::<crate::ecs::drag::DragConfig>(current) {
            return Some((current, config.clone()));
        }
        if let Some(child_of) = world.get::<bevy_ecs::prelude::ChildOf>(current) {
            current = child_of.parent();
        } else {
            return None;
        }
    }
}