File: avatar_toolbar_button_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (2868 lines) | stat: -rw-r--r-- 123,187 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/profiles/avatar_toolbar_button.h"

#include <optional>
#include <string>
#include <string_view>

#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/with_feature_override.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/enterprise/browser_management/management_service_factory.h"
#include "chrome/browser/enterprise/util/managed_browser_utils.h"
#include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h"
#include "chrome/browser/profiles/keep_alive/scoped_profile_keep_alive.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/signin/signin_ui_delegate.h"
#include "chrome/browser/signin/signin_ui_util.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window/public/browser_window_features.h"
#include "chrome/browser/ui/profiles/profile_colors_util.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/profiles/profile_menu_coordinator.h"
#include "chrome/browser/ui/views/profiles/profile_menu_view_base.h"
#include "chrome/browser/ui/views/toolbar/toolbar_view.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/branded_strings.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/profile_destruction_waiter.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/user_education/interactive_feature_promo_test.h"
#include "components/keep_alive_registry/keep_alive_types.h"
#include "components/keep_alive_registry/scoped_keep_alive.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/management/management_service.h"
#include "components/policy/core/common/management/scoped_management_service_override_for_testing.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/base/signin_metrics.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/signin/public/identity_manager/accounts_mutator.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/signin/public/identity_manager/primary_account_mutator.h"
#include "components/signin/public/identity_manager/signin_constants.h"
#include "components/sync/service/sync_service.h"
#include "components/sync/test/test_sync_service.h"
#include "components/user_education/common/user_education_features.h"
#include "content/public/browser/browser_context.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"
#include "google_apis/gaia/core_account_id.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/mojom/themes.mojom.h"
#include "ui/base/ui_base_features.h"
#include "ui/events/base_event_utils.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_unittest_util.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "ash/constants/ash_switches.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/testing_profile.h"
#include "components/user_manager/user_names.h"
#endif

using signin::constants::kNoHostedDomainFound;

namespace {
using ::testing::StrictMock;
using ::testing::ValuesIn;
using ::testing::WithParamInterface;

ui::mojom::BrowserColorVariant kColorVariant =
    ui::mojom::BrowserColorVariant::kTonalSpot;

const gfx::Image kSignedInImage = gfx::test::CreateImage(20, 20, SK_ColorBLUE);
const char kSignedInImageUrl[] = "SIGNED_IN_IMAGE_URL";

constexpr std::string_view kTestPassphrase = "testpassphrase";

#if !BUILDFLAG(IS_CHROMEOS)
constexpr std::u16string_view kGivenName = u"TestName";
#endif  // !BUILDFLAG(IS_CHROMEOS)

enum class ColorThemeType { kAutogeneratedTheme, kUserColor };

std::unique_ptr<KeyedService> TestingSyncFactoryFunction(
    content::BrowserContext* context) {
  return std::make_unique<syncer::TestSyncService>();
}

class ProfileLoader {
 public:
  Profile* LoadFirstAndOnlyProfile() {
    auto* profile_manager = g_browser_process->profile_manager();
    auto& storage = profile_manager->GetProfileAttributesStorage();
    EXPECT_EQ(1U, storage.GetNumberOfProfiles());

    profile_manager->LoadProfileByPath(
        storage.GetAllProfilesAttributes()[0]->GetPath(), /*incognito=*/false,
        base::BindRepeating(&ProfileLoader::OnProfileLoaded,
                            base::Unretained(this)));

    profile_loading_run_loop_.Run();
    return profile_;
  }

 private:
  void OnProfileLoaded(Profile* profile) {
    profile_ = profile;
    profile_loading_run_loop_.Quit();
  }

  raw_ptr<Profile> profile_ = nullptr;
  base::RunLoop profile_loading_run_loop_;
};

class MockSigninUiDelegate : public signin_ui_util::SigninUiDelegate {
 public:
  MOCK_METHOD(void,
              ShowTurnSyncOnUI,
              (Profile*,
               signin_metrics::AccessPoint,
               signin_metrics::PromoAction,
               const CoreAccountId&,
               TurnSyncOnHelper::SigninAbortedMode,
               bool,
               bool),
              (override));
  MOCK_METHOD(void,
              ShowSigninUI,
              (Profile*,
               bool,
               signin_metrics::AccessPoint,
               signin_metrics::PromoAction),
              (override));
  MOCK_METHOD(void,
              ShowReauthUI,
              (Profile*,
               const std::string&,
               bool,
               signin_metrics::AccessPoint,
               signin_metrics::PromoAction),
              (override));
};

}  // namespace

class AvatarToolbarButtonBaseBrowserTest {
 public:
  AvatarToolbarButtonBaseBrowserTest()
      : dependency_manager_subscription_(
            BrowserContextDependencyManager::GetInstance()
                ->RegisterCreateServicesCallbackForTesting(base::BindRepeating(
                    &AvatarToolbarButtonBaseBrowserTest::SetTestingFactories,
                    base::Unretained(this)))) {
    // By default make all delays infinite to avoid flakiness. The tests that
    // needs to test bypass the delay effects will have to enforce timing out
    // the delays using
    // `AvatarToolbarButton::TriggerTimeoutForTesting()`. This allows to
    // properly test the behavior pre/post delay without being time dependent.
    SetInfiniteAvatarDelay(AvatarDelayType::kNameGreeting);
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
    SetInfiniteAvatarDelay(AvatarDelayType::kSigninPendingText);
    SetInfiniteAvatarDelay(AvatarDelayType::kHistorySyncOptin);
#endif  // BUILDFLAG(ENABLE_DICE_SUPPORT)
  }

  AvatarToolbarButtonBaseBrowserTest(
      const AvatarToolbarButtonBaseBrowserTest&) = delete;
  AvatarToolbarButtonBaseBrowserTest& operator=(
      const AvatarToolbarButtonBaseBrowserTest&) = delete;
  ~AvatarToolbarButtonBaseBrowserTest() = default;

  AvatarToolbarButton* GetAvatarToolbarButton(Browser* browser) {
    return BrowserView::GetBrowserViewForBrowser(browser)->toolbar()->avatar_;
  }

  virtual Browser* GetBrowser() const = 0;

  // Allows overriding the delay of different events that have a timing
  // duration. Sets the delay to infinite in order to be able to test the
  // behavior while the delay is happening. In order to stop the delay, use
  // `AvatarToolbarButton::TriggerTimeoutForTesting()` at any point.
  void SetInfiniteAvatarDelay(AvatarDelayType delay_type) {
    delay_resets_.push_back(
        AvatarToolbarButton::CreateScopedInfiniteDelayOverrideForTesting(
            delay_type));
  }

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
  // Special override for the `AvatarDelayType::kSigninPendingText` delay to set
  // it to 0 given that the start time is stored as a ProfileUserData, which can
  // remain even if no browser exist. Setting it to 0 allows testing the
  // behavior where the delay is elapsed and then opening a new browser (while
  // no browser existed already).
  void SetZeroAvatarDelayForSigninPendingText() {
    delay_resets_.push_back(
        AvatarToolbarButton::
            CreateScopedZeroDelayOverrideSigninPendingTextForTesting());
  }
#endif  // BUILDFLAG(ENABLE_DICE_SUPPORT)

  // Returns the window count in avatar button text, if it exists.
  std::optional<int> GetWindowCountInAvatarButtonText(
      AvatarToolbarButton* avatar_button) {
    const std::u16string_view button_text = avatar_button->GetText();

    size_t before_number = button_text.find('(');
    if (before_number == std::u16string_view::npos) {
      return std::optional<int>();
    }

    size_t after_number = button_text.find(')');
    EXPECT_NE(std::u16string_view::npos, after_number);

    const std::u16string_view number_text =
        button_text.substr(before_number + 1, after_number - before_number - 1);
    int window_count;
    return base::StringToInt(number_text, &window_count)
               ? std::optional<int>(window_count)
               : std::optional<int>();
  }

  ProfileAttributesEntry* GetProfileAttributesEntry(Profile* profile) {
    ProfileAttributesEntry* entry =
        g_browser_process->profile_manager()
            ->GetProfileAttributesStorage()
            .GetProfileAttributesWithPath(profile->GetPath());
    CHECK(entry);
    return entry;
  }

  // - Helper functions

  signin::IdentityManager* GetIdentityManager() {
    return IdentityManagerFactory::GetForProfile(GetBrowser()->profile());
  }

  // Make account primary account with `consent_level` set and sets the account
  // name to `name`.
  AccountInfo MakePrimaryAccountAvailableWithName(
      signin::ConsentLevel consent_level,
      const std::u16string& email,
      const std::u16string& name) {
    AccountInfo account_info = signin::MakePrimaryAccountAvailable(
        GetIdentityManager(), base::UTF16ToUTF8(email), consent_level);
    EXPECT_FALSE(account_info.IsEmpty());

    account_info.given_name = base::UTF16ToUTF8(name);
    account_info.full_name = base::UTF16ToUTF8(name);
    account_info.picture_url = "SOME_FAKE_URL";
    account_info.hosted_domain = kNoHostedDomainFound;
    account_info.locale = "en";

    // Make sure account is valid so that all changes are persisted properly.
    CHECK(account_info.IsValid());

    signin::UpdateAccountInfoForAccount(GetIdentityManager(), account_info);

    GetTestSyncService()->SetSignedIn(consent_level, account_info);
    SetHistoryAndTabsSyncingPreference(/*enable_sync=*/false);

    return account_info;
  }

  // Signs in to Chrome with `email` and set the `name` to the account name.
  AccountInfo Signin(const std::u16string& email, const std::u16string& name) {
    return MakePrimaryAccountAvailableWithName(signin::ConsentLevel::kSignin,
                                               email, name);
  }

  // Make sure `image_url` is different for each new image in order for the
  // changes to reflect into the profile as well.
  void AddAccountImage(CoreAccountId account_id,
                       gfx::Image image,
                       const std::string& image_url) {
    signin::SimulateAccountImageFetch(GetIdentityManager(), account_id,
                                      image_url, image);
  }

  // Sets `kSignedInImage` by default as the account image. This will allow to
  // show the name greeting.
  void AddSignedInImage(CoreAccountId account_id) {
    AddAccountImage(account_id, kSignedInImage, kSignedInImageUrl);
  }

  // Checks that the current image on the avtar button is the added account
  // image. Uses `kSignedInImage` by default.
  bool IsSignedInImageUsed(gfx::Image account_image = kSignedInImage) {
    AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(GetBrowser());
    gfx::Image current_avatar_icon = gfx::Image(
        avatar_button->GetImage(views::Button::ButtonState::STATE_NORMAL));
    gfx::Image adapted_signed_in_image = profiles::GetSizedAvatarIcon(
        account_image, avatar_button->GetIconSize(),
        avatar_button->GetIconSize(), profiles::SHAPE_CIRCLE);
    return gfx::test::AreImagesEqual(current_avatar_icon,
                                     adapted_signed_in_image);
  }

  // Sign in with an image should show the greeting name.
  AccountInfo SigninWithImage(const std::u16string& email,
                              const std::u16string& name = u"account_name") {
    AccountInfo account_info = Signin(email, name);
    AddSignedInImage(account_info.account_id);
    return account_info;
  }

  // Sign in with the full account information that triggers the name greeting
  // followed by the history sync opt-in promo (if enabled and not syncing), but
  // force timing both out right away to clear the animation (in all windows).
  AccountInfo SigninWithImageAndClearGreetingAndSyncPromo(
      AvatarToolbarButton* avatar,
      const std::u16string& email,
      const std::u16string& name = u"account_name") {
    AccountInfo account_info = SigninWithImage(email, name);
    avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
    // Make sure the cross window animation replay is not triggered. This is
    // needed to clear the animation in all windows.
    delay_resets_.push_back(
        signin_ui_util::
            CreateZeroOverrideDelayForCrossWindowAnimationReplayForTesting());
    ClearHistorySyncOptinPromoIfEnabled(avatar);
    return account_info;
  }

  // Clears the history sync optin promo if it is enabled. This is a no-op if
  // the promo is disabled.
  void ClearHistorySyncOptinPromoIfEnabled(AvatarToolbarButton* avatar) {
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
    if (base::FeatureList::IsEnabled(
            switches::kEnableHistorySyncOptinExpansionPill)) {
      avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
    }
#endif  // BUILDFLAG(ENABLE_DICE_SUPPORT)
  }

