steam-user 0.1.0

Steam User web client for Rust - HTTP-based Steam Community interactions
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
//! User interaction services.

use std::sync::OnceLock;

use scraper::Selector;
use serde::Deserialize;
use steamid::SteamID;

use crate::{
    client::SteamUser,
    endpoint::{steam_endpoint, Host},
    error::SteamUserError,
    utils::{
        avatar::{extract_custom_url, get_avatar_hash_from_url, get_avatar_url_from_hash, AvatarSize},
        debug::dump_html,
    },
};

// =========================================================================
// Deserialization helpers
//
// Steam's JSON sometimes returns numeric fields as strings, sometimes as
// numbers, and sometimes wraps strings with thousands-separator commas
// (e.g. "1,234"). The helpers below normalise those shapes into typed
// fields so call sites can be `#[derive(Deserialize)]` instead of walking
// `serde_json::Value` by hand.
// =========================================================================

/// Accepts either an integer or a numeric string and produces a `u32`.
/// Strips ASCII commas so values like `"1,234"` round-trip correctly.
fn de_u32_int_or_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
    use serde::de::Error;
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum N {
        Int(u64),
        Str(String),
    }
    match N::deserialize(d)? {
        N::Int(n) => u32::try_from(n).map_err(D::Error::custom),
        N::Str(s) => s.replace(',', "").parse().map_err(D::Error::custom),
    }
}

/// Accepts either an integer or a numeric string and produces an `Option<i32>`.
/// Missing fields, JSON null, or unparseable strings collapse to `None`.
fn de_opt_i32_int_or_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<i32>, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum N {
        Int(i64),
        Str(String),
        Null,
    }
    Ok(match Option::<N>::deserialize(d)? {
        Some(N::Int(n)) => i32::try_from(n).ok(),
        Some(N::Str(s)) => s.replace(',', "").parse().ok(),
        Some(N::Null) | None => None,
    })
}

/// Accepts either an integer or a numeric string and produces an `Option<u64>`.
fn de_opt_u64_int_or_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum N {
        Int(u64),
        Str(String),
        Null,
    }
    Ok(match Option::<N>::deserialize(d)? {
        Some(N::Int(n)) => Some(n),
        Some(N::Str(s)) => s.replace(',', "").parse().ok(),
        Some(N::Null) | None => None,
    })
}

/// Accepts either an integer (treated as `1` ⇒ true) or a bool. Defaults to
/// `false` on missing fields.
fn de_bool_int_or_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum B {
        Bool(bool),
        Int(i64),
        Null,
    }
    Ok(match Option::<B>::deserialize(d)? {
        Some(B::Bool(b)) => b,
        Some(B::Int(n)) => n == 1,
        Some(B::Null) | None => false,
    })
}

// =========================================================================
// Raw response shapes
// =========================================================================

/// Raw shape of the `/search/SearchCommunityAjax` response.
#[derive(Deserialize)]
struct CommunitySearchResponseRaw {
    #[serde(default)]
    success: i64,
    #[serde(default)]
    html: String,
    #[serde(default = "default_search_filter")]
    search_filter: String,
    #[serde(default, deserialize_with = "de_opt_u64_int_or_string")]
    search_page: Option<u64>,
    #[serde(default, deserialize_with = "de_u32_int_or_string")]
    search_result_count: u32,
    #[serde(default)]
    search_text: String,
}

fn default_search_filter() -> String {
    "users".to_string()
}

/// Raw shape of a quick-invite "invite" sub-document.
#[derive(Deserialize, Default)]
struct QuickInviteRaw {
    #[serde(default)]
    invite_token: Option<String>,
    #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
    invite_limit: Option<i32>,
    #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
    invite_duration: Option<i32>,
    #[serde(default, deserialize_with = "de_opt_u64_int_or_string")]
    time_created: Option<u64>,
}

/// Raw shape of `/invites/ajaxcreate`.
#[derive(Deserialize)]
struct QuickInviteCreateResponseRaw {
    #[serde(default, deserialize_with = "de_bool_int_or_bool")]
    success: bool,
    #[serde(default)]
    invite: Option<QuickInviteRaw>,
}

/// Raw shape of `/invites/ajaxgetall`.
#[derive(Deserialize)]
struct QuickInviteListResponseRaw {
    #[serde(default, deserialize_with = "de_bool_int_or_bool")]
    success: bool,
    #[serde(default)]
    tokens: Vec<QuickInviteTokenRaw>,
}

/// Single entry in the list returned by `/invites/ajaxgetall`.
#[derive(Deserialize)]
struct QuickInviteTokenRaw {
    #[serde(default)]
    invite_token: String,
    #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
    invite_limit: Option<i32>,
    #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
    invite_duration: Option<i32>,
    #[serde(default, deserialize_with = "de_opt_u64_int_or_string")]
    time_created: Option<u64>,
}

/// Raw shape of `/invites/ajaxredeem`.
#[derive(Deserialize)]
struct RedeemResponseRaw {
    #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
    success: Option<i32>,
}

/// Raw shape of the `g_rgCounts` JS variable embedded in the friends page.
#[derive(Deserialize, Default)]
#[serde(default)]
struct FriendsCountRaw {
    #[serde(rename = "cFriends", deserialize_with = "de_u32_int_or_string")]
    friends: u32,
    #[serde(rename = "cFriendsPending", deserialize_with = "de_u32_int_or_string")]
    friends_pending: u32,
    #[serde(rename = "cFriendsBlocked", deserialize_with = "de_u32_int_or_string")]
    friends_blocked: u32,
    #[serde(rename = "cFollowing", deserialize_with = "de_u32_int_or_string")]
    following: u32,
    #[serde(rename = "cGroups", deserialize_with = "de_u32_int_or_string")]
    groups: u32,
    #[serde(rename = "cGroupsPending", deserialize_with = "de_u32_int_or_string")]
    groups_pending: u32,
}

static SEL_INVITE_BLOCK_NAME: OnceLock<Selector> = OnceLock::new();
fn sel_invite_block_name() -> &'static Selector {
    SEL_INVITE_BLOCK_NAME.get_or_init(|| Selector::parse(".invite_block_name > a.linkTitle").expect("valid CSS selector"))
}

