dioxus-nox-tag-input 0.13.2

Headless tag/multi-select input primitive for Dioxus
Documentation
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
use std::cmp::Ordering;
use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};

use dioxus::prelude::*;

use crate::tag::TagLike;

static INSTANCE_COUNTER: AtomicU32 = AtomicU32::new(0);

/// A group of suggestions sharing a label.
#[derive(Clone, PartialEq, Debug)]
pub struct SuggestionGroup<T: TagLike> {
    /// Group name. Empty string for ungrouped items (tags where `group()` returns `None`).
    pub label: String,
    /// Items visible in this group (may be truncated by `max_items_per_group`).
    pub items: Vec<T>,
    /// Total matching items before `max_items_per_group` truncation.
    pub total_count: usize,
}

/// Configuration for the grouped tag input hook.
///
/// Uses `fn` pointers (not closures) because they are `Copy` and trivially
/// captured by `use_memo`.
pub struct TagInputGroupConfig<T: TagLike> {
    pub available_tags: Vec<T>,
    pub initial_selected: Vec<T>,
    /// Custom filter: receives `(tag, lowercase_query)`. Default: substring match on `name()`.
    pub filter: Option<fn(&T, &str) -> bool>,
    /// Sort items within each group. Default: no sort (insertion order).
    pub sort_items: Option<fn(&T, &T) -> Ordering>,
    /// Sort group headers. Default: no sort (first-seen order).
    pub sort_groups: Option<fn(&str, &str) -> Ordering>,
    /// Max items shown per group. `None` = unlimited. `total_count` still reflects all matches.
    pub max_items_per_group: Option<usize>,
    /// Parent-owned signal for selected tags (controlled mode). `initial_selected` ignored when set.
    pub value: Option<Signal<Vec<T>>>,
    /// Parent-owned signal for search query (controlled mode).
    pub query: Option<Signal<String>>,
}

/// Configuration for the simple tag input hook.
pub struct TagInputConfig<T: TagLike> {
    pub available_tags: Vec<T>,
    pub initial_selected: Vec<T>,
    /// Parent-owned signal for selected tags (controlled mode). `initial_selected` ignored when set.
    pub value: Option<Signal<Vec<T>>>,
    /// Parent-owned signal for search query (controlled mode).
    pub query: Option<Signal<String>>,
}

impl<T: TagLike> TagInputConfig<T> {
    pub fn new(available_tags: Vec<T>, initial_selected: Vec<T>) -> Self {
        Self {
            available_tags,
            initial_selected,
            value: None,
            query: None,
        }
    }
}

/// Find byte-offset ranges in `text` that match `query` (case-insensitive substring).
///
/// Returns `Vec<(start, end)>` pairs suitable for slicing `text` and wrapping
/// matched portions in highlight markup.
pub fn find_match_ranges(text: &str, query: &str) -> Vec<(usize, usize)> {
    if query.is_empty() {
        return Vec::new();
    }
    let text_lower = text.to_lowercase();
    let query_lower = query.to_lowercase();
    let mut ranges = Vec::new();
    let mut start = 0;
    while let Some(pos) = text_lower[start..].find(&query_lower) {
        let abs_start = start + pos;
        let abs_end = abs_start + query.len();
        ranges.push((abs_start, abs_end));
        start = abs_end;
    }
    ranges
}