  void SetHistoryAndTabsSyncingPreference(bool enable_sync) {
    GetTestSyncService()->GetUserSettings()->SetSelectedType(
        syncer::UserSelectableType::kHistory, /*is_type_on=*/enable_sync);
    GetTestSyncService()->GetUserSettings()->SetSelectedType(
        syncer::UserSelectableType::kTabs, /*is_type_on=*/enable_sync);
    GetTestSyncService()->GetUserSettings()->SetSelectedType(
        syncer::UserSelectableType::kSavedTabGroups,
        /*is_type_on=*/enable_sync);
  }

#if !BUILDFLAG(IS_CHROMEOS)
  void Signout() {
    ASSERT_TRUE(
        GetIdentityManager()->HasPrimaryAccount(signin::ConsentLevel::kSignin));

    GetIdentityManager()->GetPrimaryAccountMutator()->ClearPrimaryAccount(
        signin_metrics::ProfileSignout::kTest);

    ASSERT_FALSE(
        GetIdentityManager()->HasPrimaryAccount(signin::ConsentLevel::kSignin));
  }
#endif

  void SimulateSigninError(bool web_sign_out) {
    ASSERT_TRUE(
        GetIdentityManager()->HasPrimaryAccount(signin::ConsentLevel::kSignin));

    signin_metrics::SourceForRefreshTokenOperation token_operation_source =
        web_sign_out ? signin_metrics::SourceForRefreshTokenOperation::
                           kDiceResponseHandler_Signout
                     : signin_metrics::SourceForRefreshTokenOperation::kUnknown;

    signin::SetInvalidRefreshTokenForPrimaryAccount(GetIdentityManager(),
                                                    token_operation_source);
  }

  void ClearSigninError() {
    ASSERT_TRUE(
        GetIdentityManager()->HasPrimaryAccount(signin::ConsentLevel::kSignin));

    signin::SetRefreshTokenForPrimaryAccount(GetIdentityManager());
  }

  // Enables sync for account with `email` and set the `name` to the account
  // name.
  AccountInfo EnableSync(const std::u16string& email,
                         const std::u16string name) {
    return MakePrimaryAccountAvailableWithName(signin::ConsentLevel::kSync,
                                               email, name);
  }

  // Enables Sync with image should attempt to show the name greeting.
  AccountInfo EnableSyncWithImage(const std::u16string& email) {
    // Using a default name, this function is not expected to be used if we care
    // about the name.
    AccountInfo account_info = EnableSync(email, u"account_name");
    AddSignedInImage(account_info.account_id);
    return account_info;
  }

  // Enables sync with the full account information that triggers the name
  // greeting, but force timing it out right away to clear the animation (in all
  // windows).
  AccountInfo EnableSyncWithImageAndClearGreeting(AvatarToolbarButton* avatar,
                                                  const std::u16string& email) {
    AccountInfo account_info = EnableSyncWithImage(email);
    avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
    // Make sure the cross window animation replay is not triggered. This is
    // needed to clear the animation in all windows.
    delay_resets_.push_back(
        signin_ui_util::
            CreateZeroOverrideDelayForCrossWindowAnimationReplayForTesting());
    return account_info;
  }

  void SimulateSyncPaused() {
    ASSERT_TRUE(
        GetIdentityManager()->HasPrimaryAccount(signin::ConsentLevel::kSync));

    // Simulates Sync Paused.
    GetTestSyncService()->SetPersistentAuthError();
    GetTestSyncService()->FireStateChanged();
  }

  void ClearSyncPaused() {
    ASSERT_TRUE(
        GetIdentityManager()->HasPrimaryAccount(signin::ConsentLevel::kSync));

    // Clear Sync Paused introduced in `SimulateSyncPaused()`.
    GetTestSyncService()->ClearAuthError();
    GetTestSyncService()->FireStateChanged();
  }

  void ExpectSyncPaused(AvatarToolbarButton* avatar_button) {
    EXPECT_EQ(avatar_button->GetText(), l10n_util::GetStringUTF16(
#if !BUILDFLAG(IS_CHROMEOS)
                                            IDS_AVATAR_BUTTON_SYNC_PAUSED
#else
                                            IDS_AVATAR_BUTTON_SYNC_ERROR
#endif
                                            ));
  }

  void SimulateSyncError() {
    ASSERT_TRUE(
        GetIdentityManager()->HasPrimaryAccount(signin::ConsentLevel::kSync));

    // Triggers Sync Error.
    GetTestSyncService()->SetTrustedVaultKeyRequired(true);
    GetTestSyncService()->FireStateChanged();
  }

  void ClearSyncError() {
    ASSERT_TRUE(
        GetIdentityManager()->HasPrimaryAccount(signin::ConsentLevel::kSync));

    // Clear Sync Error introduces in `SimulateSyncError()`.
    GetTestSyncService()->SetTrustedVaultKeyRequired(false);
    GetTestSyncService()->FireStateChanged();
  }

  // Waits for `time`.
  void WaitForTime(base::TimeDelta time) {
    base::RunLoop waiting_run_loop;
    base::OneShotTimer timer;
    timer.Start(FROM_HERE, time, waiting_run_loop.QuitClosure());
    waiting_run_loop.Run();
  }

  void SimulateDisableSyncByPolicyWithError() {
    GetTestSyncService()->SetAllowedByEnterprisePolicy(false);
    // Disabling sync by policy resets the sync setup.
    GetTestSyncService()->SetInitialSyncFeatureSetupComplete(false);
    GetTestSyncService()->FireStateChanged();
  }

  void SimulateTypeManagedByPolicy(syncer::UserSelectableType type) {
    GetTestSyncService()->GetUserSettings()->SetTypeIsManagedByPolicy(type,
                                                                      true);
    GetTestSyncService()->FireStateChanged();
  }

  void SimulateTypeManagedByCustodian(syncer::UserSelectableType type) {
    GetTestSyncService()->GetUserSettings()->SetTypeIsManagedByCustodian(type,
                                                                         true);
    GetTestSyncService()->FireStateChanged();
  }

  void SimulatePassphraseError() {
    GetTestSyncService()->GetUserSettings()->SetPassphraseRequired(
        std::string(kTestPassphrase));
    GetTestSyncService()->FireStateChanged();
  }

  void ClearPassphraseError() {
    GetTestSyncService()->GetUserSettings()->SetDecryptionPassphrase(
        std::string(kTestPassphrase));
    GetTestSyncService()->FireStateChanged();
  }

  void SimulateUpgradeClientError() {
    syncer::SyncStatus sync_status;
    sync_status.sync_protocol_error.action = syncer::UPGRADE_CLIENT;
    GetTestSyncService()->SetDetailedSyncStatus(true, sync_status);
    GetTestSyncService()->FireStateChanged();
    ASSERT_TRUE(GetTestSyncService()->RequiresClientUpgrade());
  }

  void ClearUpgradeClientError() {
    syncer::SyncStatus sync_status;
    GetTestSyncService()->SetDetailedSyncStatus(true, sync_status);
    GetTestSyncService()->FireStateChanged();
    ASSERT_FALSE(GetTestSyncService()->RequiresClientUpgrade());
  }

 private:
  void SetTestingFactories(content::BrowserContext* context) {
    SyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
        context, base::BindRepeating(&TestingSyncFactoryFunction));
  }

  syncer::TestSyncService* GetTestSyncService() {
    return static_cast<syncer::TestSyncService*>(
        SyncServiceFactory::GetForProfile(GetBrowser()->profile()));
  }

  base::CallbackListSubscription dependency_manager_subscription_;
  std::vector<base::AutoReset<std::optional<base::TimeDelta>>> delay_resets_;
};

class AvatarToolbarButtonBrowserTest
    : public InProcessBrowserTest,
      public AvatarToolbarButtonBaseBrowserTest {
 protected:
  // AvatarToolbarButtonBaseBrowserTest:
  Browser* GetBrowser() const override { return browser(); }

  // InProcessBrowserTest:
  void SetUpOnMainThread() override {
    InProcessBrowserTest::SetUpOnMainThread();
    if (GetIdentityManager()) {
      // Puts `IdentityManager` in a known good state to avoid flakiness.
      signin::WaitForRefreshTokensLoaded(GetIdentityManager());
    }
  }
};

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, IncognitoWindowCount) {
  Profile* profile = browser()->profile();
  Browser* browser1 = CreateIncognitoBrowser(profile);
  AvatarToolbarButton* avatar_button1 = GetAvatarToolbarButton(browser1);
  EXPECT_TRUE(avatar_button1->GetEnabled());
  EXPECT_TRUE(avatar_button1->GetVisible());
  EXPECT_FALSE(GetWindowCountInAvatarButtonText(avatar_button1).has_value());

  Browser* browser2 = CreateIncognitoBrowser(profile);
  AvatarToolbarButton* avatar_button2 = GetAvatarToolbarButton(browser2);
  EXPECT_EQ(2, *GetWindowCountInAvatarButtonText(avatar_button1));
  EXPECT_EQ(2, *GetWindowCountInAvatarButtonText(avatar_button2));

  CloseBrowserSynchronously(browser2);
  EXPECT_FALSE(GetWindowCountInAvatarButtonText(avatar_button1).has_value());
}

#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, GuestWindowCount) {
  Browser* browser1 = CreateGuestBrowser();
  AvatarToolbarButton* avatar_button1 = GetAvatarToolbarButton(browser1);
  EXPECT_TRUE(avatar_button1->GetEnabled());
  EXPECT_TRUE(avatar_button1->GetVisible());
  EXPECT_FALSE(GetWindowCountInAvatarButtonText(avatar_button1).has_value());

  Browser* browser2 = CreateGuestBrowser();
  AvatarToolbarButton* avatar_button2 = GetAvatarToolbarButton(browser2);
  EXPECT_EQ(2, *GetWindowCountInAvatarButtonText(avatar_button1));
  EXPECT_EQ(2, *GetWindowCountInAvatarButtonText(avatar_button2));

  CloseBrowserSynchronously(browser2);
  EXPECT_FALSE(GetWindowCountInAvatarButtonText(avatar_button1).has_value());
}
#endif

#if BUILDFLAG(IS_CHROMEOS)
class AvatarToolbarButtonAshBrowserTest
    : public AvatarToolbarButtonBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    // Adding these command lines simulates Ash in Guest mode.
    command_line->AppendSwitch(ash::switches::kGuestSession);
    command_line->AppendSwitchASCII(ash::switches::kLoginUser,
                                    user_manager::kGuestUserName);
    command_line->AppendSwitchASCII(ash::switches::kLoginProfile,
                                    TestingProfile::kTestUserProfileDir);
    command_line->AppendSwitch(switches::kIncognito);
  }
};

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonAshBrowserTest, GuestSession) {
  Profile* guest_profile = browser()->profile();
  ASSERT_TRUE(guest_profile->IsGuestSession());

  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  EXPECT_TRUE(avatar_button->GetVisible());
  EXPECT_FALSE(avatar_button->GetEnabled());

  EXPECT_EQ(avatar_button->GetText(),
            l10n_util::GetPluralStringFUTF16(IDS_AVATAR_BUTTON_GUEST, 1));

  Browser* browser_2 = CreateBrowser(guest_profile);
  AvatarToolbarButton* avatar_button_2 = GetAvatarToolbarButton(browser_2);
  EXPECT_TRUE(avatar_button_2->GetVisible());
  EXPECT_FALSE(avatar_button_2->GetEnabled());

  // Browser count is not taken into consideration on purpose for Ash Guest
  // windows since the button is not enabled, both buttons still show the same
  // text as if it was a single window, which is different from other platforms.
  EXPECT_EQ(avatar_button->GetText(),
            l10n_util::GetPluralStringFUTF16(IDS_AVATAR_BUTTON_GUEST, 1));
  EXPECT_EQ(avatar_button_2->GetText(),
            l10n_util::GetPluralStringFUTF16(IDS_AVATAR_BUTTON_GUEST, 1));
}
#endif

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, DefaultBrowser) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  ASSERT_TRUE(avatar);
#if BUILDFLAG(IS_CHROMEOS)
  // No avatar button is shown in normal Ash windows.
  EXPECT_FALSE(avatar->GetVisible());
#else
  EXPECT_TRUE(avatar->GetVisible());
  EXPECT_TRUE(avatar->GetEnabled());
#endif
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, IncognitoBrowser) {
  Browser* browser1 = CreateIncognitoBrowser(browser()->profile());
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser1);
  ASSERT_TRUE(avatar);
  // Incognito browsers always show an enabled avatar button.
  EXPECT_TRUE(avatar->GetVisible());
  EXPECT_TRUE(avatar->GetEnabled());
}

#if BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, SigninBrowser) {
  // Create an Incognito browser first.
  CreateIncognitoBrowser(browser()->profile());
  // Create a portal signin browser which will not be the Incognito browser.
  Profile::OTRProfileID profile_id(
      Profile::OTRProfileID::CreateUniqueForCaptivePortal());
  Browser* browser1 = Browser::Create(Browser::CreateParams(
      browser()->profile()->GetOffTheRecordProfile(profile_id,
                                                   /*create_if_needed=*/true),
      true));
  AddBlankTabAndShow(browser1);
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser1);
  ASSERT_TRUE(avatar);
  // On ChromeOS, captive portal signin windows show a
  // disabled avatar button to indicate that the window is incognito.
  EXPECT_TRUE(avatar->GetVisible());
  EXPECT_FALSE(avatar->GetEnabled());
}
#endif