static SEL_FRIEND_PLAYER_LEVEL: OnceLock<Selector> = OnceLock::new();
fn sel_friend_player_level() -> &'static Selector {
    SEL_FRIEND_PLAYER_LEVEL.get_or_init(|| Selector::parse(".friendPlayerLevel .friendPlayerLevelNum").expect("valid CSS selector"))
}

static SEL_PERSONA_MINIPROFILE: OnceLock<Selector> = OnceLock::new();
fn sel_persona_miniprofile() -> &'static Selector {
    SEL_PERSONA_MINIPROFILE.get_or_init(|| Selector::parse(".persona[data-miniprofile]").expect("valid CSS selector"))
}

static SEL_SELECTABLE_OVERLAY: OnceLock<Selector> = OnceLock::new();
fn sel_selectable_overlay() -> &'static Selector {
    SEL_SELECTABLE_OVERLAY.get_or_init(|| Selector::parse("a.selectable_overlay").expect("valid CSS selector"))
}

static SEL_PLAYER_AVATAR_IMG: OnceLock<Selector> = OnceLock::new();
fn sel_player_avatar_img() -> &'static Selector {
    SEL_PLAYER_AVATAR_IMG.get_or_init(|| Selector::parse(".player_avatar img, .playerAvatar img").expect("valid CSS selector"))
}

static SEL_FRIEND_BLOCK_CONTENT: OnceLock<Selector> = OnceLock::new();
fn sel_friend_block_content() -> &'static Selector {
    SEL_FRIEND_BLOCK_CONTENT.get_or_init(|| Selector::parse(".friend_block_content, .friendBlockContent").expect("valid CSS selector"))
}

static SEL_PLAYER_NICKNAME_HINT: OnceLock<Selector> = OnceLock::new();
fn sel_player_nickname_hint() -> &'static Selector {
    SEL_PLAYER_NICKNAME_HINT.get_or_init(|| Selector::parse(".player_nickname_hint").expect("valid CSS selector"))
}

static SEL_FRIEND_GAME_LINK: OnceLock<Selector> = OnceLock::new();
fn sel_friend_game_link() -> &'static Selector {
    SEL_FRIEND_GAME_LINK.get_or_init(|| Selector::parse(".friend_game_link, .linkFriend_in-game").expect("valid CSS selector"))
}

static SEL_FRIEND_LAST_ONLINE: OnceLock<Selector> = OnceLock::new();
fn sel_friend_last_online() -> &'static Selector {
    SEL_FRIEND_LAST_ONLINE.get_or_init(|| Selector::parse(".friend_last_online_text").expect("valid CSS selector"))
}

static SEL_SEARCH_ROW: OnceLock<Selector> = OnceLock::new();
fn sel_search_row() -> &'static Selector {
    SEL_SEARCH_ROW.get_or_init(|| Selector::parse(".search_row").expect("valid CSS selector"))
}

static SEL_MEDIUM_HOLDER: OnceLock<Selector> = OnceLock::new();
fn sel_medium_holder() -> &'static Selector {
    SEL_MEDIUM_HOLDER.get_or_init(|| Selector::parse(".mediumHolder_default[data-miniprofile]").expect("valid CSS selector"))
}

static SEL_AVATAR_MEDIUM_IMG: OnceLock<Selector> = OnceLock::new();
fn sel_avatar_medium_img() -> &'static Selector {
    SEL_AVATAR_MEDIUM_IMG.get_or_init(|| Selector::parse(".avatarMedium a img").expect("valid CSS selector"))
}

static SEL_SEARCH_PERSONA_NAME: OnceLock<Selector> = OnceLock::new();
fn sel_search_persona_name() -> &'static Selector {
    SEL_SEARCH_PERSONA_NAME.get_or_init(|| Selector::parse("a.searchPersonaName").expect("valid CSS selector"))
}

static SEL_COMMUNITY_SEARCH_PAGING: OnceLock<Selector> = OnceLock::new();
fn sel_community_search_paging() -> &'static Selector {
    SEL_COMMUNITY_SEARCH_PAGING.get_or_init(|| Selector::parse(".community_searchresults_paging a").expect("valid CSS selector"))
}

impl SteamUser {
    /// Sends a friend request to a user.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The [`SteamID`] of the user to add.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::SteamUser;
    /// # use steamid::SteamID;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let target = SteamID::from(76561197960287930);
    /// user.add_friend(target).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(POST, host = Community, path = "/actions/AddFriendAjax", kind = Write)]
    pub async fn add_friend(&self, user_id: SteamID) -> Result<(), SteamUserError> {
        let steam_id = user_id.steam_id64().to_string();

        let response: serde_json::Value = self.post_path("/actions/AddFriendAjax").form(&[("steamid", steam_id.as_str()), ("accept_invite", "0")]).send().await?.json().await?;

        Self::check_json_success(&response, "Failed to add friend")?;

        Ok(())
    }

    /// Removes a user from the friend list.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The [`SteamID`] of the friend to remove.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::SteamUser;
    /// # use steamid::SteamID;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let target = SteamID::from(76561197960287930);
    /// user.remove_friend(target).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(POST, host = Community, path = "/actions/RemoveFriendAjax", kind = Write)]
    pub async fn remove_friend(&self, user_id: SteamID) -> Result<(), SteamUserError> {
        let steam_id = user_id.steam_id64().to_string();

        let response: serde_json::Value = self.post_path("/actions/RemoveFriendAjax").form(&[("steamid", steam_id.as_str())]).send().await?.json().await?;

        Self::check_json_success(&response, "Failed to remove friend")?;

        Ok(())
    }

    /// Accepts a pending friend request from a user.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The [`SteamID`] of the user whose request to accept.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::SteamUser;
    /// # use steamid::SteamID;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let requester = SteamID::from(76561197960287930);
    /// user.accept_friend_request(requester).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(POST, host = Community, path = "/profiles/{steam_id}/friends/action", kind = Write)]
    pub async fn accept_friend_request(&self, user_id: SteamID) -> Result<(), SteamUserError> {
        let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64().to_string();
        let target_steam_id = user_id.steam_id64().to_string();

        let url = format!("/profiles/{}/friends/action", my_steam_id);

        let response: serde_json::Value = self.post_path(&url).form(&[("steamid", my_steam_id.as_str()), ("ajax", "1"), ("action", "accept"), ("steamids[]", target_steam_id.as_str())]).send().await?.json().await?;

        Self::check_json_success(&response, "Failed to accept friend request")?;

        Ok(())
    }

