summaryrefslogtreecommitdiff
path: root/packages/bank/src/pages/home/index.tsx
blob: 3ab1481e1ad00e6c575accb9672afe18a33a8579 (plain)
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
/* eslint-disable @typescript-eslint/no-explicit-any */
import useSWR, { SWRConfig, useSWRConfig } from 'swr';
import useSWRImmutable from 'swr/immutable';
import { h, Fragment, ComponentChildren, VNode, createContext } from 'preact';
import { useCallback, useRef, useState, useEffect, StateUpdater, useContext } from 'preact/hooks';
import { Buffer } from 'buffer';
import { useTranslator, Translate } from '../../i18n';
import { QR } from '../../components/QR';
import { useNotNullLocalStorage, useLocalStorage } from '../../hooks';
import '../../scss/main.scss';
import talerLogo from '../../assets/logo-white.svg';
import { LangSelectorLikePy as LangSelector} from '../../components/menu/LangSelector';

// Uncomment to allow test runs:
// const __LIBEUFIN_UI_ALLOW_REGISTRATIONS__ = 1;
// const __LIBEUFIN_UI_IS_DEMO__ = 0;
// const __LIBEUFIN_UI_BANK_NAME__ = 0;

/**
 * FIXME:
 *
 * - INPUT elements have their 'required' attribute ignored.
 *
 * - the page needs a "home" button that either redirects to
 *   the profile page (when the user is logged in), or to
 *   the very initial home page.
 *
 * - histories 'pages' are grouped in UL elements that cause
 *   the rendering to visually separate each UL.  History elements
 *   should instead line up without any separation caused by
 *   a implementation detail.
 *
 * - Many strings need to be i18n-wrapped.
 */

/***********
 * Globals *
 **********/

/************
 * Contexts *
 ***********/
const CurrencyContext = createContext<any>(null);
const PageContext = createContext<any>(null);

/**********************************************
 * Type definitions for states and API calls. *
 *********************************************/

/**
 * Has the information to reach and
 * authenticate at the bank's backend.
 */
interface BackendStateType {
  url: string;
  username: string;
  password: string;
}

/**
 * Request body of POST /transactions.
 *
 * If the amount appears twice: both as a Payto parameter and
 * in the JSON dedicate field, the one on the Payto URI takes
 * precedence.
 */
interface TransactionRequestType {
  paytoUri: string;
  amount?: string; // with currency.
}

/**
 * Request body of /register.
 */
interface CredentialsRequestType {
  username: string;
  password: string;
}

/**
 * Request body of /register.
 */
interface LoginRequestType {
  username: string;
  password: string;
}

interface WireTransferRequestType {
  iban: string;
  subject: string;
  amount: string;
}

interface Amount {
  value: string;
  currency: string;
}

/**
 * Track page state.
 */
interface PageStateType {
  isLoggedIn: boolean;
  isRawPayto: boolean;
  tryRegister: boolean;
  tryManualTransfer: boolean;
  showPublicHistories: boolean;
  hasError: boolean;
  withdrawalInProgress: boolean;
  error?: string;
  talerWithdrawUri?: string;
  withdrawalOutcome?: string;
  transferOutcome?: string;
  /**
   * Not strictly a presentational value, could
   * be moved in a future "withdrawal state" object.
   */
  withdrawalId?: string;
}

/**
 * Bank account specific information.
 */
interface AccountStateType {
  balance: string;
  /* FIXME: Need history here.  */
}

/************
 * Helpers. *
 ***********/

function maybeDemoContent(content: VNode) {
  // @ts-ignore
  if (__LIBEUFIN_UI_IS_DEMO__) return content;
}

async function fetcher(url: string) {
  return fetch(url).then((r) => (r.json()));
}

function genCaptchaNumbers(): string {
  return `${Math.floor(Math.random() * 10)} + ${Math.floor(Math.random() * 10)}`;
}
/**
 * Bring the state to show the public accounts page.
 */
function goPublicAccounts(pageStateSetter: StateUpdater<PageStateType>) {
  return () => pageStateSetter((prevState) => ({...prevState, showPublicHistories: true}))
}

/**
 * Validate (the number part of) an amount.  If needed,
 * replace comma with a dot.  Returns 'false' whenever
 * the input is invalid, the valid amount otherwise.
 */
function validateAmount(maybeAmount: string): any {
  const amountRegex = '^[0-9]+(\.[0-9]+)?$';
  if (!maybeAmount) {
    console.log(`Entered amount (${maybeAmount}) mismatched <input> pattern.`);
    return;
  }
  if (typeof maybeAmount !== 'undefined' || maybeAmount !== '') {
    console.log(`Maybe valid amount: ${  maybeAmount}`);
    // tolerating comma instead of point.
    const re = RegExp(amountRegex)
    if (!re.test(maybeAmount)) {
      console.log(`Not using invalid amount '${maybeAmount}'.`);
      return false;
    }
  }
  return maybeAmount;
}

/**
 * Extract IBAN from a Payto URI.
 */
function getIbanFromPayto(url: string): string {
  const pathSplit = new URL(url).pathname.split('/');
  let lastIndex = pathSplit.length - 1;
  // Happens if the path ends with "/".
  if (pathSplit[lastIndex] === '') lastIndex--;
  const iban = pathSplit[lastIndex];
  return iban;
}

/**
 * Extract value and currency from a $currency:x.y amount.
 */
function parseAmount(val: string): Amount {
  const format = /^[A-Z]+:[0-9]+(\.[0-9]+)?$/;
  if (!format.test(val))
    throw Error(`Backend gave invalid amount: ${val}.`)
  const amountSplit = val.split(':');
  return {value: amountSplit[1], currency: amountSplit[0]}
}

/**
 * Get username from the backend state, and throw
 * exception if not found.
 */
function getUsername(backendState: BackendStateTypeOpt): string {
  if (typeof backendState === 'undefined') {
    throw Error('Username can\'t be found in a undefined backend state.')
  }
  return backendState.username;
}

/**
 * Helps extracting the credentials from the state
 * and wraps the actual call to 'fetch'.  Should be
 * enclosed in a try-catch block by the caller.
 */
async function postToBackend(
  uri: string,
  backendState: BackendStateTypeOpt,
  body: string
): Promise<any> {
  if (typeof backendState === 'undefined') {
    throw Error('Credentials can\'t be found in a undefined backend state.')
  }
  const { username, password } = backendState;
  const headers = prepareHeaders(username, password);
  // Backend URL must have been stored _with_ a final slash.
  const url = new URL(uri, backendState.url)
  return await fetch(url.href, {
    method: 'POST',
    headers,
    body,
  }
  );
}

function useTransactionPageNumber(): [number, StateUpdater<number>] {
  const ret = useNotNullLocalStorage('transaction-page', '0');
  const retObj = JSON.parse(ret[0]);
  const retSetter: StateUpdater<number> = function(val) {
    const newVal = val instanceof Function ? JSON.stringify(val(retObj)) : JSON.stringify(val)
    ret[1](newVal)
  }
  return [retObj, retSetter];
}

/**
 * Craft headers with Authorization and Content-Type.
 */
function prepareHeaders(username: string, password: string) {
  const headers = new Headers();
  headers.append(
    'Authorization',
    `Basic ${Buffer.from(`${username  }:${  password}`).toString('base64')}`
  );
  headers.append(
    'Content-Type',
    'application/json'
  )
  return headers;
}