// TODO(b/331746545): Check flaky test issue on windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_ShowNameOnSigninThenSync DISABLED_ShowNameOnSigninThenSync
#else
#define MAYBE_ShowNameOnSigninThenSync ShowNameOnSigninThenSync
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       MAYBE_ShowNameOnSigninThenSync) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());

  std::u16string email(u"test@gmail.com");
  std::u16string name(u"TestName");
  AccountInfo account_info = Signin(email, name);
  // The button is in a waiting for image state, the name is not yet displayed.
  EXPECT_EQ(avatar->GetText(), std::u16string());

  // The greeting will only show when the image is loaded.
  AddSignedInImage(account_info.account_id);
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING, name));

  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  ClearHistorySyncOptinPromoIfEnabled(avatar);
  // Once the name is not shown anymore, we expect no text.
  EXPECT_EQ(avatar->GetText(), std::u16string());

  // Enabling Sync after already being signed in does not show the name again.
  EnableSync(email, name);
  EXPECT_EQ(avatar->GetText(), std::u16string());
}

// TODO(b/331746545): Check flaky test issue on windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_ShowNameOnSync DISABLED_ShowNameOnSync
#else
#define MAYBE_ShowNameOnSync ShowNameOnSync
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, MAYBE_ShowNameOnSync) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());

  std::u16string email(u"test@gmail.com");
  std::u16string name(u"TestName");
  AccountInfo account_info = EnableSync(email, name);
  // The button is in a waiting for image state, the name is not yet displayed.
  EXPECT_EQ(avatar->GetText(), std::u16string());

  // The greeting will only show when the image is loaded.
  AddSignedInImage(account_info.account_id);
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING, name));

  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // Once the name is not shown anymore, we expect no text.
  EXPECT_EQ(avatar->GetText(), std::u16string());
}

// Check www.crbug.com/331499330: This test makes sure that no states attempt to
// request an update during their construction. But rather do so after all the
// states are created and the view is added to the Widget.
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       OpenNewBrowserWhileNameIsShown) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());

  std::u16string name(u"TestName");
  AccountInfo account_info = Signin(u"test@gmail.com", name);

  // The button is in a waiting for image state, the name is not yet displayed.
  EXPECT_EQ(avatar->GetText(), std::u16string());

  // The greeting will only show when the image is loaded.
  AddSignedInImage(account_info.account_id);
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING, name));

  // Creating a new browser while the refresh tokens are already loaded and the
  // name showing should not break/crash.
  Browser* new_browser = CreateBrowser(browser()->profile());
  AvatarToolbarButton* new_avatar_button = GetAvatarToolbarButton(new_browser);
  // Name is expected to be shown while it is still shown on the first browser.
  ASSERT_EQ(avatar->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING, name));
  EXPECT_EQ(new_avatar_button->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING, name));
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, SyncPaused) {
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar_button->GetText().empty());

  AccountInfo account_info =
      EnableSyncWithImageAndClearGreeting(avatar_button, u"test@gmail.com");
  SimulateSyncPaused();
  ExpectSyncPaused(avatar_button);

  ClearSyncPaused();
  EXPECT_EQ(avatar_button->GetText(), std::u16string());
}

// Checks that "Sync paused" has higher priority than passphrase errors.
// Regression test for https://crbug.com/368997513
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       SyncPausedWithPassphraseError) {
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  ASSERT_TRUE(avatar_button->GetText().empty());

  AccountInfo account_info =
      EnableSyncWithImageAndClearGreeting(avatar_button, u"test@gmail.com");
  SimulatePassphraseError();
  SimulateSyncPaused();
  ExpectSyncPaused(avatar_button);
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, SyncError) {
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar_button->GetText().empty());

  EnableSyncWithImageAndClearGreeting(avatar_button, u"test@gmail.com");
  SimulateSyncError();
  EXPECT_EQ(avatar_button->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SYNC_ERROR));

  ClearSyncError();
  EXPECT_EQ(avatar_button->GetText(), std::u16string());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       SyncPausedThenExplicitText) {
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar_button->GetText().empty());

  EnableSyncWithImageAndClearGreeting(avatar_button, u"test@gmail.com");
  SimulateSyncPaused();
  ExpectSyncPaused(avatar_button);

  std::u16string profile_switch_text(u"Profile Switch?");
  base::ScopedClosureRunner hide_callback =
      avatar_button->SetExplicitButtonState(
          profile_switch_text, /*accessibility_label=*/std::nullopt,
          /*explicit_action=*/std::nullopt);
  EXPECT_EQ(avatar_button->GetText(), profile_switch_text);

  // Clearing explicit text should go back to Sync Pause.
  hide_callback.RunAndReset();
  ExpectSyncPaused(avatar_button);
}

// Explicit text over sync paused/error.
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       ExplicitTextThenSyncPause) {
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar_button->GetText().empty());

  EnableSyncWithImageAndClearGreeting(avatar_button, u"test@gmail.com");
  std::u16string profile_switch_text(u"Profile Switch?");
  base::ScopedClosureRunner hide_callback =
      avatar_button->SetExplicitButtonState(
          profile_switch_text, /*accessibility_label=*/std::nullopt,
          /*explicit_action=*/std::nullopt);
  EXPECT_EQ(avatar_button->GetText(), profile_switch_text);

  SimulateSyncPaused();
  // Explicit text should still be shown even if Sync is now Paused.
  EXPECT_EQ(avatar_button->GetText(), profile_switch_text);

  // Clearing explicit text should go back to Sync Pause.
  hide_callback.RunAndReset();
  ExpectSyncPaused(avatar_button);
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       ShowExplicitTextAndHide) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  ASSERT_EQ(avatar->GetText(), std::u16string());

  std::u16string new_text(u"Some New Text");
  base::ScopedClosureRunner hide_callback = avatar->SetExplicitButtonState(
      new_text, /*accessibility_label=*/std::nullopt,
      /*explicit_action=*/std::nullopt);

  EXPECT_EQ(avatar->GetText(), new_text);
  hide_callback.RunAndReset();
  EXPECT_EQ(avatar->GetText(), std::u16string());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       ShowExplicitTextAndDefaultHide) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  ASSERT_EQ(avatar->GetText(), std::u16string());

  // Simulates a stack that enforces the change of text, but never explicitly
  // call the hide callback. It should still be done on explicitly destroying
  // the caller.
  {
    std::u16string new_text(u"Some New Text");
    base::ScopedClosureRunner hide_callback = avatar->SetExplicitButtonState(
        new_text, /*accessibility_label=*/std::nullopt,
        /*explicit_action=*/std::nullopt);
    EXPECT_EQ(avatar->GetText(), new_text);
  }

  EXPECT_EQ(avatar->GetText(), std::u16string());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       ShowExplicitTextWithExplicitAction) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  ASSERT_EQ(avatar->GetText(), std::u16string());
  ASSERT_FALSE(avatar->HasExplicitButtonState());

  const std::u16string text_1(u"Some New Text 1");
  base::MockCallback<base::RepeatingCallback<void(bool)>> mock_callback_1;
  base::ScopedClosureRunner reset_callback_1 = avatar->SetExplicitButtonState(
      text_1, /*accessibility_label=*/std::nullopt, mock_callback_1.Get());
  EXPECT_EQ(avatar->GetText(), text_1);
  EXPECT_TRUE(avatar->HasExplicitButtonState());
  EXPECT_CALL(mock_callback_1, Run).Times(1);
  avatar->ButtonPressed();

  const std::u16string text_2(u"Some New Text 2");
  base::MockCallback<base::RepeatingCallback<void(bool)>> mock_callback_2;
  base::ScopedClosureRunner reset_callback_2 = avatar->SetExplicitButtonState(
      text_2, /*accessibility_label=*/std::nullopt, mock_callback_2.Get());
  EXPECT_EQ(avatar->GetText(), text_2);
  EXPECT_TRUE(avatar->HasExplicitButtonState());
  EXPECT_CALL(mock_callback_2, Run).Times(1);
  avatar->ButtonPressed();

  // Calling the first reset callback should do nothing after the second call
  // to `SetExplicitButtonState`.
  reset_callback_1.RunAndReset();
  EXPECT_EQ(avatar->GetText(), text_2);
  EXPECT_TRUE(avatar->HasExplicitButtonState());

  // Calling the second reset callback should reset the text and the action.
  reset_callback_2.RunAndReset();
  EXPECT_EQ(avatar->GetText(), std::u16string());
  EXPECT_FALSE(avatar->HasExplicitButtonState());
}

// Avatar button is not shown on Ash. No need to perform those tests as the info
// checked might not be adapted.
#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, SignInOutIconEffect) {
  ASSERT_FALSE(IsSignedInImageUsed());

  SigninWithImage(u"test@gmail.com");
  EXPECT_TRUE(IsSignedInImageUsed());

  Signout();
  EXPECT_FALSE(IsSignedInImageUsed());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, SignedInChangeIcon) {
  ASSERT_FALSE(IsSignedInImageUsed());

  AccountInfo account_info = SigninWithImage(u"test@gmail.com");
  EXPECT_TRUE(IsSignedInImageUsed());

  // Same image but different color as `kSignedInImage`.
  gfx::Image updated_image = gfx::test::CreateImage(20, 20, SK_ColorGREEN);
  AddAccountImage(account_info.account_id, updated_image,
                  "UPDATED_IMAGE_FAKE_URL");

  EXPECT_TRUE(IsSignedInImageUsed(updated_image));
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       PRE_SignedInWithNewSessionKeepIcon) {
  ASSERT_FALSE(IsSignedInImageUsed());

  SigninWithImage(u"test@gmail.com");
  EXPECT_TRUE(IsSignedInImageUsed());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       SignedInWithNewSessionKeepIcon) {
  ASSERT_TRUE(
      GetIdentityManager()->HasPrimaryAccount(signin::ConsentLevel::kSignin));
  // Previously added image on signin should still be shown in the new session.
  EXPECT_TRUE(IsSignedInImageUsed());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, TooltipText) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  ASSERT_EQ(avatar->GetText(), std::u16string());

  const std::u16string account_name(u"Account name");
  AccountInfo account_info = Signin(u"test@gmail.com", account_name);

  AddSignedInImage(account_info.account_id);

  EXPECT_EQ(avatar->GetRenderedTooltipText(gfx::Point()), account_name);

  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);

  // Tooltip is the same after hiding the name.
  EXPECT_EQ(avatar->GetRenderedTooltipText(gfx::Point()), account_name);
}

// TODO(b/331746545): Check flaky test issue on windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_EnableSyncWithSyncDisabled DISABLED_EnableSyncWithSyncDisabled
#else
#define MAYBE_EnableSyncWithSyncDisabled EnableSyncWithSyncDisabled
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       MAYBE_EnableSyncWithSyncDisabled) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  ASSERT_EQ(avatar->GetText(), std::u16string());

  EnableSyncWithImageAndClearGreeting(avatar, u"test@gmail.com");
  EXPECT_EQ(avatar->GetText(), std::u16string());

  SimulateDisableSyncByPolicyWithError();

  EXPECT_EQ(avatar->GetText(), std::u16string());

  Browser* new_browser = CreateBrowser(browser()->profile());
  AvatarToolbarButton* new_avatar = GetAvatarToolbarButton(new_browser);
  EXPECT_EQ(new_avatar->GetText(), std::u16string());
}

#endif