    /// Ignores or declines a pending friend request.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The [`SteamID`] of the user whose request to ignore.
    #[steam_endpoint(POST, host = Community, path = "/actions/IgnoreFriendInviteAjax", kind = Write)]
    pub async fn ignore_friend_request(&self, user_id: SteamID) -> Result<(), SteamUserError> {
        let steam_id = user_id.steam_id64().to_string();

        let response: serde_json::Value = self.post_path("/actions/IgnoreFriendInviteAjax").form(&[("steamid", steam_id.as_str())]).send().await?.json().await?;

        Self::check_json_success(&response, "Failed to ignore friend request")?;

        Ok(())
    }

    /// Sets or removes a communication block (block/unblock) for a user.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The [`SteamID`] of the user to block or unblock.
    /// * `block` - `true` to block, `false` to unblock.
    #[steam_endpoint(POST, host = Community, path = "/actions/BlockUserAjax", kind = Write)]
    pub async fn set_communication_block(&self, user_id: SteamID, block: bool) -> Result<(), SteamUserError> {
        let steam_id = user_id.steam_id64().to_string();
        let block_val = if block { "1" } else { "0" };

        let response: serde_json::Value = self.post_path("/actions/BlockUserAjax").form(&[("steamid", steam_id.as_str()), ("block", block_val)]).send().await?.json().await?;

        Self::check_json_success(&response, &format!("Failed to {} user", if block { "block" } else { "unblock" }))?;

        Ok(())
    }

    /// Blocks all communication from a specified user.
    // delegates to `set_communication_block` — no #[steam_endpoint]
    #[tracing::instrument(skip(self), fields(target_steam_id = user_id.steam_id64()))]
    pub async fn block_user(&self, user_id: SteamID) -> Result<(), SteamUserError> {
        self.set_communication_block(user_id, true).await
    }

    /// Unblocks a previously blocked user.
    // delegates to `set_communication_block` — no #[steam_endpoint]
    #[tracing::instrument(skip(self), fields(target_steam_id = user_id.steam_id64()))]
    pub async fn unblock_user(&self, user_id: SteamID) -> Result<(), SteamUserError> {
        self.set_communication_block(user_id, false).await
    }

    /// Fetches the raw friend list from the AJAX endpoint.
    ///
    /// Returns `(success_code, friends_array)`. Handles success code 21 (no
    /// friends) by returning an empty array.
    #[steam_endpoint(GET, host = Community, path = "/textfilter/ajaxgetfriendslist", kind = Read)]
    async fn fetch_friends_list_raw(&self) -> Result<(i64, Vec<serde_json::Value>), SteamUserError> {
        let response: serde_json::Value = self.get_path("/textfilter/ajaxgetfriendslist").send().await?.json().await?;

        let success = response.get("success").and_then(|v| v.as_i64()).unwrap_or(0);

        if success != 1 {
            if success == 21 {
                return Ok((21, Vec::new()));
            }
            return Err(SteamUserError::from_eresult(i32::try_from(success).unwrap_or(i32::MIN)));
        }

        let friends_list = response.get("friendslist").and_then(|v| v.get("friends")).and_then(|v| v.as_array()).ok_or_else(|| SteamUserError::MalformedResponse("Missing friends list".into()))?;

        Ok((1, friends_list.clone()))
    }

    /// Retrieves the friend list with relationship status codes.
    ///
    /// Fetches a list of friends and their relationship status (e.g., 3 for
    /// Friend, 2 for Request Sent, etc.).
    ///
    /// # Returns
    ///
    /// Returns a `HashMap<SteamID, i32>` where the key is the SteamID and the
    /// value is the relationship status integer.
    // delegates to `fetch_friends_list_raw` — no #[steam_endpoint]
    #[tracing::instrument(skip(self))]
    pub async fn get_friends_list(&self) -> Result<std::collections::HashMap<SteamID, i32>, SteamUserError> {
        let (_, friends_list) = self.fetch_friends_list_raw().await?;

        let mut friends = std::collections::HashMap::with_capacity(friends_list.len());
        for friend in &friends_list {
            if let (Some(id), Some(rel)) = (friend.get("ulfriendid").and_then(|v| v.as_str()), friend.get("efriendrelationship").and_then(|v| v.as_i64())) {
                if let Ok(steam_id) = id.parse::<u64>() {
                    if let Ok(rel_i32) = i32::try_from(rel) {
                        friends.insert(SteamID::from(steam_id), rel_i32);
                    }
                }
            }
        }

        Ok(friends)
    }

    /// Retrieves the friend list for the currently authenticated user with full
    /// profile details.
    ///
    /// Scrapes the user's friends page to gather detailed information about
    /// each friend.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<FriendDetails>` containing information like usernames,
    /// online status, and avatars.
    // delegates to `get_friends_details_of_user` — no #[steam_endpoint]
    #[tracing::instrument(skip(self))]
    pub async fn get_friends_details(&self) -> Result<crate::types::FriendListPage, SteamUserError> {
        let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
        self.get_friends_details_of_user(steam_id).await
    }

    /// Retrieves the friend list for a specific Steam account with full
    /// details.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The [`SteamID`] of the user whose friend list you want to
    ///   retrieve.
    #[steam_endpoint(GET, host = Community, path = "/profiles/{user_id}/friends/", kind = Read)]
    pub async fn get_friends_details_of_user(&self, user_id: SteamID) -> Result<crate::types::FriendListPage, SteamUserError> {
        let body = self.get_path(format!("/profiles/{}/friends/", user_id.steam_id64())).send().await?.text().await?;
        Ok(parse_friend_list(&body))
    }

    /// Follows a user on Steam to see their public activity in your activity
    /// feed.
    #[steam_endpoint(POST, host = Community, path = "/profiles/{user_id}/followuser/", kind = Write)]
    pub async fn follow_user(&self, user_id: SteamID) -> Result<(), SteamUserError> {
        self.send_profile_follow_action(user_id, "follow").await
    }