/// Headless state for the tag input component.
///
/// All fields are `Signal` or `Memo`, which are `Copy` in Dioxus 0.7,
/// so `TagInputState` manually implements `Clone`, `Copy`, and `PartialEq`
/// without requiring `T: Copy` or `T: PartialEq`.
#[allow(clippy::type_complexity)]
pub struct TagInputState<T: TagLike> {
    /// The current search/filter query text.
    pub search_query: Signal<String>,
    /// The tags currently selected by the user.
    pub selected_tags: Signal<Vec<T>>,
    /// All tags available for selection.
    pub available_tags: Signal<Vec<T>>,
    /// Index of the keyboard-selected pill, or `None` when the cursor is in the text input.
    pub active_pill: Signal<Option<usize>>,
    /// Index of the pill whose popover is open, or `None` when no popover is shown.
    pub popover_pill: Signal<Option<usize>>,
    /// Optional callback for creating new tags on Enter when no suggestion is highlighted.
    ///
    /// When `Some`, pressing Enter with a non-empty query and no highlighted suggestion
    /// will call this callback with the query text. Return `Some(tag)` to accept the
    /// new tag, or `None` to reject it.
    ///
    /// Default: `None` (feature off — Enter just opens the dropdown).
    pub on_create: Signal<Option<Callback<String, Option<T>>>>,
    /// Optional callback fired when a tag is about to be removed.
    ///
    /// Called with the tag being removed, before it is actually removed from `selected_tags`.
    /// Fires from `remove_tag()` and `remove_last_tag()`.
    ///
    /// Default: `None`
    pub on_remove: Signal<Option<Callback<T>>>,
    /// Optional callback fired when a tag is added.
    ///
    /// Called with the newly added tag after it has been pushed to `selected_tags`.
    /// Fires from `add_tag()` (and by extension `create_tag()`).
    ///
    /// Default: `None`
    pub on_add: Signal<Option<Callback<T>>>,
    /// Optional callback fired when the input text (search query) changes.
    ///
    /// Consumers can use this for external filtering, async fetching, or
    /// debounced search. Replaces the old `on_search` callback.
    ///
    /// Default: `None`
    pub on_query_change: Signal<Option<EventHandler<String>>>,
    /// Optional callback fired when the user presses Enter/delimiter with text
    /// and no `on_create` handler is set.
    ///
    /// This allows consumers to handle the "commit" action externally (e.g.,
    /// to open a dropdown, trigger a search, or perform a custom action).
    ///
    /// Default: `None`
    pub on_commit: Signal<Option<EventHandler<String>>>,
    /// Whether the tag input is disabled (no interaction allowed).
    ///
    /// When `true`, `handle_keydown`, `set_query`, `add_tag`, `remove_tag`, and
    /// `handle_click` become no-ops. Consumers should also apply `disabled` /
    /// `aria-disabled="true"` attributes and visual styling based on this signal.
    pub is_disabled: Signal<bool>,
    /// Screen-reader status message for `aria-live` announcements.
    ///
    /// Updated automatically when tags are added/removed and when the suggestion
    /// count changes. Consumers render this inside a `<div role="status" aria-live="polite">`
    /// element to provide announcements to assistive technology.
    ///
    /// Example messages:
    /// - `"Apple added. 3 tags selected."`
    /// - `"Cherry removed. 2 tags selected."`
    /// - `"5 suggestions available."`
    /// - `"No suggestions found."`
    /// - `"Maximum of 5 tags reached."`
    pub status_message: Signal<String>,
    /// Optional callback fired when text is pasted into the input.
    ///
    /// Called with the raw clipboard text. Return a `Vec<T>` of tags to add.
    /// If the callback returns an empty vec, no tags are added.
    ///
    /// Takes priority over `paste_delimiters` when set.
    ///
    /// Default: `None`
    pub on_paste: Signal<Option<Callback<String, Vec<T>>>>,
    /// Delimiter characters for splitting pasted text into tags.
    ///
    /// When set and `on_paste` is `None`, pasted text is split by these delimiters.
    /// Each non-empty token is passed to `on_create` (if set) to create a tag.
    /// Common delimiters: `[',', '\n', '\t']`.
    ///
    /// Default: `None` (paste behaves normally — text enters the input field)
    pub paste_delimiters: Signal<Option<Vec<char>>>,
    // ── Phase 2: Editing & Reorder ──────────────────────────────────────
    /// Index of the pill currently being edited inline, or `None`.
    ///
    /// When `Some(idx)`, the consumer should render an `<input>` instead of a
    /// `<span>` for that pill. Use `start_editing(idx)` to enter edit mode,
    /// `commit_edit(new_name)` to apply changes, and `cancel_edit()` to discard.
    pub editing_pill: Signal<Option<usize>>,
    /// Optional callback for applying an inline edit to a tag.
    ///
    /// Called with `(current_tag, new_name_string)`. Return `Some(updated_tag)` to
    /// accept the edit, or `None` to reject it. The consumer is responsible for
    /// constructing the updated tag (the library doesn't know your tag's internals).
    ///
    /// Default: `None` (editing disabled)
    pub on_edit: Signal<Option<Callback<(T, String), Option<T>>>>,
    /// Optional callback fired after a tag is reordered via `move_tag`.
    ///
    /// Called with `(from_index, to_index)` after the move completes.
    ///
    /// Default: `None`
    pub on_reorder: Signal<Option<Callback<(usize, usize)>>>,
    // ── Phase 3: Validation & Limits ────────────────────────────────────
    /// Delimiter characters that commit the current query as a tag.
    ///
    /// When set, typing any of these characters commits the current query:
    /// if a suggestion is highlighted, it's selected; otherwise `on_create`
    /// is called (if set). Common delimiters: `[',', ';', '\t']`.
    /// `Enter` is always a commit key and doesn't need to be in this list.
    ///
    /// Default: `None` (only Enter commits)
    pub delimiters: Signal<Option<Vec<char>>>,
    /// Maximum number of tags that can be selected.
    ///
    /// When set and the limit is reached, `add_tag` becomes a no-op and
    /// `status_message` announces "Maximum of N tags reached."
    ///
    /// Default: `None` (unlimited)
    pub max_tags: Signal<Option<usize>>,
    /// Whether the maximum tag limit has been reached.
    ///
    /// Reactive memo derived from `max_tags` and `selected_tags.len()`.
    /// Consumers can use this to disable the input or hide suggestions.
    pub is_at_limit: Memo<bool>,
    /// Optional validation callback called before a tag is committed.
    ///
    /// Called with the tag about to be added. Return `Ok(())` to accept,
    /// or `Err("message")` to reject. The rejection message is stored in
    /// `validation_error` for the consumer to render.
    ///
    /// Default: `None` (no validation — all tags accepted)
    pub validate: Signal<Option<Callback<T, Result<(), String>>>>,
    /// The most recent validation error message, or `None` if valid.
    ///
    /// Set by `add_tag` when `validate` returns `Err(msg)`. Cleared on the
    /// next successful `add_tag` or when `set_query` is called.
    pub validation_error: Signal<Option<String>>,
    // ── Phase 4: Production Guards ─────────────────────────────────────
    /// Whether duplicate tags are allowed.
    ///
    /// When `false` (default), `add_tag` rejects tags whose ID already exists
    /// in `selected_tags`. When `true`, the duplicate check is skipped entirely.
    ///
    /// Default: `false`
    pub allow_duplicates: Signal<bool>,
    /// Optional callback fired when a duplicate tag is rejected.
    ///
    /// Only fires when `allow_duplicates` is `false` and a duplicate is attempted.
    ///
    /// Default: `None`
    pub on_duplicate: Signal<Option<Callback<T>>>,
    /// Whether to restrict tag selection to only items in `available_tags`.
    ///
    /// When `true`, `on_create` is blocked and only tags present in `available_tags`
    /// can be added. Pasted tags not in the allow list are also rejected.
    ///
    /// Default: `false`
    pub enforce_allow_list: Signal<bool>,
    /// List of forbidden tag names (case-insensitive).
    ///
    /// Tags whose `name()` matches any entry (case-insensitive) are rejected by
    /// `add_tag` and filtered out of suggestions.
    ///
    /// Default: `None` (no deny list)
    pub deny_list: Signal<Option<Vec<String>>>,
    /// Minimum number of required tags (informational for form validation).
    ///
    /// Does NOT prevent removal — `is_below_minimum` is a reactive memo that
    /// consumers can use to show validation warnings or disable form submission.
    ///
    /// Default: `None` (no minimum)
    pub min_tags: Signal<Option<usize>>,
    /// Whether the selected tag count is below `min_tags`.
    ///
    /// Reactive memo: `true` when `min_tags` is `Some(n)` and `selected_tags.len() < n`.
    pub is_below_minimum: Memo<bool>,
    /// Whether the tag input is in read-only mode.
    ///
    /// When `true`, tags are displayed but cannot be added, removed, or edited.
    /// Pill navigation (ArrowLeft/Right) and Escape still work.
    ///
    /// Default: `false`
    pub is_readonly: Signal<bool>,
    // ── Phase 6: UX Polish ─────────────────────────────────────────────
    /// Maximum character length for tag names.
    ///
    /// When set, `add_tag` and `create_tag` reject tags whose `name().len()`
    /// exceeds this limit, setting `validation_error`.
    ///
    /// Default: `None` (unlimited)
    pub max_tag_length: Signal<Option<usize>>,
    /// Custom filter function for `use_tag_input()`.
    ///
    /// When `Some`, used instead of the default case-insensitive substring match.
    /// Receives `(tag, lowercase_query)`. Provides parity with the grouped hook's
    /// `TagInputGroupConfig::filter`.
    ///
    /// Default: `None`
    pub filter: Signal<Option<fn(&T, &str) -> bool>>,
    /// Maximum number of tag pills to display before collapsing.
    ///
    /// When set, consumers should render only `visible_tags` and show an
    /// "+N more" badge using `overflow_count`.
    ///
    /// Default: `None` (show all)
    pub max_visible_tags: Signal<Option<usize>>,
    /// Count of tags hidden by `max_visible_tags`.
    ///
    /// `selected_tags.len() - max_visible_tags` when limit is active, else `0`.
    pub overflow_count: Memo<usize>,
    /// The truncated slice of selected tags for rendering.
    ///
    /// When `max_visible_tags` is set, contains only the first N tags.
    /// Otherwise contains all selected tags.
    pub visible_tags: Memo<Vec<T>>,
    /// Optional sort function applied to `selected_tags` after add/remove.
    ///
    /// When `Some`, `selected_tags` is automatically sorted in place after
    /// each mutation.
    ///
    /// Default: `None` (insertion order preserved)
    pub sort_selected: Signal<Option<fn(&T, &T) -> Ordering>>,
    // ── Phase 7: Form Helpers ────────────────────────────────────────────
    /// JSON-serialized selected tag IDs for hidden form inputs.
    ///
    /// Format: `["id1","id2","id3"]`. Empty array `[]` when no tags selected.
    pub form_value: Memo<String>,
    /// Whether to operate in single-value select mode.
    ///
    /// When `true` and `max_tags` is `Some(1)`, adding a new tag replaces the
    /// existing one instead of rejecting.
    ///
    /// Default: `false`
    pub select_mode: Signal<bool>,
    /// Unique instance ID for scoping DOM element IDs when multiple tag inputs coexist.
    instance_id: u32,
}

