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

(() => {
    'use strict';

    // Get API Configuration from Config Manager
    const getAPIRoot = () => {
        if (window.AIMHSA && window.AIMHSA.Config) {
            return window.AIMHSA.Config.getApiBaseUrl();
        }
        
        // Fallback to intelligent detection
        let apiRoot;
        try {
            const loc = window.location;
            if (loc.port === '8000') {
                apiRoot = `${loc.protocol}//${loc.hostname}:7860`;
            } else if (loc.port === '7860' || loc.port === '') {
                apiRoot = loc.origin;
            } else {
                apiRoot = 'https://prodevroger-ishingiro.hf.space';
            }
        } catch (_) {
            apiRoot = 'https://prodevroger-ishingiro.hf.space';
        }
        return apiRoot;
    };
    
    const API_ROOT = getAPIRoot();

    // Global variables
    let currentSection = 'dashboard';
    let charts = {};
    let dataTables = {};
    let currentProfessionalId = null;
    let currentUser = null;
    let userRole = 'admin'; // Default role

    // Initialize when DOM is ready
    $(document).ready(function() {
        console.log('Admin Dashboard Initializing...');
        
        try {
            // Check if jQuery is loaded
            if (typeof $ === 'undefined') {
                console.error('jQuery not loaded');
                showErrorMessage('jQuery library not loaded. Please refresh the page.');
                return;
            }
            
            console.log('jQuery loaded');
            
            // Check user authentication and role
            checkUserAuthentication();
            
            // Initialize components
        initializeAdminLTE();
        initializeNavigation();
        initializeDataTables();
        initializeCharts();
        initializeSelect2();
        initializeExpertiseAreas();
        initializeEventHandlers();
            
            // Load dashboard data with error handling
        loadDashboardData();
            
            // Start auto-refresh
        startAutoRefresh();
            
            console.log(' Admin Dashboard initialized successfully');
            
            // Show success message
            setTimeout(() => {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Dashboard Ready!',
                        text: `Welcome ${currentUser?.username || 'Admin'}! Dashboard loaded successfully.`,
                        icon: 'success',
                        timer: 2000,
                        toast: true,
                        position: 'top-end'
                    });
                }
            }, 1000);
            
        } catch (error) {
            console.error(' Error initializing admin dashboard:', error);
            showErrorMessage('Dashboard initialization failed: ' + error.message);
        }
    });
    
    /**
     * Check user authentication and role
     */
    function checkUserAuthentication() {
        console.log('🔐 Checking user authentication...');
        
        // Check localStorage for user session
        const adminSession = localStorage.getItem('aimhsa_admin');
        const professionalSession = localStorage.getItem('aimhsa_professional');
        const userSession = localStorage.getItem('aimhsa_account');
        
        if (adminSession) {
            try {
                currentUser = JSON.parse(adminSession);
                userRole = 'admin';
                console.log(' Admin user authenticated:', currentUser.username);
                updateUserInterface();
            } catch (error) {
                console.warn(' Invalid admin session, using default');
                setDefaultUser();
            }
        } else if (professionalSession) {
            try {
                currentUser = JSON.parse(professionalSession);
                userRole = 'professional';
                console.log(' Professional user authenticated:', currentUser.username);
                updateUserInterface();
            } catch (error) {
                console.warn(' Invalid professional session, using default');
                setDefaultUser();
            }
        } else if (userSession) {
            try {
                currentUser = JSON.parse(userSession);
                userRole = 'user';
                console.log(' Regular user authenticated:', currentUser.username);
                updateUserInterface();
            } catch (error) {
                console.warn(' Invalid user session, using default');
                setDefaultUser();
            }
        } else {
            console.warn(' No user session found, using default admin');
            setDefaultUser();
        }
    }
    
    /**
     * Set default user when no session is found
     */
    function setDefaultUser() {
        currentUser = {
            username: 'admin',
            email: 'admin@aimhsa.rw',
            fullname: 'System Administrator',
            role: 'admin'
        };
        userRole = 'admin';
        updateUserInterface();
    }
    
    /**
     * Update user interface based on current user
     */
    function updateUserInterface() {
        console.log('👤 Updating user interface for:', currentUser.username, 'Role:', userRole);
        
        // Update sidebar user info
        $('.user-panel .info a').text(currentUser.fullname || currentUser.username);
        $('.user-panel .info small').text(getRoleDisplayName(userRole));
        
        // Update navbar user info
        $('.navbar-nav .nav-item:last-child .nav-link span').text(currentUser.fullname || currentUser.username);
        
        // Update page title based on role
        if (userRole === 'professional') {
            $('#pageTitle').text('Professional Dashboard');
            $('.brand-text').text('AIMHSA Professional');
        } else if (userRole === 'user') {
            $('#pageTitle').text('User Dashboard');
            $('.brand-text').text('AIMHSA User');
        } else {
            $('#pageTitle').text('Admin Dashboard');
            $('.brand-text').text('AIMHSA Admin');
        }
        
        // Show/hide sections based on role
        updateNavigationForRole();
    }
    
    /**
     * Get display name for user role
     */
    function getRoleDisplayName(role) {
        const roleNames = {
            'admin': 'System Administrator',
            'professional': 'Mental Health Professional',
            'user': 'User Account'
        };
        return roleNames[role] || 'User';
    }
    
    /**
     * Update navigation based on user role
     */
    function updateNavigationForRole() {
        if (userRole === 'professional') {
            // Hide admin-only sections
            $('.nav-item[data-section="professionals"]').hide();
            $('.nav-item[data-section="reports"]').hide();
            $('.nav-item[data-section="settings"]').hide();
            
            // Show professional-specific sections
            $('.nav-item[data-section="bookings"]').show();
            $('.nav-item[data-section="risk-monitor"]').show();
            $('.nav-item[data-section="analytics"]').show();
        } else if (userRole === 'user') {
            // Hide admin and professional sections
            $('.nav-item[data-section="professionals"]').hide();
            $('.nav-item[data-section="reports"]').hide();
            $('.nav-item[data-section="settings"]').hide();
            $('.nav-item[data-section="bookings"]').hide();
            
            // Show user-specific sections
            $('.nav-item[data-section="risk-monitor"]').show();
            $('.nav-item[data-section="analytics"]').show();
        } else {
            // Admin - show all sections
            $('.nav-item').show();
        }
    }
    
    /**
     * Show error message to user
     */
    function showErrorMessage(message) {
        const errorHtml = `
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <strong>Dashboard Error:</strong> ${message}
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            </div>
        `;
        $('.content-wrapper').prepend(errorHtml);
    }

    /**
     * Initialize AdminLTE components
     */
    function initializeAdminLTE() {
        console.log('🔧 Initializing AdminLTE components...');
        
        try {
            // Initialize push menu with fallback
            if (typeof $.fn.PushMenu !== 'undefined') {
        $('[data-widget="pushmenu"]').PushMenu('toggle');
            } else {
                // Fallback for push menu
                $('[data-widget="pushmenu"]').on('click', function(e) {
                    e.preventDefault();
                    $('body').toggleClass('sidebar-collapse');
                });
            }
        
        // Initialize tooltips
            if (typeof $.fn.tooltip !== 'undefined') {
        $('[data-toggle="tooltip"]').tooltip();
            }
        
        // Initialize popovers
            if (typeof $.fn.popover !== 'undefined') {
        $('[data-toggle="popover"]').popover();
            }
        
            // Initialize card widgets with fallback
            if (typeof $.fn.cardWidget !== 'undefined') {
        $('.card').cardWidget();
            } else {
                // Fallback for card widgets
                $('[data-card-widget="collapse"]').on('click', function(e) {
                    e.preventDefault();
                    const card = $(this).closest('.card');
                    card.toggleClass('collapsed-card');
                });
                
                $('[data-card-widget="remove"]').on('click', function(e) {
                    e.preventDefault();
                    const card = $(this).closest('.card');
                    card.fadeOut(300, function() {
                        $(this).remove();
                    });
                });
            }
            
            // Initialize direct chat with fallback
            if (typeof $.fn.DirectChat !== 'undefined') {
        $('[data-widget="chat-pane-toggle"]').DirectChat('toggle');
            } else {
                $('[data-widget="chat-pane-toggle"]').on('click', function(e) {
                    e.preventDefault();
                    $(this).closest('.direct-chat').toggleClass('direct-chat-contacts-open');
                });
            }
            
            console.log(' AdminLTE components initialized');
            
        } catch (error) {
            console.warn(' Some AdminLTE components failed to initialize:', error);
        }
    }

    /**
     * Initialize navigation system
     */
    function initializeNavigation() {
        // Handle sidebar navigation
        $('.nav-sidebar .nav-link').on('click', function(e) {
            e.preventDefault();
            
            const section = $(this).data('section');
            if (section) {
                showSection(section);
                updateActiveNavItem($(this));
                updateBreadcrumb(section);
            }
        });

        // Handle breadcrumb navigation
        $('.breadcrumb a').on('click', function(e) {
            e.preventDefault();
            const section = $(this).attr('href').substring(1);
            showSection(section);
        });
    }

    /**
     * Show specific section and hide others
     */
    function showSection(sectionName) {
        // Hide all sections with fade effect
        $('.content-section').fadeOut(200, function() {
            // Show target section
            $(`#${sectionName}-section`).fadeIn(200);
        });
        
        // Update current section
        console.log('🔄 Switching to section:', sectionName);
        currentSection = sectionName;
        
        // Load section-specific data
        loadSectionData(sectionName);
    }

    /**
     * Update active navigation item
     */
    function updateActiveNavItem(activeItem) {
        $('.nav-sidebar .nav-link').removeClass('active');
        activeItem.addClass('active');
    }

    /**
     * Update breadcrumb
     */
    function updateBreadcrumb(section) {
        const sectionNames = {
            'dashboard': 'Dashboard',
            'professionals': 'Professionals',
            'bookings': 'Bookings',
            'risk-monitor': 'Risk Monitor',
            'analytics': 'Analytics',
            'rag-status': 'RAG Status',
            'reports': 'Reports',
            'settings': 'Settings'
        };
        
        $('#pageTitle').text(sectionNames[section] || 'Dashboard');
        $('#breadcrumbActive').text(sectionNames[section] || 'Dashboard');
    }

    /**
     * Initialize DataTables
     */
    function initializeDataTables() {
        // Professionals table
        if ($('#professionalsTable').length) {
            dataTables.professionals = $('#professionalsTable').DataTable({
                responsive: true,
                processing: true,
                serverSide: false,
                pageLength: 25,
                order: [[0, 'desc']],
                columnDefs: [
                    { targets: [-1], orderable: false }
                ],
                language: {
                    search: "Search:",
                    lengthMenu: "Show _MENU_ entries per page",
                    info: "Showing _START_ to _END_ of _TOTAL_ entries",
                    paginate: {
                        first: "First",
                        last: "Last",
                        next: "Next",
                        previous: "Previous"
                    }
                }
            });
        }

        // Bookings table
        if ($('#bookingsTable').length) {
            dataTables.bookings = $('#bookingsTable').DataTable({
                responsive: true,
                processing: true,
                serverSide: false,
                pageLength: 25,
                order: [[0, 'desc']],
                columnDefs: [
                    { targets: [-1], orderable: false }
                ],
                language: {
                    search: "Search:",
                    lengthMenu: "Show _MENU_ entries per page",
                    info: "Showing _START_ to _END_ of _TOTAL_ entries",
                    paginate: {
                        first: "First",
                        last: "Last",
                        next: "Next",
                        previous: "Previous"
                    }
                }
            });
        }

    }

    /**
     * Initialize charts
     */
    function initializeCharts() {
        // Risk trend chart - will be updated with real data
        if ($('#riskTrendChart').length) {
            const ctx = document.getElementById('riskTrendChart').getContext('2d');
            charts.riskTrend = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Critical',
                        data: [],
                        borderColor: '#dc3545',
                        backgroundColor: 'rgba(220, 53, 69, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'High',
                        data: [],
                        borderColor: '#ffc107',
                        backgroundColor: 'rgba(255, 193, 7, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'Medium',
                        data: [],
                        borderColor: '#17a2b8',
                        backgroundColor: 'rgba(23, 162, 184, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'Low',
                        data: [],
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // Load real data for risk trend chart after a short delay
            setTimeout(() => {
                loadRiskTrendData();
            }, 100);
        }

        // Risk distribution chart - will be updated with real data
        if ($('#riskDistributionChart').length) {
            const ctx = document.getElementById('riskDistributionChart').getContext('2d');
            charts.riskDistribution = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['Critical', 'High', 'Medium', 'Low'],
                    datasets: [{
                        data: [0, 0, 0, 0],
                        backgroundColor: ['#dc3545', '#ffc107', '#17a2b8', '#28a745'],
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
            
            // Load real data for risk distribution chart after a short delay
            setTimeout(() => {
                loadRiskDistributionData();
            }, 100);
        }

        // Monthly trends chart
        if ($('#monthlyTrendsChart').length) {
            const ctx = document.getElementById('monthlyTrendsChart').getContext('2d');
            charts.monthlyTrends = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                    datasets: [{
                        label: 'Bookings',
                        data: [45, 52, 38, 61, 55, 67],
                        backgroundColor: '#007bff'
                    }, {
                        label: 'Completed',
                        data: [42, 48, 35, 58, 52, 63],
                        backgroundColor: '#28a745'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // Professional performance chart
        if ($('#professionalPerformanceChart').length) {
            const ctx = document.getElementById('professionalPerformanceChart').getContext('2d');
            charts.professionalPerformance = new Chart(ctx, {
                type: 'radar',
                data: {
                    labels: ['Sessions', 'Satisfaction', 'Response Time', 'Availability', 'Quality'],
                    datasets: [{
                        label: 'Dr. Marie',
                        data: [85, 92, 88, 90, 87],
                        borderColor: '#007bff',
                        backgroundColor: 'rgba(0, 123, 255, 0.2)'
                    }, {
                        label: 'Dr. John',
                        data: [78, 85, 82, 88, 84],
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.2)'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        r: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });
        }
    }

    /**
     * Load risk trend data for chart
     */
    function loadRiskTrendData() {
        if (!charts.riskTrend) {
            console.warn('Risk trend chart not initialized yet');
            return;
        }
        
        fetch(`${API_ROOT}/admin/risk-assessments?limit=100`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.assessments && charts.riskTrend) {
                    // Group assessments by day for the last 7 days
                    const last7Days = [];
                    for (let i = 6; i >= 0; i--) {
                        const date = new Date();
                        date.setDate(date.getDate() - i);
                        last7Days.push(date.toISOString().split('T')[0]);
                    }
                    
                    const riskCounts = {
                        critical: new Array(7).fill(0),
                        high: new Array(7).fill(0),
                        medium: new Array(7).fill(0),
                        low: new Array(7).fill(0)
                    };
                    
                    data.assessments.forEach(assessment => {
                        const assessmentDate = new Date(assessment.assessment_timestamp * 1000).toISOString().split('T')[0];
                        const dayIndex = last7Days.indexOf(assessmentDate);
                        if (dayIndex !== -1) {
                            const riskLevel = assessment.risk_level.toLowerCase();
                            if (riskCounts[riskLevel]) {
                                riskCounts[riskLevel][dayIndex]++;
                            }
                        }
                    });
                    
                    // Update chart data
                    charts.riskTrend.data.labels = last7Days.map(date => {
                        const d = new Date(date);
                        return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                    });
                    charts.riskTrend.data.datasets[0].data = riskCounts.critical;
                    charts.riskTrend.data.datasets[1].data = riskCounts.high;
                    charts.riskTrend.data.datasets[2].data = riskCounts.medium;
                    charts.riskTrend.data.datasets[3].data = riskCounts.low;
                    charts.riskTrend.update();
                }
            })
            .catch(error => {
                console.error('Error loading risk trend data:', error);
            });
    }

    /**
     * Load risk distribution data for chart
     */
    function loadRiskDistributionData() {
        if (!charts.riskDistribution) {
            console.warn('Risk distribution chart not initialized yet');
            return;
        }
        
        fetch(`${API_ROOT}/admin/risk-assessments?limit=100`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.assessments && charts.riskDistribution) {
                    const riskCounts = {
                        critical: 0,
                        high: 0,
                        medium: 0,
                        low: 0
                    };
                    
                    data.assessments.forEach(assessment => {
                        const riskLevel = assessment.risk_level.toLowerCase();
                        if (riskCounts.hasOwnProperty(riskLevel)) {
                            riskCounts[riskLevel]++;
                        }
                    });
                    
                    // Update chart data
                    charts.riskDistribution.data.datasets[0].data = [
                        riskCounts.critical,
                        riskCounts.high,
                        riskCounts.medium,
                        riskCounts.low
                    ];
                    charts.riskDistribution.update();
                }
            })
            .catch(error => {
                console.error('Error loading risk distribution data:', error);
            });
    }

    /**
     * Initialize Select2
     */
    function initializeSelect2() {
        $('.select2').select2({
            theme: 'bootstrap4',
            width: '100%'
        });
    }

    /**
     * Initialize event handlers
     */
    function initializeEventHandlers() {
        // Professional management
        $('#addProfessionalBtn').on('click', function() {
            console.log('➕ Opening Add Professional modal...');
            resetProfessionalForm();
            $('#modalTitle').text('Add New Professional');
            $('#passwordRequired').text('*');
            $('#passwordHelp').hide();
            $('#professionalModal').modal('show');
            
            // Ensure inputs work properly
            setTimeout(() => {
                ensureInputsWorking();
                forceInputFunctionality();
                debugFormInputs();
                const firstInput = $('#professionalModal input[required]').first();
                if (firstInput.length) {
                    firstInput.focus();
                    console.log(' Focused on first input:', firstInput.attr('name'));
                }
            }, 300);
        });

        // Handle form submission
        $('#professionalForm').on('submit', function(e) {
            e.preventDefault();
            saveProfessional();
        });
        
        // Also handle button click as backup
        $('#saveProfessionalBtn').on('click', function() {
            $('#professionalForm').submit();
        });

        // Refresh buttons
        $('[id$="RefreshBtn"], [id$="refreshBtn"]').on('click', function() {
            const section = $(this).closest('.content-section').attr('id').replace('-section', '');
            loadSectionData(section);
        });

        // Global refresh button
        $('#refreshAllBtn').on('click', function() {
            refreshAllData();
        });

        // Expertise areas change handler
        $(document).on('change', 'input[name="expertise"]', function() {
            updateExpertiseValidation();
        });

        // Export buttons
        $('#exportBookingsBtn').on('click', function() {
            exportTableToCSV('bookingsTable', 'bookings.csv');
        });
        
        // Initialize bookings filtering
        initializeBookingsFiltering();

        // Search functionality
        $('#professionalSearch').on('keyup', function() {
            if (dataTables.professionals) {
                dataTables.professionals.search(this.value).draw();
            }
        });

        // Filter functionality
        $('#statusFilter, #riskLevelFilter, #specializationFilter').on('change', function() {
            applyFilters();
        });

        // Professional search functionality
        $('#professionalSearch').on('input', function() {
            const searchTerm = $(this).val().toLowerCase();
            filterProfessionals(searchTerm);
        });

        // Professional specialization filter
        $('#professionalSpecializationFilter').on('change', function() {
            const specialization = $(this).val();
            filterProfessionalsBySpecialization(specialization);
        });

        // Logout
        $('#logoutBtn').on('click', function() {
            Swal.fire({
                title: 'Logout?',
                text: `Are you sure you want to logout, ${currentUser?.username || 'User'}?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, logout!'
            }).then((result) => {
                if (result.isConfirmed) {
                    logoutUser();
                }
            });
        });
    }

    /**
     * Check API health
     */
    function checkAPIHealth() {
        const endpoints = [
            '/admin/bookings',
            '/admin/professionals', 
            '/admin/risk-assessments',
            '/monitor/risk-stats',
            '/monitor/recent-assessments'
        ];
        
        Promise.all(endpoints.map(endpoint => 
            fetch(`${API_ROOT}${endpoint}`)
                .then(response => ({ endpoint, status: response.ok, statusCode: response.status }))
                .catch(error => ({ endpoint, status: false, error: error.message }))
        )).then(results => {
            const failedEndpoints = results.filter(r => !r.status);
            if (failedEndpoints.length > 0) {
                console.warn('Some API endpoints are not responding:', failedEndpoints);
                // Show a warning to the user
                if (failedEndpoints.length === endpoints.length) {
                    Swal.fire({
                        title: 'API Connection Error',
                        text: 'Unable to connect to the backend API. Please check if the server is running.',
                        icon: 'error',
                        timer: 5000
                    });
                }
            }
        });
    }

    /**
     * Load dashboard data
     */
    function loadDashboardData() {
        console.log(' Loading dashboard data for role:', userRole);
        
        // Show loading state
        showLoadingState();
        
        // Check API health first
        checkAPIHealth();
        
        // Load role-specific data
        if (userRole === 'admin') {
            loadAdminDashboardData();
        } else if (userRole === 'professional') {
            loadProfessionalDashboardData();
        } else if (userRole === 'user') {
            loadUserDashboardData();
        } else {
            loadAdminDashboardData(); // Default to admin
        }
        
        // Hide loading state after a delay
        setTimeout(() => {
            hideLoadingState();
        }, 2000);
    }
    
    /**
     * Load admin dashboard data
     */
    function loadAdminDashboardData() {
        console.log('👑 Loading admin dashboard data...');
        loadKPIData();
        loadRecentBookings();
        loadSystemStatus();
        loadNotifications();
    }
    
    /**
     * Load professional dashboard data
     */
    function loadProfessionalDashboardData() {
        console.log(' Loading professional dashboard data...');
        loadProfessionalKPIData();
        loadProfessionalBookings();
        loadProfessionalNotifications();
        loadNotifications();
    }
    
    /**
     * Load user dashboard data
     */
    function loadUserDashboardData() {
        console.log('👤 Loading user dashboard data...');
        loadUserKPIData();
        loadUserRiskHistory();
        loadUserBookings();
        loadNotifications();
    }
    
    /**
     * Show loading state
     */
    function showLoadingState() {
        $('#loadingOverlay').show();
        // Add loading class to KPI cards
        $('.small-box .inner h3').html('<i class="fas fa-spinner fa-spin"></i>');
    }
    
    /**
     * Hide loading state
     */
    function hideLoadingState() {
        $('#loadingOverlay').hide();
    }

    /**
     * Load section-specific data
     */
    function loadSectionData(section) {
        console.log('🔄 Loading section data for:', section);
        try {
            switch (section) {
                case 'professionals':
                    console.log('📋 Loading professionals...');
                    loadProfessionals();
                    break;
                case 'bookings':
                    console.log('📋 Loading bookings...');
                    loadBookings();
                    break;
                case 'risk-monitor':
                    loadRiskData();
                    break;
                case 'analytics':
                    loadAnalyticsData();
                    break;
                case 'rag-status':
                    loadRAGStatus();
                    break;
                default:
                    console.warn(`Unknown section: ${section}`);
            }
        } catch (error) {
            console.error(`Error loading section data for ${section}:`, error);
        }
    }

    /**
     * Load KPI data from database
     */
    function loadKPIData() {
        console.log(' Loading KPI data...');
        
        // Show loading state
        $('#kpiActiveBookings, #kpiCritical, #kpiProfessionals, #kpiAssessments').html('<i class="fas fa-spinner fa-spin"></i>');
        
        // Try to load data from API endpoints with timeout
        const timeout = 5000; // 5 second timeout
        
        const apiPromises = [
            fetch(`${API_ROOT}/admin/bookings`, { signal: AbortSignal.timeout(timeout) })
                .then(res => res.ok ? res.json() : null)
                .catch(err => {
                    console.warn('Bookings API failed:', err);
                    return null;
                }),
            fetch(`${API_ROOT}/admin/professionals`, { signal: AbortSignal.timeout(timeout) })
                .then(res => res.ok ? res.json() : null)
                .catch(err => {
                    console.warn('Professionals API failed:', err);
                    return null;
                }),
            fetch(`${API_ROOT}/admin/risk-assessments?limit=100`, { signal: AbortSignal.timeout(timeout) })
                .then(res => res.ok ? res.json() : null)
                .catch(err => {
                    console.warn('Risk assessments API failed:', err);
                    return null;
                }),
            fetch(`${API_ROOT}/monitor/risk-stats`, { signal: AbortSignal.timeout(timeout) })
                .then(res => res.ok ? res.json() : null)
                .catch(err => {
                    console.warn('Risk stats API failed:', err);
                    return null;
                })
        ];
        
        Promise.all(apiPromises).then(([bookingsData, professionalsData, riskData, riskStats]) => {
            console.log(' API Data received:', { bookingsData, professionalsData, riskData, riskStats });
            
            let hasRealData = false;
            
            // Active bookings (pending + confirmed)
            const activeBookings = bookingsData?.bookings ? 
                bookingsData.bookings.filter(b => ['pending', 'confirmed'].includes(b.booking_status)).length : 0;
            $('#kpiActiveBookings').text(activeBookings);
            if (activeBookings > 0) hasRealData = true;
            
            // Critical risks
            const criticalRisks = riskStats?.critical || 
                (riskData?.assessments ? riskData.assessments.filter(r => r.risk_level === 'critical').length : 0);
            $('#kpiCritical').text(criticalRisks);
            if (criticalRisks > 0) hasRealData = true;
            
            // Total professionals
            const totalProfessionals = professionalsData?.professionals ? professionalsData.professionals.length : 0;
            $('#kpiProfessionals').text(totalProfessionals);
            if (totalProfessionals > 0) hasRealData = true;
            
            // Assessments today
            const today = new Date().toISOString().split('T')[0];
            const assessmentsToday = riskData?.assessments ? 
                riskData.assessments.filter(r => {
                    const assessmentDate = new Date(r.assessment_timestamp * 1000).toISOString().split('T')[0];
                    return assessmentDate === today;
                }).length : 0;
            $('#kpiAssessments').text(assessmentsToday);
            if (assessmentsToday > 0) hasRealData = true;
            
            if (!hasRealData) {
                console.log(' No real data found, showing demo data');
                showDemoData();
            } else {
                console.log(' KPI data loaded successfully');
            }
            
        }).catch(error => {
            console.warn(' API not available, using demo data:', error);
            showDemoData();
        });
    }
    
    /**
     * Show demo data when API is not available
     */
    function showDemoData() {
        // Show demo data when API is not available
        $('#kpiActiveBookings').html('<span class="text-success" title="Demo data">12</span>');
        $('#kpiCritical').html('<span class="text-danger" title="Demo data">3</span>');
        $('#kpiProfessionals').html('<span class="text-info" title="Demo data">8</span>');
        $('#kpiAssessments').text('25');
        
        // Show demo mode notification
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Demo Mode',
                text: 'Backend API not available. Showing demo data.',
                icon: 'info',
                timer: 3000,
                toast: true,
                position: 'top-end'
            });
        }
    }

    /**
     * Load recent bookings from database
     */
    function loadRecentBookings() {
        console.log('📋 Loading recent bookings...');
        
        const tbody = $('#recentBookingsTable');
        tbody.html('<tr><td colspan="4" class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>');
        
        // Try to load real data with timeout
        fetch(`${API_ROOT}/admin/bookings?limit=5`, { signal: AbortSignal.timeout(5000) })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('📋 Bookings data received:', data);
        tbody.empty();

                if (data.bookings && data.bookings.length > 0) {
                    data.bookings.forEach(booking => {
            const row = `
                <tr>
                                <td>${booking.booking_id || 'N/A'}</td>
                                <td>${booking.user_account || 'Guest'}</td>
                                <td><span class="badge badge-${getRiskBadgeClass(booking.risk_level)}">${booking.risk_level || 'Unknown'}</span></td>
                                <td><span class="badge badge-${getStatusBadgeClass(booking.booking_status)}">${booking.booking_status || 'Unknown'}</span></td>
                </tr>
            `;
            tbody.append(row);
                    });
                    console.log(' Recent bookings loaded successfully');
                } else {
                    showDemoBookings();
                }
            })
            .catch(error => {
                console.warn(' Error loading recent bookings, showing demo data:', error);
                showDemoBookings();
            });
    }
    
    /**
     * Show demo bookings data
     */
    function showDemoBookings() {
        const tbody = $('#recentBookingsTable');
        tbody.html(`
            <tr>
                <td>BK001</td>
                <td>Demo User</td>
                <td><span class="badge badge-danger">Critical</span></td>
                <td><span class="badge badge-warning">Pending</span></td>
            </tr>
            <tr>
                <td>BK002</td>
                <td>Test User</td>
                <td><span class="badge badge-warning">High</span></td>
                <td><span class="badge badge-info">Confirmed</span></td>
            </tr>
            <tr>
                <td>BK003</td>
                <td>Sample User</td>
                <td><span class="badge badge-info">Medium</span></td>
                <td><span class="badge badge-success">Completed</span></td>
            </tr>
            <tr>
                <td colspan="4" class="text-center text-info">
                    <i class="fas fa-info-circle"></i> Demo data - API not available
                </td>
            </tr>
        `);
    }
    
    /**
     * Load professional KPI data
     */
    function loadProfessionalKPIData() {
        console.log(' Loading professional KPI data...');
        
        // Update KPI labels for professional
        $('#kpiActiveBookings').parent().find('p').text('My Sessions');
        $('#kpiCritical').parent().find('p').text('High Risk Cases');
        $('#kpiProfessionals').parent().find('p').text('Total Patients');
        $('#kpiAssessments').parent().find('p').text('Today\'s Assessments');
        
        // Try to load professional-specific data
        fetch(`${API_ROOT}/professional/dashboard-stats`, { signal: AbortSignal.timeout(5000) })
            .then(response => response.json())
            .then(data => {
                console.log(' Professional data received:', data);
                
                $('#kpiActiveBookings').text(data.totalSessions || 0);
                $('#kpiCritical').text(data.highRiskCases || 0);
                $('#kpiProfessionals').text(data.activeUsers || 0);
                $('#kpiAssessments').text(data.unreadNotifications || 0);
                
                console.log(' Professional KPI data loaded successfully');
            })
            .catch(error => {
                console.warn(' Professional API not available, using demo data:', error);
                showProfessionalDemoData();
            });
    }
    
    /**
     * Show professional demo data
     */
    function showProfessionalDemoData() {
        $('#kpiActiveBookings').html('<span class="text-success" title="Demo data">15</span>');
        $('#kpiCritical').html('<span class="text-danger" title="Demo data">2</span>');
        $('#kpiProfessionals').html('<span class="text-info" title="Demo data">8</span>');
        $('#kpiAssessments').text('5');
    }
    
    /**
     * Load user KPI data
     */
    function loadUserKPIData() {
        console.log('👤 Loading user KPI data...');
        
        // Update KPI labels for user
        $('#kpiActiveBookings').parent().find('p').text('My Bookings');
        $('#kpiCritical').parent().find('p').text('Risk Level');
        $('#kpiProfessionals').parent().find('p').text('Sessions Completed');
        $('#kpiAssessments').parent().find('p').text('Assessments Done');
        
        // Show user-specific demo data
        $('#kpiActiveBookings').html('<span class="text-info" title="Demo data">3</span>');
        $('#kpiCritical').html('<span class="text-warning" title="Demo data">Medium</span>');
        $('#kpiProfessionals').html('<span class="text-success" title="Demo data">2</span>');
        $('#kpiAssessments').text('12');
    }
    
    /**
     * Load professional bookings
     */
    function loadProfessionalBookings() {
        console.log(' Loading professional bookings...');
        // This would load bookings specific to the professional
        loadRecentBookings(); // Use existing function for now
    }
    
    /**
     * Load professional notifications
     */
    function loadProfessionalNotifications() {
        console.log(' Loading professional notifications...');
        // This would load notifications for the professional
        // For now, just show demo data
    }
    
    /**
     * Load user risk history
     */
    function loadUserRiskHistory() {
        console.log('👤 Loading user risk history...');
        // This would load the user's risk assessment history
    }
    
    /**
     * Load user bookings
     */
    function loadUserBookings() {
        console.log('👤 Loading user bookings...');
        // This would load bookings specific to the user
        loadRecentBookings(); // Use existing function for now
    }
    
    /**
     * Logout user
     */
    function logoutUser() {
        console.log('🚪 Logging out user:', currentUser?.username);
        
        // Clear all session data
        localStorage.removeItem('aimhsa_admin');
        localStorage.removeItem('aimhsa_professional');
        localStorage.removeItem('aimhsa_account');
        
        // Show logout message
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Logged Out',
                text: 'You have been successfully logged out.',
                icon: 'success',
                timer: 2000
            }).then(() => {
                // Redirect to login page
                window.location.href = 'login.html';
            });
        } else {
            // Fallback redirect
            window.location.href = 'login.html';
        }
    }

    /**
     * Load system status
     */
    function loadSystemStatus() {
        // System status is already set in HTML
        // This function can be used to update real-time status
    }
    
    /**
     * Load notifications from database
     */
    function loadNotifications() {
        console.log('🔔 Loading notifications from database...');
        
        fetch(`${API_ROOT}/notifications`, { signal: AbortSignal.timeout(5000) })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('🔔 Notifications data received:', data);
                updateNotificationUI(data);
            })
            .catch(error => {
                console.warn(' Error loading notifications, using demo data:', error);
                showDemoNotifications();
            });
    }
    
    /**
     * Update notification UI with real data
     */
    function updateNotificationUI(data) {
        // Update notification badge
        const totalNotifications = data.totalNotifications || 0;
        $('.nav-link .badge').text(totalNotifications);
        
        // Update notification dropdown content
        const notificationsHtml = generateNotificationsHTML(data);
        $('.dropdown-menu.notifications-menu').html(notificationsHtml);
        
        console.log(' Notifications UI updated with real data');
    }
    
    /**
     * Generate notifications HTML from database data
     */
    function generateNotificationsHTML(data) {
        const notifications = data.notifications || [];
        const totalNotifications = data.totalNotifications || 0;
        
        let html = `
            <span class="dropdown-item dropdown-header">${totalNotifications} Notifications</span>
            <div class="dropdown-divider"></div>
        `;
        
        if (notifications.length === 0) {
            html += `
                <a href="#" class="dropdown-item">
                    <i class="fas fa-info-circle text-info mr-2"></i>
                    No new notifications
                </a>
            `;
        } else {
            notifications.slice(0, 5).forEach(notification => {
                const iconClass = getNotificationIcon(notification.type);
                const timeAgo = notification.timeAgo || 'Unknown';
                const isRead = notification.isRead ? '' : 'font-weight-bold';
                
                html += `
                    <a href="#" class="dropdown-item ${isRead}">
                        <i class="${iconClass} mr-2"></i>
                        ${notification.title}
                        <span class="float-right text-muted text-sm">${timeAgo}</span>
                    </a>
                `;
            });
        }
        
        html += `
            <div class="dropdown-divider"></div>
            <a href="#" class="dropdown-item dropdown-footer">See All Notifications</a>
        `;
        
        return html;
    }
    
    /**
     * Get icon class for notification type
     */
    function getNotificationIcon(type) {
        const iconMap = {
            'booking': 'fas fa-calendar-check text-success',
            'risk': 'fas fa-exclamation-triangle text-danger',
            'message': 'fas fa-envelope text-info',
            'user': 'fas fa-user text-primary',
            'system': 'fas fa-cog text-secondary',
            'default': 'fas fa-bell text-warning'
        };
        return iconMap[type] || iconMap['default'];
    }
    
    /**
     * Show demo notifications when API is not available
     */
    function showDemoNotifications() {
        const demoData = {
            totalNotifications: 15,
            notifications: [
                {
                    id: 1,
                    title: '4 new messages',
                    type: 'message',
                    timeAgo: '3 mins',
                    isRead: false
                },
                {
                    id: 2,
                    title: '8 friend requests',
                    type: 'user',
                    timeAgo: '12 hours',
                    isRead: false
                },
                {
                    id: 3,
                    title: '3 new reports',
                    type: 'system',
                    timeAgo: '2 days',
                    isRead: true
                }
            ]
        };
        
        updateNotificationUI(demoData);
        console.log('📱 Demo notifications displayed');
    }

    /**
     * Load professionals data from database
     */
    function loadProfessionals() {
        console.log('👥 Loading professionals...');
        const tbody = $('#professionalsTableBody');
        tbody.html('<tr><td colspan="8" class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>');
        
        fetch(`${API_ROOT}/admin/professionals`)
            .then(response => {
                console.log('📡 Professionals API response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log(' Professionals data received:', data);
        tbody.empty();

                if (data.professionals && data.professionals.length > 0) {
                    data.professionals.forEach(prof => {
                        const fullName = `${prof.first_name || ''} ${prof.last_name || ''}`.trim();
                        const statusClass = prof.is_active ? 'success' : 'secondary';
                        const statusText = prof.is_active ? 'Active' : 'Inactive';
                        
            const row = `
                <tr>
                    <td>${prof.id}</td>
                                <td>${fullName || 'N/A'}</td>
                                <td>${prof.specialization || 'N/A'}</td>
                                <td>${prof.email || 'N/A'}</td>
                                <td>${prof.phone || 'N/A'}</td>
                                <td>${prof.experience_years || 0} years</td>
                                <td><span class="badge badge-${statusClass}">${statusText}</span></td>
                                <td>
                                    <button class="btn btn-sm btn-primary" onclick="editProfessional(${prof.id})" title="Edit">
                            <i class="fas fa-edit"></i>
                        </button>
                                    <button class="btn btn-sm btn-${prof.is_active ? 'warning' : 'success'}" 
                                            onclick="toggleProfessionalStatus(${prof.id})" 
                                            title="${prof.is_active ? 'Deactivate' : 'Activate'}">
                                        <i class="fas fa-${prof.is_active ? 'pause' : 'play'}"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger" onclick="deleteProfessional(${prof.id})" title="Delete">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
                    console.log(' Professionals loaded successfully');
                } else {
                    tbody.html('<tr><td colspan="8" class="text-center text-muted">No professionals found</td></tr>');
                }

                // Update DataTable if it exists
        if (dataTables.professionals) {
            dataTables.professionals.clear().rows.add($(tbody).find('tr')).draw();
        }
            })
            .catch(error => {
                console.error(' Error loading professionals:', error);
                tbody.html(`
                    <tr>
                        <td colspan="8" class="text-center text-danger">
                            <i class="fas fa-exclamation-triangle"></i> Error loading professionals
                            <br><small>${error.message}</small>
                        </td>
                    </tr>
                `);
            });
    }

    /**
     * Load bookings data from database with full user details
     */
    function loadBookings() {
        console.log(' Starting loadBookings function...');
        const tbody = $('#bookingsTableBody');
        console.log('Table body element:', tbody);
        console.log('Table body length:', tbody.length);
        console.log('Table is visible:', tbody.is(':visible'));
        
        tbody.html('<tr><td colspan="7" class="text-center bookings-loading"><i class="fas fa-spinner fa-spin"></i> Loading bookings...</td></tr>');
        
        // Show loading state in stats
        updateBookingStats({ total: 0, confirmed: 0, pending: 0, critical: 0 });
        
        fetch(`${API_ROOT}/admin/bookings`)
            .then(response => response.json())
            .then(data => {
        tbody.empty();

                if (data.bookings && data.bookings.length > 0) {
                    // Update stats
                    updateBookingStats(data);
                    
                    // Log the data for debugging
                    console.log(' Bookings data received:', {
                        total: data.total,
                        confirmed: data.confirmed,
                        pending: data.pending,
                        critical: data.critical,
                        bookingsCount: data.bookings ? data.bookings.length : 0
                    });
                    
                    console.log('🔄 Processing bookings data...');
                    data.bookings.forEach((booking, index) => {
                        console.log(`📋 Processing booking ${index + 1}:`, {
                            id: booking.booking_id,
                            user: booking.user_fullname,
                            professional: booking.professional_name,
                            status: booking.booking_status,
                            risk: booking.risk_level
                        });
                        
                        const scheduledTime = new Date(booking.scheduled_datetime * 1000).toLocaleString();
                        const professionalName = booking.professional_name || 'Unassigned';
                        const professionalSpecialization = booking.professional_specialization || '';
                        
                        // Get user initials for avatar
                        const userInitials = getUserInitials(booking.user_fullname || booking.user_account || 'Guest');
                        
                        // Create user details HTML
                        const userDetails = createUserDetailsHTML(booking);
                        
                        // Create professional details HTML
                        const professionalDetails = createProfessionalDetailsHTML(booking);
                        
                        // Create risk badge HTML
                        const riskBadge = createRiskBadgeHTML(booking.risk_level);
                        
                        // Create status badge HTML
                        const statusBadge = createStatusBadgeHTML(booking.booking_status);
                        
                        // Create action buttons HTML
                        const actionButtons = createActionButtonsHTML(booking.booking_id, booking.booking_status);
                        
            const row = `
                <tr>
                                <td>
                                    <div class="booking-id">
                                        <code>${booking.booking_id.substring(0, 8)}...</code>
                                        <small class="text-muted d-block">${booking.booking_id}</small>
                                    </div>
                    </td>
                                <td>${userDetails}</td>
                                <td>${professionalDetails}</td>
                                <td>${riskBadge}</td>
                                <td>
                                    <div class="scheduled-time">
                                        <i class="fas fa-calendar-alt text-primary"></i>
                                        <span class="ml-1">${scheduledTime}</span>
                                    </div>
                                </td>
                                <td>${statusBadge}</td>
                                <td>${actionButtons}</td>
                </tr>
            `;
            tbody.append(row);
            console.log(` Added row ${index + 1} to table`);
        });
        
        console.log(' Total rows in tbody:', tbody.find('tr').length);
                } else {
                    tbody.html(`
                        <tr>
                            <td colspan="7" class="text-center bookings-empty">
                                <i class="fas fa-calendar-times"></i>
                                <h4>No Bookings Found</h4>
                                <p>There are currently no bookings in the system.</p>
                            </td>
                        </tr>
                    `);
                    updateBookingStats({ total: 0, confirmed: 0, pending: 0, critical: 0 });
                }

                // Update DataTable
        console.log(' Checking DataTable status...');
        console.log('DataTable object:', dataTables.bookings);
        console.log('DataTable exists:', !!dataTables.bookings);
        
        // First, let's try to show the data without DataTable
        console.log(' Table body HTML after adding rows:');
        console.log(tbody.html());

        if (dataTables.bookings) {
            console.log('🔄 Updating DataTable with', tbody.find('tr').length, 'rows');
            try {
            dataTables.bookings.clear().rows.add($(tbody).find('tr')).draw();
                console.log(' DataTable updated successfully');
            } catch (error) {
                console.error(' Error updating DataTable:', error);
                console.log('🔄 Trying to destroy and recreate DataTable...');
                try {
                    dataTables.bookings.destroy();
                    dataTables.bookings = $('#bookingsTable').DataTable({
                        responsive: true,
                        processing: true,
                        serverSide: false,
                        pageLength: 25,
                        order: [[0, 'desc']],
                        columnDefs: [
                            { targets: [-1], orderable: false }
                        ],
                        language: {
                            search: "Search:",
                            lengthMenu: "Show _MENU_ entries per page",
                            info: "Showing _START_ to _END_ of _TOTAL_ entries",
                            paginate: {
                                first: "First",
                                last: "Last",
                                next: "Next",
                                previous: "Previous"
                            }
                        }
                    });
                    console.log(' DataTable recreated successfully');
                } catch (recreateError) {
                    console.error(' Error recreating DataTable:', recreateError);
                }
            }
        } else {
            console.log(' DataTable not initialized - trying to reinitialize...');
            // Try to reinitialize the DataTable
            if ($('#bookingsTable').length) {
                dataTables.bookings = $('#bookingsTable').DataTable({
                    responsive: true,
                    processing: true,
                    serverSide: false,
                    pageLength: 25,
                    order: [[0, 'desc']],
                    columnDefs: [
                        { targets: [-1], orderable: false }
                    ],
                    language: {
                        search: "Search:",
                        lengthMenu: "Show _MENU_ entries per page",
                        info: "Showing _START_ to _END_ of _TOTAL_ entries",
                        paginate: {
                            first: "First",
                            last: "Last",
                            next: "Next",
                            previous: "Previous"
                        }
                    }
                });
                console.log(' DataTable reinitialized');
            }
        }
                
                console.log(' Bookings loaded successfully:', data.bookings?.length || 0, 'bookings');
            })
            .catch(error => {
                console.error('Error loading bookings:', error);
                tbody.html(`
                    <tr>
                        <td colspan="7" class="text-center text-danger">
                            <i class="fas fa-exclamation-triangle"></i>
                            Error loading bookings data
                        </td>
                    </tr>
                `);
            });
    }
    
    /**
     * Create user details HTML with full information
     */
    function createUserDetailsHTML(booking) {
        const userFullName = booking.user_fullname || booking.user_account || 'Guest User';
        const userEmail = booking.user_email || 'No email provided';
        const userPhone = booking.user_phone || 'No phone provided';
        const userLocation = booking.user_location || 'Location not specified';
        const userInitials = getUserInitials(userFullName);
        
        return `
            <div class="user-details">
                <div class="user-avatar">
                    ${userInitials}
                </div>
                <div class="user-info">
                    <h6 class="user-name">${userFullName}</h6>
                    <div class="user-contact">
                        <a href="mailto:${userEmail}" title="Email user">
                            <i class="fas fa-envelope"></i> ${userEmail}
                        </a>
                        <a href="tel:${userPhone}" title="Call user">
                            <i class="fas fa-phone"></i> ${userPhone}
                        </a>
                    </div>
                    <div class="user-location">
                        <i class="fas fa-map-marker-alt"></i>
                        <span>${userLocation}</span>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * Create professional details HTML
     */
    function createProfessionalDetailsHTML(booking) {
        const professionalName = booking.professional_name || 'Unassigned';
        const professionalSpecialization = booking.professional_specialization || '';
        const professionalInitials = getUserInitials(professionalName);
        
        if (professionalName === 'Unassigned') {
            return `
                <div class="professional-info">
                    <div class="professional-avatar" style="background: linear-gradient(135deg, #6b7280 0%, #9ca3af 100%);">
                        <i class="fas fa-user-slash"></i>
                    </div>
                    <div>
                        <div class="professional-name">Unassigned</div>
                        <div class="professional-specialization">Awaiting assignment</div>
                    </div>
                </div>
            `;
        }
        
        return `
            <div class="professional-info">
                <div class="professional-avatar">
                    ${professionalInitials}
                </div>
                <div>
                    <div class="professional-name">${professionalName}</div>
                    <div class="professional-specialization">${professionalSpecialization}</div>
                </div>
            </div>
        `;
    }
    
    /**
     * Create risk badge HTML
     */
    function createRiskBadgeHTML(riskLevel) {
        const riskIcons = {
            critical: 'fas fa-exclamation-triangle',
            high: 'fas fa-exclamation-circle',
            medium: 'fas fa-info-circle',
            low: 'fas fa-check-circle'
        };
        
        const icon = riskIcons[riskLevel.toLowerCase()] || 'fas fa-question-circle';
        
        return `
            <span class="risk-badge ${riskLevel.toLowerCase()}">
                <i class="${icon}"></i>
                ${riskLevel.toUpperCase()}
            </span>
        `;
    }
    
    /**
     * Create status badge HTML
     */
    function createStatusBadgeHTML(status) {
        const statusIcons = {
            pending: 'fas fa-clock',
            confirmed: 'fas fa-check-circle',
            completed: 'fas fa-check-double',
            declined: 'fas fa-times-circle',
            cancelled: 'fas fa-ban'
        };
        
        const icon = statusIcons[status.toLowerCase()] || 'fas fa-question-circle';
        
        return `
            <span class="status-badge ${status.toLowerCase()}">
                <i class="${icon}"></i>
                ${status.toUpperCase()}
            </span>
        `;
    }
    
    /**
     * Create action buttons HTML
     */
    function createActionButtonsHTML(bookingId, status) {
        const canEdit = status === 'pending' || status === 'confirmed';
        const canComplete = status === 'confirmed';
        const canCancel = status === 'pending' || status === 'confirmed';
        
        return `
            <div class="action-buttons">
                <button class="action-btn btn-info" onclick="viewBooking('${bookingId}')" title="View Details">
                    <i class="fas fa-eye"></i>
                </button>
                ${canEdit ? `
                    <button class="action-btn btn-warning" onclick="editBooking('${bookingId}')" title="Edit Booking">
                        <i class="fas fa-edit"></i>
                    </button>
                ` : ''}
                ${canComplete ? `
                    <button class="action-btn btn-success" onclick="completeBooking('${bookingId}')" title="Mark as Completed">
                        <i class="fas fa-check"></i>
                    </button>
                ` : ''}
                ${canCancel ? `
                    <button class="action-btn btn-danger" onclick="cancelBooking('${bookingId}')" title="Cancel Booking">
                        <i class="fas fa-times"></i>
                    </button>
                ` : ''}
            </div>
        `;
    }
    
    /**
     * Get user initials for avatar
     */
    function getUserInitials(name) {
        if (!name || name === 'Guest') return 'G';
        
        const words = name.trim().split(' ');
        if (words.length >= 2) {
            return (words[0][0] + words[1][0]).toUpperCase();
        }
        return name[0].toUpperCase();
    }
    
    /**
     * Update booking statistics
     */
    function updateBookingStats(data) {
        const stats = {
            total: data.total || 0,
            confirmed: data.confirmed || 0,
            pending: data.pending || 0,
            critical: data.critical || 0
        };
        
        $('#totalBookings').text(stats.total);
        $('#confirmedBookings').text(stats.confirmed);
        $('#pendingBookings').text(stats.pending);
        $('#criticalBookings').text(stats.critical);
    }

    /**
     * Load risk data from database
     */
    function loadRiskData() {
        // Show loading state
        $('#criticalCount, #highCount, #mediumCount, #lowCount').text('...');
        
        fetch(`${API_ROOT}/admin/risk-assessments?limit=100`)
            .then(response => response.json())
            .then(data => {
                if (data.assessments) {
                    const riskCounts = {
                        critical: 0,
                        high: 0,
                        medium: 0,
                        low: 0
                    };
                    
                    data.assessments.forEach(assessment => {
                        const riskLevel = assessment.risk_level.toLowerCase();
                        if (riskCounts.hasOwnProperty(riskLevel)) {
                            riskCounts[riskLevel]++;
                        }
                    });
                    
                    $('#criticalCount').text(riskCounts.critical);
                    $('#highCount').text(riskCounts.high);
                    $('#mediumCount').text(riskCounts.medium);
                    $('#lowCount').text(riskCounts.low);
                    
                    // Update recent assessments
                    updateRecentAssessments(data.assessments.slice(0, 10));
                } else {
                    $('#criticalCount, #highCount, #mediumCount, #lowCount').text('0');
                }
            })
            .catch(error => {
                console.error('Error loading risk data:', error);
                $('#criticalCount, #highCount, #mediumCount, #lowCount').text('0');
            });
    }
    
    /**
     * Update recent assessments display
     */
    function updateRecentAssessments(assessments) {
        const container = $('#recentAssessments');
        container.empty();
        
        if (assessments.length === 0) {
            container.html('<p class="text-muted">No recent assessments</p>');
            return;
        }
        
        assessments.forEach(assessment => {
            const timeAgo = getTimeAgo(assessment.assessment_timestamp);
            const riskClass = getRiskBadgeClass(assessment.risk_level);
            
            const assessmentItem = `
                <div class="timeline-item">
                    <span class="time"><i class="fas fa-clock"></i> ${timeAgo}</span>
                    <h3 class="timeline-header">
                        <span class="badge badge-${riskClass}">${assessment.risk_level.toUpperCase()}</span>
                        Risk Assessment
                    </h3>
                    <div class="timeline-body">
                        <p><strong>User:</strong> ${assessment.user_account || 'Guest'}</p>
                        <p><strong>Score:</strong> ${(assessment.risk_score * 100).toFixed(1)}%</p>
                        <p><strong>Indicators:</strong> ${assessment.detected_indicators || 'None detected'}</p>
                    </div>
                </div>
            `;
            container.append(assessmentItem);
        });
    }
    
    /**
     * Get time ago string
     */
    function getTimeAgo(timestamp) {
        const now = Date.now() / 1000;
        const diff = now - timestamp;
        
        if (diff < 60) return 'Just now';
        if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
        if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
        return `${Math.floor(diff / 86400)}d ago`;
    }

    /**
     * Load analytics data from database
     */
    function loadAnalyticsData() {
        // Show loading state
        $('#totalProfessionals, #activeBookings, #completedSessions, #assessmentsToday').text('...');
        
        Promise.all([
            fetch(`${API_ROOT}/admin/professionals`).then(res => res.json()),
            fetch(`${API_ROOT}/admin/bookings`).then(res => res.json()),
            fetch(`${API_ROOT}/admin/risk-assessments?limit=100`).then(res => res.json())
        ]).then(([professionalsData, bookingsData, riskData]) => {
            // Total professionals
            const totalProfessionals = professionalsData.professionals ? professionalsData.professionals.length : 0;
            $('#totalProfessionals').text(totalProfessionals);
            
            // Active bookings
            const activeBookings = bookingsData.bookings ? 
                bookingsData.bookings.filter(b => ['pending', 'confirmed'].includes(b.booking_status)).length : 0;
            $('#activeBookings').text(activeBookings);
            
            // Completed sessions
            const completedSessions = bookingsData.bookings ? 
                bookingsData.bookings.filter(b => b.booking_status === 'completed').length : 0;
            $('#completedSessions').text(completedSessions);
            
            // Assessments today
            const today = new Date().toISOString().split('T')[0];
            const assessmentsToday = riskData.assessments ? 
                riskData.assessments.filter(r => {
                    const assessmentDate = new Date(r.assessment_timestamp * 1000).toISOString().split('T')[0];
                    return assessmentDate === today;
                }).length : 0;
            $('#assessmentsToday').text(assessmentsToday);
            
        }).catch(error => {
            console.error('Error loading analytics data:', error);
            $('#totalProfessionals, #activeBookings, #completedSessions, #assessmentsToday').text('0');
        });
    }

    /**
     * Load RAG status
     */
    function loadRAGStatus() {
        // RAG status is already set in HTML
        // This function can be used to update real-time status
    }


    /**
     * Save professional
     */
    function saveProfessional() {
        console.log('Saving professional...');
        
        // Validate form
        if (!validateProfessionalForm()) {
            console.log('Form validation failed');
            return;
        }

        // Get form data
        const form = $('#professionalForm');
        const formData = new FormData(form[0]);
        const data = Object.fromEntries(formData.entries());
        
        console.log('Form data collected:', data);
        
        // Get expertise areas
        const expertiseAreas = $('input[name="expertise"]:checked').map(function() {
            return this.value;
        }).get();
        
        console.log('Expertise areas selected:', expertiseAreas);
        
        const professionalData = {
            username: data.username,
            first_name: data.first_name,
            last_name: data.last_name,
            email: data.email,
            phone: data.phone || '',
            specialization: data.specialization,
            experience_years: parseInt(data.experience_years) || 0,
            expertise_areas: expertiseAreas,
            district: data.district || '',
            consultation_fee: parseFloat(data.consultation_fee) || 0,
            bio: data.bio || '',
            languages: ['english'], // Default languages
            qualifications: [], // Default qualifications
            availability_schedule: {} // Default schedule
        };

        // Add password only for new professionals or if provided in edit mode
        const isEditMode = $('#modalTitle').text().includes('Edit');
        if (!isEditMode) {
            professionalData.password = data.password;
        } else {
            // For edit mode, only include password if provided
            const password = data.password;
            if (password && password.trim()) {
                professionalData.password = password;
            }
        }

        console.log('Professional data to send:', professionalData);

        // Show loading state
        $('#saveProfessionalBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');

        const url = isEditMode ? 
            `${API_ROOT}/admin/professionals/${currentProfessionalId}` : 
            `${API_ROOT}/admin/professionals`;
        const method = isEditMode ? 'PUT' : 'POST';
        
        console.log('Sending request to:', url, 'Method:', method);

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(professionalData)
        })
        .then(response => response.json())
        .then(data => {
            console.log(' Response data:', data);
            if (data.success) {
        Swal.fire({
            title: 'Success!',
                    text: isEditMode ? 'Professional updated successfully!' : 'Professional added successfully!',
            icon: 'success',
            timer: 2000
        }).then(() => {
            $('#professionalModal').modal('hide');
            loadProfessionals();
                    resetProfessionalForm();
                });
            } else {
                Swal.fire({
                    title: 'Error!',
                    text: data.error || 'Failed to save professional.',
                    icon: 'error'
                });
            }
        })
        .catch(error => {
            console.error('Error saving professional:', error);
            Swal.fire({
                title: 'Error!',
                text: 'Failed to save professional. Please try again.',
                icon: 'error'
            });
        })
        .finally(() => {
            $('#saveProfessionalBtn').prop('disabled', false).html('Save Professional');
        });
    }
    
    /**
     * Validate professional form
     */
    function validateProfessionalForm() {
        console.log('Validating professional form...');
        
        const requiredFields = ['username', 'first_name', 'last_name', 'email', 'specialization'];
        const isEditMode = $('#modalTitle').text().includes('Edit');
        
        // Check if password is required (only for new professionals)
        if (!isEditMode) {
            requiredFields.push('password');
        } else {
            // For edit mode, make password optional
            $('#password').prop('required', false);
        }
        
        let isValid = true;
        let errorMessage = '';
        
        // Clear previous validation errors
        $('.is-invalid').removeClass('is-invalid');
        
        // Check required fields
        requiredFields.forEach(field => {
            const value = $(`#${field}`).val().trim();
            if (!value) {
                $(`#${field}`).addClass('is-invalid');
                isValid = false;
                const fieldName = field.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
                errorMessage += `${fieldName} is required.\n`;
            } else {
                $(`#${field}`).removeClass('is-invalid');
            }
        });
        
        // Validate email format
        const email = $('#email').val().trim();
        if (email && !isValidEmail(email)) {
            $('#email').addClass('is-invalid');
            isValid = false;
            errorMessage += 'Please enter a valid email address.\n';
        }
        
        // Validate phone format (if provided)
        const phone = $('#phone').val().trim();
        if (phone && !isValidPhone(phone)) {
            $('#phone').addClass('is-invalid');
            isValid = false;
            errorMessage += 'Please enter a valid phone number.\n';
        }
        
        // Check if at least one expertise area is selected
        if (!validateExpertiseAreas()) {
            isValid = false;
            errorMessage += 'Please select at least one expertise area.\n';
        }
        
        // Validate experience years
        const experienceYears = parseInt($('#experience_years').val()) || 0;
        if (experienceYears < 0) {
            $('#experience_years').addClass('is-invalid');
            isValid = false;
            errorMessage += 'Experience years cannot be negative.\n';
        }
        
        // Validate consultation fee
        const consultationFee = parseFloat($('#consultation_fee').val()) || 0;
        if (consultationFee < 0) {
            $('#consultation_fee').addClass('is-invalid');
            isValid = false;
            errorMessage += 'Consultation fee cannot be negative.\n';
        }
        
        if (!isValid) {
            console.error(' Form validation failed:', errorMessage);
            Swal.fire({
                title: 'Validation Error',
                text: errorMessage.trim(),
                icon: 'error',
                confirmButtonText: 'Fix Issues'
            });
        } else {
            console.log(' Form validation passed');
        }
        
        return isValid;
    }
    
    /**
     * Validate email format
     */
    function isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }
    
    /**
     * Validate phone format
     */
    function isValidPhone(phone) {
        const phoneRegex = /^[\+]?[0-9\s\-\(\)]{10,}$/;
        return phoneRegex.test(phone);
    }
    

    /**
     * Reset professional form
     */
    function resetProfessionalForm() {
        $('#professionalForm')[0].reset();
        $('input[name="expertise"]').prop('checked', false);
        $('.is-invalid').removeClass('is-invalid');
        currentProfessionalId = null;
        $('#password').prop('required', true);
    }
    
    /**
     * Ensure all inputs are working properly
     */
    function ensureInputsWorking() {
        const form = $('#professionalForm');
        const inputs = form.find('input, select, textarea');
        
        console.log('🔧 Ensuring input functionality for', inputs.length, 'inputs');
        
        inputs.each(function() {
            const input = $(this);
            
            // Ensure all inputs are enabled
            input.prop('disabled', false);
            input.prop('readonly', false);
            
            // Force CSS properties
            input.css({
                'background-color': '#fff !important',
                'color': '#497060 !important',
                'pointer-events': 'auto !important',
                'user-select': 'text !important',
                'cursor': 'text !important'
            });
            
            // Add click handler to ensure focus
            input.off('click.ensureFocus').on('click.ensureFocus', function() {
                $(this).focus();
                console.log(' Input clicked:', $(this).attr('name'));
            });
            
            // Add keydown handler to ensure typing works
            input.off('keydown.ensureTyping').on('keydown.ensureTyping', function(e) {
                console.log(' Key pressed:', e.key, 'in', $(this).attr('name'));
                // Allow all normal typing
                if (e.key.length === 1 || e.key === 'Backspace' || e.key === 'Delete' || 
                    e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'Tab') {
                    return true;
                }
            });
            
            // Add input handler for real-time validation
            input.off('input.validate').on('input.validate', function() {
                console.log(' Input changed:', $(this).attr('name'), '=', $(this).val());
                validateInput($(this));
            });
        });
        
        console.log(' Input functionality ensured for', inputs.length, 'inputs');
    }
    
    /**
     * Validate individual input
     */
    function validateInput(input) {
        const value = input.val().trim();
        const isRequired = input.prop('required');
        
        if (isRequired && !value) {
            input.removeClass('is-valid').addClass('is-invalid');
        } else if (value) {
            input.removeClass('is-invalid').addClass('is-valid');
        } else {
            input.removeClass('is-invalid is-valid');
        }
        
        // Check form validity
        checkFormValidity();
    }
    
    /**
     * Check overall form validity
     */
 function checkFormValidity() {
        const form = $('#professionalForm');
        const requiredFields = form.find('[required]');
        let isValid = true;
        
        requiredFields.each(function() {
            const field = $(this);
            const value = field.val().trim();
            if (!value) {
                isValid = false;
                return false;
            }
        });
        
        // Check expertise areas
        if (!validateExpertiseAreas()) {
            isValid = false;
        }
        
        // Enable/disable submit button
        const submitBtn = form.find('button[type="submit"]');
        if (submitBtn.length) {
            submitBtn.prop('disabled', !isValid);
        }
        
        return isValid;
    }
    
    /**
     * Debug form inputs
     */
    function debugFormInputs() {
        const form = $('#professionalForm');
        const inputs = form.find('input, select, textarea');
        
        console.log(' Debugging form inputs:');
        inputs.each(function(index) {
            const input = $(this);
            const isFocusable = function() {
                try {
                    input.focus();
                    return document.activeElement === input[0];
                } catch (e) {
                    return false;
                }
            }();
            
            console.log(`Input ${index}:`, {
                type: input.attr('type') || input.prop('tagName').toLowerCase(),
                name: input.attr('name'),
                id: input.attr('id'),
                value: input.val(),
                disabled: input.prop('disabled'),
                readonly: input.prop('readonly'),
                focusable: isFocusable,
                style: input.attr('style')
            });
        });
    }
    
    /**
     * Force input functionality
     */
    function forceInputFunctionality() {
        const form = $('#professionalForm');
        const inputs = form.find('input, select, textarea');
        
        inputs.each(function() {
            const input = $(this);
            
            // Force enable inputs
            input.prop('disabled', false);
            input.prop('readonly', false);
            
            // Force CSS properties
            input.css({
                'background-color': '#fff',
                'color': '#497060',
                'pointer-events': 'auto',
                'user-select': 'text',
                'cursor': 'text'
            });
            
            // Add event listeners
            input.off('click.force').on('click.force', function() {
                $(this).focus();
                console.log(' Input clicked:', $(this).attr('name'));
            });
            
            input.off('keydown.force').on('keydown.force', function(e) {
                console.log(' Key pressed:', e.key, 'in', $(this).attr('name'));
            });
            
            input.off('input.force').on('input.force', function() {
                console.log(' Input changed:', $(this).attr('name'), '=', $(this).val());
            });
        });
        
        console.log('🔧 Forced input functionality for', inputs.length, 'inputs');
    }

    /**
     * Filter professionals by search term
     */
    function filterProfessionals(searchTerm) {
        console.log(' Filtering professionals by:', searchTerm);
        
        if (dataTables.professionals) {
            dataTables.professionals.search(searchTerm).draw();
        } else {
            // Fallback: filter table rows manually
            $('#professionalsTableBody tr').each(function() {
                const row = $(this);
                const text = row.text().toLowerCase();
                if (text.includes(searchTerm)) {
                    row.show();
                } else {
                    row.hide();
                }
            });
        }
    }

    /**
     * Filter professionals by specialization
     */
    function filterProfessionalsBySpecialization(specialization) {
        console.log(' Filtering professionals by specialization:', specialization);
        
        if (dataTables.professionals) {
            if (specialization === '') {
                dataTables.professionals.column(2).search('').draw();
            } else {
                dataTables.professionals.column(2).search(specialization).draw();
            }
        } else {
            // Fallback: filter table rows manually
            $('#professionalsTableBody tr').each(function() {
                const row = $(this);
                const specializationCell = row.find('td:eq(2)').text().toLowerCase();
                if (specialization === '' || specializationCell.includes(specialization.toLowerCase())) {
                    row.show();
                } else {
                    row.hide();
                }
            });
        }
    }

    /**
     * Apply filters
     */
    function applyFilters() {
        const status = $('#statusFilter').val();
        const riskLevel = $('#riskLevelFilter').val();
        const specialization = $('#specializationFilter').val();

        // Apply filters to DataTables
        if (dataTables.bookings) {
            dataTables.bookings.column(5).search(status).draw();
        }
        if (dataTables.professionals) {
            dataTables.professionals.column(2).search(specialization).draw();
        }
    }

    /**
     * Export table to CSV
     */
    function exportTableToCSV(tableId, filename) {
        const table = document.getElementById(tableId);
        const rows = table.querySelectorAll('tr');
        let csv = [];

        for (let i = 0; i < rows.length; i++) {
            const row = [];
            const cols = rows[i].querySelectorAll('td, th');
            
            for (let j = 0; j < cols.length; j++) {
                row.push(cols[j].innerText);
            }
            csv.push(row.join(','));
        }

        const csvContent = csv.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    }

    /**
     * Get risk badge class
     */
    function getRiskBadgeClass(riskLevel) {
        const classes = {
            'critical': 'danger',
            'high': 'warning',
            'medium': 'info',
            'low': 'success'
        };
        return classes[riskLevel.toLowerCase()] || 'secondary';
    }

    /**
     * Get status badge class
     */
    function getStatusBadgeClass(status) {
        const classes = {
            'pending': 'warning',
            'confirmed': 'info',
            'completed': 'success',
            'declined': 'danger',
            'active': 'success',
            'inactive': 'secondary'
        };
        return classes[status.toLowerCase()] || 'secondary';
    }

    /**
     * Get current professional ID for editing
     */
    function getCurrentProfessionalId() {
        return currentProfessionalId;
    }

    /**
     * Handle API errors gracefully
     */
    function handleAPIError(error, context = 'API call') {
        console.error(`Error in ${context}:`, error);
        
        // Show user-friendly error message
        Swal.fire({
            title: 'Connection Error',
            text: 'Unable to connect to the server. Please check your internet connection and try again.',
            icon: 'error',
            timer: 5000
        });
    }

    /**
     * Refresh all data
     */
    function refreshAllData() {
        // Show loading state
        const refreshBtn = $('#refreshAllBtn');
        const originalText = refreshBtn.html();
        refreshBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Refreshing...');
        
        // Refresh current section data
        if (currentSection === 'dashboard') {
            loadDashboardData();
        } else {
            loadSectionData(currentSection);
        }
        
        // Reset button after a delay
        setTimeout(() => {
            refreshBtn.prop('disabled', false).html(originalText);
        }, 2000);
    }

    /**
     * Start auto-refresh
     */
    function startAutoRefresh() {
        setInterval(() => {
            if (currentSection === 'dashboard') {
                loadDashboardData();
            } else {
                loadSectionData(currentSection);
            }
        }, 30000); // Refresh every 30 seconds
    }

    /**
     * Toggle professional status
     */
    function toggleProfessionalStatus(profId) {
        // Get current status from the button
        const button = $(`button[onclick="toggleProfessionalStatus(${profId})"]`);
        const isCurrentlyActive = button.hasClass('btn-warning'); // warning = active, success = inactive
        
        fetch(`${API_ROOT}/admin/professionals/${profId}/status`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                is_active: !isCurrentlyActive
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    title: 'Success!',
                    text: data.message || 'Professional status updated.',
                    icon: 'success',
                    timer: 2000
                }).then(() => {
                    loadProfessionals();
                });
            } else {
                Swal.fire({
                    title: 'Error!',
                    text: data.error || 'Failed to update professional status.',
                    icon: 'error'
                });
            }
        })
        .catch(error => {
            console.error('Error toggling professional status:', error);
            Swal.fire({
                title: 'Error!',
                text: 'Failed to update professional status.',
                icon: 'error'
            });
        });
    }

    /**
     * Global functions for onclick handlers
     */
    window.editProfessional = function(id) {
        console.log(' Editing professional with ID:', id);
        
        // Show loading state
        Swal.fire({
            title: 'Loading...',
            text: 'Loading professional data...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Load professional data and populate form
        fetch(`${API_ROOT}/admin/professionals`)
            .then(response => {
                console.log('📡 Edit professional API response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log(' Professional data for editing:', data);
                const professional = data.professionals.find(p => p.id === id);
                
                if (professional) {
                    console.log(' Professional found:', professional);
                    
                    // Store current professional ID for editing
                    currentProfessionalId = id;
                    
                    // Populate form with professional data
                    $('#username').val(professional.username || '');
                    $('#first_name').val(professional.first_name || '');
                    $('#last_name').val(professional.last_name || '');
                    $('#email').val(professional.email || '');
                    $('#phone').val(professional.phone || '');
                    $('#specialization').val(professional.specialization || '');
                    $('#experience_years').val(professional.experience_years || 0);
                    $('#district').val(professional.district || '');
                    $('#consultation_fee').val(professional.consultation_fee || 0);
                    $('#bio').val(professional.bio || '');
                    
                    // Set expertise checkboxes
                    if (professional.expertise_areas) {
                        let expertiseAreas = [];
                        if (Array.isArray(professional.expertise_areas)) {
                            expertiseAreas = professional.expertise_areas;
                        } else if (typeof professional.expertise_areas === 'string') {
                            expertiseAreas = professional.expertise_areas.split(',').map(area => area.trim());
                        }
                        
                    $('input[name="expertise"]').prop('checked', false);
                    expertiseAreas.forEach(area => {
                            const trimmedArea = area.trim();
                            if (trimmedArea) {
                                $(`#expertise_${trimmedArea}`).prop('checked', true);
                            }
                    });
                    } else {
                        $('input[name="expertise"]').prop('checked', false);
                    }
                    
                    // Update modal for edit mode
                    $('#modalTitle').text('Edit Professional');
                    $('#passwordRequired').text('');
                    $('#passwordHelp').show();
                    $('#password').prop('required', false).val('');
                    
                    // Close loading dialog and show modal
                    Swal.close();
                    $('#professionalModal').modal('show');
                    
                    // Ensure inputs work properly after modal is shown
                    setTimeout(() => {
                        ensureInputsWorking();
                        forceInputFunctionality();
                        debugFormInputs();
                        const firstInput = $('#professionalModal input[required]').first();
                        if (firstInput.length) {
                            firstInput.focus();
                            console.log(' Focused on first input:', firstInput.attr('name'));
                        }
                    }, 300);
                    
                    console.log(' Professional form populated successfully');
                } else {
                    console.error(' Professional not found with ID:', id);
                    Swal.fire('Error', 'Professional not found.', 'error');
                }
            })
            .catch(error => {
                console.error(' Error loading professional:', error);
                Swal.fire('Error', `Failed to load professional data: ${error.message}`, 'error');
            });
    };

    window.deleteProfessional = function(id) {
        Swal.fire({
            title: 'Delete Professional?',
            text: 'This action cannot be undone!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch(`${API_ROOT}/admin/professionals/${id}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                Swal.fire('Deleted!', 'Professional has been deleted.', 'success');
                loadProfessionals();
                    } else {
                        Swal.fire('Error!', data.error || 'Failed to delete professional.', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error deleting professional:', error);
                    Swal.fire('Error!', 'Failed to delete professional.', 'error');
                });
            }
        });
    };

    window.toggleProfessionalStatus = toggleProfessionalStatus;

    window.viewBooking = function(id) {
        // Show loading state
        $('#bookingDetails').html('<div class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading booking details...</div>');
        $('#bookingModal').modal('show');
        
        // Load booking details
        fetch(`${API_ROOT}/admin/bookings`)
            .then(response => response.json())
            .then(data => {
                const booking = data.bookings.find(b => b.booking_id === id);
                if (booking) {
                    const scheduledTime = new Date(booking.scheduled_datetime * 1000).toLocaleString();
                    const createdTime = new Date(booking.created_ts * 1000).toLocaleString();
                    const userInitials = getUserInitials(booking.user_fullname || booking.user_account || 'Guest');
                    const professionalInitials = getUserInitials(booking.professional_name || 'Unassigned');
                    
                    const bookingDetails = `
                        <!-- Booking Header -->
                        <div class="booking-header mb-4">
                            <div class="row">
                                <div class="col-md-8">
                                    <h4 class="mb-2">
                                        <i class="fas fa-calendar-check text-primary"></i>
                                        Booking Details
                                    </h4>
                                    <p class="text-muted mb-0">Booking ID: <code>${booking.booking_id}</code></p>
                                </div>
                                <div class="col-md-4 text-right">
                                    <span class="status-badge ${booking.booking_status.toLowerCase()}">
                                        <i class="fas fa-${getStatusIcon(booking.booking_status)}"></i>
                                        ${booking.booking_status.toUpperCase()}
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- User Information -->
                        <div class="card mb-4">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-user"></i> User Information
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-2">
                                        <div class="user-avatar-large">
                                            ${userInitials}
                                        </div>
                                    </div>
                                    <div class="col-md-10">
                        <div class="row">
                            <div class="col-md-6">
                                                <h6 class="text-primary">Personal Details</h6>
                                                <p><strong>Full Name:</strong> ${booking.user_fullname || booking.user_account || 'Guest User'}</p>
                                                <p><strong>Username:</strong> ${booking.user_account || 'N/A'}</p>
                                                <p><strong>Email:</strong> 
                                                    <a href="mailto:${booking.user_email || ''}" class="text-primary">
                                                        <i class="fas fa-envelope"></i> ${booking.user_email || 'No email provided'}
                                                    </a>
                                                </p>
                                                <p><strong>Phone:</strong> 
                                                    <a href="tel:${booking.user_phone || ''}" class="text-primary">
                                                        <i class="fas fa-phone"></i> ${booking.user_phone || 'No phone provided'}
                                                    </a>
                                                </p>
                            </div>
                            <div class="col-md-6">
                                                <h6 class="text-primary">Location Information</h6>
                                                <p><strong>Province:</strong> ${booking.user_province || 'Not specified'}</p>
                                                <p><strong>District:</strong> ${booking.user_district || 'Not specified'}</p>
                                                <p><strong>Full Location:</strong> ${booking.user_location || 'Location not specified'}</p>
                                                <p><strong>IP Address:</strong> ${booking.user_ip || 'N/A'}</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Professional Information -->
                        <div class="card mb-4">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-user-md"></i> Professional Information
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-2">
                                        <div class="professional-avatar-large">
                                            ${professionalInitials}
                                        </div>
                                    </div>
                                    <div class="col-md-10">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h6 class="text-success">Professional Details</h6>
                                                <p><strong>Name:</strong> ${booking.professional_name || 'Unassigned'}</p>
                                                <p><strong>Specialization:</strong> ${booking.professional_specialization || 'Not specified'}</p>
                                                <p><strong>Email:</strong> 
                                                    <a href="mailto:${booking.professional_email || ''}" class="text-success">
                                                        <i class="fas fa-envelope"></i> ${booking.professional_email || 'No email provided'}
                                                    </a>
                                                </p>
                                                <p><strong>Phone:</strong> 
                                                    <a href="tel:${booking.professional_phone || ''}" class="text-success">
                                                        <i class="fas fa-phone"></i> ${booking.professional_phone || 'No phone provided'}
                                                    </a>
                                                </p>
                                            </div>
                                            <div class="col-md-6">
                                                <h6 class="text-success">Assignment Status</h6>
                                                <p><strong>Status:</strong> ${booking.professional_name ? 'Assigned' : 'Unassigned'}</p>
                                                <p><strong>Assignment Date:</strong> ${booking.professional_name ? createdTime : 'Pending'}</p>
                                                <p><strong>Professional ID:</strong> ${booking.professional_id || 'N/A'}</p>
                                                <p><strong>Experience:</strong> ${booking.professional_experience || 'N/A'} years</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Booking Details -->
                        <div class="card mb-4">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-calendar-alt"></i> Booking Details
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6 class="text-info">Schedule Information</h6>
                                <p><strong>Scheduled Time:</strong> ${scheduledTime}</p>
                                <p><strong>Created:</strong> ${createdTime}</p>
                                        <p><strong>Session Type:</strong> ${booking.session_type || 'Emergency'}</p>
                                        <p><strong>Duration:</strong> ${booking.session_duration || '60 minutes'}</p>
                                    </div>
                                    <div class="col-md-6">
                                        <h6 class="text-info">Risk Assessment</h6>
                                        <p><strong>Risk Level:</strong> 
                                            <span class="risk-badge ${booking.risk_level.toLowerCase()}">
                                                <i class="fas fa-${getRiskIcon(booking.risk_level)}"></i>
                                                ${booking.risk_level.toUpperCase()}
                                            </span>
                                        </p>
                                <p><strong>Risk Score:</strong> ${(booking.risk_score * 100).toFixed(1)}%</p>
                                        <p><strong>Detected Indicators:</strong> ${booking.detected_indicators || 'None detected'}</p>
                                        <p><strong>Assessment Time:</strong> ${new Date(booking.assessment_timestamp * 1000).toLocaleString()}</p>
                            </div>
                        </div>
                            </div>
                        </div>

                        <!-- Additional Information -->
                        <div class="card">
                            <div class="card-header bg-warning text-dark">
                                <h5 class="mb-0">
                                    <i class="fas fa-info-circle"></i> Additional Information
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6 class="text-warning">Session Details</h6>
                                        <p><strong>Location Preference:</strong> ${booking.location_preference || 'Not specified'}</p>
                                        <p><strong>Session Notes:</strong> ${booking.session_notes || 'No notes available'}</p>
                                        <p><strong>Treatment Plan:</strong> ${booking.treatment_plan || 'Not available'}</p>
                                    </div>
                                    <div class="col-md-6">
                                        <h6 class="text-warning">System Information</h6>
                                        <p><strong>Conversation ID:</strong> ${booking.conv_id || 'N/A'}</p>
                                        <p><strong>Booking Source:</strong> ${booking.booking_source || 'Automated'}</p>
                                        <p><strong>Last Updated:</strong> ${new Date(booking.updated_ts * 1000).toLocaleString()}</p>
                                        <p><strong>System Notes:</strong> ${booking.notes || 'No additional notes'}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    $('#bookingDetails').html(bookingDetails);
                } else {
                    $('#bookingDetails').html('<div class="alert alert-warning">Booking not found.</div>');
                }
            })
            .catch(error => {
                console.error('Error loading booking details:', error);
                $('#bookingDetails').html('<div class="alert alert-danger">Error loading booking details.</div>');
            });
    };
    
    /**
     * Get status icon for display
     */
    function getStatusIcon(status) {
        const statusIcons = {
            pending: 'clock',
            confirmed: 'check-circle',
            completed: 'check-double',
            declined: 'times-circle',
            cancelled: 'ban'
        };
        return statusIcons[status.toLowerCase()] || 'question-circle';
    }
    
    /**
     * Get risk icon for display
     */
    function getRiskIcon(riskLevel) {
        const riskIcons = {
            critical: 'exclamation-triangle',
            high: 'exclamation-circle',
            medium: 'info-circle',
            low: 'check-circle'
        };
        return riskIcons[riskLevel.toLowerCase()] || 'question-circle';
    }

    window.editBooking = function(id) {
        Swal.fire({
            title: 'Edit Booking',
            text: `Edit booking with ID: ${id}`,
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: 'View Details',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                viewBooking(id);
            }
        });
    };



    // Global debug functions
    window.debugFormInputs = debugFormInputs;
    window.forceInputFunctionality = forceInputFunctionality;
    window.ensureInputsWorking = ensureInputsWorking;
    window.testInputs = function() {
        console.log('🧪 Testing input functionality...');
        const form = $('#professionalForm');
        if (form.length === 0) {
            console.log(' Form not found');
            return;
        }
        
        const inputs = form.find('input, select, textarea');
        console.log('📝 Found', inputs.length, 'inputs');
        
        inputs.each(function(index) {
            const input = $(this);
            console.log(`Input ${index}:`, {
                name: input.attr('name'),
                type: input.attr('type'),
                value: input.val(),
                disabled: input.prop('disabled'),
                readonly: input.prop('readonly')
            });
        });
        
        // Test focus
        const firstInput = inputs.first();
        if (firstInput.length) {
            firstInput.focus();
            console.log(' Focused on first input:', firstInput.attr('name'));
        }
    };

    // Show dashboard by default
    showSection('dashboard');

    /**
     * Initialize expertise areas functionality
     */
    function initializeExpertiseAreas() {
        console.log('🧠 Initializing expertise areas functionality...');
        
        // Select All button
        $('#selectAllExpertise').on('click', function() {
            $('input[name="expertise"]').prop('checked', true);
            updateExpertiseCount();
            updateExpertiseValidation();
            console.log(' All expertise areas selected');
        });
        
        // Clear All button
        $('#clearAllExpertise').on('click', function() {
            $('input[name="expertise"]').prop('checked', false);
            updateExpertiseCount();
            updateExpertiseValidation();
            console.log(' All expertise areas cleared');
        });
        
        // Individual checkbox change
        $('input[name="expertise"]').on('change', function() {
            updateExpertiseCount();
            updateExpertiseValidation();
            
            // Add visual feedback
            const label = $(this).next('.expertise-label');
            if ($(this).is(':checked')) {
                label.addClass('selected');
                console.log(' Expertise selected:', $(this).val());
            } else {
                label.removeClass('selected');
                console.log(' Expertise deselected:', $(this).val());
            }
        });
        
        // Initialize count
        updateExpertiseCount();
        updateExpertiseValidation();
        
        console.log(' Expertise areas functionality initialized');
    }
    
    /**
     * Update expertise selection count
     */
    function updateExpertiseCount() {
        const selectedCount = $('input[name="expertise"]:checked').length;
        const totalCount = $('input[name="expertise"]').length;
        
        $('#selectedCount').text(selectedCount);
        
        // Update select all button state
        const selectAllBtn = $('#selectAllExpertise');
        const clearAllBtn = $('#clearAllExpertise');
        
        if (selectedCount === totalCount) {
            selectAllBtn.addClass('btn-primary').removeClass('btn-outline-primary');
            selectAllBtn.html('<i class="fas fa-check-square"></i> All Selected');
        } else {
            selectAllBtn.addClass('btn-outline-primary').removeClass('btn-primary');
            selectAllBtn.html('<i class="fas fa-check-square"></i> Select All');
        }
        
        if (selectedCount === 0) {
            clearAllBtn.addClass('btn-secondary').removeClass('btn-outline-secondary');
            clearAllBtn.html('<i class="fas fa-square"></i> All Cleared');
        } else {
            clearAllBtn.addClass('btn-outline-secondary').removeClass('btn-secondary');
            clearAllBtn.html('<i class="fas fa-square"></i> Clear All');
        }
    }
    
    /**
     * Update expertise validation state
     */
    function updateExpertiseValidation() {
        const selectedCount = $('input[name="expertise"]:checked').length;
        const expertiseContainer = $('.form-group:has(input[name="expertise"])');
        
        if (selectedCount === 0) {
            expertiseContainer.addClass('is-invalid').removeClass('is-valid');
            $('input[name="expertise"]').addClass('is-invalid');
        } else {
            expertiseContainer.removeClass('is-invalid').addClass('is-valid');
            $('input[name="expertise"]').removeClass('is-invalid');
        }
    }
    
    /**
     * Validate expertise areas selection
     */
    function validateExpertiseAreas() {
        const selectedCount = $('input[name="expertise"]:checked').length;
        return selectedCount > 0;
    }
    
    /**
     * Initialize bookings filtering functionality
     */
    function initializeBookingsFiltering() {
        console.log(' Initializing bookings filtering...');
        
        // Filter change events
        $('#statusFilter, #riskLevelFilter, #professionalFilter, #fromDateFilter, #toDateFilter').on('change', function() {
            applyBookingsFilters();
        });
        
        // Search input
        $('#bookingSearch').on('keyup', function() {
            clearTimeout(this.searchTimeout);
            this.searchTimeout = setTimeout(() => {
                applyBookingsFilters();
            }, 300);
        });
        
        // Clear filters button
        $('#clearFiltersBtn').on('click', function() {
            clearBookingsFilters();
        });
        
        // Apply filters button
        $('#applyFiltersBtn').on('click', function() {
            applyBookingsFilters();
        });
        
        console.log(' Bookings filtering initialized');
    }
    
    /**
     * Apply bookings filters
     */
    function applyBookingsFilters() {
        const status = $('#statusFilter').val();
        const riskLevel = $('#riskLevelFilter').val();
        const professional = $('#professionalFilter').val();
        const fromDate = $('#fromDateFilter').val();
        const toDate = $('#toDateFilter').val();
        const search = $('#bookingSearch').val().toLowerCase();
        
        console.log(' Applying filters:', { status, riskLevel, professional, fromDate, toDate, search });
        
        if (dataTables.bookings) {
            dataTables.bookings.column(5).search(status); // Status column
            dataTables.bookings.column(3).search(riskLevel); // Risk level column
            dataTables.bookings.column(2).search(professional); // Professional column
            dataTables.bookings.search(search).draw();
        }
        
        // Update filter button states
        updateFilterButtonStates();
    }
    
    /**
     * Clear all bookings filters
     */
    function clearBookingsFilters() {
        $('#statusFilter, #riskLevelFilter, #professionalFilter').val('');
        $('#fromDateFilter, #toDateFilter').val('');
        $('#bookingSearch').val('');
        
        if (dataTables.bookings) {
            dataTables.bookings.search('').columns().search('').draw();
        }
        
        updateFilterButtonStates();
        console.log('🧹 Filters cleared');
    }
    
    /**
     * Update filter button states
     */
    function updateFilterButtonStates() {
        const hasActiveFilters = $('#statusFilter').val() || 
                                $('#riskLevelFilter').val() || 
                                $('#professionalFilter').val() || 
                                $('#fromDateFilter').val() || 
                                $('#toDateFilter').val() || 
                                $('#bookingSearch').val();
        
        if (hasActiveFilters) {
            $('#clearFiltersBtn').removeClass('btn-outline-secondary').addClass('btn-secondary');
            $('#applyFiltersBtn').removeClass('btn-outline-primary').addClass('btn-primary');
        } else {
            $('#clearFiltersBtn').removeClass('btn-secondary').addClass('btn-outline-secondary');
            $('#applyFiltersBtn').removeClass('btn-primary').addClass('btn-outline-primary');
        }
    }
    
    /**
     * Complete booking action
     */
    window.completeBooking = function(bookingId) {
        Swal.fire({
            title: 'Complete Booking',
            text: 'Are you sure you want to mark this booking as completed?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Complete',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#10b981'
        }).then((result) => {
            if (result.isConfirmed) {
                // Update booking status
                updateBookingStatus(bookingId, 'completed');
            }
        });
    };
    
    /**
     * Cancel booking action
     */
    window.cancelBooking = function(bookingId) {
        Swal.fire({
            title: 'Cancel Booking',
            text: 'Are you sure you want to cancel this booking?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, Cancel',
            cancelButtonText: 'Keep Booking',
            confirmButtonColor: '#ef4444'
        }).then((result) => {
            if (result.isConfirmed) {
                // Update booking status
                updateBookingStatus(bookingId, 'cancelled');
            }
        });
    };
    
    /**
     * Update booking status
     */
    function updateBookingStatus(bookingId, newStatus) {
        console.log(`📝 Updating booking ${bookingId} to ${newStatus}`);
        
        // Show loading
        Swal.fire({
            title: 'Updating...',
            text: 'Please wait while we update the booking status.',
            allowOutsideClick: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Simulate API call (replace with actual API call)
        setTimeout(() => {
            Swal.fire({
                title: 'Success!',
                text: `Booking has been ${newStatus}.`,
                icon: 'success',
                confirmButtonText: 'OK'
            }).then(() => {
                // Reload bookings
                loadBookings();
            });
        }, 1000);
    }

})();