    /// Unfollows a previously followed user.
    #[steam_endpoint(POST, host = Community, path = "/profiles/{user_id}/unfollowuser/", kind = Write)]
    pub async fn unfollow_user(&self, user_id: SteamID) -> Result<(), SteamUserError> {
        self.send_profile_follow_action(user_id, "unfollow").await
    }

    /// Searches for Steam Community users by their profile name.
    ///
    /// # Arguments
    ///
    /// * `query` - The search string.
    /// * `page` - The results page number (starting from 1).
    #[steam_endpoint(GET, host = Community, path = "/search/SearchCommunityAjax", kind = Read)]
    pub async fn search_users(&self, query: &str, page: u32) -> Result<crate::types::CommunitySearchResult, SteamUserError> {
        let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64().to_string();

        let raw: CommunitySearchResponseRaw = self.get_path("/search/SearchCommunityAjax").query(&[("text", query), ("filter", "users"), ("steamid", steam_id.as_str()), ("accept_invite", "0"), ("page", &page.to_string())]).send().await?.json().await?;

        if raw.success != 1 {
            return Err(SteamUserError::SteamError("Search failed".to_string()));
        }

        let search_page = raw.search_page.and_then(|n| u32::try_from(n).ok()).unwrap_or(page);
        let search_text = if raw.search_text.is_empty() { query.to_string() } else { raw.search_text };

        let (players, prev_page, next_page) = parse_search_results(&raw.html, search_page);

        Ok(crate::types::CommunitySearchResult {
            players,
            prev_page,
            next_page,
            search_filter: raw.search_filter,
            search_page,
            search_result_count: raw.search_result_count,
            search_text,
        })
    }

    /// Creates an instant friend invite link for the current user.
    ///
    /// This generates a short link (e.g., `https://s.team/p/XXXX-XXXX/TOKEN`) that anyone can use
    /// to instantly add you as a friend without searching.
    // delegates to `get_quick_invite_data` — no #[steam_endpoint]
    #[tracing::instrument(skip(self))]
    pub async fn create_instant_invite(&self) -> Result<String, SteamUserError> {
        let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
        let short_url = format!("https://s.team/p/{}", steam_friend_code::create_short_steam_friend_code(my_steam_id.account_id));
        let invite_data = self.get_quick_invite_data().await?;

        if let Some(token) = invite_data.invite_token {
            Ok(format!("{}/{}", short_url, token))
        } else {
            Err(SteamUserError::SteamError("Failed to generate invite token".to_string()))
        }
    }

    /// Retrieves the primary quick invite token and associated metadata for the
    /// current user.
    #[steam_endpoint(POST, host = Community, path = "/invites/ajaxcreate", kind = Write)]
    pub async fn get_quick_invite_data(&self) -> Result<crate::types::QuickInviteData, SteamUserError> {
        let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;

        let raw: QuickInviteCreateResponseRaw = self.post_path("/invites/ajaxcreate").form(&[("steamid_user", my_steam_id.steam_id64().to_string()), ("duration", "2592000".to_string())]).send().await?.json().await?;

        if let (true, Some(invite)) = (raw.success, raw.invite) {
            Ok(crate::types::QuickInviteData {
                success: true,
                invite_token: invite.invite_token,
                invite_limit: invite.invite_limit,
                invite_duration: invite.invite_duration,
                time_created: invite.time_created,
                steam_id: Some(my_steam_id),
            })
        } else {
            Ok(crate::types::QuickInviteData {
                success: false,
                invite_token: None,
                invite_limit: None,
                invite_duration: None,
                time_created: None,
                steam_id: Some(my_steam_id),
            })
        }
    }

    /// Retrieves all active quick invite tokens for the authenticated user.
    #[steam_endpoint(GET, host = Community, path = "/invites/ajaxgetall", kind = Read)]
    pub async fn get_current_quick_invite_tokens(&self) -> Result<crate::types::QuickInviteTokensResponse, SteamUserError> {
        let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;

        let raw: QuickInviteListResponseRaw = self.get_path("/invites/ajaxgetall").send().await?.json().await?;

        let tokens = raw
            .tokens
            .into_iter()
            .map(|t| crate::types::QuickInviteToken {
                invite_token: t.invite_token,
                invite_limit: t.invite_limit.unwrap_or(0),
                invite_duration: t.invite_duration.unwrap_or(0),
                time_created: t.time_created.unwrap_or(0),
                steam_id: Some(my_steam_id),
            })
            .collect();

        Ok(crate::types::QuickInviteTokensResponse { success: raw.success, tokens })
    }

    /// Internal helper for follow/unfollow actions.
    #[steam_endpoint(POST, host = Community, path = "/profiles/{user_id}/{action}user/", kind = Write)]
    async fn send_profile_follow_action(&self, user_id: SteamID, action: &str) -> Result<(), SteamUserError> {
        let target_steam_id = user_id.steam_id64().to_string();

        let response: serde_json::Value = self.post_path(format!("/profiles/{}/{}user/", target_steam_id, action)).form(&([] as [(&str, &str); 0])).send().await?.json().await?;
        Self::check_json_success(&response, &format!("Failed to {} user", action))?;
        Ok(())
    }

    // =========================================================================
    // Extended Friend Management Methods
    // =========================================================================

    /// Retrieves the list of players the current user is following.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<FriendDetails>` containing information about each
    /// followed user.
    // delegates to `get_following_list_of_user` — no #[steam_endpoint]
    #[tracing::instrument(skip(self))]
    pub async fn get_following_list(&self) -> Result<crate::types::FriendListPage, SteamUserError> {
        let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
        self.get_following_list_of_user(steam_id).await
    }

    /// Retrieves the list of players a specific user is following.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The [`SteamID`] of the user whose following list to
    ///   retrieve.
    #[steam_endpoint(GET, host = Community, path = "/profiles/{user_id}/following/", kind = Read)]
    pub async fn get_following_list_of_user(&self, user_id: SteamID) -> Result<crate::types::FriendListPage, SteamUserError> {
        let body = self.get_path(format!("/profiles/{}/following/", user_id.steam_id64())).send().await?.text().await?;
        Ok(parse_friend_list(&body))
    }