class AvatarToolbarButtonWithInteractiveFeaturePromoBrowserTest
    : public InteractiveFeaturePromoTest,
      public AvatarToolbarButtonBaseBrowserTest {
 protected:
  AvatarToolbarButtonWithInteractiveFeaturePromoBrowserTest()
      : InteractiveFeaturePromoTest(UseDefaultTrackerAllowingPromos({})) {}

  // AvatarToolbarButtonBaseBrowserTest:
  Browser* GetBrowser() const override { return browser(); }

  // InteractiveFeaturePromoTest:
  void SetUpOnMainThread() override {
    InteractiveFeaturePromoTest::SetUpOnMainThread();
    if (GetIdentityManager()) {
      // Puts `IdentityManager` in a known good state to avoid flakiness.
      signin::WaitForRefreshTokensLoaded(GetIdentityManager());
    }
  }
};

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
class AvatarToolbarButtonHistorySyncOptinBrowserTest
    : public AvatarToolbarButtonWithInteractiveFeaturePromoBrowserTest {
 protected:
  explicit AvatarToolbarButtonHistorySyncOptinBrowserTest(
      base::FieldTrialParams feature_parameters = {}) {
    feature_list_.InitAndEnableFeatureWithParameters(
        switches::kEnableHistorySyncOptinExpansionPill, feature_parameters);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonHistorySyncOptinBrowserTest,
                       HistorySyncOptinNotShownIfGreetingNotShown) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  Signin(/*email=*/u"test@gmail.com", /*name=*/u"TestName");
  // The button is in a waiting for image state, the greeting is not yet
  // displayed, hence the history sync opt-in should not be shown.
  EXPECT_EQ(avatar->GetText(), std::u16string());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinNotShownWhenSyncEnabled \
  DISABLED_HistorySyncOptinNotShownWhenSyncEnabled
#else
#define MAYBE_HistorySyncOptinNotShownWhenSyncEnabled \
  HistorySyncOptinNotShownWhenSyncEnabled
#endif
// TODO(crbug.com/407964657): Merge this test with
// AvatarToolbarButtonBrowserTest.SyncError once the feature is enabled by
// default.
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonHistorySyncOptinBrowserTest,
                       MAYBE_HistorySyncOptinNotShownWhenSyncEnabled) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const AccountInfo account = EnableSyncWithImage(/*email=*/u"test@gmail.com");
  ASSERT_EQ(avatar->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING,
                                       base::UTF8ToUTF16(account.given_name)));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should NOT be followed by the history sync opt-in entry point
  // if sync is already enabled.
  EXPECT_TRUE(avatar->GetText().empty());
  SimulateSyncError();
  // The sync error should be shown.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SYNC_ERROR));
  ClearSyncError();
  // After clearing the sync error, the history sync opt-in entry point should
  // NOT be shown.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
// TODO(crbug.com/331746545): Re-enable this test
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinNotShownWhenPromotionsDisabled \
  DISABLED_HistorySyncOptinNotShownWhenPromotionsDisabled
#else
#define MAYBE_HistorySyncOptinNotShownWhenPromotionsDisabled \
  HistorySyncOptinNotShownWhenPromotionsDisabled
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonHistorySyncOptinBrowserTest,
                       MAYBE_HistorySyncOptinNotShownWhenPromotionsDisabled) {
  TestingBrowserProcess::GetGlobal()->local_state()->SetBoolean(
      prefs::kPromotionsEnabled, false);
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const AccountInfo account = SigninWithImage(/*email=*/u"test@gmail.com");
  ASSERT_EQ(avatar->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING,
                                       base::UTF8ToUTF16(account.given_name)));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should NOT be followed by the history sync opt-in entry point
  // if promotions are disabled.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinNotShownWhenSyncNotAllowed \
  DISABLED_HistorySyncOptinNotShownWhenSyncNotAllowed
#else
#define MAYBE_HistorySyncOptinNotShownWhenSyncNotAllowed \
  HistorySyncOptinNotShownWhenSyncNotAllowed
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonHistorySyncOptinBrowserTest,
                       MAYBE_HistorySyncOptinNotShownWhenSyncNotAllowed) {
  SimulateDisableSyncByPolicyWithError();
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should NOT be followed by the history sync opt-in entry point
  // if sync is not allowed.
  EXPECT_TRUE(avatar->GetText().empty());
}

enum class ManagedBy {
  kPolicy,
  kCustodian,
};

struct HistorySyncOptinSyncManagedTypeTestCase {
  ManagedBy managed_by;
  syncer::UserSelectableType managed_type;
};

class AvatarToolbarButtonHistorySyncOptinManagedTypeTest
    : public AvatarToolbarButtonHistorySyncOptinBrowserTest,
      public WithParamInterface<HistorySyncOptinSyncManagedTypeTestCase> {};

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinNotShownWhenSyncManaged \
  DISABLED_HistorySyncOptinNotShownWhenSyncManaged
#else
#define MAYBE_HistorySyncOptinNotShownWhenSyncManaged \
  HistorySyncOptinNotShownWhenSyncManaged
#endif
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonHistorySyncOptinManagedTypeTest,
                       MAYBE_HistorySyncOptinNotShownWhenSyncManaged) {
  switch (GetParam().managed_by) {
    case ManagedBy::kPolicy:
      SimulateTypeManagedByPolicy(GetParam().managed_type);
      break;
    case ManagedBy::kCustodian:
      SimulateTypeManagedByCustodian(GetParam().managed_type);
      break;
    default:
      NOTREACHED();
  }
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should NOT be followed by the history sync opt-in entry point
  // if sync is not allowed.
  EXPECT_TRUE(avatar->GetText().empty());
}

const HistorySyncOptinSyncManagedTypeTestCase
    kHistorySyncOptinSyncManagedTypeTestCases[] = {
        {
            ManagedBy::kPolicy,
            syncer::UserSelectableType::kHistory,
        },
        {
            ManagedBy::kPolicy,
            syncer::UserSelectableType::kTabs,
        },
        {
            ManagedBy::kCustodian,
            syncer::UserSelectableType::kHistory,
        },
        {
            ManagedBy::kCustodian,
            syncer::UserSelectableType::kTabs,
        },
};

INSTANTIATE_TEST_SUITE_P(HistorySyncOptinManagedType,
                         AvatarToolbarButtonHistorySyncOptinManagedTypeTest,
                         ValuesIn(kHistorySyncOptinSyncManagedTypeTestCases));

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinThenPassphraseError \
  DISABLED_HistorySyncOptinThenPassphraseError
#else
#define MAYBE_HistorySyncOptinThenPassphraseError \
  HistorySyncOptinThenPassphraseError
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonHistorySyncOptinBrowserTest,
                       MAYBE_HistorySyncOptinThenPassphraseError) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES));
  SimulatePassphraseError();
  // The history sync opt-in entry point should be replaced by the passphrase
  // error message.
  EXPECT_EQ(avatar->GetText(), l10n_util::GetStringUTF16(
                                   IDS_SYNC_ERROR_USER_MENU_PASSPHRASE_BUTTON));
  ClearPassphraseError();
  // After clearing the passphrase error, the history sync opt-in entry point
  // should NOT be shown.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinThenClientUpgradeError \
  DISABLED_HistorySyncOptinThenClientUpgradeError
#else
#define MAYBE_HistorySyncOptinThenClientUpgradeError \
  HistorySyncOptinThenClientUpgradeError
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonHistorySyncOptinBrowserTest,
                       MAYBE_HistorySyncOptinThenClientUpgradeError) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES));
  SimulateUpgradeClientError();
  // The history sync opt-in entry point should be replaced by the passphrase
  // error message.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_SYNC_ERROR_USER_MENU_UPGRADE_BUTTON));
  ClearUpgradeClientError();
  // After clearing the passphrase error, the history sync opt-in entry point
  // should NOT be shown.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinThenSigninPending \
  DISABLED_HistorySyncOptinThenSigninPending
#else
#define MAYBE_HistorySyncOptinThenSigninPending \
  HistorySyncOptinThenSigninPending
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonHistorySyncOptinBrowserTest,
                       MAYBE_HistorySyncOptinThenSigninPending) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES));
  SimulateSigninError(/*web_sign_out=*/false);
  // The history sync opt-in entry point should be replaced by the signin
  // pending message.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));
  ClearSigninError();
  // After clearing the sign in error, the history sync opt-in entry point
  // should NOT be shown.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinThenExplicitText \
  DISABLED_HistorySyncOptinThenExplicitText
#else
#define MAYBE_HistorySyncOptinThenExplicitText HistorySyncOptinThenExplicitText
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonHistorySyncOptinBrowserTest,
                       MAYBE_HistorySyncOptinThenExplicitText) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES));
  const std::u16string explicit_text(u"Explicit Text");
  base::ScopedClosureRunner hide_callback = avatar->SetExplicitButtonState(
      explicit_text, /*accessibility_label=*/std::nullopt,
      /*explicit_action=*/std::nullopt);
  // The history sync opt-in entry point should be replaced by the explicit
  // text message.
  EXPECT_EQ(avatar->GetText(), explicit_text);
  hide_callback.RunAndReset();
  // After clearing the explicit text, the history sync opt-in entry point
  // should NOT be shown.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinNotShownIfErrorBeforeGreetingTimesOut \
  DISABLED_HistorySyncOptinNotShownIfErrorBeforeGreetingTimesOut
#else
#define MAYBE_HistorySyncOptinNotShownIfErrorBeforeGreetingTimesOut \
  HistorySyncOptinNotShownIfErrorBeforeGreetingTimesOut
#endif
IN_PROC_BROWSER_TEST_F(
    AvatarToolbarButtonHistorySyncOptinBrowserTest,
    MAYBE_HistorySyncOptinNotShownIfErrorBeforeGreetingTimesOut) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  SimulatePassphraseError();
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // No history sync opt-in entry point should be shown if the error is shown
  // before the greeting times out.
  EXPECT_EQ(avatar->GetText(), l10n_util::GetStringUTF16(
                                   IDS_SYNC_ERROR_USER_MENU_PASSPHRASE_BUTTON));
  ClearPassphraseError();
  // After clearing the passphrase error, the history sync opt-in entry point
  // should NOT be shown.
  EXPECT_TRUE(avatar->GetText().empty());
}

struct HistorySyncOptinExpansionPillOptionTestCase {
  std::string feature_param;
  int expected_history_sync_message_id;
};

class AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest
    : public AvatarToolbarButtonHistorySyncOptinBrowserTest,
      public WithParamInterface<HistorySyncOptinExpansionPillOptionTestCase> {
 public:
  AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest()
      : AvatarToolbarButtonHistorySyncOptinBrowserTest(/*feature_parameters=*/
                                                       {{"history-sync-optin-"
                                                         "expansion-pill-"
                                                         "option",
                                                         GetParam()
                                                             .feature_param}}) {
  }
};

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_CollapsesOnSyncTurnedOn DISABLED_CollapsesOnSyncTurnedOn
#else
#define MAYBE_CollapsesOnSyncTurnedOn CollapsesOnSyncTurnedOn
#endif
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest,
                       MAYBE_CollapsesOnSyncTurnedOn) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string email(u"test@gmail.com");
  const std::u16string account_name(u"Account name");
  const AccountInfo account_info = SigninWithImage(email, account_name);
  EXPECT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  EnableSync(email, account_name);
  // Once sync is turned on, the button should return to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_CollapsesOnSignOut DISABLED_CollapsesOnSignOut
#else
#define MAYBE_CollapsesOnSignOut CollapsesOnSignOut
#endif
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest,
                       MAYBE_CollapsesOnSignOut) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string email(u"test@gmail.com");
  const std::u16string account_name(u"Account name");
  const AccountInfo account_info = SigninWithImage(email, account_name);
  EXPECT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  Signout();
  // Once the user signs out, the button should return to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_PRE_ShowsOnBrowserRestart DISABLED_PRE_ShowsOnBrowserRestart
#define MAYBE_ShowsOnBrowserRestart DISABLED_ShowsOnBrowserRestart
#else
#define MAYBE_PRE_ShowsOnBrowserRestart PRE_ShowsOnBrowserRestart
#define MAYBE_ShowsOnBrowserRestart ShowsOnBrowserRestart
#endif
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest,
                       MAYBE_PRE_ShowsOnBrowserRestart) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string email(u"test@gmail.com");
  const std::u16string account_name(u"Account name");
  const AccountInfo account_info = SigninWithImage(email, account_name);
  EXPECT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  // The button should return to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
}

IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest,
                       MAYBE_ShowsOnBrowserRestart) {
  // Disable the preferences about syncing the tabs and history to make the
  // avatar promo eligible.
  SetHistoryAndTabsSyncingPreference(/*enable_sync=*/false);

  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // The greeting is shown after the restart.
  ASSERT_EQ(
      avatar->GetText(),
      l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING, u"Account name"));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  // The button should return to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinShowsAfterGreetingAndOnInactivity \
  DISABLED_HistorySyncOptinShowsAfterGreetingAndOnInactivity
#else
#define MAYBE_HistorySyncOptinShowsAfterGreetingAndOnInactivity \
  HistorySyncOptinShowsAfterGreetingAndOnInactivity