// Window can be mocked this way:
// https://gist.github.com/theKashey/07090691c0a4680ed773375d8dbeebc1#file-webpack-conf-js
// That allows the app to be pointed to a arbitrary
// euFin backend when launched via "pnpm dev".
const getRootPath = () => {
  const maybeRootPath = typeof window !== undefined
    ? window.location.origin + window.location.pathname
    : '/';
  if (!maybeRootPath.endsWith('/')) return `${maybeRootPath  }/`;
  return maybeRootPath;
};

/*******************
 * State managers. *
 ******************/

/**
 * Stores in the state a object containing a 'username'
 * and 'password' field, in order to avoid losing the
 * handle of the data entered by the user in <input> fields.
 */
function useShowPublicAccount(
  state?: string
): [string | undefined, StateUpdater<string | undefined>] {

  const ret = useLocalStorage('show-public-account', JSON.stringify(state));
  const retObj: string | undefined = ret[0] ? JSON.parse(ret[0]) : ret[0];
  const retSetter: StateUpdater<string | undefined> = function(val) {
    const newVal = val instanceof Function ? JSON.stringify(val(retObj)) : JSON.stringify(val)
    ret[1](newVal)
  }
  return [retObj, retSetter]
}

/**
 * Stores the raw Payto value entered by the user in the state.
 */
type RawPaytoInputType = string;
type RawPaytoInputTypeOpt = RawPaytoInputType | undefined;
function useRawPaytoInputType(
  state?: RawPaytoInputType
): [RawPaytoInputTypeOpt, StateUpdater<RawPaytoInputTypeOpt>] {

  const ret = useLocalStorage('raw-payto-input-state', state);
  const retObj: RawPaytoInputTypeOpt = ret[0];
  const retSetter: StateUpdater<RawPaytoInputTypeOpt> = function(val) {
    const newVal = val instanceof Function ? val(retObj) : val
    ret[1](newVal)
  }
  return [retObj, retSetter]
}

/**
 * Stores in the state a object representing a wire transfer,
 * in order to avoid losing the handle of the data entered by
 * the user in <input> fields.  FIXME: name not matching the
 * purpose, as this is not a HTTP request body but rather the
 * state of the <input>-elements.
 */
type WireTransferRequestTypeOpt = WireTransferRequestType | undefined;
function useWireTransferRequestType(
  state?: WireTransferRequestType
): [WireTransferRequestTypeOpt, StateUpdater<WireTransferRequestTypeOpt>] {

  const ret = useLocalStorage('wire-transfer-request-state', JSON.stringify(state));
  const retObj: WireTransferRequestTypeOpt = ret[0] ? JSON.parse(ret[0]) : ret[0];
  const retSetter: StateUpdater<WireTransferRequestTypeOpt> = function(val) {
    const newVal = val instanceof Function ? JSON.stringify(val(retObj)) : JSON.stringify(val)
    ret[1](newVal)
  }
  return [retObj, retSetter]
}

/**
 * Stores in the state a object containing a 'username'
 * and 'password' field, in order to avoid losing the
 * handle of the data entered by the user in <input> fields.
 */
type CredentialsRequestTypeOpt = CredentialsRequestType | undefined;
function useCredentialsRequestType(
  state?: CredentialsRequestType
): [CredentialsRequestTypeOpt, StateUpdater<CredentialsRequestTypeOpt>] {

  const ret = useLocalStorage('credentials-request-state', JSON.stringify(state));
  const retObj: CredentialsRequestTypeOpt = ret[0] ? JSON.parse(ret[0]) : ret[0];
  const retSetter: StateUpdater<CredentialsRequestTypeOpt> = function(val) {
    const newVal = val instanceof Function ? JSON.stringify(val(retObj)) : JSON.stringify(val)
    ret[1](newVal)
  }
  return [retObj, retSetter]
}

/**
 * Return getters and setters for
 * login credentials and backend's
 * base URL.
 */
type BackendStateTypeOpt = BackendStateType | undefined;
function useBackendState(
  state?: BackendStateType
): [BackendStateTypeOpt, StateUpdater<BackendStateTypeOpt>] {

  const ret = useLocalStorage('backend-state', JSON.stringify(state));
  const retObj: BackendStateTypeOpt = ret[0] ? JSON.parse(ret[0]) : ret[0];
  const retSetter: StateUpdater<BackendStateTypeOpt> = function(val) {
    const newVal = val instanceof Function ? JSON.stringify(val(retObj)) : JSON.stringify(val)
    ret[1](newVal)
  }
  return [retObj, retSetter]
}

/**
 * Keep mere business information, like account balance or
 * transactions history.
 */
type AccountStateTypeOpt = AccountStateType | undefined;
function useAccountState(
  state?: AccountStateType
): [AccountStateTypeOpt, StateUpdater<AccountStateTypeOpt>] {

  const ret = useLocalStorage('account-state', JSON.stringify(state));
  const retObj: AccountStateTypeOpt = ret[0] ? JSON.parse(ret[0]) : ret[0];
  const retSetter: StateUpdater<AccountStateTypeOpt> = function(val) {
    const newVal = val instanceof Function ? JSON.stringify(val(retObj)) : JSON.stringify(val)
    ret[1](newVal)
  }
  return [retObj, retSetter]
}

/**
 * Wrapper providing defaults.
 */
function usePageState(
  state: PageStateType = {
    isLoggedIn: false,
    isRawPayto: false,
    tryRegister: false,
    tryManualTransfer: false,
    showPublicHistories: false,
    hasError: false,
    withdrawalInProgress: false,
  }
): [PageStateType, StateUpdater<PageStateType>] {
  const ret = useNotNullLocalStorage('page-state', JSON.stringify(state));
  const retObj: PageStateType = JSON.parse(ret[0]);
  console.log('Current page state', retObj);
  const retSetter: StateUpdater<PageStateType> = function(val) {
    const newVal = val instanceof Function ? JSON.stringify(val(retObj)) : JSON.stringify(val)
    console.log('Setting new page state', newVal)
    ret[1](newVal)
  }
  return [retObj, retSetter];
}

/**
 * Request preparators.
 *
 * These functions aim at sanitizing the input received
 * from users - for example via a HTML form - and create
 * a HTTP request object out of that.
 */

/******************
 * HTTP wrappers. *
 *****************/

/**
 * A 'wrapper' is typically a function that prepares one
 * particular API call and updates the state accordingly.  */

/**
 * Abort a withdrawal operation via the Access API's /abort.
 */
async function abortWithdrawalCall(
  backendState: BackendStateTypeOpt,
  withdrawalId: string | undefined,
  pageStateSetter: StateUpdater<PageStateType>
) {
  if (typeof backendState === 'undefined') {
    console.log('No credentials found.');
    pageStateSetter((prevState) => ({...prevState, hasError: true, error: 'No credentials found.'}))
    return;
  }
  if (typeof withdrawalId === 'undefined') {
    console.log('No withdrawal ID found.');
    pageStateSetter((prevState) => ({...prevState, hasError: true, error: 'No withdrawal ID found.'}))
    return;
  }

  try {
    const { username, password } = backendState;
    const headers = prepareHeaders(username, password);
    /**
     * NOTE: tests show that when a same object is being
     * POSTed, caching might prevent same requests from being
     * made.  Hence, trying to POST twice the same amount might
     * get silently ignored.  Needs more observation!
     *
     * headers.append("cache-control", "no-store");
     * headers.append("cache-control", "no-cache");
     * headers.append("pragma", "no-cache");
     * */

    // Backend URL must have been stored _with_ a final slash.
    const url = new URL(
      `access-api/accounts/${backendState.username}/withdrawals/${withdrawalId}/abort`,
      backendState.url
    )
    var res = await fetch(url.href, {method: 'POST', headers})
  } catch (error) {
    console.log('Could not abort the withdrawal', error);
    pageStateSetter((prevState) => ({
      ...prevState,
      hasError: true,
      error: `Could not abort the withdrawal: ${error}`}))
    return;
  }
  if (!res.ok) {
    console.log(`Withdrawal abort gave response error (${res.status})`, res.statusText);
    pageStateSetter((prevState) => ({
      ...prevState,
      hasError: true,
      error: `Withdrawal abortion gave response error (${res.status})`}))
    return;
  } 
  console.log('Withdrawal operation aborted!');
  pageStateSetter((prevState) => {
    const { talerWithdrawUri, withdrawalId, ...rest } = prevState;
    return {
      ...rest,
      withdrawalOutcome: 'Withdrawal aborted!'
    }})
  
}

