File size: 47,139 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import config from '@automattic/calypso-config';
import page from '@automattic/calypso-router';
import { Gridicon, FormLabel } from '@automattic/components';
import { addLocaleToPath, localizeUrl, getLanguage } from '@automattic/i18n-utils';
import clsx from 'clsx';
import emailValidator from 'email-validator';
import { localize, fixMe } from 'i18n-calypso';
import PropTypes from 'prop-types';
import { Component } from 'react';
import { connect } from 'react-redux';
import AppPromo from 'calypso/blocks/app-promo';
import { shouldUseMagicCode } from 'calypso/blocks/login/utils/should-use-magic-code';
import FormButton from 'calypso/components/forms/form-button';
import FormTextInput from 'calypso/components/forms/form-text-input';
import GlobalNotices from 'calypso/components/global-notices';
import GravatarLoginLogo from 'calypso/components/gravatar-login-logo';
import LocaleSuggestions from 'calypso/components/locale-suggestions';
import Main from 'calypso/components/main';
import Notice from 'calypso/components/notice';
import isAkismetRedirect from 'calypso/lib/akismet/is-akismet-redirect';
import getGravatarOAuth2Flow from 'calypso/lib/get-gravatar-oauth2-flow';
import {
	isGravatarFlowOAuth2Client,
	isGravatarOAuth2Client,
	isWPJobManagerOAuth2Client,
	isGravPoweredOAuth2Client,
	isStudioAppOAuth2Client,
} from 'calypso/lib/oauth2-clients';
import { login } from 'calypso/lib/paths';
import getToSAcceptancePayload from 'calypso/lib/tos-acceptance-tracking';
import wpcom from 'calypso/lib/wp';
import OneLoginLayout from 'calypso/login/wp-login/components/one-login-layout';
import {
	recordTracksEventWithClientId as recordTracksEvent,
	recordPageViewWithClientId as recordPageView,
	enhanceWithSiteType,
} from 'calypso/state/analytics/actions';
import { sendEmailLogin } from 'calypso/state/auth/actions';
import { rebootAfterLogin } from 'calypso/state/login/actions';
import {
	hideMagicLoginRequestForm,
	fetchMagicLoginAuthenticate,
} from 'calypso/state/login/magic-login/actions';
import { CHECK_YOUR_EMAIL_PAGE } from 'calypso/state/login/magic-login/constants';
import {
	getLastCheckedUsernameOrEmail,
	getTwoFactorNotificationSent,
	isTwoFactorEnabled,
	getRedirectToSanitized,
	getRedirectToOriginal,
} from 'calypso/state/login/selectors';
import {
	infoNotice,
	errorNotice,
	successNotice,
	removeNotice,
} from 'calypso/state/notices/actions';
import { getCurrentOAuth2Client } from 'calypso/state/oauth2-clients/ui/selectors';
import getCurrentLocaleSlug from 'calypso/state/selectors/get-current-locale-slug';
import getCurrentQueryArguments from 'calypso/state/selectors/get-current-query-arguments';
import { getCurrentRoute } from 'calypso/state/selectors/get-current-route';
import getInitialQueryArguments from 'calypso/state/selectors/get-initial-query-arguments';
import getIsWCCOM from 'calypso/state/selectors/get-is-wccom';
import getLocaleSuggestions from 'calypso/state/selectors/get-locale-suggestions';
import getMagicLoginCurrentView from 'calypso/state/selectors/get-magic-login-current-view';
import getMagicLoginPublicToken from 'calypso/state/selectors/get-magic-login-public-token';
import getMagicLoginRequestAuthError from 'calypso/state/selectors/get-magic-login-request-auth-error';
import getMagicLoginRequestEmailError from 'calypso/state/selectors/get-magic-login-request-email-error';
import getMagicLoginRequestedAuthSuccessfully from 'calypso/state/selectors/get-magic-login-requested-auth-successfully';
import isFetchingMagicLoginAuth from 'calypso/state/selectors/is-fetching-magic-login-auth';
import isFetchingMagicLoginEmail from 'calypso/state/selectors/is-fetching-magic-login-email';
import isMagicLoginEmailRequested from 'calypso/state/selectors/is-magic-login-email-requested';
import isWooJPCFlow from 'calypso/state/selectors/is-woo-jpc-flow';
import { withEnhancers } from 'calypso/state/utils';
import MainContentWooCoreProfiler from './main-content-woo-core-profiler';
import RequestLoginCode from './request-login-code';
import RequestLoginEmailForm from './request-login-email-form';
import './style.scss';

const RESEND_EMAIL_COUNTDOWN_TIME = 90; // In seconds
const GRAVATAR_FROM_3RD_PARTY = '3rd-party';
const GRAVATAR_FROM_QUICK_EDITOR = 'quick-editor';

class MagicLogin extends Component {
	static propTypes = {
		path: PropTypes.string.isRequired,

		// mapped to dispatch
		hideMagicLoginRequestForm: PropTypes.func.isRequired,
		recordPageView: PropTypes.func.isRequired,
		recordTracksEvent: PropTypes.func.isRequired,
		sendEmailLogin: PropTypes.func.isRequired,
		fetchMagicLoginAuthenticate: PropTypes.func.isRequired,
		infoNotice: PropTypes.func.isRequired,
		errorNotice: PropTypes.func.isRequired,
		successNotice: PropTypes.func.isRequired,
		removeNotice: PropTypes.func.isRequired,
		rebootAfterLogin: PropTypes.func.isRequired,

		// mapped to state
		locale: PropTypes.string.isRequired,
		query: PropTypes.object,
		showCheckYourEmail: PropTypes.bool.isRequired,
		isSendingEmail: PropTypes.bool.isRequired,
		emailRequested: PropTypes.bool.isRequired,
		localeSuggestions: PropTypes.array,
		isValidatingCode: PropTypes.bool,
		isCodeValidated: PropTypes.bool,
		codeValidationError: PropTypes.object,
		twoFactorEnabled: PropTypes.bool,
		twoFactorNotificationSent: PropTypes.string,
		redirectToSanitized: PropTypes.string,

		// From `localize`
		translate: PropTypes.func.isRequired,
		isWooJPC: PropTypes.bool,
	};

	state = {
		usernameOrEmail: this.props.userEmail || '',
		resendEmailCountdown: RESEND_EMAIL_COUNTDOWN_TIME,
		verificationCodeInputValue: '',
		isRequestingEmail: false,
		requestEmailErrorMessage: null,
		isSecondaryEmail: false,
		isNewAccount: false,
		publicToken: null,
		showSecondaryEmailOptions: false,
		showEmailCodeVerification: false,
		maskedEmailAddress: '',
		hashedEmail: null,
	};