#endif
IN_PROC_BROWSER_TEST_P(
    AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest,
    MAYBE_HistorySyncOptinShowsAfterGreetingAndOnInactivity) {
  base::TimeDelta last_active_time;
  RunTestSequence(SetLastActive(last_active_time));
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  const AccountInfo account_info =
      Signin(/*email=*/u"test@gmail.com", account_name);
  // Simulate inactivity for enough time to trigger the new session.
  last_active_time += user_education::features::GetIdleTimeBetweenSessions();
  RunTestSequence(SetLastActive(last_active_time));
  // The history sync opt-in entry point should NOT be shown after the
  // inactivity period if the greeting has not been shown yet.
  EXPECT_TRUE(avatar->GetText().empty());
  AddSignedInImage(account_info.account_id);
  EXPECT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  // Once the history sync opt-in entry point collapses, the button should
  // return to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
  // Simulate inactivity for enough time to trigger the new session.
  last_active_time += user_education::features::GetIdleTimeBetweenSessions();
  RunTestSequence(SetLastActive(last_active_time));
  // The history sync opt-in entry point should be shown again after the
  // inactivity period.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  // Once the history sync opt-in entry point collapses, the button should
  // return to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
  // Simulate inactivity for short time to not trigger the new session.
  const base::TimeDelta short_inactivity = base::Minutes(30);
  ASSERT_GT(user_education::features::GetIdleTimeBetweenSessions(),
            short_inactivity);
  last_active_time += short_inactivity;
  RunTestSequence(SetLastActive(last_active_time));
  // The history sync opt-in entry point should NOT be shown after the short
  // inactivity period.
  EXPECT_TRUE(avatar->GetText().empty());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinNotShownIfMaxShownCountReached \
  DISABLED_HistorySyncOptinNotShownIfMaxShownCountReached
#else
#define MAYBE_HistorySyncOptinNotShownIfMaxShownCountReached \
  HistorySyncOptinNotShownIfMaxShownCountReached
#endif
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest,
                       MAYBE_HistorySyncOptinNotShownIfMaxShownCountReached) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name_1(u"Account name");
  SigninWithImage(/*email=*/u"test@gmail.com", account_name_1);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name_1));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  int shown_count = 1;
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  // The button comes back to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
  for (; shown_count < user_education::features::GetNewBadgeShowCount();
       ++shown_count) {
    // Simulate inactivity for enough time to trigger the new session.
    RunTestSequence(SetLastActive(
        shown_count * user_education::features::GetIdleTimeBetweenSessions()));
    EXPECT_EQ(
        avatar->GetText(),
        l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
    avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
    // The button comes back to the normal state.
    EXPECT_TRUE(avatar->GetText().empty());
  }
  RunTestSequence(SetLastActive(
      shown_count * user_education::features::GetIdleTimeBetweenSessions()));
  // The history sync opt-in entry point should NOT be shown after the
  // inactivity period if the max shown count has been reached.
  EXPECT_TRUE(avatar->GetText().empty());

  Signout();
  const std::u16string account_name_2(u"Account name 2");
  SigninWithImage(/*email=*/u"test2@gmail.com", account_name_2);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name_2));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point
  // (rate limiting is per account).
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
}

const HistorySyncOptinExpansionPillOptionTestCase kHistorySyncOptinTestCases[] =
    {
        {
            "browse-across-devices",
            IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES,
        },
        {
            "sync-history",
            IDS_AVATAR_BUTTON_SYNC_HISTORY,
        },
        {
            "see-tabs-from-other-devices",
            IDS_AVATAR_BUTTON_SEE_TABS_FROM_OTHER_DEVICES,
        },
        {
            "browse-across-devices-new-profile-menu-promo-variant",
            IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES,
        },
};

INSTANTIATE_TEST_SUITE_P(
    HistorySyncOptinExpansionPillOptions,
    AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest,
    ValuesIn(kHistorySyncOptinTestCases));

class AvatarToolbarButtonHistorySyncOptinClickBrowserTest
    : public AvatarToolbarButtonHistorySyncOptinWithParamBrowserTest {
 protected:
  AvatarToolbarButtonHistorySyncOptinClickBrowserTest()
      : delegate_auto_reset_(signin_ui_util::SetSigninUiDelegateForTesting(
            &mock_signin_ui_delegate_)) {}

  void Click(views::View* clickable_view) {
    clickable_view->OnMousePressed(
        ui::MouseEvent(ui::EventType::kMousePressed, gfx::Point(), gfx::Point(),
                       ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0));
    clickable_view->OnMouseReleased(ui::MouseEvent(
        ui::EventType::kMouseReleased, gfx::Point(), gfx::Point(),
        ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0));
  }

  void ClickSyncButton(ProfileMenuViewBase* profile_menu_view) {
    ASSERT_NE(profile_menu_view, nullptr);
    profile_menu_view->GetFocusManager()->AdvanceFocus(/*reverse=*/false);
    views::View* focused_item =
        profile_menu_view->GetFocusManager()->GetFocusedView();
    ASSERT_NE(focused_item, nullptr);
    Click(focused_item);
  }

  StrictMock<MockSigninUiDelegate> mock_signin_ui_delegate_;

 private:
  base::AutoReset<signin_ui_util::SigninUiDelegate*> delegate_auto_reset_;
};

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_CollapsesOnClickAndTriggersProfileMenuStartup \
  DISABLED_CollapsesOnClickAndTriggersProfileMenuStartup
#else
#define MAYBE_CollapsesOnClickAndTriggersProfileMenuStartup \
  CollapsesOnClickAndTriggersProfileMenuStartup
#endif
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonHistorySyncOptinClickBrowserTest,
                       MAYBE_CollapsesOnClickAndTriggersProfileMenuStartup) {
  base::HistogramTester histogram_tester;
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  const AccountInfo account_info =
      SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  // `Signin.SyncOptIn.IdentityPill.Shown` should be recorded with the correct
  // access point.
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnStartup,
      /*expected_count=*/1);
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnInactivity,
      /*expected_count=*/0);
  // The button action should be overridden.
  histogram_tester.ExpectTotalCount(
      "Signin.SyncOptIn.IdentityPill.DurationBeforeClick",
      /*expected_count=*/0);
  Click(avatar);
  histogram_tester.ExpectTotalCount(
      "Signin.SyncOptIn.IdentityPill.DurationBeforeClick",
      /*expected_count=*/1);
  auto* coordinator = browser()->GetFeatures().profile_menu_coordinator();
  ASSERT_NE(coordinator, nullptr);
  EXPECT_TRUE(coordinator->IsShowing());
  EXPECT_TRUE(avatar->GetText().empty());
  // Once the history sync opt-in entry point collapses, the button action
  // should be reset to the default behavior.
  // Clicking the sync button in the profile menu should trigger the sync
  // dialog with the correct access point
  // (`kHistorySyncOptinExpansionPillOnStartup`).
  EXPECT_CALL(
      mock_signin_ui_delegate_,
      ShowTurnSyncOnUI(
          browser()->profile(),
          signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnStartup,
          signin_metrics::PromoAction::PROMO_ACTION_WITH_DEFAULT,
          account_info.account_id,
          TurnSyncOnHelper::SigninAbortedMode::KEEP_ACCOUNT,
          /*is_sync_promo=*/false,
          /*turn_sync_on_signed_profile=*/true));
  ASSERT_NO_FATAL_FAILURE(
      ClickSyncButton(coordinator->GetProfileMenuViewBaseForTesting()));
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_CollapsesOnClickAndTriggersProfileMenuInactivity \
  DISABLED_CollapsesOnClickAndTriggersProfileMenuInactivity
#else
#define MAYBE_CollapsesOnClickAndTriggersProfileMenuInactivity \
  CollapsesOnClickAndTriggersProfileMenuInactivity
#endif
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonHistorySyncOptinClickBrowserTest,
                       MAYBE_CollapsesOnClickAndTriggersProfileMenuInactivity) {
  base::HistogramTester histogram_tester;
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name(u"Account name");
  const AccountInfo account_info =
      SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  // `Signin.SyncOptIn.IdentityPill.Shown` should be recorded with the correct
  // access point.
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnStartup,
      /*expected_count=*/1);
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnInactivity,
      /*expected_count=*/0);
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  // The button comes back to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
  // Simulate inactivity for enough time to trigger the new session.
  RunTestSequence(
      SetLastActive(user_education::features::GetIdleTimeBetweenSessions()));
  // The history sync opt-in entry point should be shown again after the
  // inactivity period.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  // `Signin.SyncOptIn.IdentityPill.Shown` should be recorded with the correct
  // access point.
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnStartup,
      /*expected_count=*/1);
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnInactivity,
      /*expected_count=*/1);
  // The button action should be overridden.
  histogram_tester.ExpectTotalCount(
      "Signin.SyncOptIn.IdentityPill.DurationBeforeClick",
      /*expected_count=*/0);
  Click(avatar);
  histogram_tester.ExpectTotalCount(
      "Signin.SyncOptIn.IdentityPill.DurationBeforeClick",
      /*expected_count=*/1);
  auto* coordinator = browser()->GetFeatures().profile_menu_coordinator();
  ASSERT_NE(coordinator, nullptr);
  EXPECT_TRUE(coordinator->IsShowing());
  // The button comes back to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
  EXPECT_TRUE(coordinator->IsShowing());
  // Clicking the sync button in the profile menu should trigger the sync
  // dialog with the correct access point
  // (`kHistorySyncOptinExpansionPillOnInactivity`).
  EXPECT_CALL(
      mock_signin_ui_delegate_,
      ShowTurnSyncOnUI(browser()->profile(),
                       signin_metrics::AccessPoint::
                           kHistorySyncOptinExpansionPillOnInactivity,
                       signin_metrics::PromoAction::PROMO_ACTION_WITH_DEFAULT,
                       account_info.account_id,
                       TurnSyncOnHelper::SigninAbortedMode::KEEP_ACCOUNT,
                       /*is_sync_promo=*/false,
                       /*turn_sync_on_signed_profile=*/true));
  ASSERT_NO_FATAL_FAILURE(
      ClickSyncButton(coordinator->GetProfileMenuViewBaseForTesting()));
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_HistorySyncOptinNotShownIfUsedLimitReached \
  DISABLED_HistorySyncOptinNotShownIfUsedLimitReached
#else
#define MAYBE_HistorySyncOptinNotShownIfUsedLimitReached \
  HistorySyncOptinNotShownIfUsedLimitReached