/**
 * This function confirms a withdrawal operation AFTER
 * the wallet has given the exchange's payment details
 * to the bank (via the Integration API).  Such details
 * can be given by scanning a QR code or by passing the
 * raw taler://withdraw-URI to the CLI wallet.
 *
 * This function will set the confirmation status in the
 * 'page state' and let the related components refresh.
 */
async function confirmWithdrawalCall(
  backendState: BackendStateTypeOpt,
  withdrawalId: string | undefined,
  pageStateSetter: StateUpdater<PageStateType>
) {

  if (typeof backendState === 'undefined') {
    console.log('No credentials found.');
    pageStateSetter((prevState) => ({...prevState, hasError: true, error: 'No credentials found.'}))
    return;
  }
  if (typeof withdrawalId === 'undefined') {
    console.log('No withdrawal ID found.');
    pageStateSetter((prevState) => ({...prevState, hasError: true, error: 'No withdrawal ID found.'}))
    return;
  }

  try {
    const { username, password } = backendState;
    const headers = prepareHeaders(username, password);
    /**
     * NOTE: tests show that when a same object is being
     * POSTed, caching might prevent same requests from being
     * made.  Hence, trying to POST twice the same amount might
     * get silently ignored.
     *
     * headers.append("cache-control", "no-store");
     * headers.append("cache-control", "no-cache");
     * headers.append("pragma", "no-cache");
     * */

    // Backend URL must have been stored _with_ a final slash.
    const url = new URL(
      `access-api/accounts/${backendState.username}/withdrawals/${withdrawalId}/confirm`,
      backendState.url
    )
    var res = await fetch(url.href, {
      method: 'POST',
      headers
    })
  } catch (error) {
    console.log('Could not POST withdrawal confirmation to the bank', error);
    pageStateSetter((prevState) => ({
      ...prevState,
      hasError: true,
      error: `Could not confirm the withdrawal: ${error}`}))
    return;
  }
  if (!res.ok) {
    console.log(`Withdrawal confirmation gave response error (${res.status})`, res.statusText);
    pageStateSetter((prevState) => ({
      ...prevState,
      hasError: true,
      error: `Withdrawal confirmation gave response error (${res.status})`}))
    return;
  } 
  console.log('Withdrawal operation confirmed!');
  pageStateSetter((prevState) => {
    const { talerWithdrawUri, ...rest } = prevState;
    return {
      ...rest,
      withdrawalOutcome: 'Withdrawal confirmed!'
    }})
  
}

/**
 * This function creates a new transaction.  It reads a Payto
 * address entered by the user and POSTs it to the bank.  No
 * sanity-check of the input happens before the POST as this is
 * already conducted by the backend.
 */
async function createTransactionCall(
  req: TransactionRequestType,
  backendState: BackendStateTypeOpt,
  pageStateSetter: StateUpdater<PageStateType>,
  /**
   * Optional since the raw payto form doesn't have
   * a stateful management of the input data yet.
   */
  submitDataSetter?: StateUpdater<any>
) {
  try {
    var res = await postToBackend(
      `access-api/accounts/${getUsername(backendState)}/transactions`,
      backendState,
      JSON.stringify(req)
    )
  }
  catch (error) {
    console.log('Could not POST transaction request to the bank', error);
    pageStateSetter((prevState) => ({
      ...prevState,
      hasError: true,
      error: `Could not create the wire transfer: ${error}`}))
    return;
  }
  // POST happened, status not sure yet.
  if (!res.ok) {
    const responseText = JSON.stringify(await res.json());
    console.log(`Transfer creation gave response error: ${responseText} (${res.status})`);
    pageStateSetter((prevState) => ({
      ...prevState,
      hasError: true,
      error: `Transfer creation gave response error: ${responseText} (${res.status})`}))
    return;
  }
  // status is 200 OK here, tell the user.
  console.log('Wire transfer created!');
  pageStateSetter((prevState) => ({
    ...prevState,
    transferOutcome: 'Wire transfer created!'
  }))
  // Only at this point the input data can
  // be discarded.
  if (submitDataSetter) submitDataSetter(undefined);
}

/**
 * This function creates a withdrawal operation via the Access API.
 *
 * After having successfully created the withdrawal operation, the
 * user should receive a QR code of the "taler://withdraw/" type and
 * supposed to scan it with their phone.
 *
 * TODO: (1) after the scan, the page should refresh itself and inform
 * the user about the operation's outcome.  (2) use POST helper.  */
async function createWithdrawalCall(
  amount: string,
  backendState: BackendStateTypeOpt,
  pageStateSetter: StateUpdater<PageStateType>
) {
  if (typeof backendState === 'undefined') {
    console.log('Page has a problem: no credentials found in the state.');
    pageStateSetter((prevState) => ({...prevState, hasError: true, error: 'No credentials given.'}))
    return;
  }
  try {
    const { username, password } = backendState;
    const headers = prepareHeaders(username, password);

    // Let bank generate withdraw URI:
    const url = new URL(
      `access-api/accounts/${backendState.username}/withdrawals`,
      backendState.url
    )
    var res = await fetch(url.href, {
      method: 'POST',
      headers,
      body: JSON.stringify({amount}),
    }
    );
  } catch (error) {
    console.log('Could not POST withdrawal request to the bank', error);
    pageStateSetter((prevState) => ({
      ...prevState,
      hasError: true,
      error: `Could not create withdrawal operation: ${error}`}))
    return;
  }
  if (!res.ok) {
    const responseText = await res.text();
    console.log(`Withdrawal creation gave response error: ${responseText} (${res.status})`);
    pageStateSetter((prevState) => ({
      ...prevState,
      hasError: true,
      error: `Withdrawal creation gave response error: ${responseText} (${res.status})`}))
    return;
  }

  console.log('Withdrawal operation created!');
  const resp = await res.json();
  pageStateSetter((prevState: PageStateType) => ({
    ...prevState,
    withdrawalInProgress: true,
    talerWithdrawUri: resp.taler_withdraw_uri,
    withdrawalId: resp.withdrawal_id}))
}

async function loginCall(
  req: CredentialsRequestType,
  /**
   * FIXME: figure out if the two following
   * functions can be retrieved from the state.
   */
  backendStateSetter: StateUpdater<BackendStateTypeOpt>,
  pageStateSetter: StateUpdater<PageStateType>
) {

  /**
   * Optimistically setting the state as 'logged in', and
   * let the Account component request the balance to check
   * whether the credentials are valid.  */
  pageStateSetter((prevState) => ({ ...prevState, isLoggedIn: true }));
  let baseUrl = getRootPath();
  if (!baseUrl.endsWith('/')) {
    baseUrl += '/';
  }
  backendStateSetter((prevState) => ({
    ...prevState,
    url: baseUrl,
    username: req.username,
    password: req.password,
  }));
}


/**
 * This function requests /register.
 *
 * This function is responsible to change two states:
 * the backend's (to store the login credentials) and
 * the page's (to indicate a successful login or a problem).
 */
