communitas-ui-api 0.8.4

Shared view models and API types for Communitas UI stacks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
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
//! Call and WebRTC related DTOs for real-time communication.

use serde::{Deserialize, Serialize};

/// Type of call (determines participant limits and features).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum CallType {
    /// Direct one-on-one call.
    #[default]
    Direct,
    /// Group call with multiple participants.
    Group,
    /// Channel-wide call (like Discord voice channel).
    Channel,
}

impl CallType {
    /// Returns a human-readable label for the call type.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Direct => "Call",
            Self::Group => "Group Call",
            Self::Channel => "Voice Channel",
        }
    }

    /// Returns the default maximum participants for this call type.
    pub fn default_max_participants(&self) -> u32 {
        match self {
            Self::Direct => 2,
            Self::Group => 25,
            Self::Channel => 100,
        }
    }

    /// Returns true if this call type supports host controls.
    pub fn has_host_controls(&self) -> bool {
        !matches!(self, Self::Direct)
    }
}

/// Role of a participant in a call.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ParticipantRole {
    /// Regular participant.
    #[default]
    Participant,
    /// Co-host with limited admin capabilities.
    CoHost,
    /// Full host with all controls.
    Host,
}

impl ParticipantRole {
    /// Returns a human-readable label for the role.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Participant => "Participant",
            Self::CoHost => "Co-Host",
            Self::Host => "Host",
        }
    }

    /// Returns true if this role can mute other participants.
    pub fn can_mute_others(&self) -> bool {
        matches!(self, Self::CoHost | Self::Host)
    }

    /// Returns true if this role can remove participants.
    pub fn can_remove_participants(&self) -> bool {
        matches!(self, Self::CoHost | Self::Host)
    }

    /// Returns true if this role can promote others.
    pub fn can_promote(&self) -> bool {
        matches!(self, Self::Host)
    }

    /// Returns true if this role can end the call for everyone.
    pub fn can_end_call(&self) -> bool {
        matches!(self, Self::Host)
    }

    /// Returns true if this role can start/stop recording.
    pub fn can_manage_recording(&self) -> bool {
        matches!(self, Self::CoHost | Self::Host)
    }
}

/// State of the current call.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum CallState {
    /// No active call.
    #[default]
    Idle,
    /// Establishing connection.
    Connecting,
    /// Active call in progress.
    InCall,
    /// Connection lost, attempting to reconnect.
    Reconnecting,
    /// Call ended normally or connection failed.
    Disconnected,
    /// Media capture failed.
    MediaError,
}

impl CallState {
    /// Returns true if this state represents an active or connecting call.
    pub fn is_active(&self) -> bool {
        matches!(self, Self::Connecting | Self::InCall | Self::Reconnecting)
    }

    /// Returns true if this state indicates the call has ended.
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Idle | Self::Disconnected | Self::MediaError)
    }
}

/// State of call recording.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum RecordingState {
    /// Not recording.
    #[default]
    NotRecording,
    /// Recording in progress.
    Recording,
    /// Recording paused.
    Paused,
    /// Recording stopped, file being finalized.
    Finalizing,
}

impl RecordingState {
    /// Returns true if recording is active (recording or paused).
    pub fn is_active(&self) -> bool {
        matches!(self, Self::Recording | Self::Paused | Self::Finalizing)
    }

    /// Returns a human-readable label for the recording state.
    pub fn label(&self) -> &'static str {
        match self {
            Self::NotRecording => "Not Recording",
            Self::Recording => "Recording",
            Self::Paused => "Paused",
            Self::Finalizing => "Saving...",
        }
    }

    /// Returns a CSS class for UI styling.
    pub fn status_class(&self) -> &'static str {
        match self {
            Self::NotRecording => "text-slate-400",
            Self::Recording => "text-red-500 animate-pulse",
            Self::Paused => "text-amber-500",
            Self::Finalizing => "text-blue-500",
        }
    }
}

/// Type of screen share source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ScreenShareSourceType {
    /// Entire monitor/display.
    Monitor,
    /// Single application window.
    Window,
}

impl ScreenShareSourceType {
    /// Returns a human-readable label for the source type.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Monitor => "Entire Screen",
            Self::Window => "Application Window",
        }
    }

    /// Returns an icon name for UI display.
    pub fn icon(&self) -> &'static str {
        match self {
            Self::Monitor => "display",
            Self::Window => "window",
        }
    }
}

/// A screen share source (monitor or window) that can be shared.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ScreenShareSource {
    /// Unique identifier for this source.
    pub id: String,
    /// Display name (e.g., "Built-in Display" or "Firefox").
    pub name: String,
    /// Type of source.
    pub source_type: ScreenShareSourceType,
    /// Optional application name (for windows).
    pub app_name: Option<String>,
    /// Whether this is the primary display (for monitors).
    pub is_primary: bool,
    /// Base64-encoded PNG thumbnail data.
    pub thumbnail: Option<String>,
    /// Thumbnail width in pixels.
    pub thumbnail_width: Option<u32>,
    /// Thumbnail height in pixels.
    pub thumbnail_height: Option<u32>,
}

impl ScreenShareSource {
    /// Create a new monitor source.
    pub fn monitor(id: impl Into<String>, name: impl Into<String>, is_primary: bool) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            source_type: ScreenShareSourceType::Monitor,
            app_name: None,
            is_primary,
            thumbnail: None,
            thumbnail_width: None,
            thumbnail_height: None,
        }
    }

    /// Create a new window source.
    pub fn window(
        id: impl Into<String>,
        name: impl Into<String>,
        app_name: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            source_type: ScreenShareSourceType::Window,
            app_name: Some(app_name.into()),
            is_primary: false,
            thumbnail: None,
            thumbnail_width: None,
            thumbnail_height: None,
        }
    }

    /// Add thumbnail data to this source.
    pub fn with_thumbnail(mut self, data: String, width: u32, height: u32) -> Self {
        self.thumbnail = Some(data);
        self.thumbnail_width = Some(width);
        self.thumbnail_height = Some(height);
        self
    }
}

/// Information about the active screen share session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ScreenShareInfo {
    /// The source being shared.
    pub source: ScreenShareSource,
    /// When the screen share started (ms since epoch).
    pub started_at: u64,
    /// Whether viewers have control (for remote assistance).
    pub allow_control: bool,
    /// Whether audio from the source is being shared.
    pub share_audio: bool,
}

impl ScreenShareInfo {
    /// Create new screen share info.
    pub fn new(source: ScreenShareSource, started_at: u64) -> Self {
        Self {
            source,
            started_at,
            allow_control: false,
            share_audio: false,
        }
    }
}

/// Information about an ongoing or completed recording.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecordingInfo {
    /// Unique recording identifier.
    pub id: String,
    /// Start timestamp (ms since epoch).
    pub started_at: u64,
    /// Total duration recorded (ms), excluding paused time.
    pub duration_ms: u64,
    /// Current recording state.
    pub state: RecordingState,
    /// File path where recording will be saved (if known).
    pub file_path: Option<String>,
    /// Estimated file size in bytes.
    pub file_size_bytes: u64,
    /// Whether audio is being recorded.
    pub includes_audio: bool,
    /// Whether video is being recorded.
    pub includes_video: bool,
    /// Whether screen share is being recorded.
    pub includes_screen: bool,
    /// Participant who started the recording.
    pub started_by: String,
}

impl Default for RecordingInfo {
    fn default() -> Self {
        Self {
            id: String::new(),
            started_at: 0,
            duration_ms: 0,
            state: RecordingState::NotRecording,
            file_path: None,
            file_size_bytes: 0,
            includes_audio: true,
            includes_video: false,
            includes_screen: false,
            started_by: String::new(),
        }
    }
}

impl RecordingInfo {
    /// Returns the formatted duration as MM:SS.
    pub fn formatted_duration(&self) -> String {
        let total_seconds = self.duration_ms / 1000;
        let minutes = total_seconds / 60;
        let seconds = total_seconds % 60;
        format!("{:02}:{:02}", minutes, seconds)
    }

    /// Returns the formatted file size (KB, MB, etc.).
    pub fn formatted_size(&self) -> String {
        if self.file_size_bytes < 1024 {
            format!("{} B", self.file_size_bytes)
        } else if self.file_size_bytes < 1024 * 1024 {
            format!("{:.1} KB", self.file_size_bytes as f64 / 1024.0)
        } else if self.file_size_bytes < 1024 * 1024 * 1024 {
            format!("{:.1} MB", self.file_size_bytes as f64 / (1024.0 * 1024.0))
        } else {
            format!(
                "{:.2} GB",
                self.file_size_bytes as f64 / (1024.0 * 1024.0 * 1024.0)
            )
        }
    }
}

/// Type of media device.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DeviceType {
    Microphone,
    Speaker,
    Camera,
}

impl DeviceType {
    /// Returns a human-readable label for the device type.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Microphone => "Microphone",
            Self::Speaker => "Speaker",
            Self::Camera => "Camera",
        }
    }
}

/// Information about an available media device.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MediaDevice {
    /// Unique device identifier.
    pub id: String,
    /// Human-readable device name.
    pub name: String,
    /// Type of device.
    pub device_type: DeviceType,
    /// Whether this is the system default device.
    pub is_default: bool,
    /// Whether the device is currently available.
    pub is_available: bool,
}