#endif
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonHistorySyncOptinClickBrowserTest,
                       MAYBE_HistorySyncOptinNotShownIfUsedLimitReached) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());
  const std::u16string account_name_1(u"Account name");
  SigninWithImage(/*email=*/u"test@gmail.com", account_name_1);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name_1));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point.
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  // The button action should be overridden.
  Click(avatar);
  // The button comes back to the normal state.
  EXPECT_TRUE(avatar->GetText().empty());
  int used_count = 1;
  for (; used_count < user_education::features::GetNewBadgeFeatureUsedCount();
       ++used_count) {
    // Simulate inactivity for enough time to trigger the new session.
    RunTestSequence(SetLastActive(
        used_count * user_education::features::GetIdleTimeBetweenSessions()));
    EXPECT_EQ(
        avatar->GetText(),
        l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
    Click(avatar);
    // The button comes back to the normal state.
    EXPECT_TRUE(avatar->GetText().empty());
  }
  RunTestSequence(SetLastActive(
      used_count * user_education::features::GetIdleTimeBetweenSessions()));
  // The history sync opt-in entry point should NOT be shown after the
  // inactivity period if the max used count has been reached.
  EXPECT_TRUE(avatar->GetText().empty());

  Signout();
  const std::u16string account_name_2(u"Account name 2");
  SigninWithImage(/*email=*/u"test2@gmail.com", account_name_2);
  ASSERT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, account_name_2));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The greeting should be followed by the history sync opt-in entry point
  // (rate limiting is per account).
  EXPECT_EQ(
      avatar->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_TriggersAndCollapsesConsistentlyAcrossMultipleBrowsers \
  DISABLED_TriggersAndCollapsesConsistentlyAcrossMultipleBrowsers
#else
#define MAYBE_TriggersAndCollapsesConsistentlyAcrossMultipleBrowsers \
  TriggersAndCollapsesConsistentlyAcrossMultipleBrowsers
#endif
IN_PROC_BROWSER_TEST_P(
    AvatarToolbarButtonHistorySyncOptinClickBrowserTest,
    MAYBE_TriggersAndCollapsesConsistentlyAcrossMultipleBrowsers) {
  // Make the delay for cross window animation replay zero to avoid flakiness.
  base::AutoReset<std::optional<base::TimeDelta>> delay_override_reset =
      signin_ui_util::
          CreateZeroOverrideDelayForCrossWindowAnimationReplayForTesting();
  base::HistogramTester histogram_tester;
  Profile* profile = browser()->profile();
  Browser* browser_1 = browser();
  AvatarToolbarButton* avatar_1 = GetAvatarToolbarButton(browser_1);
  // Normal state.
  ASSERT_TRUE(avatar_1->GetText().empty());
  const std::u16string account_name(u"Account name");
  const AccountInfo account_info =
      SigninWithImage(/*email=*/u"test@gmail.com", account_name);
  ASSERT_EQ(avatar_1->GetText(), l10n_util::GetStringFUTF16(
                                     IDS_AVATAR_BUTTON_GREETING, account_name));
  avatar_1->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);

  // The greeting should be followed by the history sync opt-in.
  EXPECT_EQ(
      avatar_1->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  // Open the second browser before the history sync opt-in collapses.
  Browser* browser_2 = CreateBrowser(profile);
  AvatarToolbarButton* avatar_2 = GetAvatarToolbarButton(browser_2);
  // The history sync opt-in should be shown in the second browser as well.
  EXPECT_EQ(
      avatar_2->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  // `Signin.SyncOptIn.IdentityPill.Shown` histogram should be recorded only
  // once.
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnStartup,
      /*expected_count=*/1);
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnInactivity,
      /*expected_count=*/0);
  avatar_1->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  // The button in both browsers comes back to the normal state.
  EXPECT_TRUE(avatar_1->GetText().empty());
  EXPECT_TRUE(avatar_2->GetText().empty());

  // Simulate inactivity for enough time to trigger the new session.
  RunTestSequence(
      SetLastActive(user_education::features::GetIdleTimeBetweenSessions()));
  // The history sync opt-in entry point should be shown again after the
  // inactivity period (in both browsers).
  EXPECT_EQ(
      avatar_1->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  EXPECT_EQ(
      avatar_2->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  // Open the third browser before the history sync opt-in collapses.
  Browser* browser_3 = CreateBrowser(profile);
  AvatarToolbarButton* avatar_3 = GetAvatarToolbarButton(browser_3);
  // The history sync opt-in should be shown in the third browser as well.
  EXPECT_EQ(
      avatar_3->GetText(),
      l10n_util::GetStringUTF16(GetParam().expected_history_sync_message_id));
  // `Signin.SyncOptIn.IdentityPill.Shown` histogram should be recorded only
  // once.
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnStartup,
      /*expected_count=*/1);
  histogram_tester.ExpectBucketCount(
      "Signin.SyncOptIn.IdentityPill.Shown",
      signin_metrics::AccessPoint::kHistorySyncOptinExpansionPillOnInactivity,
      /*expected_count=*/1);
  // Clicking the button on any browser should collapse the history sync opt-in
  // in all browsers.
  Click(avatar_2);
  // `Signin.SyncOptIn.IdentityPill.DurationBeforeClick` histogram should be
  // recorded only once.
  histogram_tester.ExpectTotalCount(
      "Signin.SyncOptIn.IdentityPill.DurationBeforeClick",
      /*expected_count=*/1);
  EXPECT_TRUE(avatar_1->GetText().empty());
  EXPECT_TRUE(avatar_2->GetText().empty());
  EXPECT_TRUE(avatar_3->GetText().empty());
}

INSTANTIATE_TEST_SUITE_P(HistorySyncOptinExpansionPillOptions,
                         AvatarToolbarButtonHistorySyncOptinClickBrowserTest,
                         ValuesIn(kHistorySyncOptinTestCases));
#endif  // BUILDFLAG(ENABLE_DICE_SUPPORT)

// Test suite for testing `AvatarToolbarButton`'s responsibility of updating
// color information in `ProfileAttributesStorage`.
class AvatarToolbarButtonProfileColorBrowserTest
    : public AvatarToolbarButtonBrowserTest,
      public WithParamInterface<ColorThemeType> {
 public:
  AvatarToolbarButtonProfileColorBrowserTest() = default;

  void SetUpOnMainThread() override {
    AvatarToolbarButtonBrowserTest::SetUpOnMainThread();
    theme_service(browser()->profile())
        ->SetBrowserColorScheme(ThemeService::BrowserColorScheme::kLight);
  }

  void SetColorTheme(Profile* profile, SkColor color) {
    ThemeService* service = theme_service(profile);
    switch (GetParam()) {
      case ColorThemeType::kAutogeneratedTheme:
        service->BuildAutogeneratedThemeFromColor(color);
        break;
      case ColorThemeType::kUserColor:
        service->SetUserColorAndBrowserColorVariant(color, kColorVariant);
        service->UseDeviceTheme(false);
        break;
    }
  }

  void SetDefaultTheme(Profile* profile) {
    ThemeService* service = theme_service(profile);
    switch (GetParam()) {
      case ColorThemeType::kAutogeneratedTheme:
        service->UseDefaultTheme();
        break;
      case ColorThemeType::kUserColor:
        service->SetUserColorAndBrowserColorVariant(SK_ColorTRANSPARENT,
                                                    kColorVariant);
        service->UseDeviceTheme(false);
        break;
    }
  }

  ThemeService* theme_service(Profile* profile) {
    return ThemeServiceFactory::GetForProfile(profile);
  }

  ProfileThemeColors ComputeProfileThemeColorsForBrowser(
      Browser* target_browser = nullptr) {
    target_browser = target_browser ? target_browser : browser();
    return GetCurrentProfileThemeColors(
        *target_browser->window()->GetColorProvider(),
        *ThemeServiceFactory::GetForProfile(target_browser->profile()));
  }
};

// Tests that the profile theme colors are updated when an autogenerated theme
// is set up.
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonProfileColorBrowserTest,
                       PRE_AutogeneratedTheme) {
  Profile* profile = browser()->profile();
  ProfileAttributesEntry* entry = GetProfileAttributesEntry(profile);
  SetDefaultTheme(profile);
  EXPECT_EQ(entry->GetProfileThemeColors(),
            ComputeProfileThemeColorsForBrowser());

  SetColorTheme(profile, SK_ColorGREEN);
  ProfileThemeColors theme_colors = entry->GetProfileThemeColors();
  EXPECT_EQ(theme_colors, ComputeProfileThemeColorsForBrowser());

  // Check that a switch to another autogenerated theme updates the colors.
  SetColorTheme(profile, SK_ColorMAGENTA);
  ProfileThemeColors theme_colors2 = entry->GetProfileThemeColors();
  EXPECT_NE(theme_colors, theme_colors2);
  EXPECT_NE(theme_colors2, GetDefaultProfileThemeColors());
  EXPECT_EQ(theme_colors2, ComputeProfileThemeColorsForBrowser());

  // Reset the cached colors to test that they're recreated on the next startup.
  entry->SetProfileThemeColors(std::nullopt);
  EXPECT_EQ(entry->GetProfileThemeColors(), GetDefaultProfileThemeColors());
}

// Tests that the profile theme colors are updated to reflect the autogenerated
// colors on startup.
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonProfileColorBrowserTest,
                       AutogeneratedTheme) {
  EXPECT_EQ(
      GetProfileAttributesEntry(browser()->profile())->GetProfileThemeColors(),
      ComputeProfileThemeColorsForBrowser());
}

// Tests that switching to the default theme updates profile colors.
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonProfileColorBrowserTest,
                       DefaultTheme) {
  Profile* profile = browser()->profile();
  ProfileAttributesEntry* entry = GetProfileAttributesEntry(profile);

  SetColorTheme(profile, SK_ColorGREEN);
  ProfileThemeColors theme_colors = entry->GetProfileThemeColors();
  EXPECT_EQ(theme_colors, ComputeProfileThemeColorsForBrowser());

  SetDefaultTheme(profile);
  ProfileThemeColors theme_colors2 = entry->GetProfileThemeColors();
  EXPECT_NE(theme_colors, theme_colors2);
  EXPECT_EQ(theme_colors2, ComputeProfileThemeColorsForBrowser());
}

// Tests that a theme is updated after opening a browser.
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonProfileColorBrowserTest,
                       UpdateThemeOnBrowserUpdate) {
  Profile* profile = browser()->profile();
  // Keeps the browser process and the profile alive while a browser window is
  // closed.
  ScopedKeepAlive keep_alive(KeepAliveOrigin::BROWSER,
                             KeepAliveRestartOption::DISABLED);
  ScopedProfileKeepAlive profile_keep_alive(
      profile, ProfileKeepAliveOrigin::kBackgroundMode);
  SetDefaultTheme(profile);
  ProfileAttributesEntry* entry = GetProfileAttributesEntry(profile);
  ProfileThemeColors theme_colors = entry->GetProfileThemeColors();
  CloseBrowserSynchronously(browser());

  SetColorTheme(profile, SK_ColorGREEN);
  // Colors haven't been changed yet because the profile has no active browsers.
  EXPECT_EQ(theme_colors, entry->GetProfileThemeColors());

  auto* target_browser = CreateBrowser(profile);
  ProfileThemeColors theme_colors2 = entry->GetProfileThemeColors();
  EXPECT_EQ(theme_colors2, ComputeProfileThemeColorsForBrowser(target_browser));
}

// Tests profile colors are updated when the browser's color scheme has changed.
IN_PROC_BROWSER_TEST_P(AvatarToolbarButtonProfileColorBrowserTest,
                       ProfileColorsUpdateOnColorSchemeChange) {
  theme_service(browser()->profile())
      ->SetBrowserColorScheme(ThemeService::BrowserColorScheme::kDark);
  Profile* profile = browser()->profile();
  ProfileAttributesEntry* entry = GetProfileAttributesEntry(profile);

  SetDefaultTheme(profile);
  ProfileThemeColors theme_colors = entry->GetProfileThemeColors();
  EXPECT_EQ(theme_colors, ComputeProfileThemeColorsForBrowser());

  theme_service(browser()->profile())
      ->SetBrowserColorScheme(ThemeService::BrowserColorScheme::kLight);
  ProfileThemeColors theme_colors2 = entry->GetProfileThemeColors();
  EXPECT_NE(theme_colors, theme_colors2);
  EXPECT_EQ(theme_colors2, ComputeProfileThemeColorsForBrowser());
}