impl<T: TagLike> Clone for TagInputState<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: TagLike> Copy for TagInputState<T> {}

impl<T: TagLike> PartialEq for TagInputState<T> {
    fn eq(&self, other: &Self) -> bool {
        self.search_query == other.search_query
            && self.selected_tags == other.selected_tags
            && self.available_tags == other.available_tags
            && self.active_pill == other.active_pill
            && self.popover_pill == other.popover_pill
            && self.on_create == other.on_create
            && self.on_remove == other.on_remove
            && self.on_add == other.on_add
            && self.on_query_change == other.on_query_change
            && self.on_commit == other.on_commit
            && self.is_disabled == other.is_disabled
            && self.status_message == other.status_message
            && self.on_paste == other.on_paste
            && self.paste_delimiters == other.paste_delimiters
            && self.editing_pill == other.editing_pill
            && self.on_edit == other.on_edit
            && self.on_reorder == other.on_reorder
            && self.delimiters == other.delimiters
            && self.max_tags == other.max_tags
            && self.is_at_limit == other.is_at_limit
            && self.validate == other.validate
            && self.validation_error == other.validation_error
            // Phase 4
            && self.allow_duplicates == other.allow_duplicates
            && self.on_duplicate == other.on_duplicate
            && self.enforce_allow_list == other.enforce_allow_list
            && self.deny_list == other.deny_list
            && self.min_tags == other.min_tags
            && self.is_below_minimum == other.is_below_minimum
            && self.is_readonly == other.is_readonly
            // Phase 6
            && self.max_tag_length == other.max_tag_length
            && self.filter == other.filter
            && self.max_visible_tags == other.max_visible_tags
            && self.overflow_count == other.overflow_count
            && self.visible_tags == other.visible_tags
            && self.sort_selected == other.sort_selected
            // Phase 7
            && self.form_value == other.form_value
            && self.select_mode == other.select_mode
            && self.instance_id == other.instance_id
    }
}

impl<T: TagLike> TagInputState<T> {
    /// Update the search query.
    ///
    /// Clears any `validation_error` from a previous rejected `add_tag`.
    /// Fires `on_query_change` callback (if set) so consumers can react to input changes.
    pub fn set_query(&mut self, query: String) {
        if *self.is_disabled.read() || *self.is_readonly.read() {
            return;
        }
        self.search_query.set(query.clone());
        self.active_pill.set(None);
        self.popover_pill.set(None);
        self.validation_error.set(None);

        // Fire query change callback
        let cb = *self.on_query_change.read();
        if let Some(handler) = cb {
            handler.call(query);
        }
    }

    /// Add a tag to the selected list and clear the search query.
    ///
    /// Guards: disabled, readonly, duplicate, allow list, deny list, max_tags limit,
    /// max_tag_length, validation callback, select_mode replacement.
    /// Fires `on_add` callback (if set) after the tag is added.
    /// Updates `status_message` with an announcement like "Apple added. 3 tags selected."
    pub fn add_tag(&mut self, tag: T) {
        if *self.is_disabled.read() || *self.is_readonly.read() {
            return;
        }

        // Allow list enforcement guard
        if *self.enforce_allow_list.read() {
            let in_allow_list = self
                .available_tags
                .read()
                .iter()
                .any(|t| t.id() == tag.id());
            if !in_allow_list {
                self.status_message
                    .set("Only suggestions can be selected.".to_string());
                return;
            }
        }

        // Deny list guard
        if let Some(ref bl) = *self.deny_list.read() {
            let tag_name_lower = tag.name().to_lowercase();
            if bl.iter().any(|b| b.to_lowercase() == tag_name_lower) {
                let name = tag.name().to_string();
                self.status_message.set(format_status_denied(&name));
                self.validation_error.set(Some(format_status_denied(&name)));
                return;
            }
        }

        // Max tag length guard
        if let Some(max_len) = *self.max_tag_length.read()
            && tag.name().len() > max_len
        {
            self.validation_error
                .set(Some(format_error_max_length(max_len)));
            return;
        }

        // Select mode: replace existing tag when max_tags=1
        if *self.select_mode.read()
            && let Some(1) = *self.max_tags.read()
            && self.selected_tags.read().len() == 1
        {
            let old_id = self.selected_tags.read()[0].id().to_string();
            self.selected_tags.write().retain(|t| t.id() != old_id);
        }

        // Max tags guard
        if let Some(max) = *self.max_tags.read()
            && self.selected_tags.read().len() >= max
        {
            self.status_message
                .set(format!("Maximum of {max} tags reached."));
            self.search_query.set(String::new());
            return;
        }

        // Duplicate guard
        let already_selected = self.selected_tags.read().iter().any(|t| t.id() == tag.id());
        if already_selected && !*self.allow_duplicates.read() {
            let name = tag.name().to_string();
            self.status_message.set(format_status_duplicate(&name));
            if let Some(cb) = *self.on_duplicate.read() {
                cb.call(tag);
            }
            self.search_query.set(String::new());
            self.active_pill.set(None);
            self.popover_pill.set(None);
            return;
        }

        if !already_selected || *self.allow_duplicates.read() {
            // Validation guard
            let validate_cb = *self.validate.read();
            if let Some(cb) = validate_cb
                && let Err(msg) = cb.call(tag.clone())
            {
                self.validation_error.set(Some(msg));
                return;
            }
            self.validation_error.set(None);

            let name = tag.name().to_string();
            self.selected_tags.write().push(tag.clone());

            // Auto-sort selected tags if sort function is set
            if let Some(sort_fn) = *self.sort_selected.read() {
                self.selected_tags.write().sort_by(sort_fn);
            }

            let count = self.selected_tags.read().len();
            self.status_message.set(format_status_added(&name, count));

            if let Some(cb) = *self.on_add.read() {
                cb.call(tag);
            }
        }
        self.search_query.set(String::new());
        self.active_pill.set(None);
        self.popover_pill.set(None);
    }