    /// Retrieves a simple list of friend SteamIDs for the current user.
    ///
    /// This method uses the AJAX API to fetch only SteamIDs of confirmed
    /// friends, filtering out pending requests and other relationship
    /// types.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<SteamID>` containing the SteamIDs of all confirmed
    /// friends.
    // delegates to `fetch_friends_list_raw` — no #[steam_endpoint]
    #[tracing::instrument(skip(self))]
    pub async fn get_my_friends_id_list(&self) -> Result<Vec<SteamID>, SteamUserError> {
        let (_, friends_list) = self.fetch_friends_list_raw().await?;

        // EFriendRelationship.Friend = 3
        const FRIEND_RELATIONSHIP: i64 = 3;

        let mut friends = Vec::new();
        for friend in &friends_list {
            let relationship = friend.get("efriendrelationship").and_then(|v| v.as_i64()).unwrap_or(0);

            if relationship == FRIEND_RELATIONSHIP {
                if let Some(id_str) = friend.get("ulfriendid").and_then(|v| v.as_str()) {
                    if let Ok(steam_id) = id_str.parse::<u64>() {
                        friends.push(SteamID::from(steam_id));
                    }
                }
            }
        }

        Ok(friends)
    }

    /// Retrieves the list of pending friend requests (both incoming and
    /// outgoing).
    ///
    /// # Returns
    ///
    /// Returns a `PendingFriendList` containing both sent and received friend
    /// invites.
    #[steam_endpoint(GET, host = Community, path = "/profiles/{steam_id}/friends/pending", kind = Read)]
    pub async fn get_pending_friend_list(&self) -> Result<crate::types::PendingFriendList, SteamUserError> {
        let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64();

        let body = self.get_path(format!("/profiles/{}/friends/pending", steam_id)).send().await?.text().await?;

        let sent_invites = parse_pending_friend_list(&body, "#search_results_sentinvites > div");
        let received_invites = parse_pending_friend_list(&body, "#search_results > div");

        Ok(crate::types::PendingFriendList { sent_invites, received_invites })
    }

    /// Removes multiple friends at once.
    ///
    /// # Arguments
    ///
    /// * `steam_ids` - A slice of [`SteamID`]s to remove from the friend list.
    #[steam_endpoint(POST, host = Community, path = "/profiles/{steam_id}/friends/action", kind = Write)]
    pub async fn remove_friends(&self, steam_ids: &[SteamID]) -> Result<(), SteamUserError> {
        if steam_ids.is_empty() {
            return Ok(());
        }

        let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64().to_string();

        let mut params = vec![("steamid", my_steam_id), ("ajax", "1".to_string()), ("action", "remove".to_string())];

        for steam_id in steam_ids {
            params.push(("steamids[]", steam_id.steam_id64().to_string()));
        }

        let response: serde_json::Value = self.post_path(format!("/profiles/{}/friends/action", params[0].1)).form(&params).send().await?.json().await?;

        Self::check_json_success(&response, "Failed to remove friends")?;
        Ok(())
    }

    /// Unfollows multiple users at once.
    ///
    /// # Arguments
    ///
    /// * `steam_ids` - A slice of [`SteamID`]s to unfollow.
    #[steam_endpoint(POST, host = Community, path = "/profiles/{steam_id}/friends/action", kind = Write)]
    pub async fn unfollow_users(&self, steam_ids: &[SteamID]) -> Result<(), SteamUserError> {
        if steam_ids.is_empty() {
            return Ok(());
        }

        let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64().to_string();

        let path = format!("/profiles/{}/friends/action", my_steam_id);

        let mut params = vec![("steamid", my_steam_id.clone()), ("ajax", "1".to_string()), ("action", "unfollow".to_string())];

        for steam_id in steam_ids {
            params.push(("steamids[]", steam_id.steam_id64().to_string()));
        }

        let response: serde_json::Value = self.post_path(&path).form(&params).send().await?.json().await?;

        Self::check_json_success(&response, "Failed to unfollow users")?;
        Ok(())
    }

    /// Unfollows all users the current user is following.
    // composite — no #[steam_endpoint]
    #[tracing::instrument(skip(self))]
    pub async fn unfollow_all_following(&self) -> Result<(), SteamUserError> {
        let page = self.get_following_list().await?;
        if page.friends.is_empty() {
            return Ok(());
        }

        let steam_ids: Vec<SteamID> = page.friends.iter().map(|f| f.steam_id).collect();
        self.unfollow_users(&steam_ids).await
    }

    /// Cancels a pending outgoing friend request.
    ///
    /// # Arguments
    /// This is equivalent to removing a friend - the same API endpoint is used.
    ///
    ///
    /// * `steam_id` - The [`SteamID`] of the user whose friend request to
    ///   cancel.
    // delegates to `remove_friend` — no #[steam_endpoint]
    #[tracing::instrument(skip(self), fields(target_steam_id = steam_id.steam_id64()))]
    pub async fn cancel_friend_request(&self, steam_id: SteamID) -> Result<(), SteamUserError> {
        self.remove_friend(steam_id).await
    }

    /// Retrieves mutual friends between the current user and another user.
    ///
    /// # Arguments
    ///
    /// * `steam_id` - The [`SteamID`] of the user to find mutual friends with.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<FriendDetails>` containing mutual friends.
    #[steam_endpoint(GET, host = Community, path = "/actions/PlayerList/", kind = Read)]
    pub async fn get_friends_in_common(&self, steam_id: SteamID) -> Result<Vec<crate::types::FriendDetails>, SteamUserError> {
        let account_id = steam_id.account_id.to_string();
        let body = self.get_path("/actions/PlayerList/").query(&[("type", "friendsincommon"), ("target", &account_id)]).send().await?.text().await?;
        Ok(parse_friend_list(&body).friends)
    }