INSTANTIATE_TEST_SUITE_P(,
                         AvatarToolbarButtonProfileColorBrowserTest,
                         testing::Values(ColorThemeType::kAutogeneratedTheme,
                                         ColorThemeType::kUserColor),
                         [](const auto& info) {
                           switch (info.param) {
                             case ColorThemeType::kAutogeneratedTheme:
                               return "AutogeneratedTheme";
                             case ColorThemeType::kUserColor:
                               return "UserColor";
                           }
                         });

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
class AvatarToolbarButtonEnterpriseBadgingBrowserTest
    : public AvatarToolbarButtonWithInteractiveFeaturePromoBrowserTest {
 public:
  AvatarToolbarButtonEnterpriseBadgingBrowserTest() {
    scoped_feature_list_.InitWithFeatures(
        {features::kEnterpriseProfileBadgingForAvatar}, {});
  }
  void SetUpInProcessBrowserTestFixture() override {
    provider_.SetDefaultReturns(
        true /* is_initialization_complete_return */,
        true /* is_first_policy_load_complete_return */);
    policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
  }

  void SetUpOnMainThread() override {
    scoped_browser_management_ =
        std::make_unique<policy::ScopedManagementServiceOverrideForTesting>(
            policy::ManagementServiceFactory::GetForProfile(
                browser()->profile()),
            policy::EnterpriseManagementAuthority::CLOUD);
    AvatarToolbarButtonWithInteractiveFeaturePromoBrowserTest::
        SetUpOnMainThread();
  }

  void TearDownOnMainThread() override { scoped_browser_management_.reset(); }

 protected:
  testing::NiceMock<policy::MockConfigurationPolicyProvider> provider_;
  std::unique_ptr<policy::ScopedManagementServiceOverrideForTesting>
      scoped_browser_management_;
  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       WorkProfileTextBadging) {
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  // Ensure enterprise badging can be shown.
  std::u16string work_label = u"Work";

  {
    enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(),
                                                      true);
    EXPECT_EQ(avatar_button->GetText(), work_label);
    auto clear_closure = avatar_button->SetExplicitButtonState(
        u"Explicit text", /*accessibility_label=*/std::nullopt,
        /*explicit_action=*/std::nullopt);
    EXPECT_NE(avatar_button->GetText(), work_label);
    clear_closure.RunAndReset();
    EXPECT_EQ(avatar_button->GetText(), work_label);
    // The profile name should be the default profile name.
    std::u16string local_name =
        GetProfileAttributesEntry(browser()->profile())->GetLocalProfileName();
    EXPECT_TRUE(g_browser_process->profile_manager()
                    ->GetProfileAttributesStorage()
                    .IsDefaultProfileName(local_name, true));
  }

  {
    enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(),
                                                      false);
    EXPECT_NE(avatar_button->GetText(), work_label);
    base::ScopedClosureRunner clear_closure =
        avatar_button->SetExplicitButtonState(
            u"Explicit text", /*accessibility_label=*/std::nullopt,
            /*explicit_action=*/std::nullopt);
    EXPECT_NE(avatar_button->GetText(), work_label);
    clear_closure.RunAndReset();
    EXPECT_NE(avatar_button->GetText(), work_label);
    EXPECT_EQ(GetProfileAttributesEntry(browser()->profile())
                  ->GetEnterpriseProfileLabel(),
              std::u16string());
    // The profile name should be the default profile name.
    std::u16string local_name =
        GetProfileAttributesEntry(browser()->profile())->GetLocalProfileName();
    EXPECT_TRUE(g_browser_process->profile_manager()
                    ->GetProfileAttributesStorage()
                    .IsDefaultProfileName(local_name, true));
  }
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       DefaultBadgeUpdatedWithManagementChanges) {
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  {
    policy::ScopedManagementServiceOverrideForTesting profile_management{
        policy::ManagementServiceFactory::GetForProfile(browser()->profile()),
        policy::EnterpriseManagementAuthority::CLOUD};
    policy::ManagementServiceFactory::GetForProfile(browser()->profile())
        ->TriggerPolicyStatusChangedForTesting();
    EXPECT_EQ(avatar_button->GetText(), u"Work");
  }
  {
    policy::ScopedManagementServiceOverrideForTesting profile_management{
        policy::ManagementServiceFactory::GetForProfile(browser()->profile()),
        policy::EnterpriseManagementAuthority::NONE};
    policy::ManagementServiceFactory::GetForProfile(browser()->profile())
        ->TriggerPolicyStatusChangedForTesting();
    EXPECT_EQ(avatar_button->GetText(), std::u16string());
  }
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       DefaultBadgeDisabledbyPolicy) {
  std::u16string work_label = u"Work";
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  browser()->profile()->GetPrefs()->SetInteger(
      prefs::kEnterpriseProfileBadgeToolbarSettings, 1);

  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);

  // There should be no text because the policy fully disables badging.
  EXPECT_EQ(avatar_button->GetText(), std::u16string());
  EXPECT_EQ(GetProfileAttributesEntry(browser()->profile())
                ->GetEnterpriseProfileLabel(),
            std::u16string());
  // The profile name should be the default profile name.
  std::u16string local_name =
      GetProfileAttributesEntry(browser()->profile())->GetLocalProfileName();
  EXPECT_TRUE(g_browser_process->profile_manager()
                  ->GetProfileAttributesStorage()
                  .IsDefaultProfileName(local_name, true));
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       CustomBadgeDisabledbyPolicy) {
  browser()->profile()->GetPrefs()->SetString(
      prefs::kEnterpriseCustomLabelForProfile, "Custom Label");
  browser()->profile()->GetPrefs()->SetInteger(
      prefs::kEnterpriseProfileBadgeToolbarSettings, 1);

  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());

  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);

  // There should be no text because the policy fully disables badging.
  EXPECT_EQ(avatar_button->GetText(), std::u16string());
  EXPECT_EQ(GetProfileAttributesEntry(browser()->profile())
                ->GetEnterpriseProfileLabel(),
            std::u16string());
  // The profile name should be the default profile name.
  std::u16string local_name =
      GetProfileAttributesEntry(browser()->profile())->GetLocalProfileName();
  EXPECT_TRUE(g_browser_process->profile_manager()
                  ->GetProfileAttributesStorage()
                  .IsDefaultProfileName(local_name, true));
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       CustomBadgeLengthLimited) {
  browser()->profile()->GetPrefs()->SetString(
      prefs::kEnterpriseCustomLabelForProfile,
      "Custom Label Can Be Max 16 Characters");

  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());

  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);
  // The text should be tuncated to 16 characters followed by "...".
  EXPECT_EQ(avatar_button->GetText(), u"Custom Label Can…");
  // The profile label will be handled by the individual UI components.
  EXPECT_EQ(GetProfileAttributesEntry(browser()->profile())
                ->GetEnterpriseProfileLabel(),
            u"Custom Label Can Be Max 16 Characters");
  EXPECT_EQ(
      GetProfileAttributesEntry(browser()->profile())->GetLocalProfileName(),
      u"Custom Label Can Be Max 16 Characters");
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       WorkNewBrowserShowsBadgeWithCustomLabel) {
  browser()->profile()->GetPrefs()->SetString(
      prefs::kEnterpriseCustomLabelForProfile, "Custom Label");
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);

  Browser* second_browser = CreateBrowser(browser()->profile());
  AvatarToolbarButton* second_browser_avatar_button =
      GetAvatarToolbarButton(second_browser);
  EXPECT_EQ(second_browser_avatar_button->GetText(), u"Custom Label");

  browser()->profile()->GetPrefs()->SetString(
      prefs::kEnterpriseCustomLabelForProfile, "Updated Label");
  EXPECT_EQ(second_browser_avatar_button->GetText(), u"Updated Label");
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       WorkNewBrowserShowsBadge) {
  std::u16string work_label = u"Work";
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);

  Browser* second_browser = CreateBrowser(browser()->profile());
  AvatarToolbarButton* second_browser_avatar_button =
      GetAvatarToolbarButton(second_browser);
  EXPECT_EQ(second_browser_avatar_button->GetText(), work_label);
}

// Sync Pause/Error has priority over WorkBadge.
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       WorkBadgeAndSyncPaused) {
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  ASSERT_TRUE(avatar_button->GetText().empty());

  std::u16string work_label = u"Work";
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);
  EXPECT_EQ(avatar_button->GetText(), work_label);

  EnableSyncWithImageAndClearGreeting(avatar_button, u"work@managed.com");
  SimulateSyncPaused();
  // Sync Paused has priority over the Work badge.
  ExpectSyncPaused(avatar_button);

  ClearSyncPaused();
  // Non transient mode should permanently show the work badge by default.
  // TODO(b/324018028): This test result might change with the ongoing changes.
  // At the end, the exact behavior could be set again. To review.
  EXPECT_EQ(avatar_button->GetText(), work_label);
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       DecliningManagementShouldRemoveWorkBadge) {
  AvatarToolbarButton* avatar_button = GetAvatarToolbarButton(browser());
  ASSERT_TRUE(avatar_button->GetText().empty());

  std::u16string work_label = u"Work";
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);
  EXPECT_EQ(avatar_button->GetText(), work_label);

  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(),
                                                    false);
  EXPECT_EQ(avatar_button->GetText(), std::u16string());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonEnterpriseBadgingBrowserTest,
                       GreetingNotShownWhenManagementAccepted) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());

  AccountInfo account_info = Signin(u"work@managed.com", u"TestName");
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);

  // The greeting would only show when the image is loaded. Set the image to
  // make sure we do not have a false positive later.
  AddSignedInImage(account_info.account_id);

  // We do not expect a greeting to be shown if user accepted management.
  EXPECT_EQ(avatar->GetText(), u"Work");
}

class AvatarToolbarButtonEnterpriseBadgingWithSyncPromoParamsBrowserTest
    : public base::test::WithFeatureOverride,
      public AvatarToolbarButtonEnterpriseBadgingBrowserTest {
 protected:
  AvatarToolbarButtonEnterpriseBadgingWithSyncPromoParamsBrowserTest()
      : WithFeatureOverride(switches::kEnableHistorySyncOptinExpansionPill) {}
};

// TODO(crbug.com/331746545): Check flaky test issue on windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_GreetingShownWhenManagementNotAccepted \
  DISABLED_GreetingShownWhenManagementNotAccepted
#else
#define MAYBE_GreetingShownWhenManagementNotAccepted \
  GreetingShownWhenManagementNotAccepted
#endif
// test makes sure the greeting is not shown when the management badge is shown
// in the profile avatar pill.
IN_PROC_BROWSER_TEST_P(
    AvatarToolbarButtonEnterpriseBadgingWithSyncPromoParamsBrowserTest,
    MAYBE_GreetingShownWhenManagementNotAccepted) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());

  std::u16string name(u"TestName");
  AccountInfo account_info = Signin(u"work@managed.com", name);
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(),
                                                    false);

  // The button is in a waiting for image state, the name is not yet displayed.
  // At this point the user has not accepted management yet.
  EXPECT_EQ(avatar->GetText(), std::u16string());

  // The greeting will only show when the image is loaded.
  AddSignedInImage(account_info.account_id);

  // Since the user has not accepted management, the greeting will still be
  // shown.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING, name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  if (IsParamFeatureEnabled()) {
    // The greeting is followed by the history sync opt-in.
    EXPECT_EQ(avatar->GetText(), l10n_util::GetStringUTF16(
                                     IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES));
    avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  }
  // Once the name (or sync promo) is not shown anymore, we expect no text.
  EXPECT_EQ(avatar->GetText(), std::u16string());
}

// TODO(crbug.com/331746545): Check flaky test issue on windows.
// TODO(crbug.com/331746545): Check flaky test issue on windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_PRE_SignedInWithNewSessionKeepWorkBadge DISABLED_PRE_SignedInWithNewSessionKeepWorkBadge
#define MAYBE_SignedInWithNewSessionKeepWorkBadge DISABLED_SignedInWithNewSessionKeepWorkBadge
#else
#define MAYBE_PRE_SignedInWithNewSessionKeepWorkBadge PRE_SignedInWithNewSessionKeepWorkBadge
#define MAYBE_SignedInWithNewSessionKeepWorkBadge SignedInWithNewSessionKeepWorkBadge
#endif
// Tests the flow for a managed sign-in.
IN_PROC_BROWSER_TEST_P(
    AvatarToolbarButtonEnterpriseBadgingWithSyncPromoParamsBrowserTest,
    MAYBE_PRE_SignedInWithNewSessionKeepWorkBadge) {
  // Sign in.
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  std::u16string name(u"TestName");
  AccountInfo account_info = SigninWithImage(u"work@managed.com", name);

  // Since the user has not accepted management yet, the greeting will be
  // shown.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING, name));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  if (IsParamFeatureEnabled()) {
    // The greeting is followed by the history sync opt-in.
    EXPECT_EQ(avatar->GetText(), l10n_util::GetStringUTF16(
                                     IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES));
    avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  }

  // Once the name (or sync promo) is not shown anymore, we expect no text since
  // management is not accepted.
  EXPECT_EQ(avatar->GetText(), std::u16string());

  // Management is usually accepted by the time the greeting is finished. The
  // work badgge should be shown once this happens.
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);
  browser()->profile()->GetPrefs()->SetString(
      prefs::kEnterpriseCustomLabelForProfile, "Custom Label");

  EXPECT_EQ(avatar->GetText(), u"Custom Label");
}

// Test that the work badge remains upon restart for a user that is managed.
// Note that we need to unset and reset UserAcceptedAccountManagement due to the
// management service override.
IN_PROC_BROWSER_TEST_P(
    AvatarToolbarButtonEnterpriseBadgingWithSyncPromoParamsBrowserTest,
    MAYBE_SignedInWithNewSessionKeepWorkBadge) {
  // Disable the preferences about syncing the tabs and history to make the
  // avatar promo eligible.
  SetHistoryAndTabsSyncingPreference(/*enable_sync=*/false);

  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // The greetings are shown due to the management service override (unaware of
  // the management acceptance after restart).
  EXPECT_EQ(avatar->GetText(), l10n_util::GetStringFUTF16(
                                   IDS_AVATAR_BUTTON_GREETING, u"TestName"));
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  if (IsParamFeatureEnabled()) {
    // The greeting is followed by the history sync opt-in.
    EXPECT_EQ(avatar->GetText(), l10n_util::GetStringUTF16(
                                     IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES));
    avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  }

  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(),
                                                    false);
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);

  EXPECT_EQ(avatar->GetText(), u"Custom Label");
  EXPECT_EQ(GetProfileAttributesEntry(browser()->profile())
                ->GetEnterpriseProfileLabel(),
            u"Custom Label");
  EXPECT_EQ(
      GetProfileAttributesEntry(browser()->profile())->GetLocalProfileName(),
      u"Custom Label");
  // Previously added image on signin should still be shown in the new session.
  EXPECT_TRUE(IsSignedInImageUsed());
}

// TODO(crbug.com/331746545): Check the flaky test issue on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_SyncPromoShownOnInactivityWhenManagementAccepted \
  DISABLED_SyncPromoShownOnInactivityWhenManagementAccepted
#else
#define MAYBE_SyncPromoShownOnInactivityWhenManagementAccepted \
  SyncPromoShownOnInactivityWhenManagementAccepted
#endif
IN_PROC_BROWSER_TEST_P(
    AvatarToolbarButtonEnterpriseBadgingWithSyncPromoParamsBrowserTest,
    MAYBE_SyncPromoShownOnInactivityWhenManagementAccepted) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // Normal state.
  ASSERT_TRUE(avatar->GetText().empty());

  AccountInfo account_info = Signin(u"work@managed.com", u"TestName");
  enterprise_util::SetUserAcceptedAccountManagement(browser()->profile(), true);

  // The greeting would only show when the image is loaded. Set the image to
  // make sure we do not have a false positive later.
  AddSignedInImage(account_info.account_id);
  // We do not expect a greeting to be shown if user accepted management.
  EXPECT_EQ(avatar->GetText(), u"Work");
  // Simulate long enough inactivity to trigger the sync promo.
  RunTestSequence(
      SetLastActive(user_education::features::GetIdleTimeBetweenSessions()));
  if (IsParamFeatureEnabled()) {
    EXPECT_EQ(avatar->GetText(), l10n_util::GetStringUTF16(
                                     IDS_AVATAR_BUTTON_BROWSE_ACROSS_DEVICES));
    avatar->TriggerTimeoutForTesting(AvatarDelayType::kHistorySyncOptin);
  }
  EXPECT_EQ(avatar->GetText(), u"Work");
}