async function registrationCall(
  req: CredentialsRequestType,
  /**
   * FIXME: figure out if the two following
   * functions can be retrieved somewhat from
   * the state.
   */
  backendStateSetter: StateUpdater<BackendStateTypeOpt>,
  pageStateSetter: StateUpdater<PageStateType>
) {

  let baseUrl = getRootPath();
  /**
   * If the base URL doesn't end with slash and the path
   * is not empty, then the concatenation made by URL()
   * drops the last path element.
   */
  if (!baseUrl.endsWith('/')) {
    baseUrl += '/'
  }
  const headers = new Headers();
  headers.append(
    'Content-Type',
    'application/json'
  )
  const url = new URL('access-api/testing/register', baseUrl)
  try {
    var res = await fetch(url.href, {
      method: 'POST',
      body: JSON.stringify(req),
      headers
    });
  } catch (error) {
    console.log(`Could not POST new registration to the bank (${url.href})`, error);
    pageStateSetter((prevState) => ({
      ...prevState, hasError: true, error: 'Registration failed, please report.'
    }));
    return;
  }
  if (!res.ok) {
    const errorRaw = await res.text();
    console.log(`New registration gave response error (${res.status})`, errorRaw);
    pageStateSetter((prevState) => ({
      ...prevState,
      hasError: true,
      error: errorRaw
    }));
  } else {
    pageStateSetter((prevState) => ({
      ...prevState,
      isLoggedIn: true,
      tryRegister: false
    }));
    backendStateSetter((prevState) => ({
      ...prevState,
      url: baseUrl,
      username: req.username,
      password: req.password,
    }));
  }
}

/**************************
 * Functional components. *
 *************************/

function Currency(): VNode {
  const { data, error } = useSWR(`${getRootPath()}integration-api/config`, fetcher);
  if (typeof error !== 'undefined') {
    return <b>error: currency could not be retrieved</b>;
  }
  if (typeof data === 'undefined') return <Fragment>"..."</Fragment>;
  console.log('found bank config', data);
  return data.currency;
}

function ErrorBanner(Props: any): VNode | null {
  const [pageState, pageStateSetter] = Props.pageState;
  const i18n = useTranslator();
  if (!pageState.hasError) return null;
  return (
    <p class="informational informational-fail">{pageState.error}
      &nbsp;&nbsp;<a href="#" onClick={() => {
        pageStateSetter((prevState: PageStateType) => {
          delete prevState.error; // delete error message
	  return {...prevState, hasError: false} // delete error state
        })}}>
        {i18n`Clear`}
      </a>
    </p>);
}

function BankFrame(Props: any): VNode {
  const i18n = useTranslator();
  const [pageState, pageStateSetter] = useContext(PageContext);
  console.log('BankFrame state', pageState);
  const logOut = (
    <a
      href="#"
      class="pure-button logout-button"
      onClick={() => {
        pageStateSetter((prevState: PageStateType) => {
          const {
            talerWithdrawUri,
            withdrawalOutcome,
            transferOutcome,
            withdrawalId, ...rest } = prevState;
          return {
            ...rest,
            isLoggedIn: false,
            withdrawalInProgress: false,
            isRawPayto: false,
            tryManualTransfer: false,
          };
        });
      }}>{i18n`Logout`}</a>);

  // Prepare demo sites links.
  const DEMO_SITES = [
    ['Landing', '__DEMO_SITE_LANDING_URL__'],
    ['Bank', '__DEMO_SITE_BANK_URL__'],
    ['Blog', '__DEMO_SITE_BLOG_URL__'],
    ['Donations', '__DEMO_SITE_DONATIONS_URL__'],
    ['Survey', '__DEMO_SITE_SURVEY_URL__'],
  ];
  const demo_sites = [];
  for (const i in DEMO_SITES) {
    demo_sites.push(<a href={DEMO_SITES[i][1]}>{DEMO_SITES[i][0]}</a>)
  }
  return (
    <Fragment>
      <header class="demobar" style="display: flex; flex-direction: row; justify-content: space-between;">
        <div style="max-width: 50em; margin-left: 2em;">
          <h1>
            <span class="it">
              <a href="/">__LIBEUFIN_UI_BANK_NAME__</a>
            </span>
          </h1>{
            maybeDemoContent(<p><Translate>
              This part of the demo shows how a bank that supports
  	      Taler directly would work. In addition to using your own
  	      bank account, you can also see the transaction history of
  	      some <a href="#" onClick={goPublicAccounts(pageStateSetter)}>Public Accounts</a>.
  	      </Translate></p>
	    )
	  }
        </div>
        <a href="https://taler.net/">
          <img
            src={talerLogo}
  	  height="100"
  	  width="224"
  	  style="margin: 2em 2em" />
        </a>
      </header>
      <div style="display:flex; flex-direction: column;" class="navcontainer">
        <nav class="demolist">
          {maybeDemoContent(<Fragment>{demo_sites}</Fragment>)}
          <div class="right">
            <LangSelector />
  	  </div>
        </nav>
      </div>
      <section id="main" class="content">
        <ErrorBanner pageState={[pageState, pageStateSetter]} />
        {pageState.isLoggedIn ? logOut : null}
        {Props.children}
        <hr />
        <div>
          <p>You can learn more about GNU Taler on our <a href="https://taler.net">main website</a>.</p>
        </div>
        <div style="flex-grow:1" />
        <p>Copyright &copy; 2014&mdash;2022 Taler Systems SA</p>
      </section>
    </Fragment>);
}