	componentDidMount() {
		const { oauth2Client, query } = this.props;

		this.props.recordPageView( '/log-in/link', 'Login > Link' );

		if ( isGravPoweredOAuth2Client( oauth2Client ) ) {
			const isGravatarFlow = isGravatarFlowOAuth2Client( oauth2Client );

			this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_form', {
				client_id: oauth2Client.id,
				client_name: oauth2Client.title,
				from: query?.gravatar_from,
				is_gravatar_flow: isGravatarFlow,
				is_gravatar_flow_with_email: !! ( isGravatarFlow && query?.email_address ),
				is_initial_view: true,
			} );
		}
	}

	componentDidUpdate( prevProps, prevState ) {
		const {
			oauth2Client,
			emailRequested,
			emailRequestError,
			localeSuggestions,
			path,
			showCheckYourEmail,
			isCodeValidated,
			twoFactorEnabled,
			twoFactorNotificationSent,
			redirectToSanitized,
			query,
		} = this.props;
		const { showSecondaryEmailOptions, showEmailCodeVerification } = this.state;

		/**
		 * If the user is not allowed to use magic links and we have auto trigger enabled,
		 * we simply show the password login form.
		 *
		 * If we don't check for auto trigger here, the normal wp.com login flow will confuse the users
		 * when they land here without the auto trigger, i.e. when they click on "Email me a login link"
		 * at wp.com/log-in
		 */
		if ( 'login_link_not_allowed' === emailRequestError?.code && query?.auto_trigger ) {
			this.onClickEnterPasswordInstead();
		}

		if ( isGravPoweredOAuth2Client( oauth2Client ) ) {
			if ( prevProps.isSendingEmail && emailRequested ) {
				this.startResendEmailCountdown();
			}

			if ( ! prevProps.localeSuggestions && localeSuggestions ) {
				const userLocale = localeSuggestions.find(
					( { locale } ) => locale === navigator.language.toLowerCase()
				);

				if ( userLocale ) {
					page( addLocaleToPath( path, userLocale.locale ) );
				}
			}

			const eventOptions = { client_id: oauth2Client.id, client_name: oauth2Client.title };

			if (
				( prevProps.showCheckYourEmail && ! showCheckYourEmail ) ||
				( prevState.showEmailCodeVerification && ! showEmailCodeVerification ) ||
				( prevState.showSecondaryEmailOptions && ! showSecondaryEmailOptions )
			) {
				const isGravatarFlow = isGravatarFlowOAuth2Client( oauth2Client );

				this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_form', {
					...eventOptions,
					from: query?.gravatar_from,
					is_gravatar_flow: isGravatarFlow,
					is_gravatar_flow_with_email: !! ( isGravatarFlow && query?.email_address ),
					is_initial_view: false,
				} );
			}

			if ( ! prevState.showSecondaryEmailOptions && showSecondaryEmailOptions ) {
				this.props.recordTracksEvent(
					'calypso_gravatar_powered_magic_login_secondary_email_options',
					eventOptions
				);

				this.props.recordTracksEvent(
					'calypso_gravatar_powered_magic_login_click_main_account',
					eventOptions
				);
			}

			if ( ! prevState.showEmailCodeVerification && showEmailCodeVerification ) {
				this.props.recordTracksEvent(
					'calypso_gravatar_powered_magic_login_email_code_verification',
					eventOptions
				);
			}

			if ( ! prevProps.showCheckYourEmail && showCheckYourEmail ) {
				this.props.recordTracksEvent(
					'calypso_gravatar_powered_magic_login_email_link_verification',
					eventOptions
				);
			}

			// Proceed to the next step if the magic code is validated.
			if ( ! prevProps.isCodeValidated && isCodeValidated ) {
				if ( ! twoFactorEnabled ) {
					this.props.rebootAfterLogin( { magic_login: 1 } );
				} else {
					page(
						login( {
							// If no notification is sent, the user is using the authenticator for 2FA by default.
							twoFactorAuthType: twoFactorNotificationSent.replace( 'none', 'authenticator' ),
							redirectTo: redirectToSanitized,
							oauth2ClientId: oauth2Client.id,
							locale: this.props.locale,
						} )
					);
				}
			}
		}
	}

	onClickEnterPasswordInstead = ( event ) => {
		event?.preventDefault();

		this.props.recordTracksEvent( 'calypso_login_email_link_page_click_back' );

		const loginParameters = {
			isJetpack: this.props.isJetpackLogin,
			locale: this.props.locale,
			emailAddress: this.props.userEmail,
			signupUrl: this.props.query?.signup_url,
			usernameOnly: true,
			twoFactorAuthType: this.props.twoFactorNotificationSent?.replace( 'none', 'authenticator' ),
			redirectTo: this.props.redirectToOriginal,
			oauth2ClientId: this.props.oauth2Client?.id,
			from: this.props.query?.from,
		};

		page( login( loginParameters ) );
	};

	renderLinks() {
		const {
			isJetpackLogin,
			locale,
			showCheckYourEmail,
			translate,
			query,
			twoFactorNotificationSent,
			redirectToSanitized,
			oauth2Client,
		} = this.props;

		const isA4A = query?.redirect_to?.includes( 'agencies.automattic.com/client' ) ?? false;

		if ( showCheckYourEmail ) {
			if ( isA4A ) {
				return null;
			}
			return (
				<AppPromo
					title={ translate( 'Stay logged in with the Jetpack Mobile App' ) }
					campaign="calypso-login-link-check-email"
					className="magic-link-app-promo"
					iconSize={ 32 }
					hasQRCode
					hasGetAppButton={ false }
				/>
			);
		}

		// The email address from the URL (if present) is added to the login
		// parameters in this.onClickEnterPasswordInstead(). But it's left out
		// here deliberately, to ensure that if someone copies this link to
		// paste somewhere else, their email address isn't included in it.
		const loginParameters = {
			isJetpack: isJetpackLogin,
			locale: locale,
			signupUrl: query?.signup_url,
			twoFactorAuthType: twoFactorNotificationSent?.replace( 'none', 'authenticator' ),
			redirectTo: redirectToSanitized,
			oauth2ClientId: oauth2Client?.id,
			from: query?.from,
		};

		let linkBack = translate( 'Enter a password instead' );
		if ( query?.username_only === 'true' ) {
			linkBack = translate( 'Use username and password instead' );
		}

		return (
			<>
				<div className="wp-login__login-block-footer">
					<a
						className="magic-login__footer-link"
						href={ login( loginParameters ) }
						onClick={ this.onClickEnterPasswordInstead }
					>
						{ linkBack }
					</a>
				</div>
				{ ! oauth2Client && (
					<AppPromo
						title={ translate( 'Stay logged in with the Jetpack Mobile App' ) }
						campaign="calypso-login-link"
						className="magic-link-app-promo"
						iconSize={ 32 }
						hasQRCode
						hasGetAppButton={ false }
					/>
				) }
			</>
		);
	}

	renderLocaleSuggestions() {
		const { locale, path, showCheckYourEmail } = this.props;

		if ( showCheckYourEmail ) {
			return null;
		}

		return <LocaleSuggestions locale={ locale } path={ path } />;
	}

	handleGravPoweredEmailCodeSend = async ( email, cb = () => {} ) => {
		const { oauth2Client, query, locale, translate } = this.props;
		const { isSecondaryEmail, isNewAccount } = this.state;
		const noticeId = 'email-code-notice';
		const duration = 4000;
		const eventOptions = { client_id: oauth2Client.id, client_name: oauth2Client.title };

		this.setState( { isRequestingEmail: true } );

		try {
			this.props.infoNotice( translate( 'Sending email…' ), { id: noticeId, duration } );

			this.props.recordTracksEvent(
				'calypso_gravatar_powered_magic_login_email_code_requesting',
				eventOptions
			);

			const { public_token } = await wpcom.req.post(
				'/auth/send-login-email',
				{ apiVersion: '1.3' },
				{
					client_id: config( 'wpcom_signup_id' ),
					client_secret: config( 'wpcom_signup_key' ),
					locale,
					lang_id: getLanguage( locale ).value,
					email,
					redirect_to: query?.redirect_to,
					flow: getGravatarOAuth2Flow( oauth2Client ),
					create_account: true,
					tos: getToSAcceptancePayload(),
					token_type: 'code',
					...( isSecondaryEmail ? { gravatar_main: ! isNewAccount } : {} ),
				}
			);

			this.setState( { publicToken: public_token, showEmailCodeVerification: true } );
			this.startResendEmailCountdown();
			cb();

			this.props.removeNotice( noticeId );
			this.props.successNotice( translate( 'Email Sent. Check your mail app!' ), { duration } );

			this.props.recordTracksEvent(
				'calypso_gravatar_powered_magic_login_email_code_success',
				eventOptions
			);
		} catch ( error ) {
			if ( error.error ) {
				this.setState( { requestEmailErrorMessage: error.message } );
			} else {
				this.setState( {
					requestEmailErrorMessage: translate( 'Something went wrong. Please try again.' ),
				} );
			}

			this.props.removeNotice( noticeId );
			this.props.errorNotice( translate( 'Sorry, we couldn’t send the email.' ), { duration } );

			this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_code_failure', {
				...eventOptions,
				error_code: error.status,
				error_message: error.message,
			} );
		}

		this.setState( { isRequestingEmail: false } );
	};

	handleGravPoweredEmailSubmit = async ( usernameOrEmail, e ) => {
		e.preventDefault();

		const { translate, oauth2Client } = this.props;
		const eventOptions = { client_id: oauth2Client.id, client_name: oauth2Client.title };

		if ( ! emailValidator.validate( usernameOrEmail ) ) {
			return this.setState( { requestEmailErrorMessage: translate( 'Invalid email.' ) } );
		}

		this.setState( { usernameOrEmail, isRequestingEmail: true } );

		try {
			this.props.recordTracksEvent(
				'calypso_gravatar_powered_magic_login_gravatar_info_fetching',
				eventOptions
			);

			const { is_secondary, main_email_masked } = await wpcom.req.get( '/auth/get-gravatar-info', {
				email: usernameOrEmail,
			} );

			if ( is_secondary ) {
				this.setState( {
					usernameOrEmail,
					isSecondaryEmail: true,
					showSecondaryEmailOptions: true,
					maskedEmailAddress: main_email_masked,
					isRequestingEmail: false,
				} );
			} else {
				this.handleGravPoweredEmailCodeSend( usernameOrEmail );
			}

			this.props.recordTracksEvent(
				'calypso_gravatar_powered_magic_login_gravatar_info_success',
				eventOptions
			);
		} catch ( error ) {
			switch ( error.error ) {
				case 'not_found':
					this.setState( { isNewAccount: true } );
					this.handleGravPoweredEmailCodeSend( usernameOrEmail );
					break;
				case 'invalid_email':
					this.setState( {
						requestEmailErrorMessage: translate( 'Invalid email.' ),
						isRequestingEmail: false,
					} );
					break;
				default:
					this.setState( {
						requestEmailErrorMessage: translate( 'Something went wrong. Please try again.' ),
						isRequestingEmail: false,
					} );
			}

			this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_gravatar_info_failure', {
				...eventOptions,
				error_code: error.status,
				error_message: error.message,
			} );
		}
	};

	handleGravPoweredCodeInputChange = ( e ) => {
		let value = e.target.value.toUpperCase();

		if ( ! /^[A-Z0-9]*$/.test( value ) || value.length > 6 ) {
			value = this.state.verificationCodeInputValue;
		}

		this.setState( { verificationCodeInputValue: value } );
	};

	handleGravPoweredCodeSubmit = ( e ) => {
		e.preventDefault();

		const { oauth2Client, query } = this.props;
		const { publicToken, verificationCodeInputValue } = this.state;

		this.props.fetchMagicLoginAuthenticate(
			`${ publicToken }:${ btoa( verificationCodeInputValue ) }`,
			query?.redirect_to,
			getGravatarOAuth2Flow( oauth2Client ),
			true
		);
	};

	handleGravPoweredEmailSwitch = () => {
		const { oauth2Client, hideMagicLoginRequestForm: showEmailForm } = this.props;

		this.setState( {
			showSecondaryEmailOptions: false,
			showEmailCodeVerification: false,
			verificationCodeInputValue: '',
			isNewAccount: false,
		} );
		showEmailForm();

		this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_click_switch_email', {
			client_id: oauth2Client.id,
			client_name: oauth2Client.title,
		} );
	};

	renderGravPoweredMagicLoginTos() {
		const { oauth2Client, translate } = this.props;

		const textOptions = {
			components: {
				tosLink: (
					<a
						href={ localizeUrl( 'https://wordpress.com/tos/' ) }
						target="_blank"
						rel="noopener noreferrer"
					/>
				),
				privacyLink: (
					<a
						href={ localizeUrl( 'https://automattic.com/privacy/' ) }
						target="_blank"
						rel="noopener noreferrer"
					/>
				),
				wpAccountLink: (
					<a
						href={ localizeUrl( 'https://support.gravatar.com/why-wordpress-com/' ) }
						target="_blank"
						rel="noopener noreferrer"
					/>
				),
			},
		};

		return (
			<div className="grav-powered-magic-login__tos">
				{ isGravatarOAuth2Client( oauth2Client )
					? translate(
							`By clicking “Continue“, you agree to our {{tosLink}}Terms of Service{{/tosLink}}, have read our {{privacyLink}}Privacy Policy{{/privacyLink}}, and understand that you're creating {{wpAccountLink}}a WordPress.com account{{/wpAccountLink}} if you don't already have one.`,
							textOptions
					  )
					: translate(
							`By clicking “Send me sign in link“, you agree to our {{tosLink}}Terms of Service{{/tosLink}}, have read our {{privacyLink}}Privacy Policy{{/privacyLink}}, and understand that you're creating a Gravatar account if you don't already have one.`,
							textOptions
					  ) }
			</div>
		);
	}

	resendEmailCountdownId = null;

	resetResendEmailCountdown = () => {
		if ( ! this.resendEmailCountdownId ) {
			return;
		}

		clearInterval( this.resendEmailCountdownId );
		this.resendEmailCountdownId = null;
		this.setState( { resendEmailCountdown: RESEND_EMAIL_COUNTDOWN_TIME } );
	};

	startResendEmailCountdown = () => {
		this.resetResendEmailCountdown();

		this.resendEmailCountdownId = setInterval( () => {
			if ( ! this.state.resendEmailCountdown ) {
				clearInterval( this.resendEmailCountdownId );
				return;
			}

			this.setState( ( prevState ) => ( {
				resendEmailCountdown: prevState.resendEmailCountdown - 1,
			} ) );
		}, 1000 );
	};

	emailToSha256 = async ( email ) => {
		if ( ! window.crypto?.subtle ) {
			return null;
		}

		const data = new TextEncoder().encode( email );
		const hashBuffer = await crypto.subtle.digest( 'SHA-256', data );

		return Array.from( new Uint8Array( hashBuffer ) )
			.map( ( byte ) => byte.toString( 16 ).padStart( 2, '0' ) )
			.join( '' );
	};

	renderGravPoweredLogo() {
		const { oauth2Client } = this.props;

		return (
			<GravatarLoginLogo
				iconUrl={ oauth2Client.icon }
				alt={ oauth2Client.title }
				isCoBrand={ isGravatarFlowOAuth2Client( oauth2Client ) }
			/>
		);
	}

	renderGravPoweredSecondaryEmailOptions() {
		const { oauth2Client, translate, query } = this.props;
		const {
			usernameOrEmail,
			isNewAccount,
			maskedEmailAddress,
			isRequestingEmail,
			requestEmailErrorMessage,
			hashedEmail,
		} = this.state;
		const eventOptions = { client_id: oauth2Client.id, client_name: oauth2Client.title };
		const isFromGravatar3rdPartyApp =
			isGravatarOAuth2Client( oauth2Client ) && query?.gravatar_from === GRAVATAR_FROM_3RD_PARTY;
		const isFromGravatarQuickEditor =
			isGravatarOAuth2Client( oauth2Client ) && query?.gravatar_from === GRAVATAR_FROM_QUICK_EDITOR;
		const isGravatarFlowWithEmail = !! (
			isGravatarFlowOAuth2Client( oauth2Client ) && query?.email_address
		);
		const shouldShowSwitchEmail =
			! isFromGravatar3rdPartyApp && ! isFromGravatarQuickEditor && ! isGravatarFlowWithEmail;

		this.emailToSha256( usernameOrEmail ).then( ( email ) =>
			this.setState( { hashedEmail: email } )
		);

		return (
			<div className="grav-powered-magic-login__content">
				{ this.renderGravPoweredLogo() }
				<h1 className="grav-powered-magic-login__header">{ translate( 'Important note' ) }</h1>
				<p className="grav-powered-magic-login__sub-header">
					{ translate(
						'The submitted email is already linked to an existing Gravatar account as a secondary email:'
					) }
				</p>
				<div className="grav-powered-magic-login__account-info">
					<div className="grav-powered-magic-login__masked-email-address">
						{ translate( 'Account: {{strong}}%(maskedEmailAddress)s{{/strong}}', {
							components: { strong: <strong /> },
							args: { maskedEmailAddress },
						} ) }
					</div>
					{ hashedEmail && (
						<a href={ `https://gravatar.com/${ hashedEmail }` } target="_blank" rel="noreferrer">
							{ translate( 'Open profile' ) }
						</a>
					) }
				</div>
				<div className="grav-powered-magic-login__account-options">
					<button
						className={ clsx( 'grav-powered-magic-login__account-option', {
							'grav-powered-magic-login__account-option--selected': ! isNewAccount,
						} ) }
						onClick={ () => {
							this.setState( { isNewAccount: false } );

							this.props.recordTracksEvent(
								'calypso_gravatar_powered_magic_login_click_main_account',
								eventOptions
							);
						} }
						disabled={ isRequestingEmail }
					>
						{ translate( 'Log in with main account (recommended)' ) }
					</button>
					{ ! isNewAccount && (
						<div>
							{ translate(
								'Log in with your main account and edit there your avatar for your secondary email address.'
							) }
						</div>
					) }
					<button
						className={ clsx( 'grav-powered-magic-login__account-option', {
							'grav-powered-magic-login__account-option--selected': isNewAccount,
						} ) }
						onClick={ () => {
							this.setState( { isNewAccount: true } );

							this.props.recordTracksEvent(
								'calypso_gravatar_powered_magic_login_click_new_account',
								eventOptions
							);
						} }
						disabled={ isRequestingEmail }
					>
						{ translate( 'Create a new account' ) }
					</button>
					{ isNewAccount && (
						<div>
							{ translate(
								'If you continue a new account will be created, and {{strong}}%(emailAddress)s{{/strong}} will be disconnected from the current main account.',
								{
									components: { strong: <strong /> },
									args: { emailAddress: usernameOrEmail },
								}
							) }
						</div>
					) }
				</div>
				{ requestEmailErrorMessage && (
					<Notice
						duration={ 10000 }
						text={ requestEmailErrorMessage }
						className="magic-login__request-login-email-form-notice"
						showDismiss={ false }
						onDismissClick={ () => this.setState( { requestEmailErrorMessage: null } ) }
						status="is-transparent-info"
					/>
				) }
				<FormButton
					onClick={ () =>
						this.handleGravPoweredEmailCodeSend( usernameOrEmail, () =>
							this.setState( { showSecondaryEmailOptions: false } )
						)
					}
					disabled={ isRequestingEmail || !! requestEmailErrorMessage }
					busy={ isRequestingEmail }
				>
					{ translate( 'Continue' ) }
				</FormButton>
				<footer className="grav-powered-magic-login__footer">
					{ shouldShowSwitchEmail && (
						<button onClick={ this.handleGravPoweredEmailSwitch }>
							{ translate( 'Switch email' ) }
						</button>
					) }
					<a href="https://gravatar.com/support" target="_blank" rel="noreferrer">
						{ translate( 'Need help logging in?' ) }
					</a>
				</footer>
			</div>
		);
	}

	renderGravPoweredEmailCodeVerification() {
		const {
			oauth2Client,
			translate,
			isValidatingCode,
			isCodeValidated,
			codeValidationError,
			query,
		} = this.props;
		const {
			isSecondaryEmail,
			isNewAccount,
			isRequestingEmail,
			maskedEmailAddress,
			usernameOrEmail,
			verificationCodeInputValue,
			resendEmailCountdown,
		} = this.state;
		const isFromGravatar3rdPartyApp =
			isGravatarOAuth2Client( oauth2Client ) && query?.gravatar_from === GRAVATAR_FROM_3RD_PARTY;
		const isFromGravatarQuickEditor =
			isGravatarOAuth2Client( oauth2Client ) && query?.gravatar_from === GRAVATAR_FROM_QUICK_EDITOR;
		const isGravatarFlowWithEmail = !! (
			isGravatarFlowOAuth2Client( oauth2Client ) && query?.email_address
		);
		const shouldShowSwitchEmail =
			! isFromGravatar3rdPartyApp && ! isFromGravatarQuickEditor && ! isGravatarFlowWithEmail;
		const isProcessingCode = isValidatingCode || isCodeValidated;
		let errorText = translate( 'Something went wrong. Please try again.' );

		if ( codeValidationError?.type === 'sms_code_throttled' ) {
			errorText = translate(
				'Your two-factor code via SMS can only be requested once per minute. Please wait, then request a new code via email to proceed.'
			);
		} else if ( codeValidationError?.type === 'user_email' ) {
			errorText = translate(
				"We're sorry, you can't create a new account at this time. Please try a different email address or disable any VPN before trying again."
			);
		} else if ( codeValidationError?.code === 403 ) {
			errorText = translate(
				'Invalid code. If the error persists, please request a new code and try again.'
			);
		} else if ( codeValidationError?.code === 429 ) {
			errorText = translate( 'Please wait a minute before trying again.' );
		}

		return (
			<div className="grav-powered-magic-login__content">
				{ this.renderGravPoweredLogo() }
				<h1 className="grav-powered-magic-login__header">{ translate( 'Check your email' ) }</h1>
				<p className="grav-powered-magic-login__sub-header">
					<span>
						{ translate(
							'Enter the verification code we’ve sent to {{strong}}%(emailAddress)s{{/strong}}.',
							{
								components: { strong: <strong /> },
								args: {
									emailAddress:
										isSecondaryEmail && ! isNewAccount ? maskedEmailAddress : usernameOrEmail,
								},
							}
						) }
					</span>
					{ isSecondaryEmail && isNewAccount && (
						<span>{ translate( ' A new Gravatar account will be created.' ) }</span>
					) }
					{ isSecondaryEmail && ! isNewAccount && (
						<span>{ translate( ' This email already exists and is synced with Gravatar.' ) }</span>
					) }
				</p>
				{ isNewAccount && this.renderGravPoweredMagicLoginTos() }
				<form
					className="grav-powered-magic-login__verification-code-form"
					onSubmit={ this.handleGravPoweredCodeSubmit }
				>
					<FormLabel htmlFor="verification-code" hidden>
						{ translate( 'Enter the verification code' ) }
					</FormLabel>
					<FormTextInput
						id="verification-code"
						value={ verificationCodeInputValue }
						onChange={ this.handleGravPoweredCodeInputChange }
						placeholder={ translate( 'Verification code' ) }
						disabled={ isProcessingCode }
						isError={ !! codeValidationError }
						autoFocus // eslint-disable-line jsx-a11y/no-autofocus
					/>
					{ codeValidationError && (
						<Notice
							text={ errorText }
							className="magic-login__request-login-email-form-notice"
							showDismiss={ false }
							status="is-transparent-info"
						/>
					) }
					<FormButton
						primary
						disabled={
							! verificationCodeInputValue ||
							verificationCodeInputValue.length < 6 ||
							isProcessingCode
						}
						busy={ isProcessingCode }
					>
						{ translate( 'Continue' ) }
					</FormButton>
				</form>
				<footer
					className={ clsx( 'grav-powered-magic-login__footer', {
						'grav-powered-magic-login__footer--vertical': ! isFromGravatar3rdPartyApp,
					} ) }
				>
					<button
						onClick={ () => {
							this.handleGravPoweredEmailCodeSend( usernameOrEmail );

							this.props.recordTracksEvent(
								'calypso_gravatar_powered_magic_login_click_resend_email',
								{ type: 'code', client_id: oauth2Client.id, client_name: oauth2Client.title }
							);
						} }
						disabled={ isRequestingEmail || resendEmailCountdown }
					>
						{ resendEmailCountdown === 0
							? translate( 'Send again' )
							: translate( 'Send again (%(countdown)d)', {
									args: { countdown: resendEmailCountdown },
							  } ) }
					</button>
					{ shouldShowSwitchEmail && (
						<button
							onClick={ () => {
								this.resetResendEmailCountdown();
								this.handleGravPoweredEmailSwitch();
							} }
						>
							{ translate( 'Switch email' ) }
						</button>
					) }
					<a href="https://gravatar.com/support" target="_blank" rel="noreferrer">
						{ translate( 'Need help logging in?' ) }
					</a>
				</footer>
			</div>
		);
	}

	renderGravPoweredEmailLinkVerification() {
		const {
			oauth2Client,
			translate,
			query,
			isSendingEmail,
			sendEmailLogin: resendEmail,
		} = this.props;
		const { usernameOrEmail, resendEmailCountdown } = this.state;
		const emailAddress = usernameOrEmail.includes( '@' ) ? usernameOrEmail : null;

		const emailTextOptions = {
			components: {
				sendEmailButton: (
					<button
						onClick={ () => {
							resendEmail( usernameOrEmail, {
								redirectTo: query?.redirect_to,
								requestLoginEmailFormFlow: true,
								createAccount: true,
								flow: getGravatarOAuth2Flow( oauth2Client ),
								showGlobalNotices: true,
							} );

							this.props.recordTracksEvent(
								'calypso_gravatar_powered_magic_login_click_resend_email',
								{ type: 'link', client_id: oauth2Client.id, client_name: oauth2Client.title }
							);
						} }
						disabled={ isSendingEmail }
					/>
				),
				showMagicLoginButton: (
					<button
						className="grav-powered-magic-login__show-magic-login"
						onClick={ () => {
							this.resetResendEmailCountdown();
							this.handleGravPoweredEmailSwitch();
						} }
					/>
				),
			},
		};

		return (
			<div className="grav-powered-magic-login__content">
				{ this.renderGravPoweredLogo() }
				<h1 className="grav-powered-magic-login__header">{ translate( 'Check your email!' ) }</h1>
				<p className="grav-powered-magic-login__sub-header">
					{ emailAddress
						? translate(
								"We've sent an email with a verification link to {{strong}}%(emailAddress)s{{/strong}}",
								{
									components: { strong: <strong /> },
									args: { emailAddress },
								}
						  )
						: translate(
								'We just emailed you a link. Please check your inbox and click the link to log in.'
						  ) }
				</p>
				<hr className="grav-powered-magic-login__divider" />
				<div className="grav-powered-magic-login__footer">
					<div>{ translate( 'Are you having issues receiving it?' ) }</div>
					<div>
						{ resendEmailCountdown === 0
							? translate(
									'{{sendEmailButton}}Resend the verification email{{/sendEmailButton}} or {{showMagicLoginButton}}use a different email address{{/showMagicLoginButton}}.',
									emailTextOptions
							  )
							: translate(
									'{{showMagicLoginButton}}Use a different email address{{/showMagicLoginButton}}.',
									emailTextOptions
							  ) }
					</div>
				</div>
			</div>
		);
	}

	renderGravPoweredMagicLogin() {
		const { oauth2Client, translate, locale, query } = this.props;
		const { isRequestingEmail, requestEmailErrorMessage } = this.state;

		const isGravatarFlow = isGravatarFlowOAuth2Client( oauth2Client );
		const isGravatarFlowWithEmail = !! ( isGravatarFlow && query?.email_address );
		const isGravatar = isGravatarOAuth2Client( oauth2Client );
		const isWPJobManager = isWPJobManagerOAuth2Client( oauth2Client );
		const isFromGravatarSignup = isGravatar && query?.gravatar_from === 'signup';
		const isFromGravatar3rdPartyApp =
			isGravatar && query?.gravatar_from === GRAVATAR_FROM_3RD_PARTY;
		const isFromGravatarQuickEditor =
			isGravatar && query?.gravatar_from === GRAVATAR_FROM_QUICK_EDITOR;
		const isEmailInputDisabled =
			isFromGravatar3rdPartyApp ||
			isFromGravatarQuickEditor ||
			isRequestingEmail ||
			isGravatarFlowWithEmail;
		const submitButtonLabel = isGravatar
			? translate( 'Continue' )
			: translate( 'Send me sign in link' );
		const loginUrl = login( {
			locale,
			redirectTo: query?.redirect_to,
			oauth2ClientId: query?.client_id,
			gravatarFrom: query?.gravatar_from,
			gravatarFlow: isGravatarFlow,
			emailAddress: query?.email_address,
		} );
		let headerText = isFromGravatarSignup
			? translate( 'Create your Gravatar' )
			: translate( 'Edit your Gravatar' );
		headerText = isWPJobManager ? translate( 'Sign in with your email' ) : headerText;
		let subHeader = '';

		if ( isGravatarFlow ) {
			subHeader = translate( '%(clientTitle)s profiles are powered by Gravatar.', {
				args: { clientTitle: oauth2Client.title },
			} );
		} else if ( isFromGravatar3rdPartyApp || isFromGravatarQuickEditor ) {
			subHeader = translate( 'Profiles and avatars are powered by Gravatar.' );
		}

		return (
			<>
				{ this.renderLocaleSuggestions() }
				<GlobalNotices id="notices" />
				<div className="grav-powered-magic-login__content">
					{ this.renderGravPoweredLogo() }
					<RequestLoginEmailForm
						flow={ getGravatarOAuth2Flow( oauth2Client ) }
						headerText={ headerText }
						subHeaderText={ subHeader }
						inputPlaceholder={ translate( 'Enter your email address' ) }
						submitButtonLabel={ submitButtonLabel }
						tosComponent={ ! isGravatar && this.renderGravPoweredMagicLoginTos() }
						onSubmitEmail={ isGravatar ? this.handleGravPoweredEmailSubmit : undefined }
						onSendEmailLogin={ ( usernameOrEmail ) => this.setState( { usernameOrEmail } ) }
						createAccountForNewUser
						errorMessage={ requestEmailErrorMessage }
						onErrorDismiss={ () => this.setState( { requestEmailErrorMessage: null } ) }
						isEmailInputDisabled={ isEmailInputDisabled }
						isEmailInputError={ !! requestEmailErrorMessage }
						isSubmitButtonDisabled={ isRequestingEmail || !! requestEmailErrorMessage }
						isSubmitButtonBusy={ isRequestingEmail }
					/>
					{ isGravatar && (
						<div className="grav-powered-magic-login__feature-items">
							<div className="grav-powered-magic-login__feature-item">
								<svg
									className="grav-powered-magic-login__feature-icon"
									width="40"
									height="41"
									viewBox="0 0 40 41"
									fill="none"
									xmlns="http://www.w3.org/2000/svg"
								>
									<circle
										cx="20"
										cy="20.5"
										r="19.25"
										fill="white"
										stroke="#1D4FC4"
										strokeWidth="1.5"
									/>
									<path
										fillRule="evenodd"
										clipRule="evenodd"
										d="M24 17.5C24 19.7091 22.2091 21.5 20 21.5C17.7909 21.5 16 19.7091 16 17.5C16 15.2909 17.7909 13.5 20 13.5C22.2091 13.5 24 15.2909 24 17.5ZM22.5 17.5C22.5 18.8807 21.3807 20 20 20C18.6193 20 17.5 18.8807 17.5 17.5C17.5 16.1193 18.6193 15 20 15C21.3807 15 22.5 16.1193 22.5 17.5Z"
										fill="#1D4FC4"
									/>
									<path
										d="M26.75 28.5V26.5C26.75 24.9812 25.5188 23.75 24 23.75L16 23.75C14.4812 23.75 13.25 24.9812 13.25 26.5V28.5H14.75L14.75 26.5C14.75 25.8096 15.3096 25.25 16 25.25L24 25.25C24.6904 25.25 25.25 25.8096 25.25 26.5V28.5H26.75Z"
										fill="#1D4FC4"
									/>
								</svg>
								<div>
									<h4 className="grav-powered-magic-login__feature-header">
										{ translate( 'One profile, everywhere' ) }
									</h4>
									<p className="grav-powered-magic-login__feature-sub-header">
										{ translate( 'Your avatar and bio syncs across the web.' ) }
									</p>
								</div>
							</div>
							<div className="grav-powered-magic-login__feature-item">
								<svg
									className="grav-powered-magic-login__feature-icon"
									width="40"
									height="41"
									viewBox="0 0 40 41"
									fill="none"
									xmlns="http://www.w3.org/2000/svg"
								>
									<circle
										cx="20"
										cy="20.5"
										r="19.25"
										fill="white"
										stroke="#1D4FC4"
										strokeWidth="1.5"
									/>
									<path
										fillRule="evenodd"
										clipRule="evenodd"
										d="M20 11.75C17.9289 11.75 16.25 13.4289 16.25 15.5V18.5H15C14.4477 18.5 14 18.9477 14 19.5V27.5C14 28.0523 14.4477 28.5 15 28.5H25C25.5523 28.5 26 28.0523 26 27.5V19.5C26 18.9477 25.5523 18.5 25 18.5H23.75V15.5C23.75 13.4289 22.0711 11.75 20 11.75ZM22.25 18.5V15.5C22.25 14.2574 21.2426 13.25 20 13.25C18.7574 13.25 17.75 14.2574 17.75 15.5V18.5H22.25ZM15.5 27V20H24.5V27H15.5Z"
										fill="#1D4FC4"
									/>
								</svg>
								<div>
									<h4 className="grav-powered-magic-login__feature-header">
										{ translate( 'Public, open, and responsible' ) }
									</h4>
									<p className="grav-powered-magic-login__feature-sub-header">
										{ translate( 'Full control over your data and privacy.' ) }
									</p>
								</div>
							</div>
							<div className="grav-powered-magic-login__feature-item">
								<svg
									className="grav-powered-magic-login__feature-icon"
									width="40"
									height="41"
									viewBox="0 0 40 41"
									fill="none"
									xmlns="http://www.w3.org/2000/svg"
								>
									<circle
										cx="20"
										cy="20.5"
										r="19.25"
										fill="white"
										stroke="#1D4FC4"
										strokeWidth="1.5"
									/>
									<path
										d="M19 21.5V26.5H20.5V21.5H25.5V20H20.5V15H19V20H14V21.5H19Z"
										fill="#1D4FC4"
									/>
								</svg>
								<div>
									<h4 className="grav-powered-magic-login__feature-header">
										{ translate( '200+ million users' ) }
									</h4>
									<p className="grav-powered-magic-login__feature-sub-header">
										{ translate( 'Used by WordPress, Slack, and many more.' ) }
									</p>
								</div>
							</div>
						</div>
					) }
					{ isWPJobManager && (
						<hr className="grav-powered-magic-login__divider grav-powered-magic-login__divider--email-form" />
					) }
					{ ! isFromGravatarSignup && (
						<footer className="grav-powered-magic-login__footer grav-powered-magic-login__footer--email-form">
							{ translate( '{{a}}Sign in another way{{/a}}', {
								components: {
									a: (
										<a
											href={ loginUrl }
											onClick={ () =>
												this.props.recordTracksEvent(
													'calypso_gravatar_powered_magic_login_click_login_page_link',
													{ client_id: oauth2Client.id, client_name: oauth2Client.title }
												)
											}
										/>
									),
								},
							} ) }
						</footer>
					) }
				</div>
				{ isWPJobManager && (
					<div className="grav-powered-magic-login__gravatar-info">
						<div className="grav-powered-magic-login__gravatar-info-heading">
							<img
								src="https://gravatar.com/images/grav-logo-blue.svg"
								width={ 18 }
								height={ 18 }
								alt="Gravatar logo"
							/>
							{ translate( 'You will be logging in via Gravatar' ) }
						</div>
						<div className="grav-powered-magic-login__gravatar-info-items">
							<div>
								<Gridicon icon="checkmark" size={ 18 } color="#646970" />
								{ translate(
									'Gravatar accounts and profiles are free. You can log in to thousands of sites across the web with one Gravatar account.'
								) }
							</div>
							<div>
								<Gridicon icon="checkmark" size={ 18 } color="#646970" />
								{ translate( 'Control what information is shared on your public profile.' ) }
							</div>
							<div>
								<Gridicon icon="checkmark" size={ 18 } color="#646970" />
								{ translate(
									"Have questions? Please see Gravatar's {{a}}documentation here{{/a}}.",
									{
										components: {
											a: <a href="https://gravatar.com/support" target="_blank" rel="noreferrer" />,
										},
									}
								) }
							</div>
						</div>
					</div>
				) }
			</>
		);
	}

	renderTos = () => {
		const { translate } = this.props;
		const options = {
			components: {
				tosLink: (
					<a
						href={ localizeUrl( 'https://wordpress.com/tos/' ) }
						target="_blank"
						rel="noopener noreferrer"
					/>
				),
				privacyLink: (
					<a
						href={ localizeUrl( 'https://automattic.com/privacy/' ) }
						target="_blank"
						rel="noopener noreferrer"
					/>
				),
			},
		};
		const tosText = fixMe( {
			text: 'By continuing you agree to our {{tosLink}}Terms of Service{{/tosLink}} and have read our {{privacyLink}}Privacy Policy{{/privacyLink}}.',
			newCopy: translate(
				'By continuing you agree to our {{tosLink}}Terms of Service{{/tosLink}} and have read our {{privacyLink}}Privacy Policy{{/privacyLink}}.',
				options
			),
			oldCopy: translate(
				'By creating an account you agree to our {{tosLink}}Terms of Service{{/tosLink}} and have read our {{privacyLink}}Privacy Policy{{/privacyLink}}.',
				options
			),
		} );

		return <p className="magic-login__tos wp-login__tos">{ tosText }</p>;
	};

	handlePublicTokenReceived = ( publicToken ) => {
		this.setState( { publicToken } );
	};

	render() {
		const {
			oauth2Client,
			query,
			translate,
			showCheckYourEmail: showEmailLinkVerification,
			isWooJPC,
			isJetpackLogin,
			isFromJetpackOnboarding,
		} = this.props;
		const { showSecondaryEmailOptions, showEmailCodeVerification, usernameOrEmail } = this.state;

		if ( isGravPoweredOAuth2Client( oauth2Client ) ) {
			let renderContent = this.renderGravPoweredMagicLogin();
			const hasSubHeader =
				isGravatarFlowOAuth2Client( oauth2Client ) ||
				( isGravatarOAuth2Client( oauth2Client ) &&
					( query?.gravatar_from === GRAVATAR_FROM_3RD_PARTY ||
						query?.gravatar_from === GRAVATAR_FROM_QUICK_EDITOR ) );

			if ( showSecondaryEmailOptions ) {
				renderContent = this.renderGravPoweredSecondaryEmailOptions();
			} else if ( showEmailCodeVerification ) {
				renderContent = this.renderGravPoweredEmailCodeVerification();
			} else if ( showEmailLinkVerification ) {
				renderContent = this.renderGravPoweredEmailLinkVerification();
			}

			return (
				<Main
					className={ clsx( 'grav-powered-magic-login', {
						'grav-powered-magic-login--has-sub-header': hasSubHeader,
						'grav-powered-magic-login--wp-job-manager': isWPJobManagerOAuth2Client( oauth2Client ),
					} ) }
				>
					{ renderContent }
				</Main>
			);
		}

		// "query?.redirect_to" is used to determine if Studio app users are creating a new account (vs. logging in)
		const isStudio = isStudioAppOAuth2Client( oauth2Client ) && query?.redirect_to;

		// If this is part of the Jetpack login flow, some steps will display a different UI
		const requestLoginEmailFormProps = {
			...( this.props.isJetpackLogin ? { flow: 'jetpack' } : {} ),
			isJetpackMagicLinkSignUpEnabled: this.props.isJetpackLogin,
			createAccountForNewUser: true,
			isFromJetpackOnboarding,
			tosComponent: this.renderTos(),
			...( isStudio
				? {
						customFormLabel: translate( 'Your email address' ),
						submitButtonLabel: translate( 'Send activation link' ),
				  }
				: {} ),
		};

		const mainContent = (
			<Main className="magic-login magic-login__request-link">
				<GlobalNotices id="notices" />

				{ isWooJPC ? (
					<MainContentWooCoreProfiler
						emailAddress={ usernameOrEmail }
						redirectTo={ this.props.redirectToSanitized }
					/>
				) : (
					<>
						{ shouldUseMagicCode( { isJetpack: isJetpackLogin } ) ? (
							<RequestLoginCode
								{ ...requestLoginEmailFormProps }
								emailRequested={ this.props.emailRequested }
								publicToken={ this.props.publicToken }
								onPublicTokenReceived={ this.handlePublicTokenReceived }
							/>
						) : (
							<RequestLoginEmailForm { ...requestLoginEmailFormProps } />
						) }
					</>
				) }

				{ this.renderLinks() }
				{ this.renderLocaleSuggestions() }
			</Main>
		);

		return (
			<OneLoginLayout isJetpack={ isJetpackLogin } isFromAkismet={ this.props.isFromAkismet }>
				{ mainContent }
			</OneLoginLayout>
		);
	}
}