    /// Remove a tag from the selected list by its id.
    ///
    /// No-op if the tag is locked (`is_locked() == true`), disabled, or readonly.
    /// Fires `on_remove` callback (if set) before removal.
    /// Updates `status_message` with an announcement like "Cherry removed. 2 tags selected."
    pub fn remove_tag(&mut self, id: &str) {
        if *self.is_disabled.read() || *self.is_readonly.read() {
            return;
        }
        let is_locked = self
            .selected_tags
            .read()
            .iter()
            .any(|t| t.id() == id && t.is_locked());
        if is_locked {
            return;
        }

        let name = self
            .selected_tags
            .read()
            .iter()
            .find(|t| t.id() == id)
            .map(|t| t.name().to_string());

        if let Some(cb) = *self.on_remove.read()
            && let Some(tag) = self
                .selected_tags
                .read()
                .iter()
                .find(|t| t.id() == id)
                .cloned()
        {
            cb.call(tag);
        }

        self.selected_tags.write().retain(|t| t.id() != id);
        if let Some(name) = name {
            let count = self.selected_tags.read().len();
            self.status_message.set(format_status_removed(&name, count));
        }
        self.popover_pill.set(None);
    }

    /// Remove the last *unlocked* selected tag (used for Backspace on empty input).
    ///
    /// Walks backwards from the end, skipping locked tags. If all tags are locked, no-op.
    /// Fires `on_remove` callback (if set) before removal.
    /// Updates `status_message` with an announcement.
    pub fn remove_last_tag(&mut self) {
        let tags = self.selected_tags.read();
        if let Some(pos) = tags.iter().rposition(|t| !t.is_locked()) {
            let tag = tags[pos].clone();
            let name = tag.name().to_string();
            drop(tags);

            if let Some(cb) = *self.on_remove.read() {
                cb.call(tag);
            }

            self.selected_tags.write().remove(pos);
            let count = self.selected_tags.read().len();
            self.status_message.set(format_status_removed(&name, count));
        }
    }

    /// Handle click/tap on the input area — clears pill selection.
    ///
    /// Attach this to `onclick` on the text `<input>` to clear pill mode
    /// when the user taps back into the text input.
    pub fn handle_click(&mut self) {
        if *self.is_disabled.read() || *self.is_readonly.read() {
            return;
        }
        self.active_pill.set(None);
        self.popover_pill.set(None);
    }

    /// Toggle the popover for the pill at `index`.
    ///
    /// If the popover is already showing for this pill, it closes.
    pub fn toggle_popover(&mut self, index: usize) {
        let current = *self.popover_pill.read();
        if current == Some(index) {
            self.popover_pill.set(None);
        } else {
            self.popover_pill.set(Some(index));
        }
    }

    /// Close any open pill popover.
    pub fn close_popover(&mut self) {
        self.popover_pill.set(None);
    }

    /// Return a stable DOM `id` for the suggestion at `index`.
    ///
    /// Use this as the `id` attribute on each suggestion element so that
    /// keyboard navigation can scroll the highlighted item into view.
    /// The ID is scoped by `instance_id` so multiple tag inputs on the
    /// same page won't collide.
    pub fn suggestion_id(&self, index: usize) -> String {
        format!("dti-{}-s-{}", self.instance_id, index)
    }

    /// Returns the DOM ID for the suggestion listbox container.
    ///
    /// Use this as the `id` on the `<ul>` / `<div role="listbox">` element and as
    /// the value of `aria-controls` / `aria-owns` on the combobox `<input>`.
    pub fn listbox_id(&self) -> String {
        format!("dti-{}-listbox", self.instance_id)
    }

    /// Returns a stable DOM `id` for the selected pill at `index`.
    ///
    /// Use this as the `id` attribute on each pill element for focus management
    /// and ARIA relationships. The ID is scoped by `instance_id` so multiple
    /// tag inputs on the same page won't collide.
    pub fn pill_id(&self, index: usize) -> String {
        format!("dti-{}-p-{}", self.instance_id, index)
    }

    /// Create a tag and add it to both selected and available tags.
    ///
    /// The tag is appended to `available_tags` so it appears in future suggestions
    /// if the user removes and re-types it. Then it is added to `selected_tags`
    /// via `add_tag`.
    ///
    /// Used internally by `handle_keydown`; also available for consumers who want
    /// to trigger creation programmatically.
    pub fn create_tag(&mut self, tag: T) {
        self.available_tags.write().push(tag.clone());
        self.add_tag(tag);
    }

    /// Handle pasted text by splitting it into tags.
    ///
    /// Call this from the consumer's `onpaste` handler after extracting the clipboard
    /// text. The method processes the text according to these rules (in priority order):
    ///
    /// 1. If `on_paste` callback is set: calls it with the raw text. The callback
    ///    returns `Vec<T>` of tags to add.
    /// 2. If `paste_delimiters` is set: splits by delimiters, trims whitespace,
    ///    and passes each non-empty token to `on_create` (if set) to create tags.
    /// 3. Otherwise: no-op (normal paste into the input).
    ///
    /// Updates `status_message` with a summary of how many tags were added.
    pub fn handle_paste(&mut self, text: String) {
        if *self.is_disabled.read() || *self.is_readonly.read() {
            return;
        }
        if text.is_empty() {
            return;
        }

        // Priority 1: on_paste callback
        let paste_cb = *self.on_paste.read();
        if let Some(cb) = paste_cb {
            let tags = cb.call(text);
            let added = tags.len();
            for tag in tags {
                self.add_tag(tag);
            }
            if added > 0 {
                let count = self.selected_tags.read().len();
                self.status_message.set(format_status_pasted(added, count));
            }
            return;
        }

        // Priority 2: delimiter splitting + on_create
        let delimiters = self.paste_delimiters.read().clone();
        let create_cb = *self.on_create.read();
        if let Some(delimiters) = delimiters
            && let Some(cb) = create_cb
        {
            let tokens = split_by_delimiters(&text, &delimiters);
            let mut added = 0;
            for token in tokens {
                if let Some(tag) = cb.call(token) {
                    self.create_tag(tag);
                    added += 1;
                }
            }
            if added > 0 {
                let count = self.selected_tags.read().len();
                self.status_message.set(format_status_pasted(added, count));
            }
        }

        // Priority 3: no-op, let normal paste happen
    }

    /// Update the status message with a custom announcement.
    ///
    /// Consumers can call this to announce arbitrary messages to screen readers
    /// via the `status_message` signal (rendered in an `aria-live` region).
    pub fn announce(&mut self, message: String) {
        self.status_message.set(message);
    }

    // ── Phase 2: Editing methods ────────────────────────────────────────