function PaytoWireTransfer(Props: any): VNode {
  const currency = useContext(CurrencyContext);
  const [pageState, pageStateSetter] = useContext(PageContext); // NOTE: used for go-back button?
  const [submitData, submitDataSetter] = useWireTransferRequestType();
  const [rawPaytoInput, rawPaytoInputSetter] = useRawPaytoInputType();
  const i18n = useTranslator();
  const amountRegex = '^[0-9]+(\.[0-9]+)?$';
  const ibanRegex = '^[A-Z][A-Z][0-9]+$';
  const amountInput = '';
  const receiverInput = '';
  const subjectInput = '';
  let transactionData: TransactionRequestType;
  const focusInput = useRef(null);
  useEffect(() => {
    console.log('Now focus', focusInput);
    if (focusInput.current) {
      // @ts-ignore
      focusInput.current.focus();
    }
  }, []);
  console.log('wire form page state', pageState);
  const goBackForm = <a href="#" onClick={
    () => {
      pageStateSetter((prevState: PageStateType) => ({...prevState, tryManualTransfer: false}))
      submitDataSetter(undefined)
    }
  }>{i18n`Go back`}</a>;
  const goBackRawPayto = <a href="#" onClick={
    () => {
      pageStateSetter((prevState: PageStateType) => ({...prevState, isRawPayto: false}))
      rawPaytoInputSetter(undefined)
    }

  }>{i18n`Go back`}</a>;
  if (!pageState.isRawPayto) {
    console.log('wire transfer form');
    return (<article>
      <div>
        <h2>{i18n`Wire transfer`}</h2>
        <p>{i18n`Transfer money to another account of this bank:`}<br /><br /></p>
        <div name="wire-transfer-form">
          <input
            ref={focusInput}
            type="text"
            placeholder="receiver iban"
	    required
            pattern={ibanRegex}
            onInput={(e): void => {
              submitDataSetter((submitData: any) => ({
                ...submitData,
                iban: e.currentTarget.value,
              }))}} /><br /><br />
          <input
            type="text"
            placeholder="subject"
            required
            onInput={(e): void => {
              submitDataSetter((submitData: any) => ({
                ...submitData,
                subject: e.currentTarget.value,
              }))}} /><br /><br />
          <input
            type="text"
            placeholder="amount"
            required
            value={
              typeof submitData !== 'undefined'
                && typeof submitData.amount !== 'undefined' ? submitData.amount : ''
            }
            pattern={amountRegex}
            onInput={(e): void => {
              submitDataSetter((submitData: any) => ({
                ...submitData,
                amount: e.currentTarget.value.replace(',', '.'),
              }))}} />&nbsp;<label>{currency}</label><br /><br />
          <input
            type="submit"
            value="Send"
            onClick={() => {
              if (
                typeof submitData === 'undefined'
                || (typeof submitData.iban === 'undefined'
                  || submitData.iban === '')
                || (typeof submitData.subject === 'undefined'
                  || submitData.subject === '')
                || (typeof submitData.amount === 'undefined'
                  || submitData.amount === '')
              ) {
                console.log('Not all the fields were given.');
                pageStateSetter((prevState: PageStateType) =>
                  ({...prevState, hasError: true, error: 'Field(s) missing.'}))
                return;
              }
              transactionData = {
                paytoUri: `payto://iban/${submitData.iban}?message=${encodeURIComponent(submitData.subject)}`,
                amount: `${currency}:${submitData.amount}`
              };
              createTransactionCall(
                transactionData,
                Props.backendState,
                pageStateSetter,
                submitDataSetter // need here only to be cleaned.
              );
            }}  />
        </div>
        <p><a
          href="#"
          onClick={() => {
	    console.log('switch to raw payto form');
            pageStateSetter((prevState: any) => ({...prevState, isRawPayto: true}));
	  }}>{i18n`Want to try the raw payto://-format?`}
        </a></p>
      </div>
      {goBackForm}
    </article>);
  }
  console.log('rendering raw payto form');
  return (<article>
    <div>
      <h2>{i18n`Wire transfer`}</h2>
      <p>{i18n`Transfer money via the Payto system:`}<br /><br />
        Address pattern: <code style="font-size: 15px">
	  payto://iban/[receiver-iban]?message=[subject]&amount=[{currency}:X.Y]
        </code>
      </p>
      <div name="payto-form">
        <input name="address"
          size={90}
          value={rawPaytoInput}
          required
          placeholder={i18n`payto address`}
          pattern={`payto://iban/[A-Z][A-Z][0-9]+\?message=[a-zA-Z0-9 ]+&amount=${currency}:[0-9]+(\.[0-9]+)?`}
          onInput={(e): void => {
            rawPaytoInputSetter(e.currentTarget.value)
          }} />
        <input class="pure-button pure-button-primary"
          type="submit"
          value={i18n`Confirm`}
  	       onClick={() => {
            // empty string evaluates to false.
            if (!rawPaytoInput) {
              console.log('Didn\'t get any raw Payto string!');
              return;
            }
            transactionData = {paytoUri: rawPaytoInput};
            if (typeof transactionData.paytoUri === 'undefined' ||
                     transactionData.paytoUri.length === 0) return;
            createTransactionCall(
              transactionData,
              Props.backendState,
              pageStateSetter,
              rawPaytoInputSetter);
          }} />
      </div>
    </div>
    <p>{goBackRawPayto}</p>
  </article>);
}

/**
 * Additional authentication required to complete the operation.
 * Not providing a back button, only abort.
 */
function TalerWithdrawalConfirmationQuestion(Props: any): VNode {
  const [pageState, pageStateSetter] = useContext(PageContext);
  const { backendState } = Props;
  const i18n = useTranslator();
  const captchaNumbers = {
    a: Math.floor(Math.random() * 10),
    b: Math.floor(Math.random() * 10)
  }
  let captchaAnswer = '';

  return (<Fragment>
    <h1 class="nav">{i18n`Confirm Withdrawal`}</h1>
    <p><Translate>
      Please, authorize this operation by answering the following question.
    </Translate></p>
    <div>
      <label>What is <em>{captchaNumbers.a} + {captchaNumbers.b}</em> ?&nbsp;</label>
      <input
        type="text"
        required
        onInput={(e): void => {
          captchaAnswer = e.currentTarget.value;
        }} />
      <input
        type="submit"
        value="confirm"
        onClick={ () => {
          if (captchaAnswer == (captchaNumbers.a + captchaNumbers.b).toString()) {
            confirmWithdrawalCall(
              backendState,
              pageState.withdrawalId,
              pageStateSetter)
	    return;
	  }
          pageStateSetter((prevState: PageStateType) =>
	    ({...prevState, hasError: true, error: 'Answer is wrong.'}))
        }} />
      <input
        type="submit"
        value="abort"
        onClick={ () =>
	  abortWithdrawalCall(
            backendState,
            pageState.withdrawalId,
            pageStateSetter
	  )} />
    </div>
    <p><Translate>
      A this point, a <b>real</b> bank would ask for an additional
      authentication proof (PIN/TAN, one time password, ..), instead
      of a simple calculation.
    </Translate></p>
  </Fragment>);
}

function QrCodeSection({talerWithdrawUri, abortButton}:{talerWithdrawUri:string, abortButton: h.JSX.Element}) {
  const i18n = useTranslator();
  useEffect(() => {
    //Taler Wallet WebExtension is listening to headers response and tab updates.
    //In the SPA there is no header response with the Taler URI so
    //this hack manually triggers the tab update after the QR is in the DOM.
    window.location.href = `${window.location.href.split('#')[0]  }#`
  },[])

  return <section id="main" class="content">
    <h1 class="nav">{i18n`Withdraw to a Taler Wallet`}</h1>
    <p>{i18n`You can use this QR code to withdraw to your mobile wallet:`}</p>
    {QR({text: talerWithdrawUri})}
    <p>Click <a id="linkqr" href={talerWithdrawUri}>{i18n`this link`}</a> to open your Taler wallet!</p>
    <br />
    {abortButton}
  </section>
}

/**
 * Offer the QR code (and a clickable taler://-link) to
 * permit the passing of exchange and reserve details to
 * the bank.  Poll the backend until such operation is done.
 */
function TalerWithdrawalQRCode(Props: any): VNode {
  // turns true when the wallet POSTed the reserve details:
  const [pageState, pageStateSetter] = useContext(PageContext);
  const {
    withdrawalId,
    talerWithdrawUri,
    accountLabel,
    backendState } = Props;
  const i18n = useTranslator();
  const abortButton = <a class="pure-button" onClick={() => {
    pageStateSetter((prevState: PageStateType) => {
      const { withdrawalOutcome, withdrawalId, talerWithdrawUri, ...rest } = prevState;
      return { ...rest, withdrawalInProgress: false };
    })}}>{i18n`Abort`}</a>

  console.log(`Showing withdraw URI: ${talerWithdrawUri}`);
  // waiting for the wallet:

  const { data, error, mutate } = useSWR(`integration-api/withdrawal-operation/${withdrawalId}`);

  if (typeof error !== 'undefined') {
    console.log(`withdrawal (${withdrawalId}) was never (correctly) created at the bank...`, error);
    pageStateSetter((prevState: PageStateType) => ({
      ...prevState,
      hasError: true,
      error: i18n`withdrawal (${withdrawalId}) was never (correctly) created at the bank...`
    }))
    return (<Fragment><br /><br />{abortButton}</Fragment>);
  }

  // data didn't arrive yet and wallet didn't communicate:
  if (typeof data === 'undefined') {
    return <p>{i18n`Waiting the bank to create the operaion...`}</p>
  }

  /**
   * Wallet didn't communicate withdrawal details yet:
   */
  console.log('withdrawal status', data);
  if (data.aborted) {
    pageStateSetter((prevState: PageStateType) => {
      const {
        withdrawalOutcome,
        withdrawalId,
        talerWithdrawUri,
        ...rest } = prevState;
      return {
        ...rest,
        withdrawalInProgress: false,
        hasError: true,
        error: i18n`This withdrawal was aborted!`
      };
    })
  }

  if (!data.selection_done) {
    setTimeout(() => mutate(), 1000); // check again after 1 second.
    return (<QrCodeSection talerWithdrawUri={talerWithdrawUri} abortButton={abortButton} />);
  }
  /**
   * Wallet POSTed the withdrawal details!  Ask the
   * user to authorize the operation (here CAPTCHA).
   */
  return (<TalerWithdrawalConfirmationQuestion backendState={backendState} />);
}