    /// Retrieves friends who are members of a specific group.
    ///
    /// # Arguments
    ///
    /// * `group_id` - The [`SteamID`] of the group.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<FriendDetails>` containing friends who are in the group.
    #[steam_endpoint(GET, host = Community, path = "/actions/PlayerList/", kind = Read)]
    pub async fn get_friends_in_group(&self, group_id: SteamID) -> Result<Vec<crate::types::FriendDetails>, SteamUserError> {
        let account_id = group_id.account_id.to_string();
        let body = self.get_path("/actions/PlayerList/").query(&[("type", "friendsingroup"), ("target", &account_id)]).send().await?.text().await?;
        Ok(parse_friend_list(&body).friends)
    }

    /// Retrieves friends' gameplay stats for a specific app.
    ///
    /// # Arguments
    ///
    /// * `app_id` - The App ID of the game to query.
    ///
    /// # Returns
    ///
    /// Returns a `GameplayInfoResponse` containing gameplay info.
    #[steam_endpoint(GET, host = Api, path = "/IPlayerService/GetFriendsGameplayInfo/v1", kind = Read)]
    pub async fn get_friends_gameplay_info(&self, app_id: u32) -> Result<crate::types::gameplay::GameplayInfoResponse, SteamUserError> {
        use prost::Message;
        use steam_protos::messages::player::{CPlayerGetFriendsGameplayInfoRequest, CPlayerGetFriendsGameplayInfoResponse};

        let request = CPlayerGetFriendsGameplayInfoRequest { appid: Some(app_id) };

        let mut body = Vec::new();
        request.encode(&mut body)?;

        let params = [("origin", "https://store.steampowered.com"), ("input_protobuf_encoded", &base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &body))];

        let response = self.get_path("/IPlayerService/GetFriendsGameplayInfo/v1").query(&params).send().await?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let url = response.url().to_string();
            return Err(SteamUserError::HttpStatus { status, url });
        }

        let bytes = response.bytes().await?;
        let response_proto = CPlayerGetFriendsGameplayInfoResponse::decode(bytes)?;

        let convert_list = |list: Vec<steam_protos::messages::player::c_player_get_friends_gameplay_info_response::FriendsGameplayInfo>| {
            list.into_iter()
                .map(|item| crate::types::gameplay::FriendsGameplayInfo {
                    steam_id: SteamID::from(item.steamid.unwrap_or(0)),
                    minutes_played: item.minutes_played.unwrap_or(0),
                    minutes_played_forever: item.minutes_played_forever.unwrap_or(0),
                })
                .collect()
        };

        Ok(crate::types::gameplay::GameplayInfoResponse {
            your_info: response_proto.your_info.map(|info| crate::types::gameplay::OwnGameplayInfo {
                steam_id: SteamID::from(info.steamid.unwrap_or(0)),
                minutes_played: info.minutes_played.unwrap_or(0),
                minutes_played_forever: info.minutes_played_forever.unwrap_or(0),
                in_wishlist: info.in_wishlist.unwrap_or(false),
                owned: info.owned.unwrap_or(false),
            }),
            in_game: convert_list(response_proto.in_game),
            played_recently: convert_list(response_proto.played_recently),
            played_ever: convert_list(response_proto.played_ever),
            owns: convert_list(response_proto.owns),
            in_wishlist: convert_list(response_proto.in_wishlist),
        })
    }

    /// Retrieves the date when a friendship with a user started.
    ///
    /// # Arguments
    ///
    /// * `steam_id` - The [`SteamID`] of the friend.
    ///
    /// # Returns
    ///
    /// Returns `Some(String)` with the friendship date (e.g., "13 June, 2023")
    /// or `None` if not found.
    #[steam_endpoint(GET, host = Community, path = "/tradeoffer/new/", kind = Read)]
    pub async fn get_friend_since(&self, steam_id: SteamID) -> Result<Option<String>, SteamUserError> {
        let account_id = steam_id.account_id.to_string();
        let body = self.get_path("/tradeoffer/new/").query(&[("partner", &account_id)]).send().await?.text().await?;
        Ok(parse_friend_since(&body))
    }

    /// Accepts a friend request via a quick invite link.
    ///
    /// Quick invite links are in the format `https://s.team/p/XXXX-XXXX/TOKEN`
    /// or `https://steamcommunity.com/user/XXXX/TOKEN`.
    ///
    /// # Arguments
    ///
    /// * `invite_link` - The full quick invite URL.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// user.accept_quick_invite_link("https://s.team/p/abcd-efgh/mytoken")
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Community, path = "/invites/ajaxredeem", kind = Write)]
    pub async fn accept_quick_invite_link(&self, invite_link: &str) -> Result<(), SteamUserError> {
        // Extract invite token from the URL (last path segment)
        let invite_token = invite_link.trim_end_matches('/').rsplit('/').next().ok_or_else(|| SteamUserError::MalformedResponse("Invalid invite link format".into()))?;

        // Fetch the invite page to extract the user's SteamID.
        //
        // `invite_link` is a caller-supplied URL on either `s.team`
        // (URL shortener, 302s to community) or `steamcommunity.com`.
        // Parse the URL, route to the matching `Host`, then let the
        // Steam client follow any redirect with cookies attached.
        let parsed = url::Url::parse(invite_link).map_err(|e| SteamUserError::InvalidInput(format!("invalid invite_link: {e}")))?;
        let host = match parsed.host_str() {
            Some("s.team") => Host::ShortLink,
            Some("steamcommunity.com") => Host::Community,
            Some(other) => return Err(SteamUserError::InvalidInput(format!("invite_link host must be s.team or steamcommunity.com, got {other}"))),
            None => return Err(SteamUserError::InvalidInput("invite_link has no host".into())),
        };
        let path_and_query: &str = &parsed[url::Position::BeforePath..];
        let body = self.get_path_on(host, path_and_query).send().await?.text().await?;

        // Parse g_rgProfileData from the page
        let steamid_user = parse_profile_data_steamid(&body).ok_or_else(|| SteamUserError::MalformedResponse("Could not find steamid in invite page".into()))?;

        // Redeem the invite
        let session_id = self.session.session_id.as_deref().ok_or(SteamUserError::NotLoggedIn)?;

        let raw: RedeemResponseRaw = self
            .get_path("/invites/ajaxredeem")
            .query(&[("sessionid", session_id), ("steamid_user", steamid_user.as_str()), ("invite_token", invite_token)])
            .send()
            .await?
            .json()
            .await?;

        let success = raw.success.unwrap_or(0);

        if success != 1 {
            // success: 8 = link expired, success: 91 = other error
            return Err(SteamUserError::SteamError(format!("Failed to accept invite (code: {})", success)));
        }

        Ok(())
    }

    /// Accepts a friend request via quick invite data (steamid and token).
    ///
    /// This is the lower-level method that `accept_quick_invite_link` uses
    /// internally.
    ///
    /// # Arguments
    ///
    /// * `steamid_user` - The SteamID of the user who created the invite.
    /// * `invite_token` - The unique invite token.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error with the failure code.
    #[steam_endpoint(GET, host = Community, path = "/invites/ajaxredeem", kind = Write)]
    pub async fn accept_quick_invite_data(&self, steamid_user: &str, invite_token: &str) -> Result<(), SteamUserError> {
        let session_id = self.session.session_id.as_deref().ok_or(SteamUserError::NotLoggedIn)?;

        let raw: RedeemResponseRaw = self
            .get_path("/invites/ajaxredeem")
            .query(&[("sessionid", session_id), ("steamid_user", steamid_user), ("invite_token", invite_token)])
            .send()
            .await?
            .json()
            .await?;

        let success = raw.success.unwrap_or(0);

        if success != 1 {
            // success: 1 = success
            // success: 8 = link expired
            // success: 91 = other error
            return Err(SteamUserError::SteamError(format!("Failed to accept invite (code: {})", success)));
        }

        Ok(())
    }
}