    /// Enter inline editing mode for the pill at `index`.
    ///
    /// Sets `editing_pill` to `Some(index)` and closes popover/dropdown.
    /// The consumer should render an `<input>` for this pill and call
    /// `commit_edit` or `cancel_edit` when done.
    ///
    /// No-op if `on_edit` callback is not set or if `is_disabled`.
    pub fn start_editing(&mut self, index: usize) {
        if *self.is_disabled.read() || *self.is_readonly.read() {
            return;
        }
        if self.on_edit.read().is_none() {
            return;
        }
        if index >= self.selected_tags.read().len() {
            return;
        }
        // Don't allow editing locked tags
        if self.selected_tags.read()[index].is_locked() {
            return;
        }
        self.editing_pill.set(Some(index));
        self.popover_pill.set(None);
        self.active_pill.set(Some(index));
    }

    /// Commit an inline edit, replacing the tag at the editing index.
    ///
    /// Calls `on_edit` with `(current_tag, new_name)`. If the callback returns
    /// `Some(updated_tag)`, the tag is replaced in `selected_tags`. If it returns
    /// `None`, the edit is rejected and the original tag remains.
    ///
    /// Always exits edit mode afterward.
    pub fn commit_edit(&mut self, new_name: String) {
        let idx = match *self.editing_pill.read() {
            Some(i) => i,
            None => return,
        };
        let edit_cb = *self.on_edit.read();
        if let Some(cb) = edit_cb {
            let current = self.selected_tags.read().get(idx).cloned();
            if let Some(tag) = current
                && let Some(updated) = cb.call((tag, new_name))
            {
                self.selected_tags.write()[idx] = updated;
            }
        }
        self.editing_pill.set(None);
    }

    /// Cancel inline editing without applying changes.
    pub fn cancel_edit(&mut self) {
        self.editing_pill.set(None);
    }

    // ── Phase 2: Reorder method ─────────────────────────────────────────

    /// Move a tag from one position to another in the selected list.
    ///
    /// Performs `Vec::remove(from)` then `Vec::insert(to, tag)`.
    /// Fires `on_reorder` callback (if set) with `(from, to)` after the move.
    /// Updates `status_message`.
    pub fn move_tag(&mut self, from: usize, to: usize) {
        if *self.is_disabled.read() || *self.is_readonly.read() {
            return;
        }
        let len = self.selected_tags.read().len();
        if from >= len || to >= len || from == to {
            return;
        }
        let tag = self.selected_tags.write().remove(from);
        let name = tag.name().to_string();
        self.selected_tags.write().insert(to, tag);
        self.status_message
            .set(format!("{name} moved to position {}.", to + 1));

        if let Some(cb) = *self.on_reorder.read() {
            cb.call((from, to));
        }
    }

    // ── Phase 3: Select / Clear all ─────────────────────────────────────

    /// Remove all unlocked tags from the selection.
    ///
    /// Locked tags are preserved. Fires `on_remove` for each removed tag.
    /// Updates `status_message` with a summary.
    pub fn clear_all(&mut self) {
        if *self.is_disabled.read() || *self.is_readonly.read() {
            return;
        }
        let tags = self.selected_tags.read().clone();
        let to_remove: Vec<T> = tags.into_iter().filter(|t| !t.is_locked()).collect();
        let removed_count = to_remove.len();

        let remove_cb = *self.on_remove.read();
        for tag in &to_remove {
            if let Some(cb) = remove_cb {
                cb.call(tag.clone());
            }
        }

        self.selected_tags.write().retain(|t| t.is_locked());
        self.active_pill.set(None);
        self.popover_pill.set(None);
        self.editing_pill.set(None);

        let locked_count = self.selected_tags.read().len();
        if locked_count > 0 {
            self.status_message.set(format!(
                "All tags cleared. {locked_count} locked tag{} remain{}.",
                if locked_count == 1 { "" } else { "s" },
                if locked_count == 1 { "s" } else { "" }
            ));
        } else {
            self.status_message.set(format!(
                "{removed_count} tag{} cleared.",
                if removed_count == 1 { "" } else { "s" }
            ));
        }
    }

    /// Add all available (unselected) tags to the selection.
    ///
    /// Respects `max_tags` limit — stops adding when the limit is reached.
    /// Updates `status_message` with the count added.
    pub fn select_all(&mut self) {
        if *self.is_disabled.read() || *self.is_readonly.read() {
            return;
        }
        let available = self.available_tags.read().clone();
        let mut added = 0;
        for tag in available {
            if let Some(max) = *self.max_tags.read()
                && self.selected_tags.read().len() >= max
            {
                break;
            }
            let already = self.selected_tags.read().iter().any(|t| t.id() == tag.id());
            if !already {
                self.selected_tags.write().push(tag.clone());
                added += 1;
                if let Some(cb) = *self.on_add.read() {
                    cb.call(tag);
                }
            }
        }
        if added > 0 {
            let count = self.selected_tags.read().len();
            self.status_message.set(format!(
                "{added} tag{} added. {count} tag{} selected.",
                if added == 1 { "" } else { "s" },
                if count == 1 { "" } else { "s" }
            ));
        }
    }

    /// Handle keyboard events for navigating suggestions and pills.
    pub fn handle_keydown(&mut self, event: Event<KeyboardData>) {
        if *self.is_disabled.read() {
            return;
        }
        let pill = *self.active_pill.read();
        if let Some(i) = pill {
            self.handle_pill_keydown(event, i);
        } else {
            self.handle_input_keydown(event);
        }
    }

    /// Handle keyboard events when a pill is keyboard-selected.
    ///
    /// Called by `handle_keydown` when `active_pill` is `Some(i)`, or directly
    /// by compound components that manage their own pill keydown.
    pub fn handle_pill_keydown(&mut self, event: Event<KeyboardData>, pill_index: usize) {
        let key = event.key();
        let readonly = *self.is_readonly.read();

        match key {
            Key::Enter => {
                if readonly {
                    return;
                }
                event.prevent_default();
                self.toggle_popover(pill_index);
            }
            Key::ArrowLeft => {
                event.prevent_default();
                self.popover_pill.set(None);
                if pill_index > 0 {
                    self.active_pill.set(Some(pill_index - 1));
                }
            }
            Key::ArrowRight => {
                event.prevent_default();
                self.popover_pill.set(None);
                let len = self.selected_tags.read().len();
                if pill_index < len - 1 {
                    self.active_pill.set(Some(pill_index + 1));
                } else {
                    self.active_pill.set(None); // back to input
                }
            }
            Key::Backspace | Key::Delete => {
                if readonly {
                    return;
                }
                event.prevent_default();
                if self.popover_pill.read().is_some() {
                    // First press: close popover only (same layered pattern as Escape)
                    self.popover_pill.set(None);
                } else {
                    // Second press (no popover open): delete the pill if not locked
                    let is_locked = self
                        .selected_tags
                        .read()
                        .get(pill_index)
                        .is_some_and(|t| t.is_locked());
                    if !is_locked {
                        let id = self.selected_tags.read()[pill_index].id().to_string();
                        self.remove_tag(&id);
                        let new_len = self.selected_tags.read().len();
                        if new_len == 0 {
                            self.active_pill.set(None);
                        } else if pill_index >= new_len {
                            self.active_pill.set(Some(new_len - 1));
                        }
                        // else: keep same index (now points to the next pill)
                    }
                }
            }
            Key::Home => {
                event.prevent_default();
                self.popover_pill.set(None);
                self.active_pill.set(Some(0));
            }
            Key::End => {
                event.prevent_default();
                self.popover_pill.set(None);
                let len = self.selected_tags.read().len();
                if len > 0 {
                    self.active_pill.set(Some(len - 1));
                }
            }
            Key::Escape => {
                // Layered escape: popover → pill mode
                if self.popover_pill.read().is_some() {
                    self.popover_pill.set(None);
                } else {
                    self.active_pill.set(None);
                }
            }
            _ => {
                if readonly {
                    return;
                }
                // Any typing key exits pill mode so the character goes into the input
                self.active_pill.set(None);
                self.popover_pill.set(None);
            }
        }
    }