/**
 * Let the user choose an amount and submit the withdtawal.
 */
function TalerWithdrawal(Props: any): VNode {
  const {backendState, pageStateSetter} = Props;
  const currency = useContext(CurrencyContext);
  const i18n = useTranslator();
  let submitAmount = '5.00'; // must match the first <select> child.
  // const amountRegex = "^[0-9]+(\.[0-9]+)?$"; // currently unused

  const submitButton = <input
    id="select-exchange"
    class="pure-button pure-button-primary"
    type="submit"
    value={i18n`Start withdrawal`}
    onClick={() => {
      submitAmount = validateAmount(submitAmount);
      /**
       * By invalid amounts, the validator prints error messages
       * on the console, and the browser colourizes the amount input
       * box to indicate a error.
       */
      if (!submitAmount) return;
      createWithdrawalCall(
        `${currency}:${submitAmount}`,
        backendState,
        pageStateSetter
      )}} />;

  return (<article>
    <div>
      <h2>{i18n`Withdraw Money into a Taler wallet`}</h2>
      <div id="reserve-form"
        class="pure-form"
        name="tform">
        {i18n`Amount to withdraw`}:&nbsp;
        <select id="reserve-amount"
	          name="withdraw-amount"
	          class="amount" autofocus
          onChange={(e): void => {
		    submitAmount = e.currentTarget.value; }}>
          <option value="5.00">5.00</option>
          <option value="10.00">10.00</option>
          <option value="15.00">15.00</option>
          <option value="20.00">20.00</option>
        </select>
        <input
	      type="text"
	      readonly
	      class="currency-indicator"
	      size={currency.length}
	      tabIndex={-1} value={currency} />
	  &nbsp;{submitButton}
      </div>
    </div>
  </article>);
}

/**
 * Collect and submit login data.
 */
function LoginForm(Props: any): VNode {
  const {backendStateSetter, pageStateSetter} = Props;
  const [submitData, submitDataSetter] = useCredentialsRequestType();
  const i18n = useTranslator();
  // FIXME: try removing the outer Fragment.
  return (<form action="javascript:void(0);" class="login-form">
    <h2>{i18n`Please login!`}</h2>
    <div class="pure-form">
      <input
        type="text"
        value={submitData && submitData.username}
        placeholder="username"
        required
        onInput={(e): void => {
          submitDataSetter((submitData: any) => ({
            ...submitData,
            username: e.currentTarget.value,
          }))}} />
      <input
        type="password"
        value={submitData && submitData.password}
        placeholder="password"
        required
        onInput={(e): void => {
	  submitDataSetter((submitData: any) => ({
            ...submitData,
            password: e.currentTarget.value,
          }))}} />
      <button
        autofocus
        type="submit"
        class="pure-button pure-button-primary"
        onClick={() => {
	  if (typeof submitData === 'undefined') {
            console.log('login data is undefined', submitData);
            return;
          }
          if (submitData.password.length == 0 || submitData.username.length == 0) {
            console.log('username or password is the empty string', submitData);
            return;
          }
          loginCall(
            // Deep copy, to avoid the cleanup
            // below make data disappear.
            {...submitData},
            backendStateSetter,
            pageStateSetter
          );
          submitDataSetter(undefined);
        }}>{i18n`Login`}</button>
    </div>
  </form>);
}

/**
 * Collect and submit registration data.
 */
function RegistrationForm(Props: any): VNode {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [pageState, pageStateSetter] = useContext(PageContext);
  const [submitData, submitDataSetter] = useCredentialsRequestType();
  const i18n = useTranslator();
  // https://stackoverflow.com/questions/36683770/how-to-get-the-value-of-an-input-field-using-reactjs
  return (
    <Fragment>
      <h1 class="nav">{i18n`Registration form`}</h1>
      <aside class="sidebar" id="left" />
      <article>
        <div class="register-form">
          <form action="javascript:void(0);" class="pure-form">
            {i18n`Username:`}
            <input
              type="text"
              placeholder="username"
              value={submitData && submitData.username}
              required
              autofocus
              onInput={(e): void => {
		  submitDataSetter((submitData: any) => ({
                  ...submitData,
                  username: e.currentTarget.value,
                }))}} />
            <br />
            {i18n`Password:`}
            <input
              type="password"
              placeholder="password"
              value={submitData && submitData.password}
              required
              autofocus
              onInput={(e): void => {
		  submitDataSetter((submitData: any) => ({
                  ...submitData,
                  password: e.currentTarget.value,
                }))}} />
            <br />
            {/*
              {i18n`Phone number:`}
              // FIXME: add input validation (must start with +, otherwise only numbers)
              <input
                type="phone"
                placeholder="+CC-123456789"
                value={submitData && submitData.phone}
                required
                autofocus
                onInput={(e): void => {
		  submitDataSetter((submitData: any) => ({
                    ...submitData,
                    phone: e.currentTarget.value,
                  }))}} />
              <br />
              */}
            <button
	        autofocus
              class="pure-button pure-button-primary"
              onClick={() => {
		  console.log('maybe submitting the registration..');
		  console.log(submitData);
		  if (typeof submitData === 'undefined') {
                  console.log(`submit data ${submitData} is undefined`);
                  return;
                }
	          if ((typeof submitData.password === 'undefined') ||
		      (typeof submitData.username === 'undefined')) {
                  console.log('username or password is undefined');
                  return;
                }
		  if (submitData.password.length === 0 ||
		    submitData.username.length === 0) {
                  console.log('username or password are the empty string');
                  return;
                }
		  console.log('submitting the registration..');
                registrationCall(
                  {...submitData},
                  Props.backendStateSetter, // will store BE URL, if OK.
                  pageStateSetter
                );
                console.log('Clearing the input data');
                /**
                   * FIXME: clearing the data should be done by setting
                   * it to undefined, instead of the empty strings, just
                   * like done in the login function.  Now set to the empty
                   * strings due to a non lively update of the <input> fields
                   * after setting to undefined.
                   */
                submitDataSetter({username: '', password: ''})}}>{i18n`Register`}</button>
              // FIXME: should use a different color
            <button
	        autofocus
              class="pure-button pure-button-primary"
              onClick={() => {
                pageStateSetter((prevState: PageStateType) =>({...prevState, tryRegister: false}))}}>
              {i18n`cancel`}</button>

          </form>
        </div>
      </article>
    </Fragment>
  )
}

/**
 * Show one page of transactions.
 */