INSTANTIATE_FEATURE_OVERRIDE_TEST_SUITE(
    AvatarToolbarButtonEnterpriseBadgingWithSyncPromoParamsBrowserTest);

// TODO(b/331746545): Check flaky test issue on windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_SigninPausedFromExternalErrorThenReauth \
  DISABLED_SigninPausedFromExternalErrorThenReauth
#else
#define MAYBE_SigninPausedFromExternalErrorThenReauth \
  SigninPausedFromExternalErrorThenReauth
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       MAYBE_SigninPausedFromExternalErrorThenReauth) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  SigninWithImageAndClearGreetingAndSyncPromo(avatar, u"test@gmail.com");
  ASSERT_EQ(avatar->GetText(), std::u16string());

  // Browser opened before the error.
  Browser* opened_browser = CreateBrowser(browser()->profile());
  AvatarToolbarButton* opened_browser_avatar_button =
      GetAvatarToolbarButton(opened_browser);
  ASSERT_EQ(opened_browser_avatar_button->GetText(), std::u16string());

  SimulateSigninError(/*web_sign_out=*/false);
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));
  EXPECT_EQ(opened_browser_avatar_button->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));

  // New browser opened after the error -- error should be shown directly.
  Browser* new_browser = CreateBrowser(browser()->profile());
  AvatarToolbarButton* new_browser_avatar_button =
      GetAvatarToolbarButton(new_browser);
  EXPECT_EQ(new_browser_avatar_button->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));

  ClearSigninError();
  EXPECT_EQ(avatar->GetText(), std::u16string());
  EXPECT_EQ(opened_browser_avatar_button->GetText(), std::u16string());
  EXPECT_EQ(new_browser_avatar_button->GetText(), std::u16string());
}

// TODO(b/331746545): Check flaky test issue on windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_SigninPausedFromWebSignout DISABLED_SigninPausedFromWebSignout
#else
#define MAYBE_SigninPausedFromWebSignout SigninPausedFromWebSignout
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       MAYBE_SigninPausedFromWebSignout) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());

  SigninWithImageAndClearGreetingAndSyncPromo(avatar, u"test@gmail.com");
  ASSERT_EQ(avatar->GetText(), std::u16string());

  // Browser opened before the error.
  Browser* opened_browser = CreateBrowser(browser()->profile());
  AvatarToolbarButton* opened_browser_avatar_button =
      GetAvatarToolbarButton(opened_browser);
  ASSERT_EQ(opened_browser_avatar_button->GetText(), std::u16string());

  SimulateSigninError(/*web_sign_out=*/true);
  // Text does not appear directly after a web sign out, a timer is started.
  EXPECT_EQ(avatar->GetText(), std::u16string());
  EXPECT_EQ(opened_browser_avatar_button->GetText(), std::u16string());

  // New browser opened after the error and before timer ends -- error is not
  // shown directly.
  Browser* new_browser = CreateBrowser(browser()->profile());
  AvatarToolbarButton* new_browser_avatar_button =
      GetAvatarToolbarButton(new_browser);
  EXPECT_EQ(new_browser_avatar_button->GetText(), std::u16string());

  // Simulate all the timer ends.
  avatar->TriggerTimeoutForTesting(AvatarDelayType::kSigninPendingText);
  opened_browser_avatar_button->TriggerTimeoutForTesting(
      AvatarDelayType::kSigninPendingText);
  new_browser_avatar_button->TriggerTimeoutForTesting(
      AvatarDelayType::kSigninPendingText);

  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));
  EXPECT_EQ(opened_browser_avatar_button->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));
  EXPECT_EQ(new_browser_avatar_button->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));

  ClearSigninError();
  EXPECT_EQ(avatar->GetText(), std::u16string());
  EXPECT_EQ(opened_browser_avatar_button->GetText(), std::u16string());
  EXPECT_EQ(new_browser_avatar_button->GetText(), std::u16string());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       PRE_SigninPausedFromWebSignoutThenRestartChrome) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  SigninWithImageAndClearGreetingAndSyncPromo(avatar, u"test@gmail.com",
                                              std::u16string(kGivenName));

  SimulateSigninError(/*web_sign_out=*/true);
  ASSERT_EQ(avatar->GetText(), std::u16string());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       SigninPausedFromWebSignoutThenRestartChrome) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  // The greetings are shown after the restart.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringFUTF16(IDS_AVATAR_BUTTON_GREETING,
                                       std::u16string(kGivenName)));

  avatar->TriggerTimeoutForTesting(AvatarDelayType::kNameGreeting);
  // The error text is expected to be shown even if the error delay has not
  // reached yet.
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));
}

// Regression test for https://crbug.com/348587566
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       SigninPausedDelayEndedNoBrowser) {
  ASSERT_EQ(1u, chrome::GetTotalBrowserCount());
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());

  SigninWithImageAndClearGreetingAndSyncPromo(avatar, u"test@gmail.com",
                                              u"TestName");
  SimulateSigninError(/*web_sign_out=*/true);
  ASSERT_TRUE(avatar->GetText().empty());
  Profile* profile = browser()->profile();

  // Close the browser before the delay ends, but keep the profile and Chrome
  // alive by opening an incognito browser.
  CreateIncognitoBrowser(profile);
  CloseBrowserSynchronously(browser());

  // This simulates the delay expiry for the next browser. Instead of advancing
  // time, we set the expected delay to 0, making the elapsed time greater than
  // the delay for sure - simulating the delay expiry.
  SetZeroAvatarDelayForSigninPendingText();

  // Open a new browser, this should not crash.
  Browser* new_browser = CreateBrowser(profile);
  EXPECT_EQ(GetAvatarToolbarButton(new_browser)->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));
}

// TODO(b/331746545): Check flaky test issue on windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_SigninPausedThenSignout DISABLED_SigninPausedThenSignout
#else
#define MAYBE_SigninPausedThenSignout SigninPausedThenSignout
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       MAYBE_SigninPausedThenSignout) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  SigninWithImageAndClearGreetingAndSyncPromo(avatar, u"test@gmail.com");
  ASSERT_EQ(avatar->GetText(), std::u16string());

  SimulateSigninError(/*web_sign_out=*/false);

  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));

  Signout();

  EXPECT_EQ(avatar->GetText(), std::u16string());
}

IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest, AccessibilityLabels) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());

  const std::u16string profile_name(u"new_profile_name");
  profiles::UpdateProfileName(browser()->profile(), profile_name);

  const views::ViewAccessibility& accessibility =
      avatar->GetViewAccessibility();

  EXPECT_EQ(accessibility.GetCachedName(), profile_name);
  EXPECT_EQ(accessibility.GetCachedDescription(), std::u16string());

  const std::u16string account_name(u"Test Name");
  SigninWithImageAndClearGreetingAndSyncPromo(avatar, u"test@gmail.com",
                                              account_name);

  const std::u16string expected_profile_name_with_account =
      account_name + u" (" + profile_name + u")";
  EXPECT_EQ(accessibility.GetCachedName(), expected_profile_name_with_account);
  EXPECT_EQ(accessibility.GetCachedDescription(), std::u16string());

  // Explicit text with accessibility text
  const std::u16string explicit_text(u"explicit_text");
  const std::u16string explicit_accessibility_text(u"explicit_text_acc");
  base::ScopedClosureRunner clear_explicit_text_callback =
      avatar->SetExplicitButtonState(explicit_text, explicit_accessibility_text,
                                     /*explicit_action=*/std::nullopt);

  EXPECT_EQ(accessibility.GetCachedName(), explicit_text);
  EXPECT_EQ(accessibility.GetCachedDescription(), explicit_accessibility_text);

  clear_explicit_text_callback.RunAndReset();

  EXPECT_EQ(accessibility.GetCachedName(), expected_profile_name_with_account);
  EXPECT_EQ(accessibility.GetCachedDescription(), std::u16string());

  // Explicit text without accessibility text
  base::ScopedClosureRunner clear_explicit_text_without_accessibility_callback =
      avatar->SetExplicitButtonState(explicit_text,
                                     /*accessibility_label=*/std::nullopt,
                                     /*explicit_action=*/std::nullopt);

  EXPECT_EQ(accessibility.GetCachedName(), explicit_text);
  EXPECT_EQ(accessibility.GetCachedDescription(),
            expected_profile_name_with_account);

  clear_explicit_text_without_accessibility_callback.RunAndReset();

  EXPECT_EQ(accessibility.GetCachedName(), expected_profile_name_with_account);
  EXPECT_EQ(accessibility.GetCachedDescription(), std::u16string());

  // This will trigger the immediate button content text change. Accessibility
  // text should adapt as well.
  SimulateSigninError(/*web_sign_out=*/false);

  EXPECT_EQ(accessibility.GetCachedName(),
            l10n_util::GetStringUTF16(IDS_AVATAR_BUTTON_SIGNIN_PAUSED));
  EXPECT_EQ(accessibility.GetCachedDescription(),
            l10n_util::GetStringUTF16(
                IDS_AVATAR_BUTTON_SIGNIN_PENDING_ACCESSIBILITY_LABEL));

  ClearSigninError();

  EXPECT_EQ(accessibility.GetCachedName(), expected_profile_name_with_account);
  EXPECT_EQ(accessibility.GetCachedDescription(), std::u16string());

  // This will not trigger the immediate button content text change.
  // Accessibility text should adapt as well.
  SimulateSigninError(/*web_sign_out=*/true);

  EXPECT_EQ(accessibility.GetCachedName(),
            l10n_util::GetStringUTF16(
                IDS_AVATAR_BUTTON_SIGNIN_PENDING_ACCESSIBILITY_LABEL));
  EXPECT_EQ(accessibility.GetCachedDescription(),
            expected_profile_name_with_account);

  ClearSigninError();

  EXPECT_EQ(accessibility.GetCachedName(), expected_profile_name_with_account);
  EXPECT_EQ(accessibility.GetCachedDescription(), std::u16string());

  Signout();

  EXPECT_EQ(accessibility.GetCachedName(), profile_name);
  EXPECT_EQ(accessibility.GetCachedDescription(), std::u16string());
}

// TODO(crbug.com/359995696): Flaky on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_PassphraseErrorSignedIn DISABLED_PassphraseErrorSignedIn
#else
#define MAYBE_PassphraseErrorSignedIn PassphraseErrorSignedIn
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       MAYBE_PassphraseErrorSignedIn) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  SigninWithImageAndClearGreetingAndSyncPromo(avatar, u"test@gmail.com");
  ASSERT_EQ(avatar->GetText(), std::u16string());
  SimulatePassphraseError();
  EXPECT_EQ(avatar->GetText(), l10n_util::GetStringUTF16(
                                   IDS_SYNC_ERROR_USER_MENU_PASSPHRASE_BUTTON));
}

// TODO(crbug.com/359995696): Flaky on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_PassphraseErrorSyncing DISABLED_PassphraseErrorSyncing
#else
#define MAYBE_PassphraseErrorSyncing PassphraseErrorSyncing
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       MAYBE_PassphraseErrorSyncing) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  EnableSyncWithImageAndClearGreeting(avatar, u"test@gmail.com");
  ASSERT_EQ(avatar->GetText(), std::u16string());
  SimulatePassphraseError();
  EXPECT_EQ(avatar->GetText(), l10n_util::GetStringUTF16(
                                   IDS_SYNC_ERROR_USER_MENU_PASSPHRASE_BUTTON));
}

// TODO(crbug.com/359995696): Flaky on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_UpgradeClientError DISABLED_UpgradeClientError
#else
#define MAYBE_UpgradeClientError UpgradeClientError
#endif
IN_PROC_BROWSER_TEST_F(AvatarToolbarButtonBrowserTest,
                       MAYBE_UpgradeClientError) {
  AvatarToolbarButton* avatar = GetAvatarToolbarButton(browser());
  EnableSyncWithImageAndClearGreeting(avatar, u"test@gmail.com");
  ASSERT_EQ(avatar->GetText(), std::u16string());
  SimulateUpgradeClientError();
  EXPECT_EQ(avatar->GetText(),
            l10n_util::GetStringUTF16(IDS_SYNC_ERROR_USER_MENU_UPGRADE_BUTTON));
}

#endif  // BUILDFLAG(ENABLE_DICE_SUPPORT)