/// Parses pending friend list from HTML.
fn parse_pending_friend_list(html: &str, selector: &str) -> Vec<crate::types::PendingFriend> {
    let document = scraper::Html::parse_document(html);
    let row_selector = match scraper::Selector::parse(selector) {
        Ok(s) => s,
        Err(e) => {
            tracing::warn!(selector, error = ?e, "parse_pending_friend_list: invalid CSS selector; returning empty");
            return Vec::new();
        }
    };

    let mut results = Vec::new();

    for element in document.select(&row_selector) {
        let steam_id_str = element.value().attr("data-steamid").unwrap_or("");
        let account_id_str = element.value().attr("data-accountid").unwrap_or("0");

        let steam_id = match steam_id_str.parse::<u64>() {
            Ok(id) => SteamID::from(id),
            Err(e) => {
                tracing::warn!(data_steamid = steam_id_str, error = %e, "parse_pending_friend_list: malformed data-steamid; skipping row");
                continue;
            }
        };
        let account_id = account_id_str.parse::<u32>().unwrap_or(0);

        if account_id == 0 {
            continue;
        }

        // Name
        let name = element.select(sel_invite_block_name()).next().map(|el| el.text().collect::<String>().trim().to_string()).unwrap_or_default();

        let link = element.select(sel_invite_block_name()).next().and_then(|el| el.value().attr("href")).unwrap_or("").to_string();

        // Avatar
        let avatar_selector_str = format!(".playerAvatar a > img[data-miniprofile=\"{}\"]", account_id);
        let avatar = if let Ok(avatar_selector) = scraper::Selector::parse(&avatar_selector_str) { element.select(&avatar_selector).next().and_then(|el| el.value().attr("src")).unwrap_or("").to_string() } else { String::new() };

        // Level
        let level = element.select(sel_friend_player_level()).next().map(|el| el.text().collect::<String>().trim().parse::<u32>().unwrap_or(0)).unwrap_or(0);

        results.push(crate::types::PendingFriend { name, link, avatar, steam_id, account_id, level });
    }

    results
}

/// Parses the "friends since" date from trade offer page HTML.
fn parse_friend_since(html: &str) -> Option<String> {
    let document = scraper::Html::parse_document(html);
    let container_selector = scraper::Selector::parse(".trade_partner_header.responsive_trade_offersection").ok()?;
    let info_block_selector = scraper::Selector::parse(".trade_partner_info_block").ok()?;
    let info_text_selector = scraper::Selector::parse(".trade_partner_info_text").ok()?;

    let container = document.select(&container_selector).next()?;

    for info_block in container.select(&info_block_selector) {
        let full_text: String = info_block.text().collect();

        if full_text.contains("You've been friends since") || full_text.contains("You've been friends for") {
            if let Some(info_text) = info_block.select(&info_text_selector).next() {
                let friend_since = info_text.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ");

                if !friend_since.is_empty() {
                    return Some(friend_since);
                }
            }
        }
    }

    None
}

/// Extracts and parses a JavaScript variable assignment from HTML.
///
/// Looks for `var_name = <json>;` and returns the parsed JSON value.
fn parse_js_json_var(html: &str, var_name: &str) -> Option<serde_json::Value> {
    let marker = format!("{} = ", var_name);
    let start = html.find(&marker)?;
    let rest = &html[start + marker.len()..];
    let end = rest.find(";\n").or_else(|| rest.find(";\r")).or_else(|| rest.find(";\t")).or_else(|| rest.find(';'))?;
    serde_json::from_str(rest[..end].trim()).ok()
}

/// Extracts steamid from g_rgProfileData in HTML.
fn parse_profile_data_steamid(html: &str) -> Option<String> {
    let val = parse_js_json_var(html, "g_rgProfileData")?;
    val.get("steamid").and_then(|v| v.as_str()).map(|s| s.to_string())
}