/// A participant in a call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Participant {
    /// Unique participant identifier.
    pub id: String,
    /// Display name of the participant.
    pub display_name: String,
    /// Four-word identity.
    pub four_words: String,
    /// Participant's role in the call.
    pub role: ParticipantRole,
    /// Whether the participant's microphone is muted.
    pub is_muted: bool,
    /// Whether the participant was muted by the host (not self-muted).
    pub is_muted_by_host: bool,
    /// Whether the participant's camera is enabled.
    pub is_video_enabled: bool,
    /// Whether the participant is currently speaking.
    pub is_speaking: bool,
    /// Whether the participant is currently screen sharing.
    pub is_screen_sharing: bool,
    /// Whether the participant has raised their hand.
    pub hand_raised: bool,
    /// Current audio level (0.0 to 1.0).
    pub audio_level: f32,
    /// Timestamp when the participant joined (ms since epoch).
    pub joined_at: i64,
}

impl Participant {
    /// Returns true if this participant has active media.
    pub fn has_active_media(&self) -> bool {
        !self.is_muted || self.is_video_enabled || self.is_screen_sharing
    }

    /// Returns true if this participant is the host.
    pub fn is_host(&self) -> bool {
        matches!(self.role, ParticipantRole::Host)
    }

    /// Returns true if this participant has elevated privileges (host or co-host).
    pub fn has_elevated_role(&self) -> bool {
        matches!(self.role, ParticipantRole::Host | ParticipantRole::CoHost)
    }

    /// Returns true if this participant can unmute themselves.
    /// Participants muted by host may not be able to unmute without permission.
    pub fn can_self_unmute(&self) -> bool {
        !self.is_muted_by_host || self.has_elevated_role()
    }
}

/// Information about an active call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CallInfo {
    /// Unique call identifier.
    pub call_id: String,
    /// Entity ID this call is associated with.
    pub entity_id: String,
    /// Entity name for display.
    pub entity_name: String,
    /// Type of call (direct, group, channel).
    pub call_type: CallType,
    /// Current participants in the call.
    pub participants: Vec<Participant>,
    /// Timestamp when the call started (ms since epoch).
    pub started_at: i64,
    /// Duration in seconds since call started.
    pub duration_seconds: u64,
    /// Participant ID of the current user.
    pub my_participant_id: String,
    /// Participant ID of the call host.
    pub host_id: String,
    /// Maximum number of participants allowed.
    pub max_participants: u32,
    /// Whether new participants can join.
    pub is_locked: bool,
    /// Whether all participants are muted by default when joining.
    pub mute_on_entry: bool,
}

impl CallInfo {
    /// Returns the number of participants including the current user.
    pub fn participant_count(&self) -> usize {
        self.participants.len()
    }

    /// Returns the participant for the current user.
    pub fn my_participant(&self) -> Option<&Participant> {
        self.participants
            .iter()
            .find(|p| p.id == self.my_participant_id)
    }

    /// Returns other participants (excluding the current user).
    pub fn other_participants(&self) -> Vec<&Participant> {
        self.participants
            .iter()
            .filter(|p| p.id != self.my_participant_id)
            .collect()
    }

    /// Returns the host participant.
    pub fn host(&self) -> Option<&Participant> {
        self.participants.iter().find(|p| p.id == self.host_id)
    }

    /// Returns true if the current user is the host.
    pub fn am_i_host(&self) -> bool {
        self.my_participant_id == self.host_id
    }

    /// Returns true if the current user has elevated privileges.
    pub fn am_i_elevated(&self) -> bool {
        self.my_participant()
            .map(|p| p.has_elevated_role())
            .unwrap_or(false)
    }

    /// Returns the current user's role.
    pub fn my_role(&self) -> ParticipantRole {
        self.my_participant()
            .map(|p| p.role)
            .unwrap_or(ParticipantRole::Participant)
    }

    /// Returns true if this is a group call (not direct).
    pub fn is_group_call(&self) -> bool {
        !matches!(self.call_type, CallType::Direct)
    }

    /// Returns true if more participants can join.
    pub fn can_accept_more_participants(&self) -> bool {
        !self.is_locked && (self.participants.len() as u32) < self.max_participants
    }

    /// Returns participants with elevated roles (hosts and co-hosts).
    pub fn elevated_participants(&self) -> Vec<&Participant> {
        self.participants
            .iter()
            .filter(|p| p.has_elevated_role())
            .collect()
    }

    /// Returns participants with raised hands, sorted by raise time (oldest first).
    pub fn participants_with_raised_hands(&self) -> Vec<&Participant> {
        self.participants.iter().filter(|p| p.hand_raised).collect()
    }
}

/// Kind of media error that occurred.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MediaErrorKind {
    /// User denied permission to access the device.
    PermissionDenied,
    /// The requested device was not found.
    DeviceNotFound,
    /// The device is in use by another application.
    DeviceInUse,
    /// The requested feature is not supported.
    NotSupported,
    /// An unknown error occurred.
    Unknown,
}

impl MediaErrorKind {
    /// Returns a human-readable description of the error kind.
    pub fn description(&self) -> &'static str {
        match self {
            Self::PermissionDenied => "Permission denied",
            Self::DeviceNotFound => "Device not found",
            Self::DeviceInUse => "Device is in use",
            Self::NotSupported => "Not supported",
            Self::Unknown => "Unknown error",
        }
    }

    /// Returns a suggested action for the user.
    pub fn suggestion(&self) -> &'static str {
        match self {
            Self::PermissionDenied => "Check your system permissions for this application",
            Self::DeviceNotFound => "Connect a microphone or camera and try again",
            Self::DeviceInUse => "Close other applications using this device",
            Self::NotSupported => "Try using a different device",
            Self::Unknown => "Try again or restart the application",
        }
    }
}

/// Information about a media capture error.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MediaError {
    /// Type of device that failed.
    pub device_type: DeviceType,
    /// Kind of error that occurred.
    pub error_kind: MediaErrorKind,
    /// Detailed error message.
    pub message: String,
    /// Whether the error might be recoverable by retrying.
    pub recoverable: bool,
}

impl MediaError {
    /// Creates a new media error.
    pub fn new(
        device_type: DeviceType,
        error_kind: MediaErrorKind,
        message: impl Into<String>,
    ) -> Self {
        let recoverable = !matches!(error_kind, MediaErrorKind::NotSupported);
        Self {
            device_type,
            error_kind,
            message: message.into(),
            recoverable,
        }
    }
}

/// Overall quality level for connection health display.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ConnectionQuality {
    /// Quality is unknown or not yet measured.
    #[default]
    Unknown,
    /// Excellent quality (< 50ms latency, < 1% packet loss).
    Excellent,
    /// Good quality (< 150ms latency, < 2% packet loss).
    Good,
    /// Fair quality (< 300ms latency, < 5% packet loss).
    Fair,
    /// Poor quality (> 300ms latency or > 5% packet loss).
    Poor,
    /// Very poor / failing connection.
    Critical,
}

impl ConnectionQuality {
    /// Returns a human-readable label for the quality level.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Unknown => "Unknown",
            Self::Excellent => "Excellent",
            Self::Good => "Good",
            Self::Fair => "Fair",
            Self::Poor => "Poor",
            Self::Critical => "Critical",
        }
    }

    /// Returns a color class for UI rendering (Tailwind style).
    pub fn color_class(&self) -> &'static str {
        match self {
            Self::Unknown => "text-slate-400",
            Self::Excellent => "text-emerald-400",
            Self::Good => "text-emerald-500",
            Self::Fair => "text-amber-400",
            Self::Poor => "text-orange-500",
            Self::Critical => "text-red-500",
        }
    }

    /// Returns number of "bars" to display (0-5).
    pub fn signal_bars(&self) -> u8 {
        match self {
            Self::Unknown => 0,
            Self::Critical => 1,
            Self::Poor => 2,
            Self::Fair => 3,
            Self::Good => 4,
            Self::Excellent => 5,
        }
    }

    /// Determines quality level from latency and packet loss.
    pub fn from_metrics(latency_ms: u32, packet_loss_percent: f32) -> Self {
        if packet_loss_percent > 10.0 || latency_ms > 500 {
            Self::Critical
        } else if packet_loss_percent > 5.0 || latency_ms > 300 {
            Self::Poor
        } else if packet_loss_percent > 2.0 || latency_ms > 150 {
            Self::Fair
        } else if packet_loss_percent > 1.0 || latency_ms > 50 {
            Self::Good
        } else {
            Self::Excellent
        }
    }
}

/// Real-time WebRTC quality metrics for a connection.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QualityMetrics {
    /// Round-trip time in milliseconds.
    pub latency_ms: u32,
    /// Packet loss percentage (0.0 to 100.0).
    pub packet_loss_percent: f32,
    /// Jitter in milliseconds.
    pub jitter_ms: u32,
    /// Current audio bitrate in kbps.
    pub audio_bitrate_kbps: u32,
    /// Current video bitrate in kbps (0 if no video).
    pub video_bitrate_kbps: u32,
    /// Video resolution width (0 if no video).
    pub video_width: u32,
    /// Video resolution height (0 if no video).
    pub video_height: u32,
    /// Video framerate (0 if no video).
    pub video_fps: u32,
    /// Total bytes sent in this session.
    pub bytes_sent: u64,
    /// Total bytes received in this session.
    pub bytes_received: u64,
    /// Overall connection quality assessment.
    pub quality: ConnectionQuality,
    /// Timestamp when these metrics were collected (Unix ms).
    pub timestamp: u64,
}