function Transactions(Props: any): VNode {
  const { pageNumber, accountLabel } = Props;
  const i18n = useTranslator();
  const { data, error } = useSWR(
    `access-api/accounts/${accountLabel}/transactions?page=${pageNumber}`
  );
  if (typeof error !== 'undefined') {
    console.log('transactions not found error', error);
    switch(error.status) {
    case 404: {
      return <p>Transactions page {pageNumber} was not found.</p>
    }
    case 401: {
      return <p>Wrong credentials given.</p>
    }
    default: {
      return <p>Transaction page {pageNumber} could not be retrieved.</p>
    }
    }
  }
  if (!data) {
    console.log(`History data of ${accountLabel} not arrived`);
    return <p>"Transactions page loading..."</p>;
  }
  console.log(`History data of ${accountLabel}`, data);
  return (<div class="results">
    <table class="pure-table pure-table-striped">
      <thead>
        <tr>
          <th>{i18n`Date`}</th>
          <th>{i18n`Amount`}</th>
          <th>{i18n`Counterpart`}</th>
          <th>{i18n`Subject`}</th>
        </tr>
      </thead>
      <tbody>
        {data.transactions.map((item: any) => {
          const sign = item.direction == 'DBIT' ? '-' : '';
          const counterpart = item.direction == 'DBIT' ? item.creditorIban : item.debtorIban;
          // Pattern:
          //
          // DD/MM YYYY subject -5 EUR
          // DD/MM YYYY subject 5 EUR
          const dateRegex = /^([0-9]{4})-([0-9]{2})-([0-9]{1,2})/
          const dateParse = dateRegex.exec(item.date)
          const date = dateParse !== null ? `${dateParse[3]}/${dateParse[2]} ${dateParse[1]}` : 'date not found'
          return (<tr>
            <td>{date}</td>
            <td>{sign}{item.amount} {item.currency}</td>
            <td>{counterpart}</td>
            <td>{item.subject}</td>
          </tr>);
        })}
      </tbody>
    </table>
  </div>);
}

/**
 * Show only the account's balance.  NOTE: the backend state
 * is mostly needed to provide the user's credentials to POST
 * to the bank.
 */
function Account(Props: any): VNode {
  const { cache } = useSWRConfig();
  const { accountLabel, backendState } = Props;
  // Getting the bank account balance:
  const endpoint = `access-api/accounts/${accountLabel}`;
  const { data, error } = useSWR(endpoint);
  const [pageState, pageStateSetter] = useContext(PageContext);
  const {
    withdrawalInProgress,
    tryManualTransfer,
    withdrawalOutcome,
    transferOutcome,
    withdrawalId,
    isLoggedIn,
    talerWithdrawUri } = pageState;
  const i18n = useTranslator();
  /**
   * This part shows a list of transactions: with 5 elements by
   * default and offers a "load more" button.
   */
  const [txPageNumber, setTxPageNumber] = useTransactionPageNumber()
  const txsPages = []
  for (let i = 0; i <= txPageNumber; i++) {
    txsPages.push(<Transactions accountLabel={accountLabel} pageNumber={i} />)
  }
  if (typeof error !== 'undefined') {
    console.log('account error', error);
    /**
     * FIXME: to minimize the code, try only one invocation
     * of pageStateSetter, after having decided the error
     * message in the case-branch.
     */
    switch(error.status) {
    case 404: {
      pageStateSetter((prevState: PageStateType) => ({
        ...prevState,
        hasError: true,
        isLoggedIn: false,
        error: i18n`Username or account label '${accountLabel}' not found.  Won't login.`
      }));

      /**
	 * 404 should never stick to the cache, because they
	 * taint successful future registrations.  How?  After
	 * registering, the user gets navigated to this page,
	 * therefore a previous 404 on this SWR key (the requested
	 * resource) would still appear as valid and cause this
	 * page not to be shown! A typical case is an attempted
	 * login of a unregistered user X, and then a registration
	 * attempt of the same user X: in this case, the failed
	 * login would cache a 404 error to X's profile, resulting
	 * in the legitimate request after the registration to still
	 * be flagged as 404.  Clearing the cache should prevent
	 * this.  */
      (cache as any).clear();
      return <p>Profile not found...</p>;
    }
    case 401: {
      pageStateSetter((prevState: PageStateType) => ({
        ...prevState,
        hasError: true,
        isLoggedIn: false,
	  error: i18n`Wrong credentials given.`
      }));
      return <p>Wrong credentials...</p>;
    }
    default: {
      pageStateSetter((prevState: PageStateType) => ({
        ...prevState,
        hasError: true,
        isLoggedIn: false,
	  error: i18n`Account information could not be retrieved.`
      }));
      return <p>Unknown problem...</p>;
    }
    }
  }
  if (!data) return <p>Retrieving the profile page...</p>;

  /**
   * Wire transfer reached a final state: show it.  Note:
   * such state is usually successful, as errors should
   * have been reported earlier.
   */
  if (transferOutcome) {
    return <BankFrame>
      <p>{transferOutcome}</p>
      <button onClick={() => {
        pageStateSetter((prevState: PageStateType) => {
          const {
            tryManualTransfer, // Still show the wire transfer form?
            transferOutcome,
            ...rest } = prevState;
          return {...rest};})}}>
        {i18n`Close wire transfer`}
      </button>
    </BankFrame>
  }

  /**
   * Withdrawal reached a final state: show it.
   */
  if (withdrawalOutcome) {
    return <BankFrame>
      <p>{withdrawalOutcome}</p>
      <button onClick={() => {
        pageStateSetter((prevState: PageStateType) => {
          const { withdrawalOutcome, withdrawalId, ...rest } = prevState;
          return {
            ...rest,
            withdrawalInProgress: false
          };})}}>
        {i18n`Close Taler withdrawal`}
      </button>
    </BankFrame>
  }

  /**
   * This block shows the withdrawal QR code.
   *
   * A withdrawal operation replaces everything in the page and
   * (ToDo:) starts polling the backend until either the wallet
   * selected a exchange and reserve public key, or a error / abort
   * happened.
   *
   * After reaching one of the above states, the user should be
   * brought to this ("Account") page where they get informed about
   * the outcome.
   */
  console.log(`maybe new withdrawal ${talerWithdrawUri}`);
  if (talerWithdrawUri) {
    console.log('Bank created a new Taler withdrawal');
    return (
      <BankFrame>
        <TalerWithdrawalQRCode
	  accountLabel={accountLabel}
	  backendState={backendState}
	  withdrawalId={withdrawalId}
	  talerWithdrawUri={talerWithdrawUri} />
      </BankFrame>
    );
  }
  const balance = parseAmount(data.balance.amount)
  if (tryManualTransfer) {
    return (
      <BankFrame>
        <CurrencyContext.Provider value={balance.currency}>
          <PaytoWireTransfer backendState={backendState} />
        </CurrencyContext.Provider></BankFrame>);
  }
  return (<BankFrame>
    <div>
      <h1 class="nav">
        <Translate>Welcome, {accountLabel} ({getIbanFromPayto(data.paytoUri)})!</Translate>
      </h1>
    </div>
    <section id="menu">
      <p>{i18n`Bank account balance:`} <br />
        { data.balance.credit_debit_indicator == 'debit' ? (<b>-</b>) : null }
        <b>{`${balance.value} ${balance.currency}`}</b></p>
    </section>
    <CurrencyContext.Provider value={balance.currency}>
      {Props.children}
      <TalerWithdrawal
        backendState={backendState}
        pageStateSetter={pageStateSetter} />
    </CurrencyContext.Provider>
    <section id="main">
      <article>
        <h2>{i18n`Latest transactions:`}</h2>
        <Transactions pageNumber="0" accountLabel={accountLabel} />
        <p><a href="#" onClick={() =>
          pageStateSetter((prevState: PageStateType) =>
	    ({...prevState, tryManualTransfer: true}))
        }>{i18n`Transfer money manually`}</a></p>
      </article>
    </section>
  </BankFrame>);
}