    /// Handle keyboard events for the text input.
    ///
    /// Called by `handle_keydown` when no pill is active, or directly by
    /// compound components that manage their own input keydown.
    pub fn handle_input_keydown(&mut self, event: Event<KeyboardData>) {
        let key = event.key();
        let readonly = *self.is_readonly.read();

        // ── Readonly mode: only allow pill entry and escape ─────────────
        if readonly {
            match key {
                Key::ArrowLeft => {
                    if self.search_query.read().is_empty() {
                        let len = self.selected_tags.read().len();
                        if len > 0 {
                            event.prevent_default();
                            self.active_pill.set(Some(len - 1));
                        }
                    }
                }
                Key::Escape => {
                    // Just close pill mode
                    self.active_pill.set(None);
                }
                _ => {}
            }
            return;
        }

        // ── Input mode (normal) ─────────────────────────────────────────
        match key {
            Key::ArrowLeft => {
                // Enter pill mode from the right when query is empty
                if self.search_query.read().is_empty() {
                    let len = self.selected_tags.read().len();
                    if len > 0 {
                        event.prevent_default();
                        self.active_pill.set(Some(len - 1));
                    }
                }
            }
            Key::Enter => {
                event.prevent_default();
                let query = self.search_query.read().clone();
                let callback = *self.on_create.read();
                if !query.is_empty() {
                    // enforce_allow_list blocks on_create
                    if *self.enforce_allow_list.read() {
                        // Do nothing — only suggestions can be selected
                    } else if let Some(cb) = callback {
                        if let Some(tag) = cb.call(query) {
                            self.create_tag(tag);
                        }
                    } else {
                        // No on_create handler — fire on_commit if set
                        let commit_cb = *self.on_commit.read();
                        if let Some(handler) = commit_cb {
                            handler.call(query);
                        }
                    }
                }
            }
            Key::Backspace => {
                // On empty input, select last *unlocked* pill instead of immediately deleting
                if self.search_query.read().is_empty() {
                    let tags = self.selected_tags.read();
                    if let Some(pos) = tags.iter().rposition(|t| !t.is_locked()) {
                        drop(tags);
                        self.active_pill.set(Some(pos));
                    }
                }
            }
            Key::Escape => {
                // Just close pill mode
                self.active_pill.set(None);
            }
            Key::Character(ref c) => {
                // Custom delimiter: commit query when a delimiter char is typed
                let delims = self.delimiters.read().clone();
                if let Some(delimiters) = delims
                    && let Some(ch) = c.chars().next()
                    && delimiters.contains(&ch)
                {
                    event.prevent_default();
                    // enforce_allow_list blocks on_create via delimiter too
                    if !*self.enforce_allow_list.read() {
                        let query = self.search_query.read().clone();
                        let callback = *self.on_create.read();
                        if !query.is_empty() {
                            if let Some(cb) = callback {
                                if let Some(tag) = cb.call(query) {
                                    self.create_tag(tag);
                                }
                            } else {
                                // No on_create handler — fire on_commit if set
                                let commit_cb = *self.on_commit.read();
                                if let Some(handler) = commit_cb {
                                    handler.call(query);
                                }
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

/// Create a headless tag input state.
///
/// `available_tags` is the full set of tags the user can choose from.
/// `initial_selected` is the set of tags already selected on mount.
///
/// Returns a `TagInputState<T>` with reactive signals and a memo for filtered suggestions.
#[allow(clippy::type_complexity)]
pub fn use_tag_input<T: TagLike>(
    available_tags: Vec<T>,
    initial_selected: Vec<T>,
) -> TagInputState<T> {
    use_tag_input_with(TagInputConfig::new(available_tags, initial_selected))
}

/// Create a headless tag input state with optional controlled signals.
///
/// This is the configurable version of `use_tag_input`. When `value` or `query`
/// signals are provided in the config, the hook uses those directly instead of creating
/// internal ones. All mutations (`add_tag`, `remove_tag`, etc.) write to the provided
/// signal automatically — no callbacks needed.
#[allow(clippy::type_complexity)]
pub fn use_tag_input_with<T: TagLike>(config: TagInputConfig<T>) -> TagInputState<T> {
    let instance_id = use_hook(|| INSTANCE_COUNTER.fetch_add(1, AtomicOrdering::Relaxed));

    // Always create internal signals unconditionally (hook ordering rules).
    // Use parent signal if provided, otherwise internal.
    let internal_query = use_signal(String::new);
    let internal_selected = use_signal(|| config.initial_selected);
    let internal_available = use_signal(|| config.available_tags);

    let search_query = config.query.unwrap_or(internal_query);
    let selected_tags = config.value.unwrap_or(internal_selected);
    let available_tags = internal_available;

    // Phase 4
    let deny_list: Signal<Option<Vec<String>>> = use_signal(|| None);
    // Phase 6
    let filter: Signal<Option<fn(&T, &str) -> bool>> = use_signal(|| None);

    let active_pill = use_signal(|| None);
    let popover_pill = use_signal(|| None);
    let on_create = use_signal(|| None);
    let on_remove = use_signal(|| None);
    let on_add = use_signal(|| None);
    let on_query_change: Signal<Option<EventHandler<String>>> = use_signal(|| None);
    let on_commit: Signal<Option<EventHandler<String>>> = use_signal(|| None);
    let is_disabled = use_signal(|| false);
    let status_message = use_signal(String::new);
    let on_paste = use_signal(|| None);
    let paste_delimiters = use_signal(|| None);
    // Phase 2
    let editing_pill = use_signal(|| None);
    let on_edit = use_signal(|| None);
    let on_reorder = use_signal(|| None);
    // Phase 3
    let delimiters = use_signal(|| None);
    let max_tags: Signal<Option<usize>> = use_signal(|| None);
    let is_at_limit = use_memo(move || match *max_tags.read() {
        Some(max) => selected_tags.read().len() >= max,
        None => false,
    });
    let validate = use_signal(|| None);
    let validation_error = use_signal(|| None);
    // Phase 4
    let allow_duplicates = use_signal(|| false);
    let on_duplicate = use_signal(|| None);
    let enforce_allow_list = use_signal(|| false);
    let min_tags: Signal<Option<usize>> = use_signal(|| None);
    let is_below_minimum = use_memo(move || match *min_tags.read() {
        Some(min) => selected_tags.read().len() < min,
        None => false,
    });
    let is_readonly = use_signal(|| false);
    // Phase 6
    let max_tag_length = use_signal(|| None);
    let max_visible_tags: Signal<Option<usize>> = use_signal(|| None);
    let overflow_count = use_memo(move || match *max_visible_tags.read() {
        Some(max) => {
            let len = selected_tags.read().len();
            len.saturating_sub(max)
        }
        None => 0,
    });
    let visible_tags = use_memo(move || {
        let tags = selected_tags.read().clone();
        match *max_visible_tags.read() {
            Some(max) => tags.into_iter().take(max).collect(),
            None => tags,
        }
    });
    let sort_selected: Signal<Option<fn(&T, &T) -> Ordering>> = use_signal(|| None);
    // Phase 7
    let form_value = use_memo(move || {
        let tags = selected_tags.read();
        let ids: Vec<String> = tags.iter().map(|t| format!("\"{}\"", t.id())).collect();
        format!("[{}]", ids.join(","))
    });
    let select_mode = use_signal(|| false);

    TagInputState {
        search_query,
        selected_tags,
        available_tags,
        active_pill,
        popover_pill,
        on_create,
        on_remove,
        on_add,
        on_query_change,
        on_commit,
        is_disabled,
        status_message,
        on_paste,
        paste_delimiters,
        editing_pill,
        on_edit,
        on_reorder,
        delimiters,
        max_tags,
        is_at_limit,
        validate,
        validation_error,
        // Phase 4
        allow_duplicates,
        on_duplicate,
        enforce_allow_list,
        deny_list,
        min_tags,
        is_below_minimum,
        is_readonly,
        // Phase 6
        max_tag_length,
        filter,
        max_visible_tags,
        overflow_count,
        visible_tags,
        sort_selected,
        // Phase 7
        form_value,
        select_mode,
        instance_id,
    }
}

/// Create a headless tag input state with grouped configuration.
///
/// This is the full-featured version of `use_tag_input`. It accepts custom filter/sort
/// functions via `TagInputGroupConfig`. Note: grouped suggestions are no longer built
/// internally — consumers can use the `build_groups` helper to organize tags externally.
#[allow(clippy::type_complexity)]
pub fn use_tag_input_grouped<T: TagLike>(config: TagInputGroupConfig<T>) -> TagInputState<T> {
    let instance_id = use_hook(|| INSTANCE_COUNTER.fetch_add(1, AtomicOrdering::Relaxed));

    // Always create internal signals unconditionally (hook ordering rules).
    // Use parent signal if provided, otherwise internal.
    let internal_query = use_signal(String::new);
    let internal_selected = use_signal(|| config.initial_selected);
    let internal_available = use_signal(|| config.available_tags);

    let search_query = config.query.unwrap_or(internal_query);
    let selected_tags = config.value.unwrap_or(internal_selected);
    let available_tags = internal_available;

    // Phase 4
    let deny_list: Signal<Option<Vec<String>>> = use_signal(|| None);

    let active_pill = use_signal(|| None);
    let popover_pill = use_signal(|| None);
    let on_create = use_signal(|| None);
    let on_remove = use_signal(|| None);
    let on_add = use_signal(|| None);
    let on_query_change: Signal<Option<EventHandler<String>>> = use_signal(|| None);
    let on_commit: Signal<Option<EventHandler<String>>> = use_signal(|| None);
    let is_disabled = use_signal(|| false);
    let status_message = use_signal(String::new);
    let on_paste = use_signal(|| None);
    let paste_delimiters = use_signal(|| None);
    // Phase 2
    let editing_pill = use_signal(|| None);
    let on_edit = use_signal(|| None);
    let on_reorder = use_signal(|| None);
    // Phase 3
    let delimiters = use_signal(|| None);
    let max_tags: Signal<Option<usize>> = use_signal(|| None);
    let is_at_limit = use_memo(move || match *max_tags.read() {
        Some(max) => selected_tags.read().len() >= max,
        None => false,
    });
    let validate = use_signal(|| None);
    let validation_error = use_signal(|| None);
    // Phase 4
    let allow_duplicates = use_signal(|| false);
    let on_duplicate = use_signal(|| None);
    let enforce_allow_list = use_signal(|| false);
    let min_tags: Signal<Option<usize>> = use_signal(|| None);
    let is_below_minimum = use_memo(move || match *min_tags.read() {
        Some(min) => selected_tags.read().len() < min,
        None => false,
    });
    let is_readonly = use_signal(|| false);
    // Phase 6
    let max_tag_length = use_signal(|| None);
    let filter: Signal<Option<fn(&T, &str) -> bool>> = use_signal(|| None);
    let max_visible_tags: Signal<Option<usize>> = use_signal(|| None);
    let overflow_count = use_memo(move || match *max_visible_tags.read() {
        Some(max) => {
            let len = selected_tags.read().len();
            len.saturating_sub(max)
        }
        None => 0,
    });
    let visible_tags = use_memo(move || {
        let tags = selected_tags.read().clone();
        match *max_visible_tags.read() {
            Some(max) => tags.into_iter().take(max).collect(),
            None => tags,
        }
    });
    let sort_selected: Signal<Option<fn(&T, &T) -> Ordering>> = use_signal(|| None);
    // Phase 7
    let form_value = use_memo(move || {
        let tags = selected_tags.read();
        let ids: Vec<String> = tags.iter().map(|t| format!("\"{}\"", t.id())).collect();
        format!("[{}]", ids.join(","))
    });
    let select_mode = use_signal(|| false);

    TagInputState {
        search_query,
        selected_tags,
        available_tags,
        active_pill,
        popover_pill,
        on_create,
        on_remove,
        on_add,
        on_query_change,
        on_commit,
        is_disabled,
        status_message,
        on_paste,
        paste_delimiters,
        editing_pill,
        on_edit,
        on_reorder,
        delimiters,
        max_tags,
        is_at_limit,
        validate,
        validation_error,
        // Phase 4
        allow_duplicates,
        on_duplicate,
        enforce_allow_list,
        deny_list,
        min_tags,
        is_below_minimum,
        is_readonly,
        // Phase 6
        max_tag_length,
        filter,
        max_visible_tags,
        overflow_count,
        visible_tags,
        sort_selected,
        // Phase 7
        form_value,
        select_mode,
        instance_id,
    }
}

// ---------------------------------------------------------------------------
// Status message formatting helpers (pure functions, testable)
// ---------------------------------------------------------------------------

pub(crate) fn format_status_added(name: &str, total: usize) -> String {
    format!(
        "{name} added. {total} tag{} selected.",
        if total == 1 { "" } else { "s" }
    )
}

pub(crate) fn format_status_removed(name: &str, total: usize) -> String {
    format!(
        "{name} removed. {total} tag{} selected.",
        if total == 1 { "" } else { "s" }
    )
}

pub(crate) fn format_status_pasted(added: usize, total: usize) -> String {
    format!(
        "{added} tag{} pasted. {total} tag{} selected.",
        if added == 1 { "" } else { "s" },
        if total == 1 { "" } else { "s" }
    )
}

#[cfg(test)]
pub(crate) fn format_status_suggestions(count: usize) -> String {
    format!(
        "{count} suggestion{} available.",
        if count == 1 { "" } else { "s" }
    )
}

/// Split a string by delimiter characters, trim whitespace, and return non-empty tokens.
pub(crate) fn split_by_delimiters(text: &str, delimiters: &[char]) -> Vec<String> {
    text.split(|c: char| delimiters.contains(&c))
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

// ---------------------------------------------------------------------------
// Pure helper functions used in production code
// ---------------------------------------------------------------------------

/// Format the status message for duplicate rejection.
pub(crate) fn format_status_duplicate(name: &str) -> String {
    format!("{name} already exists.")
}

/// Format the status message for deny list rejection.
pub(crate) fn format_status_denied(name: &str) -> String {
    format!("{name} is not allowed.")
}

/// Format the validation error for max tag length.
pub(crate) fn format_error_max_length(max_len: usize) -> String {
    format!("Tag must be {max_len} characters or fewer.")
}

// ---------------------------------------------------------------------------
// Pure helper functions
// ---------------------------------------------------------------------------

/// Returns `true` if the given name appears in the deny list (case-insensitive).
pub fn is_denied(name: &str, deny_list: &[String]) -> bool {
    let name_lower = name.to_lowercase();
    deny_list.iter().any(|b| b.to_lowercase() == name_lower)
}

#[cfg(test)]
pub(crate) fn is_in_allow_list<T: TagLike>(id: &str, available: &[T]) -> bool {
    available.iter().any(|t| t.id() == id)
}

#[cfg(test)]
pub(crate) fn filter_denied<T: TagLike>(items: &[T], deny_list: &[String]) -> Vec<T> {
    items
        .iter()
        .filter(|tag| !is_denied(tag.name(), deny_list))
        .cloned()
        .collect()
}

#[cfg(test)]
pub(crate) fn compute_auto_complete_text(query: &str, suggestion_name: &str) -> String {
    if query.is_empty() {
        return String::new();
    }
    if suggestion_name
        .to_lowercase()
        .starts_with(&query.to_lowercase())
    {
        suggestion_name[query.len()..].to_string()
    } else {
        String::new()
    }
}

#[cfg(test)]
pub(crate) fn format_form_value(ids: &[&str]) -> String {
    let quoted: Vec<String> = ids.iter().map(|id| format!("\"{}\"", id)).collect();
    format!("[{}]", quoted.join(","))
}

#[cfg(test)]
pub(crate) fn compute_overflow(total: usize, max_visible: Option<usize>) -> usize {
    match max_visible {
        Some(max) => total.saturating_sub(max),
        None => 0,
    }
}

#[cfg(test)]
pub(crate) fn is_below_min(count: usize, min_tags: Option<usize>) -> bool {
    match min_tags {
        Some(min) => count < min,
        None => false,
    }
}

#[cfg(test)]
pub(crate) fn format_status_truncated(shown: usize, total: usize) -> String {
    format!("Showing {shown} of {total} suggestions. Type to refine.")
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Extract the clipboard text from a paste `Event<ClipboardData>` on WASM targets.
///
/// Uses `web-sys` to cast the underlying event to a `ClipboardEvent` and read
/// `clipboardData.getData("text/plain")`. Returns `None` on non-WASM targets
/// or if the clipboard data is unavailable.
///
/// Typical usage in consumer RSX:
/// ```ignore
/// onpaste: move |evt: Event<ClipboardData>| {
///     if let Some(text) = extract_clipboard_text(&evt) {
///         evt.prevent_default();
///         state.handle_paste(text);
///     }
/// }
/// ```
#[cfg(target_arch = "wasm32")]
pub fn extract_clipboard_text(
    event: &dioxus::prelude::Event<dioxus::prelude::ClipboardData>,
) -> Option<String> {
    use wasm_bindgen::JsCast;
    let clip: &dioxus::prelude::ClipboardData = &event.data();
    let web_event: web_sys::Event = clip.downcast::<web_sys::Event>()?.clone();
    let clipboard_event: web_sys::ClipboardEvent = web_event.dyn_into().ok()?;
    let data_transfer = clipboard_event.clipboard_data()?;
    data_transfer.get_data("text/plain").ok()
}

#[cfg(not(target_arch = "wasm32"))]
pub fn extract_clipboard_text(
    _event: &dioxus::prelude::Event<dioxus::prelude::ClipboardData>,
) -> Option<String> {
    None
}

/// Build `SuggestionGroup`s from a flat list of tags, preserving first-seen group order.
#[cfg(test)]
pub(crate) fn build_groups<T: TagLike>(
    items: &[T],
    sort_items: Option<fn(&T, &T) -> Ordering>,
    sort_groups: Option<fn(&str, &str) -> Ordering>,
    max_items_per_group: Option<usize>,
) -> Vec<SuggestionGroup<T>> {
    // Collect items into groups, preserving first-seen order via Vec of (label, items).
    let mut group_order: Vec<String> = Vec::new();
    let mut group_map: Vec<(String, Vec<T>)> = Vec::new();

    for item in items {
        let label = item.group().unwrap_or("").to_string();
        if let Some(pos) = group_order.iter().position(|l| l == &label) {
            group_map[pos].1.push(item.clone());
        } else {
            group_order.push(label.clone());
            group_map.push((label, vec![item.clone()]));
        }
    }

    // Sort groups if requested
    if let Some(cmp) = sort_groups {
        group_map.sort_by(|(a, _), (b, _)| cmp(a, b));
    }

    // Sort items within each group and apply max_items truncation
    group_map
        .into_iter()
        .map(|(label, mut items)| {
            if let Some(cmp) = sort_items {
                items.sort_by(cmp);
            }
            let total_count = items.len();
            if let Some(max) = max_items_per_group {
                items.truncate(max);
            }
            SuggestionGroup {
                label,
                items,
                total_count,
            }
        })
        .collect()
}