impl Default for QualityMetrics {
    fn default() -> Self {
        Self {
            latency_ms: 0,
            packet_loss_percent: 0.0,
            jitter_ms: 0,
            audio_bitrate_kbps: 0,
            video_bitrate_kbps: 0,
            video_width: 0,
            video_height: 0,
            video_fps: 0,
            bytes_sent: 0,
            bytes_received: 0,
            quality: ConnectionQuality::Unknown,
            timestamp: 0,
        }
    }
}

impl QualityMetrics {
    /// Returns true if video is active (has resolution).
    pub fn has_video(&self) -> bool {
        self.video_width > 0 && self.video_height > 0
    }

    /// Returns the video resolution as a string (e.g., "1280x720").
    pub fn video_resolution(&self) -> String {
        if self.has_video() {
            format!("{}x{}", self.video_width, self.video_height)
        } else {
            "None".to_string()
        }
    }

    /// Returns total bandwidth usage in kbps.
    pub fn total_bitrate_kbps(&self) -> u32 {
        self.audio_bitrate_kbps + self.video_bitrate_kbps
    }

    /// Recalculates the quality assessment from current metrics.
    pub fn recalculate_quality(&mut self) {
        self.quality = ConnectionQuality::from_metrics(self.latency_ms, self.packet_loss_percent);
    }
}

/// Quality metrics for a specific participant in a call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ParticipantQuality {
    /// Participant ID this applies to.
    pub participant_id: String,
    /// Incoming stream quality (receiving from this participant).
    pub incoming: QualityMetrics,
    /// Outgoing stream quality (sending to this participant, if measured).
    pub outgoing: Option<QualityMetrics>,
}

/// User's call settings and preferences.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct CallSettings {
    /// Selected microphone device ID.
    pub selected_microphone: Option<String>,
    /// Selected speaker device ID.
    pub selected_speaker: Option<String>,
    /// Selected camera device ID.
    pub selected_camera: Option<String>,
    /// Whether to start calls with microphone muted.
    pub auto_mute_on_join: bool,
    /// Whether noise suppression is enabled.
    pub noise_suppression: bool,
    /// Whether to automatically record calls.
    pub recording_enabled: bool,
    /// Whether to include video in recordings (if recording is enabled).
    pub recording_include_video: bool,
    /// Directory path for saving recordings (None uses default drive location).
    pub recording_directory: Option<String>,
}

/// Snapshot of the current call state for UI updates.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct CallSnapshot {
    /// Current call state.
    pub state: CallState,
    /// Active call information (if in a call).
    pub call_info: Option<CallInfo>,
    /// List of participants (mirrored from call_info for convenience).
    pub participants: Vec<Participant>,
    /// Media errors that have occurred.
    pub media_errors: Vec<MediaError>,
    /// Available media devices.
    pub available_devices: Vec<MediaDevice>,
    /// Current call settings.
    pub settings: CallSettings,
    /// Whether in listen-only mode due to media failure.
    pub listen_only_mode: bool,
    /// Whether the current user is screen sharing.
    pub is_screen_sharing: bool,
    /// Information about the active screen share (if sharing).
    pub screen_share_info: Option<ScreenShareInfo>,
    /// Available screen share sources (monitors and windows).
    pub available_screen_sources: Vec<ScreenShareSource>,
    /// Overall connection quality metrics.
    pub quality_metrics: QualityMetrics,
    /// Per-participant quality metrics.
    pub participant_quality: Vec<ParticipantQuality>,
    /// Whether the call is being recorded.
    pub is_recording: bool,
    /// Recording information (if recording is active or recently stopped).
    pub recording_info: Option<RecordingInfo>,
}

impl CallSnapshot {
    /// Returns true if currently in an active call.
    pub fn is_in_call(&self) -> bool {
        self.state == CallState::InCall
    }

    /// Returns true if there are unrecoverable media errors.
    pub fn has_critical_errors(&self) -> bool {
        self.media_errors.iter().any(|e| !e.recoverable)
    }

    /// Returns quality metrics for a specific participant.
    pub fn get_participant_quality(&self, participant_id: &str) -> Option<&ParticipantQuality> {
        self.participant_quality
            .iter()
            .find(|q| q.participant_id == participant_id)
    }

    /// Returns the overall connection quality level.
    pub fn connection_quality(&self) -> ConnectionQuality {
        self.quality_metrics.quality
    }

    /// Returns true if connection quality is poor or worse.
    pub fn has_quality_issues(&self) -> bool {
        matches!(
            self.quality_metrics.quality,
            ConnectionQuality::Poor | ConnectionQuality::Critical
        )
    }

    /// Returns the current recording state.
    pub fn recording_state(&self) -> RecordingState {
        self.recording_info
            .as_ref()
            .map(|r| r.state)
            .unwrap_or(RecordingState::NotRecording)
    }

    /// Returns true if recording is currently active (recording or paused).
    pub fn is_recording_active(&self) -> bool {
        self.recording_state().is_active()
    }

    /// Returns the formatted recording duration, if recording.
    pub fn recording_duration(&self) -> Option<String> {
        self.recording_info.as_ref().map(|r| r.formatted_duration())
    }
}

// =============================================================================
// Call History Types
// =============================================================================

/// Outcome of a call (for history entries).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum CallOutcome {
    /// Call completed successfully.
    Completed,
    /// Outgoing call that wasn't answered.
    NoAnswer,
    /// Incoming call that was declined.
    Declined,
    /// Incoming call that was missed (not answered).
    Missed,
    /// Call failed due to technical issues.
    Failed,
    /// Call was cancelled before connecting.
    Cancelled,
    /// Call is ongoing (shouldn't appear in history, but useful for transitions).
    #[default]
    InProgress,
}

impl CallOutcome {
    /// Returns a human-readable label for the outcome.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Completed => "Completed",
            Self::NoAnswer => "No Answer",
            Self::Declined => "Declined",
            Self::Missed => "Missed",
            Self::Failed => "Failed",
            Self::Cancelled => "Cancelled",
            Self::InProgress => "In Progress",
        }
    }

    /// Returns true if this represents a missed call (incoming, not answered).
    pub fn is_missed(&self) -> bool {
        matches!(self, Self::Missed)
    }

    /// Returns true if this represents a successful connection.
    pub fn was_connected(&self) -> bool {
        matches!(self, Self::Completed | Self::InProgress)
    }

    /// Returns a CSS class hint for styling this outcome.
    pub fn status_class(&self) -> &'static str {
        match self {
            Self::Completed => "text-emerald-500",
            Self::NoAnswer => "text-amber-500",
            Self::Declined => "text-slate-500",
            Self::Missed => "text-red-500",
            Self::Failed => "text-red-600",
            Self::Cancelled => "text-slate-400",
            Self::InProgress => "text-blue-500",
        }
    }
}

/// Direction of a call (for history entries).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum CallDirection {
    /// Outgoing call (we initiated it).
    #[default]
    Outgoing,
    /// Incoming call (they called us).
    Incoming,
}

impl CallDirection {
    /// Returns a human-readable label for the direction.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Outgoing => "Outgoing",
            Self::Incoming => "Incoming",
        }
    }

    /// Returns an icon hint for the direction.
    pub fn icon(&self) -> &'static str {
        match self {
            Self::Outgoing => "↗️",
            Self::Incoming => "↙️",
        }
    }
}

/// Summary of a participant in a historical call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HistoryParticipant {
    /// Unique identifier of the participant.
    pub id: String,
    /// Display name at the time of the call.
    pub display_name: String,
    /// Four-word identifier at the time of the call.
    pub four_words: String,
    /// How long they were in the call (seconds).
    pub duration_seconds: u64,
    /// Whether they joined late or left early.
    pub partial_participation: bool,
}

/// A single call history entry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CallHistoryEntry {
    /// Unique ID of this call (same as CallInfo.call_id).
    pub call_id: String,
    /// Entity ID the call was associated with (contact, group, channel).
    pub entity_id: String,
    /// Entity name at the time of the call.
    pub entity_name: String,
    /// Type of call.
    pub call_type: CallType,
    /// Direction of the call.
    pub direction: CallDirection,
    /// Outcome of the call.
    pub outcome: CallOutcome,
    /// When the call started (Unix ms).
    pub started_at: i64,
    /// When the call ended (Unix ms, 0 if still in progress).
    pub ended_at: i64,
    /// Total duration in seconds (0 if not connected).
    pub duration_seconds: u64,
    /// List of participants who were in the call.
    pub participants: Vec<HistoryParticipant>,
    /// Whether video was used during the call.
    pub had_video: bool,
    /// Whether screen sharing was used during the call.
    pub had_screen_share: bool,
    /// Whether the call was recorded.
    pub was_recorded: bool,
    /// Path to recording file, if recorded and available.
    pub recording_path: Option<String>,
    /// Whether this entry has been marked as read/seen.
    pub is_read: bool,
    /// Whether the user has called back after missing this call.
    #[serde(default)]
    pub has_called_back: bool,
}

impl CallHistoryEntry {
    /// Create a new history entry for an outgoing call.
    pub fn new_outgoing(
        call_id: String,
        entity_id: String,
        entity_name: String,
        call_type: CallType,
    ) -> Self {
        let started_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);