/**
 * Factor out login credentials.
 */
function SWRWithCredentials(props: any): VNode {
  const { username, password, backendUrl } = props;
  const headers = new Headers();
  headers.append(
    'Authorization',
    `Basic ${Buffer.from(`${username  }:${  password}`).toString('base64')}`
  );
  console.log('Likely backend base URL', backendUrl);
  return (
    <SWRConfig
      value={{
        fetcher: (url) =>
          fetch(backendUrl + url || '', { headers }).then(
	    (r) => {
	      if (!r.ok) {
                throw {status: r.status, json: r.json()};
	      }
              return r.json()
	    }
	  ),
      }}>{props.children}</SWRConfig>
  );
}

function SWRWithoutCredentials(Props: any): VNode {
  const { baseUrl } = Props;
  console.log('Base URL', baseUrl);
  return (
    <SWRConfig
      value={{
        fetcher: (url) =>
          fetch(baseUrl + url || '').then(
	    (r) => {
	      if (!r.ok) {
                throw {status: r.status, json: r.json()};
	      }
              return r.json()
	    }
	  ),
      }}>{Props.children}</SWRConfig>
  );
}

/**
 * Show histories of public accounts.
 */
function PublicHistories(Props: any): VNode {
  const [showAccount, setShowAccount] = useShowPublicAccount();
  const { data, error } = useSWR('access-api/public-accounts');
  const i18n = useTranslator();

  if (typeof error !== 'undefined') {
    console.log('account error', error);
    switch(error.status) {
    case 404:
      console.log('public accounts: 404', error);
      Props.pageStateSetter((prevState: PageStateType) => ({
        ...prevState,
        hasError: true,
        showPublicHistories: false,
        error: i18n`List of public accounts was not found.`
      }));
      break;
    default:
      console.log('public accounts: non-404 error', error);
      Props.pageStateSetter((prevState: PageStateType) => ({
        ...prevState,
        hasError: true,
        showPublicHistories: false,
	  error: i18n`List of public accounts could not be retrieved.`
      }));
      break;
    }
  }
  if (!data) return <p>Waiting public accounts list...</p>
  const txs: any = {};
  const accountsBar = [];

  /**
   * Show the account specified in the props, or just one
   * from the list if that's not given.
   */
  if (typeof showAccount === 'undefined' && data.publicAccounts.length > 0)
    setShowAccount(data.publicAccounts[1].accountLabel);
  console.log(`Public history tab: ${showAccount}`);

  // Ask story of all the public accounts.
  for (const account of data.publicAccounts) {
    console.log('Asking transactions for', account.accountLabel)
    const isSelected = account.accountLabel == showAccount;
    accountsBar.push(
      <li class={isSelected ? 'pure-menu-selected pure-menu-item' : 'pure-menu-item pure-menu'}>
        <a href="#"
	   class="pure-menu-link"
          onClick={() => setShowAccount(account.accountLabel)}>{account.accountLabel}</a>
      </li>
    );
    txs[account.accountLabel] = <Transactions accountLabel={account.accountLabel} pageNumber={0} />
  }

  return (<Fragment>
    <h1 class="nav">{i18n`History of public accounts`}</h1>
    <section id="main">
      <article>
        <div class="pure-menu pure-menu-horizontal" name="accountMenu">
          <ul class="pure-menu-list">{accountsBar}</ul>
          {typeof showAccount !== 'undefined' ? txs[showAccount] : <p>No public transactions found.</p>}
          {Props.children}
        </div>
      </article>
    </section>
  </Fragment>);
}

/**
 * If the user is logged in, it displays
 * the balance, otherwise it offers to login.
 */
export function BankHome(): VNode {
  const [backendState, backendStateSetter] = useBackendState();
  const [pageState, pageStateSetter] = usePageState();
  const [accountState, accountStateSetter] = useAccountState();
  const setTxPageNumber = useTransactionPageNumber()[1];
  const i18n = useTranslator();

  if (pageState.showPublicHistories) {
    return (<SWRWithoutCredentials baseUrl={getRootPath()}>
      <PageContext.Provider value={[pageState, pageStateSetter]}>
        <BankFrame>
          <PublicHistories pageStateSetter={pageStateSetter}>
	    <br />
            <a class="pure-button" onClick={() => {
              pageStateSetter((prevState: PageStateType) =>
                ({...prevState, showPublicHistories: false}))}}>Go back</a>
          </PublicHistories>
        </BankFrame>
      </PageContext.Provider>
    </SWRWithoutCredentials>);
  }
  if (pageState.tryRegister) {
    // @ts-expect-error Global variable unknown to ts
    console.log('allow registrations?', __LIBEUFIN_UI_ALLOW_REGISTRATIONS__)
    // @ts-expect-error Global variable unknown to ts
    if (__LIBEUFIN_UI_ALLOW_REGISTRATIONS__) {
      return (
        <PageContext.Provider value={[pageState, pageStateSetter]}>
          <BankFrame>
	    <RegistrationForm backendStateSetter={backendStateSetter} />
	  </BankFrame>
        </PageContext.Provider>
      );
    }
    return (
      <PageContext.Provider value={[pageState, pageStateSetter]}>
        <BankFrame>
	  <p>{i18n`Currently, the bank is not accepting new registrations!`}</p>
        </BankFrame>
      </PageContext.Provider>
    );
  }
  if (pageState.isLoggedIn) {
    if (typeof backendState === 'undefined') {
      pageStateSetter((prevState) => ({
        ...prevState,
        hasError: true,
        isLoggedIn: false,
        error: i18n`Page has a problem: logged in but backend state is lost.`
      }));
      return <p>Error: waiting for details...</p>;
    }
    console.log('Showing the profile page..');
    return (
      <SWRWithCredentials
        username={backendState.username}
        password={backendState.password}
        backendUrl={backendState.url}>
        <PageContext.Provider value={[pageState, pageStateSetter]}>
          <Account accountLabel={backendState.username} backendState={backendState} />
        </PageContext.Provider>
      </SWRWithCredentials>
    );
  } // end of logged-in state.
  /**
   * Currency only known _after_ a user logs in / registers.  Thus not
   * mentioning the currency right at the home page (as instead the Python
   * bank did.)  FIXME: currency needed at startup too.  */
  const regMsg = function () {
    // @ts-expect-error Global variable unknown to ts
    if (__LIBEUFIN_UI_ALLOW_REGISTRATIONS__) {
      return (<Fragment>
        <p><Translate>If you are a new customer please&nbsp;
          <a href="#" onClick={() =>
	  {pageStateSetter((prevState) =>
            ({...prevState, tryRegister: true}))}}>register!</a>
        &nbsp;&nbsp;</Translate></p>{
	  maybeDemoContent(<p><Translate>Registration is fast and
            free, and it gives you a registration bonus of 100 <Currency />
	    </Translate></p>)
          /*close JS block of optional content*/ }
      </Fragment>); // close return of registrations allowance.
    } // close 'then' branch of registrations allowance.
  } // close helper function.
  return (
    <PageContext.Provider value={[pageState, pageStateSetter]}>
      <BankFrame>
        <h1 class="nav">{i18n`Welcome to the bank!`}</h1>
        <LoginForm
          pageStateSetter={pageStateSetter}
          backendStateSetter={backendStateSetter} />
        {regMsg()}
        {maybeDemoContent(<p><Translate>
	  To view transactions of public accounts, please <a href="#"
            onClick={goPublicAccounts(pageStateSetter)}>click here</a>.
        </Translate></p>
        )}
      </BankFrame>
    </PageContext.Provider>
  );
}