/// Parses page-level metadata from the friend/following HTML page.
///
/// Extracts `g_rgProfileData`, `g_rgCounts`, `g_cFriendsLimit` JS variables
/// and the wallet balance element from the already-parsed document.
fn parse_friend_page_info(html: &str, document: &scraper::Html) -> Option<crate::types::FriendPageInfo> {
    use crate::types::FriendPageInfo;

    let mut info = FriendPageInfo::default();
    let mut found_anything = false;

    if let Some(val) = parse_js_json_var(html, "g_rgProfileData") {
        if let Some(name) = val.get("personaname").and_then(|v| v.as_str()) {
            info.persona_name = name.to_string();
        }
        if let Some(url) = val.get("url").and_then(|v| v.as_str()) {
            info.profile_url = url.to_string();
        }
        if let Some(sid) = val.get("steamid").and_then(|v| v.as_str()) {
            if let Ok(id64) = sid.parse::<u64>() {
                info.steam_id = SteamID::from(id64);
            }
        }
        found_anything = true;
    }

    if let Some(val) = parse_js_json_var(html, "g_rgCounts") {
        // The deserializer accepts ints, numeric strings, or comma-formatted
        // strings. Missing or unparseable fields collapse to 0 via `Default`.
        if let Ok(counts) = serde_json::from_value::<FriendsCountRaw>(val) {
            info.friends_count = counts.friends;
            info.friends_pending_count = counts.friends_pending;
            info.blocked_count = counts.friends_blocked;
            info.following_count = counts.following;
            info.groups_count = counts.groups;
            info.groups_pending_count = counts.groups_pending;
            found_anything = true;
        }
    }

    // g_cFriendsLimit is a plain integer, not JSON
    if let Some(start) = html.find("g_cFriendsLimit = ") {
        let rest = &html[start + 18..];
        if let Some(end) = rest.find(';') {
            if let Ok(limit) = rest[..end].trim().parse::<u32>() {
                info.friends_limit = limit;
                found_anything = true;
            }
        }
    }

    let wallet = crate::services::account::parse_wallet_balance(document);
    if wallet.main_balance.is_some() {
        info.wallet_balance = Some(wallet);
        found_anything = true;
    }

    if found_anything {
        Some(info)
    } else {
        None
    }
}

fn parse_friend_list(html: &str) -> crate::types::FriendListPage {
    let document = scraper::Html::parse_document(html);
    let mut results = Vec::new();

    for element in document.select(sel_persona_miniprofile()) {
        let miniprofile = element.value().attr("data-miniprofile").and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
        if miniprofile == 0 {
            continue;
        }

        let steam_id = SteamID::from_individual_account_id(miniprofile);

        // Profile URL
        let profile_url = element.select(sel_selectable_overlay()).next().and_then(|el| el.value().attr("href")).unwrap_or("").to_string();
        if profile_url.is_empty() {
            continue;
        }

        // Avatar
        let avatar_src = element.select(sel_player_avatar_img()).next().and_then(|el| el.value().attr("src")).unwrap_or("");
        let avatar_hash = get_avatar_hash_from_url(avatar_src).unwrap_or_default();
        let avatar = get_avatar_url_from_hash(&avatar_hash, AvatarSize::Full).unwrap_or_else(|| avatar_src.to_string());

        // Username, game, last online, nickname
        let mut username = String::new();
        let mut game = String::new();
        let mut last_online = String::new();
        let mut is_nickname = false;

        if let Some(content) = element.select(sel_friend_block_content()).next() {
            is_nickname = content.select(sel_player_nickname_hint()).next().is_some();

            if let Some(game_el) = content.select(sel_friend_game_link()).next() {
                game = game_el.text().collect::<String>().trim().replace("In-Game", "").trim().to_string();
            }

            if let Some(last_el) = content.select(sel_friend_last_online()).next() {
                last_online = last_el.text().collect::<String>().trim().to_string();
            }

            // Take only the first text node to avoid getting game names/last online text
            if let Some(first_text) = content.text().next() {
                username = first_text.trim().to_string();
            }

            if username.is_empty() {
                let full_text = content.text().collect::<String>();
                username = full_text.trim().split('\n').next().unwrap_or("").trim().to_string();
            }
        }

        if username == "[deleted]" {
            continue;
        }

        let online_status = if element.value().classes().any(|c| c == "in-game") {
            "ingame"
        } else if element.value().classes().any(|c| c == "online") {
            "online"
        } else {
            "offline"
        }
        .to_string();

        let custom_url = extract_custom_url(&profile_url);

        results.push(crate::types::FriendDetails {
            username,
            steam_id,
            game,
            online_status,
            last_online,
            miniprofile: miniprofile as u64,
            is_nickname,
            avatar,
            avatar_hash,
            profile_url,
            custom_url,
        });
    }

    if results.is_empty() && !html.trim().is_empty() && document.select(sel_persona_miniprofile()).next().is_none() {
        dump_html("friends_list_empty", html);
    }

    let page_info = parse_friend_page_info(html, &document);

    crate::types::FriendListPage { friends: results, page_info }
}

fn parse_search_results(html: &str, current_page: u32) -> (Vec<crate::types::CommunitySearchPlayer>, Option<u32>, Option<u32>) {
    let document = scraper::Html::parse_document(html);
    let mut players = Vec::new();

    for element in document.select(sel_search_row()) {
        let miniprofile = element.select(sel_medium_holder()).next().and_then(|el| el.value().attr("data-miniprofile")).and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
        if miniprofile == 0 {
            continue;
        }

        let steam_id = SteamID::from_individual_account_id(miniprofile);

        let avatar_src = element.select(sel_avatar_medium_img()).next().and_then(|el| el.value().attr("src")).unwrap_or("");
        let avatar_hash = get_avatar_hash_from_url(avatar_src).unwrap_or_default();

        let search_persona_el = element.select(sel_search_persona_name()).next();
        let name = search_persona_el.map(|el| el.text().collect::<String>().trim().to_string()).unwrap_or_default();
        let profile_url = search_persona_el.and_then(|el| el.value().attr("href")).unwrap_or("").to_string();
        let custom_url = extract_custom_url(&profile_url);

        players.push(crate::types::CommunitySearchPlayer { miniprofile: miniprofile as u64, steam_id, avatar_hash, name, profile_url, custom_url });
    }

    let mut prev_page = None;
    let mut next_page = None;

    for paging_el in document.select(sel_community_search_paging()) {
        let onclick = paging_el.value().attr("onclick").unwrap_or("");
        if onclick.contains("CommunitySearch.PrevPage()") {
            prev_page = Some(current_page.saturating_sub(1));
        } else if onclick.contains("CommunitySearch.NextPage()") {
            next_page = Some(current_page + 1);
        }
    }

    if players.is_empty() && !html.trim().is_empty() && document.select(sel_search_row()).next().is_none() {
        dump_html("search_friends_empty", html);
    }

    (players, prev_page, next_page)
}