        Self {
            call_id,
            entity_id,
            entity_name,
            call_type,
            direction: CallDirection::Outgoing,
            outcome: CallOutcome::InProgress,
            started_at,
            ended_at: 0,
            duration_seconds: 0,
            participants: Vec::new(),
            had_video: false,
            had_screen_share: false,
            was_recorded: false,
            recording_path: None,
            is_read: true, // Outgoing calls are always "read"
            has_called_back: false,
        }
    }

    /// Create a new history entry for an incoming call.
    pub fn new_incoming(
        call_id: String,
        entity_id: String,
        entity_name: String,
        call_type: CallType,
    ) -> Self {
        let started_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);

        Self {
            call_id,
            entity_id,
            entity_name,
            call_type,
            direction: CallDirection::Incoming,
            outcome: CallOutcome::InProgress,
            started_at,
            ended_at: 0,
            duration_seconds: 0,
            participants: Vec::new(),
            had_video: false,
            had_screen_share: false,
            was_recorded: false,
            recording_path: None,
            is_read: false, // Incoming calls start as unread
            has_called_back: false,
        }
    }

    /// Finalize the call entry with ending details.
    pub fn finalize(&mut self, outcome: CallOutcome) {
        let ended_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);

        self.ended_at = ended_at;
        self.outcome = outcome;

        // Calculate duration if connected
        if outcome.was_connected() && self.started_at > 0 && ended_at > self.started_at {
            self.duration_seconds = ((ended_at - self.started_at) / 1000) as u64;
        }
    }

    /// Returns the formatted duration (e.g., "1:23:45" or "0:00").
    pub fn formatted_duration(&self) -> String {
        let hours = self.duration_seconds / 3600;
        let minutes = (self.duration_seconds % 3600) / 60;
        let seconds = self.duration_seconds % 60;

        if hours > 0 {
            format!("{}:{:02}:{:02}", hours, minutes, seconds)
        } else {
            format!("{}:{:02}", minutes, seconds)
        }
    }

    /// Returns the number of participants (excluding self).
    pub fn participant_count(&self) -> usize {
        self.participants.len()
    }

    /// Returns a display string for the participants.
    pub fn participants_display(&self) -> String {
        match self.participants.len() {
            0 => self.entity_name.clone(),
            1 => self.participants[0].display_name.clone(),
            2 => format!(
                "{} and {}",
                self.participants[0].display_name, self.participants[1].display_name
            ),
            n => format!("{} and {} others", self.participants[0].display_name, n - 1),
        }
    }

    /// Returns true if this is a missed call that hasn't been seen.
    pub fn is_unread_missed(&self) -> bool {
        self.outcome.is_missed() && !self.is_read
    }

    /// Mark this entry as read.
    pub fn mark_read(&mut self) {
        self.is_read = true;
    }

    /// Returns an icon/emoji hint for the call direction and outcome.
    pub fn icon(&self) -> &'static str {
        match (&self.direction, &self.outcome) {
            (_, CallOutcome::Missed) => "📵",
            (_, CallOutcome::Failed) => "",
            (CallDirection::Outgoing, CallOutcome::NoAnswer) => "📤",
            (CallDirection::Incoming, _) => "📲",
            (CallDirection::Outgoing, _) => "📱",
        }
    }
}

/// Collection of call history entries with utility methods.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CallHistory {
    /// All history entries, newest first.
    pub entries: Vec<CallHistoryEntry>,
    /// Maximum entries to keep (0 = unlimited).
    pub max_entries: usize,
}

impl CallHistory {
    /// Create a new empty call history with a max entry limit.
    pub fn new(max_entries: usize) -> Self {
        Self {
            entries: Vec::new(),
            max_entries,
        }
    }

    /// Add a new entry to the history.
    pub fn add(&mut self, entry: CallHistoryEntry) {
        // Insert at the beginning (newest first)
        self.entries.insert(0, entry);

        // Trim if over limit
        if self.max_entries > 0 && self.entries.len() > self.max_entries {
            self.entries.truncate(self.max_entries);
        }
    }

    /// Update an existing entry (e.g., when call ends).
    pub fn update(&mut self, call_id: &str, updater: impl FnOnce(&mut CallHistoryEntry)) {
        if let Some(entry) = self.entries.iter_mut().find(|e| e.call_id == call_id) {
            updater(entry);
        }
    }

    /// Get an entry by call ID.
    pub fn get(&self, call_id: &str) -> Option<&CallHistoryEntry> {
        self.entries.iter().find(|e| e.call_id == call_id)
    }

    /// Get a mutable entry by call ID.
    pub fn get_mut(&mut self, call_id: &str) -> Option<&mut CallHistoryEntry> {
        self.entries.iter_mut().find(|e| e.call_id == call_id)
    }

    /// Remove an entry by call ID.
    pub fn remove(&mut self, call_id: &str) -> Option<CallHistoryEntry> {
        if let Some(pos) = self.entries.iter().position(|e| e.call_id == call_id) {
            Some(self.entries.remove(pos))
        } else {
            None
        }
    }

    /// Clear all history entries.
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// Returns the number of entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if there are no entries.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns all missed calls.
    pub fn missed_calls(&self) -> Vec<&CallHistoryEntry> {
        self.entries
            .iter()
            .filter(|e| e.outcome.is_missed())
            .collect()
    }

    /// Returns all unread missed calls.
    pub fn unread_missed_calls(&self) -> Vec<&CallHistoryEntry> {
        self.entries
            .iter()
            .filter(|e| e.is_unread_missed())
            .collect()
    }

    /// Returns the count of unread missed calls.
    pub fn unread_missed_count(&self) -> usize {
        self.entries.iter().filter(|e| e.is_unread_missed()).count()
    }

    /// Mark all missed calls as read.
    pub fn mark_all_read(&mut self) {
        for entry in &mut self.entries {
            entry.is_read = true;
        }
    }

    /// Get history filtered by entity ID.
    pub fn for_entity(&self, entity_id: &str) -> Vec<&CallHistoryEntry> {
        self.entries
            .iter()
            .filter(|e| e.entity_id == entity_id)
            .collect()
    }

    /// Get history filtered by call type.
    pub fn by_type(&self, call_type: CallType) -> Vec<&CallHistoryEntry> {
        self.entries
            .iter()
            .filter(|e| e.call_type == call_type)
            .collect()
    }

    /// Get recent entries (up to limit).
    pub fn recent(&self, limit: usize) -> Vec<&CallHistoryEntry> {
        self.entries.iter().take(limit).collect()
    }
}

// ===== Missed Call Notification Types =====

/// A missed call notification for display in the UI.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MissedCallNotification {
    /// Unique notification ID.
    pub id: String,
    /// Call ID from history.
    pub call_id: String,
    /// Entity that called (contact, group, channel).
    pub caller_id: String,
    /// Display name of the caller.
    pub caller_name: String,
    /// Type of call that was missed.
    pub call_type: CallType,
    /// When the call was missed (Unix ms).
    pub timestamp: i64,
    /// Whether this notification has been seen/acknowledged.
    pub is_acknowledged: bool,
    /// Whether the user has called back.
    pub has_called_back: bool,
}

impl MissedCallNotification {
    /// Create a new missed call notification from a history entry.
    pub fn from_history_entry(entry: &CallHistoryEntry) -> Self {
        Self {
            id: format!("missed-{}", entry.call_id),
            call_id: entry.call_id.clone(),
            caller_id: entry.entity_id.clone(),
            caller_name: entry.entity_name.clone(),
            call_type: entry.call_type,
            timestamp: entry.started_at,
            is_acknowledged: entry.is_read,
            has_called_back: entry.has_called_back,
        }
    }

    /// Returns true if this notification should be shown prominently.
    pub fn is_urgent(&self) -> bool {
        !self.is_acknowledged && !self.has_called_back
    }

    /// Returns a human-readable time description.
    pub fn time_ago(&self) -> String {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);

        let diff_ms = now - self.timestamp;
        let diff_secs = diff_ms / 1000;
        let diff_mins = diff_secs / 60;
        let diff_hours = diff_mins / 60;
        let diff_days = diff_hours / 24;

        if diff_days > 0 {
            format!("{}d ago", diff_days)
        } else if diff_hours > 0 {
            format!("{}h ago", diff_hours)
        } else if diff_mins > 0 {
            format!("{}m ago", diff_mins)
        } else {
            "Just now".to_string()
        }
    }
}

/// Snapshot of missed call notifications for reactive UI updates.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MissedCallsSnapshot {
    /// Active missed call notifications, newest first.
    pub notifications: Vec<MissedCallNotification>,
    /// Total unread/unacknowledged count.
    pub unread_count: usize,
    /// Last time the notification list was updated (Unix ms).
    pub last_updated: i64,
}

impl MissedCallsSnapshot {
    /// Returns true if there are any unacknowledged missed calls.
    pub fn has_unread(&self) -> bool {
        self.unread_count > 0
    }

    /// Get notifications for a specific caller.
    pub fn for_caller(&self, caller_id: &str) -> Vec<&MissedCallNotification> {
        self.notifications
            .iter()
            .filter(|n| n.caller_id == caller_id)
            .collect()
    }

    /// Get only unacknowledged notifications.
    pub fn unread(&self) -> Vec<&MissedCallNotification> {
        self.notifications
            .iter()
            .filter(|n| !n.is_acknowledged)
            .collect()
    }
}

// ===== Pending Call Invite Types =====

/// Maximum number of pending call invites to store.
pub const MAX_PENDING_INVITES: usize = 10;

/// Expiration time for pending call invites in milliseconds (5 minutes).
pub const PENDING_INVITE_EXPIRY_MS: i64 = 5 * 60 * 1000;