const mapState = ( state ) => ( {
	locale: getCurrentLocaleSlug( state ),
	query: getCurrentQueryArguments( state ),
	showCheckYourEmail: getMagicLoginCurrentView( state ) === CHECK_YOUR_EMAIL_PAGE,
	isSendingEmail: isFetchingMagicLoginEmail( state ),
	emailRequested: isMagicLoginEmailRequested( state ),
	emailRequestError: getMagicLoginRequestEmailError( state ),
	isJetpackLogin: getCurrentRoute( state )?.startsWith( '/log-in/jetpack/link' ),
	oauth2Client: getCurrentOAuth2Client( state ),
	userEmail:
		getLastCheckedUsernameOrEmail( state ) ||
		getCurrentQueryArguments( state ).email_address ||
		getInitialQueryArguments( state ).email_address,
	localeSuggestions: getLocaleSuggestions( state ),
	isWCCOM: getIsWCCOM( state ),
	isValidatingCode: isFetchingMagicLoginAuth( state ),
	isCodeValidated: getMagicLoginRequestedAuthSuccessfully( state ),
	codeValidationError: getMagicLoginRequestAuthError( state ),
	twoFactorEnabled: isTwoFactorEnabled( state ),
	twoFactorNotificationSent: getTwoFactorNotificationSent( state ),
	redirectToSanitized: getRedirectToSanitized( state ),
	redirectToOriginal: getRedirectToOriginal( state ),
	isFromAutomatticForAgenciesPlugin:
		'automattic-for-agencies-client' ===
		new URLSearchParams( getRedirectToOriginal( state )?.split( '?' )[ 1 ] ).get( 'from' ),
	isFromJetpackOnboarding:
		new URLSearchParams( getRedirectToOriginal( state )?.split( '?' )[ 1 ] ).get( 'from' ) ===
		'jetpack-onboarding',
	isWooJPC: isWooJPCFlow( state ),
	publicToken: getMagicLoginPublicToken( state ),
	isFromAkismet: isAkismetRedirect(
		new URLSearchParams( getRedirectToOriginal( state )?.split( '?' )[ 1 ] ).get( 'back' )
	),
} );

const mapDispatch = {
	hideMagicLoginRequestForm,
	sendEmailLogin,
	fetchMagicLoginAuthenticate,
	rebootAfterLogin,
	recordPageView: withEnhancers( recordPageView, [ enhanceWithSiteType ] ),
	recordTracksEvent: withEnhancers( recordTracksEvent, [ enhanceWithSiteType ] ),
	infoNotice,
	errorNotice,
	successNotice,
	removeNotice,
};

export default connect( mapState, mapDispatch )( localize( MagicLogin ) );