/// A pending call invite received while offline.
///
/// When the application is offline or disconnected, incoming call invites
/// are queued and can be processed when connectivity is restored.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingCallInvite {
    /// Unique invite ID.
    pub id: String,
    /// Call ID to join.
    pub call_id: String,
    /// Entity that initiated the call.
    pub caller_id: String,
    /// Display name of the caller.
    pub caller_name: String,
    /// Entity where the call is happening (group, channel).
    pub entity_id: String,
    /// Type of call.
    pub call_type: CallType,
    /// When the invite was received (Unix ms).
    pub received_at: i64,
    /// When the invite expires (Unix ms).
    pub expires_at: i64,
}

impl PendingCallInvite {
    /// Create a new pending call invite.
    pub fn new(
        call_id: String,
        caller_id: String,
        caller_name: String,
        entity_id: String,
        call_type: CallType,
    ) -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);

        Self {
            id: format!("invite-{}-{}", call_id, now),
            call_id,
            caller_id,
            caller_name,
            entity_id,
            call_type,
            received_at: now,
            expires_at: now + PENDING_INVITE_EXPIRY_MS,
        }
    }

    /// Check if this invite has expired.
    pub fn is_expired(&self) -> bool {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);
        now >= self.expires_at
    }

    /// Returns a human-readable time remaining.
    pub fn time_remaining(&self) -> String {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);

        let remaining_ms = self.expires_at.saturating_sub(now);
        if remaining_ms <= 0 {
            return "Expired".to_string();
        }

        let remaining_secs = remaining_ms / 1000;
        let remaining_mins = remaining_secs / 60;

        if remaining_mins > 0 {
            format!("{}m {}s", remaining_mins, remaining_secs % 60)
        } else {
            format!("{}s", remaining_secs)
        }
    }
}

/// Snapshot of pending call invites for reactive UI updates.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PendingInvitesSnapshot {
    /// Pending call invites, oldest first (FIFO order).
    pub invites: Vec<PendingCallInvite>,
    /// Total count of non-expired invites.
    pub count: usize,
    /// Last time the invites list was updated.
    pub last_updated: i64,
}

impl PendingInvitesSnapshot {
    /// Returns true if there are any pending invites.
    pub fn has_invites(&self) -> bool {
        !self.invites.is_empty()
    }

    /// Get invites for a specific caller.
    pub fn for_caller(&self, caller_id: &str) -> Vec<&PendingCallInvite> {
        self.invites
            .iter()
            .filter(|i| i.caller_id == caller_id)
            .collect()
    }

    /// Get the most urgent (oldest non-expired) invite.
    pub fn most_urgent(&self) -> Option<&PendingCallInvite> {
        self.invites.iter().find(|i| !i.is_expired())
    }

    /// Get only non-expired invites.
    pub fn active(&self) -> Vec<&PendingCallInvite> {
        self.invites.iter().filter(|i| !i.is_expired()).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn call_state_is_active() {
        assert!(!CallState::Idle.is_active());
        assert!(CallState::Connecting.is_active());
        assert!(CallState::InCall.is_active());
        assert!(CallState::Reconnecting.is_active());
        assert!(!CallState::Disconnected.is_active());
        assert!(!CallState::MediaError.is_active());
    }

    #[test]
    fn call_state_is_terminal() {
        assert!(CallState::Idle.is_terminal());
        assert!(!CallState::Connecting.is_terminal());
        assert!(!CallState::InCall.is_terminal());
        assert!(!CallState::Reconnecting.is_terminal());
        assert!(CallState::Disconnected.is_terminal());
        assert!(CallState::MediaError.is_terminal());
    }

    #[test]
    fn device_type_label() {
        assert_eq!(DeviceType::Microphone.label(), "Microphone");
        assert_eq!(DeviceType::Speaker.label(), "Speaker");
        assert_eq!(DeviceType::Camera.label(), "Camera");
    }

    #[test]
    fn participant_has_active_media() {
        let participant = Participant {
            id: "p1".to_string(),
            display_name: "Alice".to_string(),
            four_words: "ocean-forest-moon-star".to_string(),
            role: ParticipantRole::Participant,
            is_muted: true,
            is_muted_by_host: false,
            is_video_enabled: false,
            is_speaking: false,
            is_screen_sharing: false,
            hand_raised: false,
            audio_level: 0.0,
            joined_at: 0,
        };
        assert!(!participant.has_active_media());

        let participant_with_audio = Participant {
            is_muted: false,
            ..participant.clone()
        };
        assert!(participant_with_audio.has_active_media());

        let participant_with_video = Participant {
            is_video_enabled: true,
            ..participant.clone()
        };
        assert!(participant_with_video.has_active_media());

        let participant_with_screen_share = Participant {
            is_screen_sharing: true,
            ..participant
        };
        assert!(participant_with_screen_share.has_active_media());
    }

    #[test]
    fn call_info_participant_helpers() {
        let call = CallInfo {
            call_id: "call1".to_string(),
            entity_id: "ent1".to_string(),
            entity_name: "Team Chat".to_string(),
            call_type: CallType::Group,
            participants: vec![
                Participant {
                    id: "me".to_string(),
                    display_name: "Me".to_string(),
                    four_words: "a-b-c-d".to_string(),
                    role: ParticipantRole::Host,
                    is_muted: false,
                    is_muted_by_host: false,
                    is_video_enabled: false,
                    is_speaking: false,
                    is_screen_sharing: false,
                    hand_raised: false,
                    audio_level: 0.0,
                    joined_at: 0,
                },
                Participant {
                    id: "other".to_string(),
                    display_name: "Other".to_string(),
                    four_words: "e-f-g-h".to_string(),
                    role: ParticipantRole::Participant,
                    is_muted: false,
                    is_muted_by_host: false,
                    is_video_enabled: false,
                    is_speaking: false,
                    is_screen_sharing: false,
                    hand_raised: false,
                    audio_level: 0.0,
                    joined_at: 0,
                },
            ],
            started_at: 0,
            duration_seconds: 0,
            my_participant_id: "me".to_string(),
            host_id: "me".to_string(),
            max_participants: 25,
            is_locked: false,
            mute_on_entry: false,
        };

        assert_eq!(call.participant_count(), 2);
        assert_eq!(
            call.my_participant().map(|p| &p.display_name),
            Some(&"Me".to_string())
        );
        assert_eq!(call.other_participants().len(), 1);
        assert_eq!(call.other_participants()[0].display_name, "Other");
    }

    #[test]
    fn media_error_kind_descriptions() {
        assert_eq!(
            MediaErrorKind::PermissionDenied.description(),
            "Permission denied"
        );
        assert_eq!(
            MediaErrorKind::DeviceNotFound.description(),
            "Device not found"
        );
        assert_eq!(
            MediaErrorKind::DeviceInUse.description(),
            "Device is in use"
        );
        assert_eq!(MediaErrorKind::NotSupported.description(), "Not supported");
        assert_eq!(MediaErrorKind::Unknown.description(), "Unknown error");
    }

    #[test]
    fn media_error_recoverable() {
        let recoverable = MediaError::new(
            DeviceType::Microphone,
            MediaErrorKind::DeviceInUse,
            "Device busy",
        );
        assert!(recoverable.recoverable);

        let not_recoverable = MediaError::new(
            DeviceType::Camera,
            MediaErrorKind::NotSupported,
            "No camera support",
        );
        assert!(!not_recoverable.recoverable);
    }

    #[test]
    fn call_snapshot_helpers() {
        let mut snapshot = CallSnapshot::default();
        assert!(!snapshot.is_in_call());
        assert!(!snapshot.has_critical_errors());
        assert!(!snapshot.is_screen_sharing);

        snapshot.state = CallState::InCall;
        assert!(snapshot.is_in_call());

        snapshot.media_errors.push(MediaError::new(
            DeviceType::Microphone,
            MediaErrorKind::NotSupported,
            "No microphone",
        ));
        assert!(snapshot.has_critical_errors());
    }

    #[test]
    fn call_settings_default() {
        let settings = CallSettings::default();
        assert!(settings.selected_microphone.is_none());
        assert!(settings.selected_speaker.is_none());
        assert!(settings.selected_camera.is_none());
        assert!(!settings.auto_mute_on_join);
        assert!(!settings.noise_suppression);
        assert!(!settings.recording_enabled);
        assert!(!settings.recording_include_video);
        assert!(settings.recording_directory.is_none());
    }

    #[test]
    fn connection_quality_labels() {
        assert_eq!(ConnectionQuality::Unknown.label(), "Unknown");
        assert_eq!(ConnectionQuality::Excellent.label(), "Excellent");
        assert_eq!(ConnectionQuality::Good.label(), "Good");
        assert_eq!(ConnectionQuality::Fair.label(), "Fair");
        assert_eq!(ConnectionQuality::Poor.label(), "Poor");
        assert_eq!(ConnectionQuality::Critical.label(), "Critical");
    }

    #[test]
    fn connection_quality_signal_bars() {
        assert_eq!(ConnectionQuality::Unknown.signal_bars(), 0);
        assert_eq!(ConnectionQuality::Critical.signal_bars(), 1);
        assert_eq!(ConnectionQuality::Poor.signal_bars(), 2);
        assert_eq!(ConnectionQuality::Fair.signal_bars(), 3);
        assert_eq!(ConnectionQuality::Good.signal_bars(), 4);
        assert_eq!(ConnectionQuality::Excellent.signal_bars(), 5);
    }

    #[test]
    fn connection_quality_from_metrics() {
        // Excellent: low latency, low packet loss
        assert_eq!(
            ConnectionQuality::from_metrics(30, 0.5),
            ConnectionQuality::Excellent
        );

        // Good: moderate latency
        assert_eq!(
            ConnectionQuality::from_metrics(80, 0.8),
            ConnectionQuality::Good
        );

        // Fair: higher latency or packet loss
        assert_eq!(
            ConnectionQuality::from_metrics(200, 1.5),
            ConnectionQuality::Fair
        );

        // Poor: significant issues
        assert_eq!(
            ConnectionQuality::from_metrics(350, 3.0),
            ConnectionQuality::Poor
        );

        // Critical: severe issues
        assert_eq!(
            ConnectionQuality::from_metrics(600, 2.0),
            ConnectionQuality::Critical
        );
        assert_eq!(
            ConnectionQuality::from_metrics(100, 15.0),
            ConnectionQuality::Critical
        );
    }

    #[test]
    fn quality_metrics_default() {
        let metrics = QualityMetrics::default();
        assert_eq!(metrics.latency_ms, 0);
        assert_eq!(metrics.packet_loss_percent, 0.0);
        assert_eq!(metrics.quality, ConnectionQuality::Unknown);
        assert!(!metrics.has_video());
    }

    #[test]
    fn quality_metrics_video_detection() {
        let mut metrics = QualityMetrics::default();
        assert!(!metrics.has_video());
        assert_eq!(metrics.video_resolution(), "None");

        metrics.video_width = 1920;
        metrics.video_height = 1080;
        assert!(metrics.has_video());
        assert_eq!(metrics.video_resolution(), "1920x1080");
    }

    #[test]
    fn quality_metrics_total_bitrate() {
        let metrics = QualityMetrics {
            audio_bitrate_kbps: 32,
            video_bitrate_kbps: 1500,
            ..Default::default()
        };
        assert_eq!(metrics.total_bitrate_kbps(), 1532);
    }

    #[test]
    fn quality_metrics_recalculate() {
        let mut metrics = QualityMetrics {
            latency_ms: 200,
            packet_loss_percent: 3.0,
            ..Default::default()
        };
        metrics.recalculate_quality();
        assert_eq!(metrics.quality, ConnectionQuality::Fair);
    }

    #[test]
    fn call_snapshot_quality_helpers() {
        let mut snapshot = CallSnapshot::default();
        assert_eq!(snapshot.connection_quality(), ConnectionQuality::Unknown);
        assert!(!snapshot.has_quality_issues());

        snapshot.quality_metrics.quality = ConnectionQuality::Poor;
        assert!(snapshot.has_quality_issues());

        snapshot.quality_metrics.quality = ConnectionQuality::Critical;
        assert!(snapshot.has_quality_issues());

        snapshot.quality_metrics.quality = ConnectionQuality::Good;
        assert!(!snapshot.has_quality_issues());
    }

    #[test]
    fn call_snapshot_participant_quality() {
        let mut snapshot = CallSnapshot::default();
        snapshot.participant_quality.push(ParticipantQuality {
            participant_id: "alice".to_string(),
            incoming: QualityMetrics {
                latency_ms: 50,
                packet_loss_percent: 0.5,
                quality: ConnectionQuality::Excellent,
                ..Default::default()
            },
            outgoing: None,
        });

        assert!(snapshot.get_participant_quality("alice").is_some());
        assert!(snapshot.get_participant_quality("bob").is_none());

        let quality = snapshot.get_participant_quality("alice").unwrap();
        assert_eq!(quality.incoming.quality, ConnectionQuality::Excellent);
    }

    #[test]
    fn recording_state_is_active() {
        assert!(!RecordingState::NotRecording.is_active());
        assert!(RecordingState::Recording.is_active());
        assert!(RecordingState::Paused.is_active());
        assert!(RecordingState::Finalizing.is_active());
    }

    #[test]
    fn recording_state_labels() {
        assert_eq!(RecordingState::NotRecording.label(), "Not Recording");
        assert_eq!(RecordingState::Recording.label(), "Recording");
        assert_eq!(RecordingState::Paused.label(), "Paused");
        assert_eq!(RecordingState::Finalizing.label(), "Saving...");
    }

    #[test]
    fn recording_state_status_class() {
        assert_eq!(
            RecordingState::NotRecording.status_class(),
            "text-slate-400"
        );
        assert_eq!(
            RecordingState::Recording.status_class(),
            "text-red-500 animate-pulse"
        );
        assert_eq!(RecordingState::Paused.status_class(), "text-amber-500");
        assert_eq!(RecordingState::Finalizing.status_class(), "text-blue-500");
    }

    #[test]
    fn recording_info_formatted_duration() {
        let info = RecordingInfo {
            duration_ms: 65_000, // 1 minute 5 seconds
            ..Default::default()
        };
        assert_eq!(info.formatted_duration(), "01:05");

        let info2 = RecordingInfo {
            duration_ms: 3_661_000, // 61 minutes 1 second
            ..Default::default()
        };
        assert_eq!(info2.formatted_duration(), "61:01");
    }

    #[test]
    fn recording_info_formatted_size() {
        let bytes_info = RecordingInfo {
            file_size_bytes: 500,
            ..Default::default()
        };
        assert_eq!(bytes_info.formatted_size(), "500 B");

        let kb_info = RecordingInfo {
            file_size_bytes: 2048,
            ..Default::default()
        };
        assert_eq!(kb_info.formatted_size(), "2.0 KB");

        let mb_info = RecordingInfo {
            file_size_bytes: 5 * 1024 * 1024,
            ..Default::default()
        };
        assert_eq!(mb_info.formatted_size(), "5.0 MB");

        let gb_info = RecordingInfo {
            file_size_bytes: 2 * 1024 * 1024 * 1024,
            ..Default::default()
        };
        assert_eq!(gb_info.formatted_size(), "2.00 GB");
    }

    #[test]
    fn recording_info_default() {
        let info = RecordingInfo::default();
        assert_eq!(info.state, RecordingState::NotRecording);
        assert!(info.includes_audio);
        assert!(!info.includes_video);
        assert!(!info.includes_screen);
    }

    #[test]
    fn call_snapshot_recording_helpers() {
        let mut snapshot = CallSnapshot::default();

        // No recording
        assert_eq!(snapshot.recording_state(), RecordingState::NotRecording);
        assert!(!snapshot.is_recording_active());
        assert!(snapshot.recording_duration().is_none());

        // With active recording
        snapshot.is_recording = true;
        snapshot.recording_info = Some(RecordingInfo {
            state: RecordingState::Recording,
            duration_ms: 30_000,
            ..Default::default()
        });

        assert_eq!(snapshot.recording_state(), RecordingState::Recording);
        assert!(snapshot.is_recording_active());
        assert_eq!(snapshot.recording_duration(), Some("00:30".to_string()));

        // Paused recording
        snapshot.recording_info.as_mut().unwrap().state = RecordingState::Paused;
        assert_eq!(snapshot.recording_state(), RecordingState::Paused);
        assert!(snapshot.is_recording_active());
    }

    #[test]
    fn call_type_labels_and_limits() {
        assert_eq!(CallType::Direct.label(), "Call");
        assert_eq!(CallType::Group.label(), "Group Call");
        assert_eq!(CallType::Channel.label(), "Voice Channel");

        assert_eq!(CallType::Direct.default_max_participants(), 2);
        assert_eq!(CallType::Group.default_max_participants(), 25);
        assert_eq!(CallType::Channel.default_max_participants(), 100);

        assert!(!CallType::Direct.has_host_controls());
        assert!(CallType::Group.has_host_controls());
        assert!(CallType::Channel.has_host_controls());
    }

    #[test]
    fn participant_role_permissions() {
        // Participant has no elevated permissions
        let participant = ParticipantRole::Participant;
        assert!(!participant.can_mute_others());
        assert!(!participant.can_remove_participants());
        assert!(!participant.can_promote());
        assert!(!participant.can_end_call());
        assert!(!participant.can_manage_recording());

        // CoHost can mute, remove, and manage recording
        let cohost = ParticipantRole::CoHost;
        assert!(cohost.can_mute_others());
        assert!(cohost.can_remove_participants());
        assert!(!cohost.can_promote());
        assert!(!cohost.can_end_call());
        assert!(cohost.can_manage_recording());

        // Host can do everything
        let host = ParticipantRole::Host;
        assert!(host.can_mute_others());
        assert!(host.can_remove_participants());
        assert!(host.can_promote());
        assert!(host.can_end_call());
        assert!(host.can_manage_recording());
    }

    #[test]
    fn participant_role_labels() {
        assert_eq!(ParticipantRole::Participant.label(), "Participant");
        assert_eq!(ParticipantRole::CoHost.label(), "Co-Host");
        assert_eq!(ParticipantRole::Host.label(), "Host");
    }

    #[test]
    fn participant_role_helpers() {
        let mut p = Participant {
            id: "p1".to_string(),
            display_name: "Alice".to_string(),
            four_words: "a-b-c-d".to_string(),
            role: ParticipantRole::Participant,
            is_muted: true,
            is_muted_by_host: false,
            is_video_enabled: false,
            is_speaking: false,
            is_screen_sharing: false,
            hand_raised: false,
            audio_level: 0.0,
            joined_at: 0,
        };

        assert!(!p.is_host());
        assert!(!p.has_elevated_role());
        assert!(p.can_self_unmute()); // Not muted by host

        p.is_muted_by_host = true;
        assert!(!p.can_self_unmute()); // Muted by host

        p.role = ParticipantRole::CoHost;
        assert!(!p.is_host());
        assert!(p.has_elevated_role());
        assert!(p.can_self_unmute()); // Elevated role can always unmute

        p.role = ParticipantRole::Host;
        assert!(p.is_host());
        assert!(p.has_elevated_role());
    }

    #[test]
    fn call_info_group_helpers() {
        let call = CallInfo {
            call_id: "call1".to_string(),
            entity_id: "ent1".to_string(),
            entity_name: "Team Chat".to_string(),
            call_type: CallType::Group,
            participants: vec![
                Participant {
                    id: "host".to_string(),
                    display_name: "Host".to_string(),
                    four_words: "a-b-c-d".to_string(),
                    role: ParticipantRole::Host,
                    is_muted: false,
                    is_muted_by_host: false,
                    is_video_enabled: false,
                    is_speaking: false,
                    is_screen_sharing: false,
                    hand_raised: false,
                    audio_level: 0.0,
                    joined_at: 0,
                },
                Participant {
                    id: "cohost".to_string(),
                    display_name: "CoHost".to_string(),
                    four_words: "e-f-g-h".to_string(),
                    role: ParticipantRole::CoHost,
                    is_muted: false,
                    is_muted_by_host: false,
                    is_video_enabled: false,
                    is_speaking: false,
                    is_screen_sharing: false,
                    hand_raised: true,
                    audio_level: 0.0,
                    joined_at: 0,
                },
                Participant {
                    id: "participant".to_string(),
                    display_name: "Participant".to_string(),
                    four_words: "i-j-k-l".to_string(),
                    role: ParticipantRole::Participant,
                    is_muted: false,
                    is_muted_by_host: false,
                    is_video_enabled: false,
                    is_speaking: false,
                    is_screen_sharing: false,
                    hand_raised: true,
                    audio_level: 0.0,
                    joined_at: 0,
                },
            ],
            started_at: 0,
            duration_seconds: 0,
            my_participant_id: "host".to_string(),
            host_id: "host".to_string(),
            max_participants: 25,
            is_locked: false,
            mute_on_entry: false,
        };

        assert!(call.is_group_call());
        assert!(call.am_i_host());
        assert!(call.am_i_elevated());
        assert_eq!(call.my_role(), ParticipantRole::Host);

        assert!(call.host().is_some());
        assert_eq!(call.host().unwrap().id, "host");

        assert!(call.can_accept_more_participants());
        assert_eq!(call.elevated_participants().len(), 2);
        assert_eq!(call.participants_with_raised_hands().len(), 2);
    }

    #[test]
    fn call_info_locked_and_full() {
        let call = CallInfo {
            call_id: "call1".to_string(),
            entity_id: "ent1".to_string(),
            entity_name: "Full Call".to_string(),
            call_type: CallType::Direct,
            participants: vec![
                Participant {
                    id: "p1".to_string(),
                    display_name: "P1".to_string(),
                    four_words: "a-b-c-d".to_string(),
                    role: ParticipantRole::Host,
                    is_muted: false,
                    is_muted_by_host: false,
                    is_video_enabled: false,
                    is_speaking: false,
                    is_screen_sharing: false,
                    hand_raised: false,
                    audio_level: 0.0,
                    joined_at: 0,
                },
                Participant {
                    id: "p2".to_string(),
                    display_name: "P2".to_string(),
                    four_words: "e-f-g-h".to_string(),
                    role: ParticipantRole::Participant,
                    is_muted: false,
                    is_muted_by_host: false,
                    is_video_enabled: false,
                    is_speaking: false,
                    is_screen_sharing: false,
                    hand_raised: false,
                    audio_level: 0.0,
                    joined_at: 0,
                },
            ],
            started_at: 0,
            duration_seconds: 0,
            my_participant_id: "p1".to_string(),
            host_id: "p1".to_string(),
            max_participants: 2,
            is_locked: false,
            mute_on_entry: false,
        };

        // Call is full
        assert!(!call.can_accept_more_participants());

        // Test locked call
        let locked_call = CallInfo {
            is_locked: true,
            max_participants: 25,
            ..call
        };
        assert!(!locked_call.can_accept_more_participants());
    }

    #[test]
    fn call_outcome_labels() {
        assert_eq!(CallOutcome::Completed.label(), "Completed");
        assert_eq!(CallOutcome::NoAnswer.label(), "No Answer");
        assert_eq!(CallOutcome::Declined.label(), "Declined");
        assert_eq!(CallOutcome::Missed.label(), "Missed");
        assert_eq!(CallOutcome::Failed.label(), "Failed");
        assert_eq!(CallOutcome::Cancelled.label(), "Cancelled");
        assert_eq!(CallOutcome::InProgress.label(), "In Progress");
    }

    #[test]
    fn call_outcome_is_missed() {
        assert!(CallOutcome::Missed.is_missed());
        assert!(!CallOutcome::Completed.is_missed());
        assert!(!CallOutcome::NoAnswer.is_missed());
    }

    #[test]
    fn call_outcome_was_connected() {
        assert!(CallOutcome::Completed.was_connected());
        assert!(CallOutcome::InProgress.was_connected());
        assert!(!CallOutcome::Missed.was_connected());
        assert!(!CallOutcome::NoAnswer.was_connected());
        assert!(!CallOutcome::Failed.was_connected());
    }

    #[test]
    fn call_direction_labels() {
        assert_eq!(CallDirection::Outgoing.label(), "Outgoing");
        assert_eq!(CallDirection::Incoming.label(), "Incoming");
    }

    #[test]
    fn call_history_entry_new_outgoing() {
        let entry = CallHistoryEntry::new_outgoing(
            "call1".to_string(),
            "ent1".to_string(),
            "Test Entity".to_string(),
            CallType::Direct,
        );

        assert_eq!(entry.call_id, "call1");
        assert_eq!(entry.direction, CallDirection::Outgoing);
        assert_eq!(entry.outcome, CallOutcome::InProgress);
        assert!(entry.is_read); // Outgoing calls are always read
        assert!(entry.started_at > 0);
    }

    #[test]
    fn call_history_entry_new_incoming() {
        let entry = CallHistoryEntry::new_incoming(
            "call1".to_string(),
            "ent1".to_string(),
            "Test Entity".to_string(),
            CallType::Direct,
        );

        assert_eq!(entry.direction, CallDirection::Incoming);
        assert!(!entry.is_read); // Incoming calls start as unread
    }

    #[test]
    fn call_history_entry_finalize() {
        let mut entry = CallHistoryEntry::new_outgoing(
            "call1".to_string(),
            "ent1".to_string(),
            "Test".to_string(),
            CallType::Direct,
        );

        // Simulate some time passing
        entry.started_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as i64
            - 5000; // 5 seconds ago

        entry.finalize(CallOutcome::Completed);

        assert_eq!(entry.outcome, CallOutcome::Completed);
        assert!(entry.ended_at > entry.started_at);
        assert!(entry.duration_seconds >= 4); // At least 4 seconds
    }

    #[test]
    fn call_history_entry_formatted_duration() {
        let mut entry = CallHistoryEntry::new_outgoing(
            "call1".to_string(),
            "ent1".to_string(),
            "Test".to_string(),
            CallType::Direct,
        );

        entry.duration_seconds = 0;
        assert_eq!(entry.formatted_duration(), "0:00");

        entry.duration_seconds = 65;
        assert_eq!(entry.formatted_duration(), "1:05");

        entry.duration_seconds = 3723; // 1 hour, 2 minutes, 3 seconds
        assert_eq!(entry.formatted_duration(), "1:02:03");
    }

    #[test]
    fn call_history_entry_participants_display() {
        let mut entry = CallHistoryEntry::new_outgoing(
            "call1".to_string(),
            "ent1".to_string(),
            "Group Chat".to_string(),
            CallType::Group,
        );

        // No participants
        assert_eq!(entry.participants_display(), "Group Chat");

        // One participant
        entry.participants.push(HistoryParticipant {
            id: "p1".to_string(),
            display_name: "Alice".to_string(),
            four_words: "a-b-c-d".to_string(),
            duration_seconds: 60,
            partial_participation: false,
        });
        assert_eq!(entry.participants_display(), "Alice");

        // Two participants
        entry.participants.push(HistoryParticipant {
            id: "p2".to_string(),
            display_name: "Bob".to_string(),
            four_words: "e-f-g-h".to_string(),
            duration_seconds: 60,
            partial_participation: false,
        });
        assert_eq!(entry.participants_display(), "Alice and Bob");

        // Three participants
        entry.participants.push(HistoryParticipant {
            id: "p3".to_string(),
            display_name: "Charlie".to_string(),
            four_words: "i-j-k-l".to_string(),
            duration_seconds: 60,
            partial_participation: false,
        });
        assert_eq!(entry.participants_display(), "Alice and 2 others");
    }

    #[test]
    fn call_history_entry_is_unread_missed() {
        let mut entry = CallHistoryEntry::new_incoming(
            "call1".to_string(),
            "ent1".to_string(),
            "Test".to_string(),
            CallType::Direct,
        );

        entry.outcome = CallOutcome::Missed;
        entry.is_read = false;
        assert!(entry.is_unread_missed());

        entry.mark_read();
        assert!(!entry.is_unread_missed());
    }

    #[test]
    fn call_history_add_and_get() {
        let mut history = CallHistory::new(100);
        assert!(history.is_empty());

        let entry1 = CallHistoryEntry::new_outgoing(
            "call1".to_string(),
            "ent1".to_string(),
            "Test 1".to_string(),
            CallType::Direct,
        );
        let entry2 = CallHistoryEntry::new_outgoing(
            "call2".to_string(),
            "ent2".to_string(),
            "Test 2".to_string(),
            CallType::Direct,
        );

        history.add(entry1);
        history.add(entry2);

        assert_eq!(history.len(), 2);
        assert_eq!(history.entries[0].call_id, "call2"); // Newest first
        assert_eq!(history.entries[1].call_id, "call1");

        assert!(history.get("call1").is_some());
        assert!(history.get("nonexistent").is_none());
    }

    #[test]
    fn call_history_max_entries() {
        let mut history = CallHistory::new(2);

        for i in 0..5 {
            let entry = CallHistoryEntry::new_outgoing(
                format!("call{}", i),
                "ent".to_string(),
                "Test".to_string(),
                CallType::Direct,
            );
            history.add(entry);
        }

        // Should only have 2 entries (newest)
        assert_eq!(history.len(), 2);
        assert_eq!(history.entries[0].call_id, "call4");
        assert_eq!(history.entries[1].call_id, "call3");
    }

    #[test]
    fn call_history_update() {
        let mut history = CallHistory::new(100);

        let entry = CallHistoryEntry::new_outgoing(
            "call1".to_string(),
            "ent1".to_string(),
            "Test".to_string(),
            CallType::Direct,
        );
        history.add(entry);

        history.update("call1", |e| {
            e.outcome = CallOutcome::Completed;
            e.duration_seconds = 120;
        });

        let updated = history.get("call1").unwrap();
        assert_eq!(updated.outcome, CallOutcome::Completed);
        assert_eq!(updated.duration_seconds, 120);
    }

    #[test]
    fn call_history_remove() {
        let mut history = CallHistory::new(100);

        let entry = CallHistoryEntry::new_outgoing(
            "call1".to_string(),
            "ent1".to_string(),
            "Test".to_string(),
            CallType::Direct,
        );
        history.add(entry);

        let removed = history.remove("call1");
        assert!(removed.is_some());
        assert!(history.is_empty());

        let not_found = history.remove("nonexistent");
        assert!(not_found.is_none());
    }

    #[test]
    fn call_history_missed_calls() {
        let mut history = CallHistory::new(100);

        let mut missed = CallHistoryEntry::new_incoming(
            "call1".to_string(),
            "ent1".to_string(),
            "Missed".to_string(),
            CallType::Direct,
        );
        missed.outcome = CallOutcome::Missed;
        missed.is_read = false;

        let completed = CallHistoryEntry::new_outgoing(
            "call2".to_string(),
            "ent1".to_string(),
            "Completed".to_string(),
            CallType::Direct,
        );

        history.add(missed);
        history.add(completed);

        assert_eq!(history.missed_calls().len(), 1);
        assert_eq!(history.unread_missed_count(), 1);

        history.mark_all_read();
        assert_eq!(history.unread_missed_count(), 0);
    }

    #[test]
    fn call_history_for_entity() {
        let mut history = CallHistory::new(100);

        let entry1 = CallHistoryEntry::new_outgoing(
            "call1".to_string(),
            "ent1".to_string(),
            "Entity 1".to_string(),
            CallType::Direct,
        );
        let entry2 = CallHistoryEntry::new_outgoing(
            "call2".to_string(),
            "ent2".to_string(),
            "Entity 2".to_string(),
            CallType::Direct,
        );
        let entry3 = CallHistoryEntry::new_outgoing(
            "call3".to_string(),
            "ent1".to_string(),
            "Entity 1 Again".to_string(),
            CallType::Direct,
        );

        history.add(entry1);
        history.add(entry2);
        history.add(entry3);

        let ent1_calls = history.for_entity("ent1");
        assert_eq!(ent1_calls.len(), 2);
    }

    #[test]
    fn call_history_recent() {
        let mut history = CallHistory::new(100);

        for i in 0..10 {
            let entry = CallHistoryEntry::new_outgoing(
                format!("call{}", i),
                "ent".to_string(),
                "Test".to_string(),
                CallType::Direct,
            );
            history.add(entry);
        }

        let recent = history.recent(3);
        assert_eq!(recent.len(), 3);
        assert_eq!(recent[0].call_id, "call9"); // Newest
    }

    // ===== Pending Call Invite Tests =====

    #[test]
    fn pending_call_invite_new() {
        let invite = PendingCallInvite::new(
            "call-123".to_string(),
            "caller-456".to_string(),
            "Alice".to_string(),
            "group-789".to_string(),
            CallType::Group,
        );

        assert_eq!(invite.call_id, "call-123");
        assert_eq!(invite.caller_id, "caller-456");
        assert_eq!(invite.caller_name, "Alice");
        assert_eq!(invite.entity_id, "group-789");
        assert_eq!(invite.call_type, CallType::Group);
        assert!(invite.id.starts_with("invite-call-123-"));
        assert!(invite.expires_at > invite.received_at);
        assert_eq!(
            invite.expires_at - invite.received_at,
            PENDING_INVITE_EXPIRY_MS
        );
    }

    #[test]
    fn pending_call_invite_is_expired() {
        let mut invite = PendingCallInvite::new(
            "call-1".to_string(),
            "caller-1".to_string(),
            "Test".to_string(),
            "entity-1".to_string(),
            CallType::Direct,
        );

        // Fresh invite should not be expired
        assert!(!invite.is_expired());

        // Set expires_at to the past
        invite.expires_at = invite.received_at - 1000;
        assert!(invite.is_expired());
    }

    #[test]
    fn pending_call_invite_time_remaining() {
        let mut invite = PendingCallInvite::new(
            "call-1".to_string(),
            "caller-1".to_string(),
            "Test".to_string(),
            "entity-1".to_string(),
            CallType::Direct,
        );

        // Fresh invite should show remaining time
        let remaining = invite.time_remaining();
        assert!(!remaining.contains("Expired"));

        // Expired invite
        invite.expires_at = invite.received_at - 1000;
        assert_eq!(invite.time_remaining(), "Expired");
    }

    #[test]
    fn pending_invites_snapshot_default() {
        let snapshot = PendingInvitesSnapshot::default();
        assert!(snapshot.invites.is_empty());
        assert_eq!(snapshot.count, 0);
        assert!(!snapshot.has_invites());
    }

    #[test]
    fn pending_invites_snapshot_has_invites() {
        let mut snapshot = PendingInvitesSnapshot::default();
        assert!(!snapshot.has_invites());

        snapshot.invites.push(PendingCallInvite::new(
            "call-1".to_string(),
            "caller-1".to_string(),
            "Alice".to_string(),
            "entity-1".to_string(),
            CallType::Direct,
        ));
        snapshot.count = 1;

        assert!(snapshot.has_invites());
    }

    #[test]
    fn pending_invites_snapshot_for_caller() {
        let mut snapshot = PendingInvitesSnapshot::default();

        snapshot.invites.push(PendingCallInvite::new(
            "call-1".to_string(),
            "alice".to_string(),
            "Alice".to_string(),
            "entity-1".to_string(),
            CallType::Direct,
        ));
        snapshot.invites.push(PendingCallInvite::new(
            "call-2".to_string(),
            "bob".to_string(),
            "Bob".to_string(),
            "entity-2".to_string(),
            CallType::Direct,
        ));
        snapshot.invites.push(PendingCallInvite::new(
            "call-3".to_string(),
            "alice".to_string(),
            "Alice".to_string(),
            "entity-3".to_string(),
            CallType::Group,
        ));

        let alice_invites = snapshot.for_caller("alice");
        assert_eq!(alice_invites.len(), 2);

        let bob_invites = snapshot.for_caller("bob");
        assert_eq!(bob_invites.len(), 1);

        let charlie_invites = snapshot.for_caller("charlie");
        assert!(charlie_invites.is_empty());
    }

    #[test]
    fn pending_invites_snapshot_most_urgent() {
        let snapshot = PendingInvitesSnapshot::default();
        assert!(snapshot.most_urgent().is_none());

        let mut snapshot_with_invites = PendingInvitesSnapshot::default();
        snapshot_with_invites.invites.push(PendingCallInvite::new(
            "call-1".to_string(),
            "caller-1".to_string(),
            "Alice".to_string(),
            "entity-1".to_string(),
            CallType::Direct,
        ));

        let urgent = snapshot_with_invites.most_urgent();
        assert!(urgent.is_some());
        assert_eq!(urgent.unwrap().call_id, "call-1");
    }

    #[test]
    fn pending_invites_snapshot_active() {
        let mut snapshot = PendingInvitesSnapshot::default();

        let mut expired_invite = PendingCallInvite::new(
            "call-expired".to_string(),
            "caller-1".to_string(),
            "Expired".to_string(),
            "entity-1".to_string(),
            CallType::Direct,
        );
        expired_invite.expires_at = expired_invite.received_at - 1000; // Expired

        let fresh_invite = PendingCallInvite::new(
            "call-fresh".to_string(),
            "caller-2".to_string(),
            "Fresh".to_string(),
            "entity-2".to_string(),
            CallType::Direct,
        );

        snapshot.invites.push(expired_invite);
        snapshot.invites.push(fresh_invite);

        let active = snapshot.active();
        assert_eq!(active.len(), 1);
        assert_eq!(active[0].call_id, "call-fresh");
    }

    #[test]
    fn pending_invite_constants() {
        assert_eq!(MAX_PENDING_INVITES, 10);
        assert_eq!(PENDING_INVITE_EXPIRY_MS, 5 * 60 * 1000); // 5 minutes
    }
}