Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

68.4 KB
Raw Blame
//! Home → Friends page (Online / All / Pending / Add Friend tabs, with the
//! Active Now column) and Home → Message Requests.

use super::{paint_avatar, paint_status_dot, paint_tag_chip, status_label};
use crate::app::RustCord;
use crate::features::FriendsTab;
use crate::style::{bold, icon, icon_font, overlay, Theme};
use discord::model::{Activity, Id, User};
use eframe::egui::{
    self, epaint::Shadow, pos2, vec2, Align2, CentralPanel, Color32, FontId, Frame, Key, Margin, Order, Rect, Response,
    RichText, ScrollArea, Sense, SidePanel, Stroke, TopBottomPanel, Ui,
};

/// Width of Discord's "Active Now" column.
const ACTIVE_NOW_W: f32 = 360.0;
/// Below this content width the column is hidden, like Discord.
const ACTIVE_NOW_MIN: f32 = 900.0;
const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);
const BRAND_HOVER: Color32 = Color32::from_rgb(0x47, 0x52, 0xc4);
const BRAND_TEXT: Color32 = Color32::from_rgb(0x94, 0x9c, 0xf7);

fn strong(size: f32) -> FontId {
    FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()))
}

fn shadow() -> Shadow {
    Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) }
}

/// `top` painted over an opaque `base` (for status-dot rings on hover).
fn over(base: Color32, top: Color32) -> Color32 {
    let k = 255 - top.a() as u16;
    let mix = |b: u8, t: u8| (t as u16 + b as u16 * k / 255).min(255) as u8;
    Color32::from_rgb(mix(base.r(), top.r()), mix(base.g(), top.g()), mix(base.b(), top.b()))
}

fn now_ms() -> u64 {
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
}

/// "just now", "20m", "3h", "1d": how long an activity has been going.
fn ago(ms: u64) -> String {
    let m = ms / 60_000;
    if m == 0 {
        "just now".into()
    } else if m < 60 {
        format!("{m}m")
    } else if m < 24 * 60 {
        format!("{}h", m / 60)
    } else {
        format!("{}d", m / (24 * 60))
    }
}

/// "22:59" / "03:30:27": the ticking "elapsed" timer (whole days are
/// dropped, as Discord does — the header says "1d").
fn clock(ms: u64) -> String {
    let s = ms / 1000;
    let (h, m, s) = (s / 3600 % 24, s / 60 % 60, s % 60);
    if h > 0 {
        format!("{h:02}:{m:02}:{s:02}")
    } else {
        format!("{m:02}:{s:02}")
    }
}

/// A listening activity's artist line: Spotify sends "A; B", Discord shows
/// "A, B".
fn artists(a: &Activity) -> String {
    let s = a.state.clone().or_else(|| a.details.clone()).unwrap_or_else(|| a.name.clone());
    if a.name == "Spotify" {
        s.replace("; ", ", ")
    } else {
        s
    }
}

#[derive(Clone, Copy, PartialEq)]
enum Pill {
    Normal,
    Selected,
    Brand,
    BrandSelected,
}

/// One of the header's pill tabs, with an optional red count badge.
fn pill(ui: &mut Ui, t: &Theme, label: &str, kind: Pill, badge: usize) -> Response {
    let galley = ui.painter().layout_no_wrap(label.to_string(), FontId::proportional(16.0), Color32::PLACEHOLDER);
    let badge_g = (badge > 0).then(|| ui.painter().layout_no_wrap(badge.to_string(), strong(12.0), Color32::WHITE));
    let badge_w = badge_g.as_ref().map_or(0.0, |g| (g.size().x + 9.0).max(16.0));
    let w = 24.0 + galley.size().x + if badge_w > 0.0 { badge_w + 8.0 } else { 0.0 };
    let (rect, resp) = ui.allocate_exact_size(vec2(w, 32.0), Sense::click());
    let hovered = resp.hovered();
    let (fill, fg) = match kind {
        Pill::Selected => (overlay(0.2), t.header_primary),
        Pill::Normal if hovered => (overlay(0.12), t.interactive_hover),
        Pill::Normal => (Color32::TRANSPARENT, t.interactive_normal),
        Pill::Brand => (if hovered { BRAND_HOVER } else { BRAND }, Color32::WHITE),
        Pill::BrandSelected => (crate::style::rgba(88, 101, 242, 40), BRAND_TEXT),
    };
    ui.painter().rect_filled(rect, 8.0, fill);
    let text_w = galley.size().x;
    ui.painter().galley(pos2(rect.left() + 12.0, rect.center().y - galley.size().y / 2.0), galley, fg);
    if let Some(g) = badge_g {
        let b = Rect::from_min_size(pos2(rect.left() + 12.0 + text_w + 8.0, rect.center().y - 8.0), vec2(badge_w, 16.0));
        ui.painter().rect_filled(b, 8.0, Color32::from_rgb(0xf2, 0x3f, 0x43));
        ui.painter().galley(b.center() - g.size() / 2.0, g, Color32::WHITE);
    }
    resp.on_hover_cursor(egui::CursorIcon::PointingHand)
}

/// A round 36px action button (message, more, accept, …). `tint` colours
/// the glyph on hover (green accept, red ignore).
fn round_button(ui: &mut Ui, t: &Theme, center: egui::Pos2, id: egui::Id, glyph: Option<&str>, tip: &str, tint: Option<Color32>) -> Response {
    let r = Rect::from_center_size(center, vec2(36.0, 36.0));
    let b = ui.interact(r, id, Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    ui.painter().circle_filled(center, 18.0, t.bg_secondary);
    let color = if b.hovered() { tint.unwrap_or(t.interactive_hover) } else { t.interactive_normal };
    match glyph {
        Some(g) => {
            ui.painter().text(center, Align2::CENTER_CENTER, g, icon_font(17.0), color);
        }
        // Vertical "more" dots.
        None => {
            for dy in [-5.0, 0.0, 5.0] {
                ui.painter().circle_filled(center + vec2(0.0, dy), 1.8, color);
            }
        }
    }
    b.on_hover_text(tip)
}

enum FriendAction {
    Message(Id),
    Accept(Id),
    Remove(Id),
    Profile(Id, egui::Pos2),
    Menu(Id, egui::Pos2),
    Guild(Id),
    Tab(FriendsTab),
    DismissNotice,
}

/// What a friend row says under the name.
enum RowSub {
    /// Activity icon, text, and how many more activities (+N).
    Game(&'static str, String, usize),
    Voice,
    Custom(Option<String>, String),
    Text(String),
}

impl RowSub {
    fn paint(&self, ui: &Ui, painter: &egui::Painter, pos: egui::Pos2, color: Color32) {
        let font = FontId::proportional(14.0);
        let with_icon = |glyph: &str, text: &str| {
            painter.text(pos2(pos.x + 7.0, pos.y), Align2::CENTER_CENTER, glyph, icon_font(13.0), color);
            super::paint_text_emoji(ui, painter, pos2(pos.x + 18.0, pos.y), text, font.clone(), color)
        };
        match self {
            RowSub::Game(glyph, name, more) => {
                let r = with_icon(glyph, name);
                if *more > 0 {
                    painter.text(pos2(r.right() + 4.0, pos.y), Align2::LEFT_CENTER, format!("+{more}"), font, color);
                }
            }
            RowSub::Voice => {
                with_icon(icon::SPEAK, "In voice");
            }
            RowSub::Custom(emoji, text) => {
                let mut x = pos.x;
                if let Some(url) = emoji {
                    let r = Rect::from_center_size(pos2(x + 8.0, pos.y), vec2(16.0, 16.0));
                    if painter.clip_rect().contains_rect(r) {
                        egui::Image::new(url.as_str()).paint_at(ui, r);
                    }
                    x += 20.0;
                }
                super::paint_text_emoji(ui, painter, pos2(x, pos.y), text, font, color);
            }
            RowSub::Text(text) => {
                painter.text(pos, Align2::LEFT_CENTER, text, font, color);
            }
        }
    }
}

struct Row {
    id: Id,
    kind: u8,
    user: User,
    name: String,
}

/// Active Now: friends hanging out in a voice channel.
struct VoiceCard {
    guild: Option<Id>,
    channel: Id,
    friends: Vec<Id>,
    members: Vec<Id>,
}

/// Active Now: a friend's game / app.
struct GameCard {
    user: Id,
    act: Activity,
    /// Friends playing the same thing (for activities without rich presence).
    party: Vec<Id>,
}

impl RustCord {
    fn friend_name(&self, id: Id) -> String {
        if let Some(n) = self.store.friend_nickname(id) {
            return n.to_string();
        }
        self.store.users.get(&id).map(|u| u.display_name().to_string()).unwrap_or_else(|| "Unknown".into())
    }

    fn row_sub(&self, id: Id, status: &str) -> RowSub {
        if let Some(p) = self.store.presences.get(&id).filter(|_| status != "offline") {
            let acts: Vec<&Activity> = p.activities.iter().filter(|a| a.kind != 4).collect();
            if let Some(a) = acts.first() {
                // Spotify & co. show the artist ("state"), games their name.
                let (glyph, text) = match a.kind {
                    2 => (icon::HEADPHONES, artists(a)),
                    1 => (icon::PLAY, a.details.clone().unwrap_or_else(|| a.name.clone())),
                    _ => (icon::GAME, a.name.clone()),
                };
                return RowSub::Game(glyph, text, acts.len() - 1);
            }
            if self.store.voice_channel_of(id).is_some() {
                return RowSub::Voice;
            }
            if let Some(super::SubLine::Status { custom: Some((emoji, text)), .. }) = super::SubLine::of(p) {
                return RowSub::Custom(emoji, text);
            }
        }
        RowSub::Text(status_label(status).to_string())
    }

    pub fn friends_ui(&mut self, ui: &mut Ui) {
        let t = self.theme.clone();
        let pending = self.store.incoming_requests();
        let mut action = None;
        TopBottomPanel::top("friends_header")
            .exact_height(48.0)
            .frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin::symmetric(16.0, 0.0)))
            .show_inside(ui, |ui| {
                let full = ui.max_rect().expand2(vec2(16.0, 0.0));
                ui.painter().hline(full.x_range(), full.bottom() - 0.5, Stroke::new(1.0_f32, t.border_subtle));
                ui.horizontal_centered(|ui| {
                    ui.spacing_mut().item_spacing.x = 8.0;
                    ui.label(RichText::new(icon::PEOPLE).font(icon_font(20.0)).color(t.text_muted));
                    ui.label(RichText::new("Friends").font(strong(16.0)).color(t.header_primary));
                    let (dot, _) = ui.allocate_exact_size(vec2(12.0, 32.0), Sense::hover());
                    ui.painter().circle_filled(dot.center(), 2.0, t.interactive_muted);
                    ui.spacing_mut().item_spacing.x = 16.0;
                    for (tab, label, badge) in [(FriendsTab::Online, "Online", 0), (FriendsTab::All, "All", 0), (FriendsTab::Pending, "Pending", pending)] {
                        let kind = if self.friends_tab == tab { Pill::Selected } else { Pill::Normal };
                        if pill(ui, &t, label, kind, badge).clicked() {
                            action = Some(FriendAction::Tab(tab));
                        }
                    }
                    let kind = if self.friends_tab == FriendsTab::AddFriend { Pill::BrandSelected } else { Pill::Brand };
                    if pill(ui, &t, "Add Friend", kind, 0).clicked() {
                        action = Some(FriendAction::Tab(FriendsTab::AddFriend));
                    }
                });
            });

        if ui.available_width() >= ACTIVE_NOW_MIN {
            SidePanel::right("active_now")
                .exact_width(ACTIVE_NOW_W)
                .resizable(false)
                .show_separator_line(false)
                .frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 17.0, right: 16.0, top: 14.0, bottom: 0.0 }))
                .show_inside(ui, |ui| {
                    let full = ui.max_rect();
                    ui.painter().vline(full.left() - 17.0, ui.clip_rect().y_range(), Stroke::new(1.0_f32, t.border_subtle));
                    if let Some(a) = self.active_now_ui(ui, &t) {
                        action = Some(a);
                    }
                });
        }

        if self.friends_tab == FriendsTab::AddFriend {
            self.add_friend_ui(ui);
            self.apply_friend_action(action);
            return;
        }

        let tab = self.friends_tab;
        let query = self.friends_search.trim().to_lowercase();
        let mut rows: Vec<Row> = self
            .store
            .relationships
            .values()
            .filter(|r| match tab {
                FriendsTab::Online => r.kind == 1 && self.store.status_of(r.id) != "offline",
                FriendsTab::All => r.kind == 1,
                FriendsTab::Pending => r.kind == 3 || r.kind == 4,
                FriendsTab::Blocked | FriendsTab::AddFriend => r.kind == 2,
            })
            .map(|r| {
                let user = self.store.users.get(&r.id).cloned().or_else(|| r.user.clone()).unwrap_or_default();
                Row { id: r.id, kind: r.kind, name: self.friend_name(r.id), user }
            })
            .filter(|r| query.is_empty() || r.name.to_lowercase().contains(&query) || r.user.username.to_lowercase().contains(&query))
            .collect();
        // Received before sent, then by name.
        rows.sort_by_cached_key(|r| (r.kind == 4, r.name.to_lowercase()));
        // Dev aid: RUSTCORD_DUMP_FRIENDS=1 logs each row's text once (for
        // comparing with the web client).
        static DUMPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
        if crate::diagnostics::dev_var_os("RUSTCORD_DUMP_FRIENDS").is_some() && !rows.is_empty() && ui.ctx().input(|i| i.time) > 6.0 && !DUMPED.swap(true, std::sync::atomic::Ordering::Relaxed) {
            for r in &rows {
                let status = self.store.status_of(r.id).to_string();
                let sub = match self.row_sub(r.id, &status) {
                    RowSub::Game(_, s, more) => format!("{s}{}", if more > 0 { format!(" +{more}") } else { String::new() }),
                    RowSub::Voice => "In voice".into(),
                    RowSub::Custom(e, s) => format!("{}{s}", if e.is_some() { "[emoji] " } else { "" }),
                    RowSub::Text(s) => s,
                };
                log::info!("friend row: {} | {sub}", r.name);
            }
        }

        let notice = self.blocked_notice && tab != FriendsTab::Blocked;
        CentralPanel::default()
            .frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 14.0, right: 16.0, top: 16.0, bottom: 0.0 }))
            .show_inside(ui, |ui| {
                ui.spacing_mut().item_spacing.y = 0.0;
                if notice {
                    if let Some(a) = blocked_notice_ui(ui, &t) {
                        action = Some(a);
                    }
                    ui.add_space(20.0);
                }
                // Search field.
                ui.horizontal(|ui| {
                    ui.add_space(10.0);
                    let w = ui.available_width();
                    Frame::none()
                        .fill(Color32::from_black_alpha(31))
                        .stroke(Stroke::new(1.0_f32, overlay(0.2)))
                        .rounding(8.0)
                        .inner_margin(Margin { left: 12.0, right: 12.0, top: 9.0, bottom: 9.0 })
                        .show(ui, |ui| {
                            ui.set_width(w - 26.0);
                            ui.horizontal(|ui| {
                                ui.label(RichText::new(icon::SEARCH).font(icon_font(15.0)).color(t.text_muted));
                                ui.add_space(4.0);
                                let field = egui::TextEdit::singleline(&mut self.friends_search)
                                    .id(egui::Id::new("friends_search_edit"))
                                    .frame(false)
                                    .hint_text(RichText::new("Search").color(t.text_muted))
                                    .font(FontId::proportional(16.0))
                                    .desired_width(ui.available_width() - 24.0);
                                ui.add(field);
                                if !self.friends_search.is_empty() {
                                    let (r, b) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click());
                                    let b = b.on_hover_cursor(egui::CursorIcon::PointingHand);
                                    ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(12.0), if b.hovered() { t.header_primary } else { t.text_muted });
                                    if b.clicked() {
                                        self.friends_search.clear();
                                    }
                                }
                            });
                        });
                });
                ui.add_space(8.0);

                let received = rows.iter().filter(|r| r.kind == 3).count();
                let title = |n: usize| match tab {
                    FriendsTab::Online => format!("Online – {n}"),
                    FriendsTab::All => format!("All friends – {n}"),
                    FriendsTab::Pending => format!("Received – {n}"),
                    _ => format!("Blocked – {n}"),
                };
                let section = |ui: &mut Ui, text: String| {
                    let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 50.0), Sense::hover());
                    ui.painter().text(pos2(r.left() + 10.0, r.top() + 25.0), Align2::LEFT_CENTER, text, FontId::proportional(14.0), t.text_normal);
                };
                if rows.is_empty() {
                    ui.add_space(60.0);
                    ui.vertical_centered(|ui| {
                        let msg = match tab {
                            _ if !query.is_empty() => "Wumpus looked, but couldn't find anyone with that name.",
                            FriendsTab::Online => "No one's around to play with Wumpus.",
                            FriendsTab::Pending => "There are no pending friend requests. Here's Wumpus for now.",
                            FriendsTab::Blocked => "You can't unblock the Wumpus.",
                            _ => "Wumpus is waiting on friends. You don't have to, though!",
                        };
                        ui.label(RichText::new(msg).size(15.0).color(t.text_muted));
                    });
                    return;
                }
                ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
                    ui.spacing_mut().item_spacing.y = 0.0;
                    if tab == FriendsTab::Pending && received > 0 || tab != FriendsTab::Pending {
                        section(ui, title(if tab == FriendsTab::Pending { received } else { rows.len() }));
                    }
                    let mut prev_hovered = true;
                    for (i, row) in rows.iter().enumerate() {
                        if tab == FriendsTab::Pending && row.kind == 4 && (i == 0 || rows[i - 1].kind != 4) {
                            if i > 0 {
                                ui.add_space(8.0);
                            }
                            section(ui, format!("Sent – {}", rows.len() - received));
                            prev_hovered = true;
                        }
                        let (a, hovered) = self.friend_row(ui, &t, row, prev_hovered);
                        prev_hovered = hovered;
                        if a.is_some() {
                            action = a;
                        }
                    }
                    ui.add_space(12.0);
                });
            });

        self.apply_friend_action(action);
        self.friend_menu_ui(ui.ctx());
    }

    /// One row of the friends list. Returns its action and whether it's hovered.
    fn friend_row(&self, ui: &mut Ui, t: &Theme, row: &Row, prev_hovered: bool) -> (Option<FriendAction>, bool) {
        let mut action = None;
        let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 62.0), Sense::click());
        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
        if !ui.is_rect_visible(rect) {
            return (None, false);
        }
        // Hovering the action buttons still counts as hovering the row.
        let hovered = ui.rect_contains_pointer(rect);
        if hovered {
            ui.painter().rect_filled(rect, 8.0, t.bg_hover);
        } else if !prev_hovered {
            ui.painter().hline(rect.left() + 10.0..=rect.right() - 10.0, rect.top() + 0.5, Stroke::new(1.0_f32, overlay(0.12)));
        }
        let status = self.store.status_of(row.id).to_string();
        let av = Rect::from_min_size(pos2(rect.left() + 10.0, rect.center().y - 16.0), vec2(32.0, 32.0));
        paint_avatar(ui, av, Some(super::avatar_uri(&row.user, 64, hovered)), &row.name);
        if let Some(deco) = super::decoration_uri(&row.user, hovered) {
            egui::Image::new(deco).paint_at(ui, av.expand(3.2));
        }
        if row.kind == 1 {
            let ring = if hovered { over(t.bg_primary, t.bg_hover) } else { t.bg_primary };
            paint_status_dot(ui, av.right_bottom() - vec2(4.0, 4.0), 5.0, self.store.dot_status(row.id), ring);
        }

        let buttons = match row.kind {
            1 | 3 => 2.0,
            _ => 1.0,
        };
        let text_right = rect.right() - 10.0 - buttons * 46.0;
        let painter = ui.painter_at(Rect::from_min_max(rect.min, pos2(text_right, rect.bottom())));
        let x = av.right() + 12.0;
        let name_y = rect.center().y - 9.0;
        let name_r = super::paint_text_emoji(ui, &painter, pos2(x, name_y), &row.name, strong(16.0), t.header_primary);
        let mut right = name_r.right();
        if let Some(r) = super::paint_bot_badge(&painter, right + 4.0, name_y, &row.user, t) {
            right = r;
        }
        if let Some((tag, badge)) = row.user.server_tag() {
            right += 4.0 + paint_tag_chip(ui, &painter, right + 4.0, name_y, &tag, badge.as_deref(), t);
        }
        let sub_pos = pos2(x, rect.center().y + 10.0);
        match row.kind {
            1 => {
                if hovered {
                    painter.text(pos2(right + 5.0, name_y + 1.0), Align2::LEFT_CENTER, &row.user.username, FontId::proportional(14.0), t.text_muted);
                }
                self.row_sub(row.id, &status).paint(ui, &painter, sub_pos, t.text_muted);
            }
            _ => {
                painter.text(sub_pos, Align2::LEFT_CENTER, &row.user.username, FontId::proportional(14.0), t.text_muted);
            }
        }

        // Round buttons on the right, right-most first.
        let center = |i: f32| pos2(rect.right() - 10.0 - 18.0 - i * 46.0, rect.center().y);
        let id = |i: u8| egui::Id::new(("friend_btn", row.id.0, i));
        let green = Some(Color32::from_rgb(0x23, 0xa5, 0x5a));
        // A change for this person is queued or on its way (friend-list changes
        // go out one at a time): a spinner where the buttons were, like
        // Discord's loading Accept button, and no second click.
        let busy = self.relationship_pending(row.id) && row.kind != 1;
        if busy {
            let c = center(if row.kind == 3 { 0.5 } else { 0.0 });
            ui.painter().circle_filled(c, 18.0, t.bg_secondary);
            egui::Spinner::new().size(18.0).color(t.interactive_normal).paint_at(ui, Rect::from_center_size(c, vec2(18.0, 18.0)));
        }
        match row.kind {
            _ if busy => {}
            1 => {
                let more = round_button(ui, t, center(0.0), id(0), None, "More", None);
                if more.clicked() {
                    action = Some(FriendAction::Menu(row.id, more.rect.left_bottom() + vec2(0.0, 4.0)));
                }
                if round_button(ui, t, center(1.0), id(1), Some(icon::MESSAGE), "Message", None).clicked() {
                    action = Some(FriendAction::Message(row.id));
                }
            }
            3 => {
                if round_button(ui, t, center(0.0), id(0), Some(icon::CLOSE), "Ignore", Some(t.danger)).clicked() {
                    action = Some(FriendAction::Remove(row.id));
                }
                if round_button(ui, t, center(1.0), id(1), Some(icon::CHECK), "Accept", green).clicked() {
                    action = Some(FriendAction::Accept(row.id));
                }
            }
            4 => {
                if round_button(ui, t, center(0.0), id(0), Some(icon::CLOSE), "Cancel", Some(t.danger)).clicked() {
                    action = Some(FriendAction::Remove(row.id));
                }
            }
            _ => {
                if round_button(ui, t, center(0.0), id(0), Some(icon::CLOSE), "Unblock", Some(t.danger)).clicked() {
                    action = Some(FriendAction::Remove(row.id));
                }
            }
        }
        if action.is_none() && resp.clicked() {
            // Like Discord: a friend's row opens your DM, others their profile.
            action = Some(match row.kind {
                1 => FriendAction::Message(row.id),
                _ => FriendAction::Profile(row.id, resp.interact_pointer_pos().unwrap_or(rect.center())),
            });
        }
        if action.is_none() && resp.secondary_clicked() {
            action = Some(FriendAction::Menu(row.id, resp.interact_pointer_pos().unwrap_or(rect.center())));
        }
        (action, hovered)
    }

    fn apply_friend_action(&mut self, action: Option<FriendAction>) {
        match action {
            Some(FriendAction::Message(id)) => self.open_dm_with(id, String::new()),
            Some(FriendAction::Accept(id)) => self.relationship(id, true, "Friends"),
            Some(FriendAction::Remove(id)) => self.relationship(id, false, "Friends"),
            Some(FriendAction::Profile(id, at)) => {
                if let Some(u) = self.store.users.get(&id).cloned() {
                    self.open_profile(u, None, at + vec2(12.0, -40.0));
                }
            }
            Some(FriendAction::Menu(id, at)) => {
                self.friend_menu = Some((id, at, self.ctx.cumulative_pass_nr(), false));
            }
            Some(FriendAction::Guild(g)) => {
                self.friends_open = false;
                self.select_guild(Some(g));
            }
            Some(FriendAction::Tab(tab)) => {
                self.friends_tab = tab;
                self.friend_menu = None;
            }
            Some(FriendAction::DismissNotice) => {
                self.blocked_notice = false;
                if let Some(dir) = &self.config_dir {
                    let _ = std::fs::create_dir_all(dir);
                    let _ = std::fs::write(dir.join("blocked-notice-dismissed"), b"1");
                }
            }
            None => {}
        }
    }

    /// The ⋮ menu on a friend row (and its "Remove Friend" confirmation).
    fn friend_menu_ui(&mut self, ctx: &egui::Context) {
        let Some((user, pos, opened, confirm)) = self.friend_menu else { return };
        let t = self.theme.clone();
        let name = self.friend_name(user);
        let nickname_row = self.friend_nickname_row(user);
        // 0 profile, 1 message, 2 remove (asks), 3 confirmed remove, 4 cancel, 5 copy id, 6 friend nickname
        let mut pick: Option<u8> = None;
        let area = egui::Area::new(egui::Id::new("friend_menu"))
            .order(Order::Foreground)
            .fixed_pos(pos)
            .constrain(true)
            .show(ctx, |ui| {
                Frame::none()
                    .fill(t.bg_floating)
                    .rounding(8.0)
                    .stroke(Stroke::new(1.0_f32, t.border_subtle))
                    .shadow(shadow())
                    .inner_margin(Margin::same(if confirm { 16.0 } else { 6.0 }))
                    .show(ui, |ui| {
                        ui.spacing_mut().item_spacing.y = 0.0;
                        if confirm {
                            ui.set_width(300.0);
                            ui.label(RichText::new(format!("Remove '{name}'")).font(strong(18.0)).color(t.header_primary));
                            ui.add_space(8.0);
                            ui.add(egui::Label::new(RichText::new(format!("Are you sure you want to remove {name} from your friends?")).size(14.0).color(t.text_normal)).wrap());
                            ui.add_space(16.0);
                            ui.horizontal(|ui| {
                                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                    let remove = egui::Button::new(bold("Remove Friend").size(14.0).color(Color32::WHITE)).fill(t.danger).rounding(8.0).min_size(vec2(0.0, 36.0));
                                    if ui.add(remove).clicked() {
                                        pick = Some(3);
                                    }
                                    ui.add_space(4.0);
                                    let cancel = egui::Button::new(bold("Cancel").size(14.0).color(t.header_primary)).fill(overlay(0.2)).rounding(8.0).min_size(vec2(0.0, 36.0));
                                    if ui.add(cancel).clicked() {
                                        pick = Some(4);
                                    }
                                });
                            });
                            return;
                        }
                        ui.set_width(188.0);
                        let mut row = |ui: &mut Ui, glyph: &str, label: &str, danger: bool, n: u8| {
                            let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click());
                            let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                            let color = if danger { t.danger } else if resp.hovered() { t.header_primary } else { t.interactive_normal };
                            if resp.hovered() {
                                ui.painter().rect_filled(r, 4.0, if danger { t.danger.gamma_multiply(0.15) } else { overlay(0.16) });
                            }
                            ui.painter().text(r.left_center() + vec2(8.0, 0.0), Align2::LEFT_CENTER, label, strong(14.0), color);
                            ui.painter().text(r.right_center() - vec2(14.0, 0.0), Align2::CENTER_CENTER, glyph, icon_font(15.0), color);
                            if resp.clicked() {
                                pick = Some(n);
                            }
                        };
                        row(ui, icon::PROFILE, "Profile", false, 0);
                        row(ui, icon::MESSAGE, "Message", false, 1);
                        if let Some(label) = nickname_row {
                            row(ui, icon::EDIT, label, false, 6);
                        }
                        row(ui, icon::ID, "Copy User ID", false, 5);
                        ui.add_space(4.0);
                        let y = ui.cursor().top();
                        ui.painter().hline(ui.max_rect().x_range().shrink(4.0), y, Stroke::new(1.0_f32, t.border_subtle));
                        ui.add_space(4.0);
                        row(ui, icon::CLOSE, "Remove Friend", true, 2);
                    });
            });
        match pick {
            None => {
                let outside = area.response.clicked_elsewhere() && ctx.cumulative_pass_nr() > opened + 1;
                if outside || ctx.input(|i| i.key_pressed(Key::Escape)) {
                    self.friend_menu = None;
                }
            }
            Some(0) => {
                self.friend_menu = None;
                if let Some(u) = self.store.users.get(&user).cloned() {
                    self.open_profile(u, None, pos + vec2(-320.0, -40.0));
                }
            }
            Some(1) => {
                self.friend_menu = None;
                self.open_dm_with(user, String::new());
            }
            Some(2) => self.friend_menu = Some((user, pos, ctx.cumulative_pass_nr(), true)),
            Some(3) => {
                self.friend_menu = None;
                self.relationship(user, false, "Context Menu");
            }
            Some(5) => {
                self.friend_menu = None;
                ctx.copy_text(user.to_string());
            }
            Some(6) => {
                self.friend_menu = None;
                self.open_friend_nickname(user);
            }
            Some(_) => self.friend_menu = None,
        }
    }

    // ---- Active Now -----------------------------------------------------------

    fn active_now_cards(&self) -> (Vec<VoiceCard>, Vec<GameCard>) {
        let friends: Vec<Id> = self.store.relationships.values().filter(|r| r.kind == 1).map(|r| r.id).collect();
        let mut voice: Vec<VoiceCard> = self
            .store
            .voice
            .iter()
            .filter_map(|(ch, users)| {
                let in_it: Vec<Id> = users.iter().copied().filter(|u| friends.contains(u)).collect();
                (!in_it.is_empty()).then(|| VoiceCard {
                    guild: self.store.channels.get(ch).and_then(|c| c.guild_id),
                    channel: *ch,
                    friends: in_it,
                    members: users.clone(),
                })
            })
            .collect();
        voice.sort_by_key(|v| std::cmp::Reverse(v.members.len()));

        let mut games: Vec<GameCard> = friends
            .iter()
            .filter(|id| self.store.status_of(**id) != "offline")
            .filter_map(|id| {
                let act = self.store.presences.get(id)?.activities.iter().find(|a| a.kind != 4)?.clone();
                Some(GameCard { user: *id, act, party: Vec::new() })
            })
            .collect();
        // Everyone playing the same plain (no rich presence) game shares a card.
        let names: Vec<(Id, String)> = games.iter().map(|g| (g.user, g.act.name.to_lowercase())).collect();
        for g in &mut games {
            let key = g.act.name.to_lowercase();
            g.party = names.iter().filter(|(_, n)| *n == key).map(|(u, _)| *u).collect();
        }
        games.sort_by_key(|g| std::cmp::Reverse(g.act.timestamps.as_ref().and_then(|t| t.start).unwrap_or(0)));
        (voice, games)
    }

    /// Discord's right-hand "Active Now" column.
    fn active_now_ui(&self, ui: &mut Ui, t: &Theme) -> Option<FriendAction> {
        let mut action = None;
        ui.spacing_mut().item_spacing.y = 0.0;
        let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::hover());
        ui.painter().text(r.left_center(), Align2::LEFT_CENTER, "Active Now", strong(20.0), t.header_primary);
        ui.add_space(12.0);
        let (voice, games) = self.active_now_cards();
        if voice.is_empty() && games.is_empty() {
            ui.add_space(4.0);
            ui.vertical_centered(|ui| {
                ui.label(RichText::new("It's quiet for now...").font(strong(16.0)).color(t.header_primary));
                ui.add_space(4.0);
                ui.add(
                    egui::Label::new(
                        RichText::new("When a friend starts an activity—like playing a game or hanging out on voice—we'll show it here!")
                            .size(14.0)
                            .color(t.text_muted),
                    )
                    .wrap(),
                );
            });
            return None;
        }
        let now = now_ms();
        let mut ticking = false;
        let mut shown_parties: Vec<String> = Vec::new();
        ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
            ui.spacing_mut().item_spacing.y = 0.0;
            for v in &voice {
                if let Some(a) = self.voice_card(ui, t, v) {
                    action = Some(a);
                }
                ui.add_space(12.0);
            }
            for g in &games {
                let rich = g.act.details.is_some() || g.act.state.is_some() || g.act.assets.is_some();
                if !rich {
                    // One card per plain game, listing everyone in it.
                    let key = g.act.name.to_lowercase();
                    if shown_parties.contains(&key) {
                        continue;
                    }
                    shown_parties.push(key);
                }
                let (a, ticks) = self.game_card(ui, t, g, rich, now);
                ticking |= ticks;
                if a.is_some() {
                    action = a;
                }
                ui.add_space(12.0);
            }
        });
        if ticking {
            // Tick the "elapsed" timers once a second.
            ui.ctx().request_repaint_after(std::time::Duration::from_millis(1000 - now % 1000 + 5));
        }
        action
    }

    /// Card frame: rounded box with a tinted 68px header. Returns (card, header).
    fn card_frame(ui: &mut Ui, t: &Theme, body_h: f32) -> (Rect, Rect, Response) {
        let h = 68.0 + body_h + 2.0;
        let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());
        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
        let fill = if resp.hovered() { over(t.bg_secondary_alt, overlay(0.06)) } else { t.bg_secondary_alt };
        ui.painter().rect(rect, 16.0, fill, Stroke::new(1.0_f32, overlay(0.12)));
        let header = Rect::from_min_size(rect.min + vec2(1.0, 1.0), vec2(rect.width() - 2.0, 68.0));
        let round = if body_h > 0.0 { egui::Rounding { nw: 15.0, ne: 15.0, sw: 0.0, se: 0.0 } } else { egui::Rounding::same(15.0) };
        ui.painter().rect_filled(header, round, overlay(0.08));
        (rect, header, resp)
    }

    fn voice_card(&self, ui: &mut Ui, t: &Theme, v: &VoiceCard) -> Option<FriendAction> {
        let guild = v.guild.and_then(|g| self.store.guilds.get(&g)).map(|gs| &gs.guild);
        let body_h = if guild.is_some() { 66.0 } else { 0.0 };
        let (rect, header, resp) = Self::card_frame(ui, t, body_h);
        if !ui.is_rect_visible(rect) {
            return None;
        }
        let first = v.friends[0];
        let user = self.store.users.get(&first).cloned().unwrap_or_default();
        let av = Rect::from_min_size(header.min + vec2(15.0, 18.0), vec2(32.0, 32.0));
        paint_avatar(ui, av, Some(user.avatar_or_default(64)), &self.friend_name(first));
        let painter = ui.painter_at(header.shrink2(vec2(16.0, 0.0)));
        // "Crumbo, CUTZBYLA and 1 other": names bold, the rest regular.
        let mut x = av.right() + 12.0;
        let y = header.top() + 25.0;
        for (i, u) in v.friends.iter().take(2).enumerate() {
            if i > 0 {
                x = painter.text(pos2(x, y), Align2::LEFT_CENTER, ", ", FontId::proportional(16.0), t.header_primary).right();
            }
            x = super::paint_text_emoji(ui, &painter, pos2(x, y), &self.friend_name(*u), strong(16.0), t.header_primary).right();
        }
        let others = v.friends.len().saturating_sub(2);
        if others > 0 {
            let more = format!(" and {others} other{}", if others == 1 { "" } else { "s" });
            painter.text(pos2(x, y), Align2::LEFT_CENTER, more, FontId::proportional(16.0), t.header_primary);
        }
        painter.text(pos2(av.right() + 12.0, header.top() + 45.0), Align2::LEFT_CENTER, "In a Voice Channel", FontId::proportional(14.0), t.text_muted);

        let mut action = None;
        if let Some(guild) = guild {
            let body = Rect::from_min_max(pos2(rect.left() + 1.0, header.bottom()), pos2(rect.right() - 1.0, rect.bottom() - 1.0));
            let icon_r = Rect::from_min_size(body.min + vec2(15.0, 17.0), vec2(32.0, 32.0));
            match guild.icon_url(64) {
                Some(url) => egui::Image::new(url).rounding(16.0).paint_at(ui, icon_r),
                None => {
                    ui.painter().circle_filled(icon_r.center(), 16.0, t.bg_primary);
                    ui.painter().text(icon_r.center(), Align2::CENTER_CENTER, super::acronym(&guild.name), FontId::proportional(12.0), t.header_primary);
                }
            }
            let badge = icon_r.right_bottom() - vec2(6.0, 6.0);
            ui.painter().circle_filled(badge, 8.0, t.bg_secondary);
            ui.painter().text(badge, Align2::CENTER_CENTER, icon::SPEAK, icon_font(9.0), t.interactive_normal);
            let channel = self.store.channels.get(&v.channel).and_then(|c| c.name.clone()).unwrap_or_default();
            let avatars = v.members.len().min(3);
            let text_right = body.right() - 16.0 - avatars as f32 * 22.0 - 8.0;
            let p = ui.painter_at(Rect::from_min_max(body.min, pos2(text_right, body.bottom())));
            super::paint_text_emoji(ui, &p, pos2(icon_r.right() + 12.0, icon_r.top() + 8.0), &guild.name, strong(14.0), t.header_primary);
            super::paint_text_emoji(ui, &p, pos2(icon_r.right() + 12.0, icon_r.top() + 25.0), &channel, FontId::proportional(12.0), t.text_muted);
            // Who's in there, right-aligned and overlapping.
            for (i, u) in v.members.iter().take(3).enumerate() {
                let user = self.store.users.get(u).cloned().unwrap_or_default();
                let c = pos2(body.right() - 16.0 - 12.0 - (avatars - 1 - i) as f32 * 22.0, icon_r.center().y);
                ui.painter().circle_filled(c, 13.5, t.bg_secondary_alt);
                paint_avatar(ui, Rect::from_center_size(c, vec2(24.0, 24.0)), Some(user.avatar_or_default(48)), user.display_name());
            }
            if resp.clicked() && resp.interact_pointer_pos().is_some_and(|p| body.contains(p)) {
                action = Some(FriendAction::Guild(guild.id));
            }
        }
        if action.is_none() && resp.clicked() {
            action = Some(FriendAction::Profile(first, resp.interact_pointer_pos().unwrap_or(rect.left_top()) - vec2(340.0, 0.0)));
        }
        action
    }

    /// Returns the action and whether it shows a ticking timer.
    fn game_card(&self, ui: &mut Ui, t: &Theme, g: &GameCard, rich: bool, now: u64) -> (Option<FriendAction>, bool) {
        let start = g.act.timestamps.as_ref().and_then(|t| t.start).filter(|s| *s <= now);
        let end = g.act.timestamps.as_ref().and_then(|t| t.end);
        let listening = g.act.kind == 2;
        // Music gets a progress bar where games get an "elapsed" timer.
        let bar = listening && start.is_some() && end.is_some_and(|e| Some(e) > start);
        let timer = start.is_some() && !listening;
        let lines = if rich { 1 + g.act.state.is_some() as usize + timer as usize } else { 2 };
        let body_h = 16.0 + (18.0 + (lines - 1) as f32 * 16.0 + if bar { 12.0 } else { 0.0 }).max(32.0) + 16.0;
        let (rect, header, resp) = Self::card_frame(ui, t, body_h);
        if !ui.is_rect_visible(rect) {
            return (None, rich && (timer || bar));
        }
        let user = self.store.users.get(&g.user).cloned().unwrap_or_default();
        let name = self.friend_name(g.user);
        let av = Rect::from_min_size(header.min + vec2(15.0, 18.0), vec2(32.0, 32.0));
        paint_avatar(ui, av, Some(user.avatar_or_default(64)), &name);
        if let Some(deco) = user.decoration_url() {
            egui::Image::new(deco).paint_at(ui, av.expand(3.2));
        }
        // Game icon in the header's corner.
        let app_icon = g.act.application_id.and_then(|a| match self.apps.get(&a) {
            Some(info) => info.icon_url(),
            None => {
                self.apps_wanted.borrow_mut().insert(a);
                None
            }
        });
        let mut text_right = header.right() - 16.0;
        if let Some(url) = &app_icon {
            let r = Rect::from_min_size(pos2(header.right() - 16.0 - 24.0, header.center().y - 12.0), vec2(24.0, 24.0));
            egui::Image::new(url.as_str()).rounding(4.0).paint_at(ui, r);
            text_right = r.left() - 8.0;
        }
        let p = ui.painter_at(Rect::from_min_max(header.min, pos2(text_right, header.bottom())));
        let x = av.right() + 12.0;
        super::paint_text_emoji(ui, &p, pos2(x, header.top() + 25.0), &name, strong(16.0), t.header_primary);
        let sub = match (g.act.kind, start) {
            (2, _) => format!("Listening to {}", g.act.name),
            (3, _) => format!("Watching {}", g.act.name),
            (1, _) => format!("Streaming {}", g.act.name),
            (_, Some(s)) => format!("{} – {}", g.act.name, ago(now - s)),
            _ => g.act.name.clone(),
        };
        p.text(pos2(x, header.top() + 45.0), Align2::LEFT_CENTER, sub, FontId::proportional(14.0), t.text_muted);

        // Body: art, then what they're doing.
        let body = Rect::from_min_max(pos2(rect.left() + 1.0, header.bottom()), pos2(rect.right() - 1.0, rect.bottom() - 1.0));
        let art = Rect::from_min_size(body.min + vec2(15.0, 16.0), vec2(32.0, 32.0));
        match g.act.large_image_url().or(app_icon) {
            Some(url) => egui::Image::new(url).rounding(4.0).paint_at(ui, art),
            None => {
                ui.painter().rect_filled(art, 4.0, t.bg_primary);
                ui.painter().text(art.center(), Align2::CENTER_CENTER, icon::GAME, icon_font(16.0), t.interactive_normal);
            }
        }
        let party = if rich { 0 } else { g.party.len().min(3) };
        let p = ui.painter_at(Rect::from_min_max(body.min, pos2(body.right() - 16.0 - party as f32 * 22.0 - 8.0, body.bottom())));
        let x = art.right() + 12.0;
        let mut y = art.top() + 9.0;
        let title = if rich { g.act.details.clone().unwrap_or_else(|| g.act.name.clone()) } else { g.act.name.clone() };
        super::paint_text_emoji(ui, &p, pos2(x, y), &title, strong(14.0), t.header_primary);
        y += 17.0;
        let small = FontId::proportional(12.0);
        if rich {
            if g.act.state.is_some() {
                let state = if listening { artists(&g.act) } else { g.act.state.clone().unwrap_or_default() };
                super::paint_text_emoji(ui, &p, pos2(x, y), &state, small.clone(), t.text_muted);
                y += 16.0;
            }
            if let (true, Some(s)) = (timer, start) {
                p.text(pos2(x, y), Align2::LEFT_CENTER, format!("{} elapsed", clock(now - s)), small, t.text_muted);
            }
            if let (true, Some(s), Some(e)) = (bar, start, end) {
                let frac = ((now - s) as f32 / (e - s) as f32).clamp(0.0, 1.0);
                let track = Rect::from_min_max(pos2(x, y - 2.0), pos2(body.right() - 16.0, y + 2.0));
                ui.painter().rect_filled(track, 2.0, overlay(0.24));
                ui.painter().rect_filled(Rect::from_min_max(track.min, pos2(track.left() + track.width() * frac, track.bottom())), 2.0, t.header_primary);
            }
        } else {
            let n = g.party.len();
            p.text(pos2(x, y), Align2::LEFT_CENTER, format!("{n} {}", if n == 1 { "Person" } else { "People" }), small, t.text_muted);
            for (i, u) in g.party.iter().take(3).enumerate() {
                let user = self.store.users.get(u).cloned().unwrap_or_default();
                let c = pos2(body.right() - 16.0 - 12.0 - (party - 1 - i) as f32 * 22.0, art.center().y);
                ui.painter().circle_filled(c, 13.5, t.bg_secondary_alt);
                paint_avatar(ui, Rect::from_center_size(c, vec2(24.0, 24.0)), Some(user.avatar_or_default(48)), user.display_name());
            }
        }
        let action = resp.clicked().then(|| FriendAction::Profile(g.user, resp.interact_pointer_pos().unwrap_or(rect.left_top()) - vec2(340.0, 0.0)));
        (action, rich && (timer || bar))
    }

    /// Friends → Add Friend: send a request by username.
    fn add_friend_ui(&mut self, ui: &mut Ui) {
        let t = self.theme.clone();
        let mut send = false;
        CentralPanel::default().frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin::symmetric(30.0, 20.0))).show_inside(ui, |ui| {
            ui.label(RichText::new("Add Friend").font(strong(20.0)).color(t.header_primary));
            ui.add_space(8.0);
            ui.label(RichText::new("You can add friends with their Discord usernames.").size(14.0).color(t.text_muted));
            ui.add_space(16.0);
            let full_w = ui.available_width();
            Frame::none()
                .fill(Color32::from_black_alpha(31))
                .rounding(8.0)
                .stroke(Stroke::new(1.0_f32, overlay(0.2)))
                .inner_margin(Margin { left: 12.0, right: 8.0, top: 8.0, bottom: 8.0 })
                .show(ui, |ui| {
                    ui.set_width(full_w - 20.0);
                    ui.horizontal(|ui| {
                        let field = ui.add(
                            egui::TextEdit::singleline(&mut self.add_friend_input)
                                .frame(false)
                                .hint_text(RichText::new("Enter a username").color(t.text_muted))
                                .desired_width(ui.available_width() - 170.0)
                                .font(FontId::proportional(16.0)),
                        );
                        send |= field.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            let ok = !self.add_friend_input.trim().is_empty();
                            let (fill, fg) = if ok { (BRAND, Color32::WHITE) } else { (BRAND.gamma_multiply(0.5), crate::style::rgba(255, 255, 255, 140)) };
                            let button = egui::Button::new(RichText::new("Send Friend Request").font(strong(14.0)).color(fg)).fill(fill).rounding(8.0).min_size(vec2(0.0, 32.0));
                            send |= ui.add_enabled(ok, button).clicked();
                        });
                    });
                });
            ui.add_space(24.0);
            let y = ui.cursor().top();
            ui.painter().hline(ui.max_rect().x_range(), y, Stroke::new(1.0_f32, t.border_subtle));
            ui.add_space(24.0);
            ui.label(RichText::new("Other Places to Make Friends").font(strong(20.0)).color(t.header_primary));
            ui.add_space(8.0);
            ui.label(RichText::new("Don’t have a username on hand? Check out our list of public servers that includes everything from gaming to cooking, music, anime and more.").size(16.0).color(t.text_normal));
            ui.add_space(16.0);
            // "Explore Discoverable Servers" tile: green tile, label, chevron.
            let (rect, resp) = ui.allocate_exact_size(vec2(270.0, 56.0), Sense::click());
            let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
            ui.painter().rect(rect, 8.0, if resp.hovered() { t.bg_hover } else { t.bg_secondary }, Stroke::new(1.0_f32, t.border_subtle));
            let tile = Rect::from_center_size(pos2(rect.left() + 28.0, rect.center().y), vec2(32.0, 32.0));
            ui.painter().rect_filled(tile, 8.0, Color32::from_rgb(0x23, 0xa5, 0x5a));
            ui.painter().text(tile.center(), Align2::CENTER_CENTER, icon::SEARCH, icon_font(16.0), Color32::WHITE);
            ui.painter().text(pos2(tile.right() + 12.0, rect.center().y), Align2::LEFT_CENTER, "Explore Discoverable Servers", strong(15.0), t.header_primary);
            ui.painter().text(pos2(rect.right() - 16.0, rect.center().y), Align2::CENTER_CENTER, icon::CHEVRON, icon_font(12.0), t.interactive_normal);
            if resp.on_hover_text("Opens on discord.com").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                ui.ctx().open_url(egui::OpenUrl::new_tab("https://discord.com/discovery/servers"));
            }
        });
        let name = self.add_friend_input.trim().to_string();
        if send && !name.is_empty() {
            self.backend.send(crate::backend::Command::SendFriendRequest(name));
        }
    }

    /// Home → Message Requests: DMs from people you don't share a server or
    /// friendship with, waiting for you to accept or ignore them.
    pub fn message_requests_ui(&mut self, ui: &mut Ui) {
        let t = self.theme.clone();
        let all: Vec<discord::model::Channel> = self.store.channels.values().filter(|c| c.is_message_request).cloned().collect();
        let spam = all.iter().filter(|c| c.is_spam).count();
        let spam_tab = self.requests_spam;
        let mut reqs: Vec<discord::model::Channel> = all.into_iter().filter(|c| c.is_spam == spam_tab).collect();
        reqs.sort_by_key(|c| std::cmp::Reverse(c.last_message_id.unwrap_or(c.id)));
        let mut switch_tab = None;
        // The clicked request, opened in a panel on the right (like Discord).
        let preview = self.request_preview.and_then(|id| self.store.channels.get(&id).filter(|c| c.is_message_request).cloned());
        let mut preview_answer = None;
        if let Some(channel) = preview {
            let pid = channel.id;
            self.ensure_loaded(pid);
            let name = self.store.label(&channel);
            let user = channel.recipients.first().cloned().unwrap_or_default();
            let mut close = false;
            SidePanel::right("request_preview")
                .exact_width(462.0_f32.min(ui.available_width() * 0.55))
                .resizable(false)
                .show_separator_line(false)
                .frame(Frame::none().fill(t.page(t.bg_primary)))
                .show_inside(ui, |ui| {
                    let full = ui.max_rect();
                    ui.painter().vline(full.left(), full.y_range(), Stroke::new(1.0_f32, t.border_subtle));
                    TopBottomPanel::top("request_preview_header")
                        .exact_height(48.0)
                        .frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin::symmetric(16.0, 0.0)))
                        .show_inside(ui, |ui| {
                            let full = ui.max_rect().expand2(vec2(16.0, 0.0));
                            ui.painter().hline(full.x_range(), full.bottom() - 0.5, Stroke::new(1.0_f32, t.border_subtle));
                            ui.horizontal_centered(|ui| {
                                let (r, _) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::hover());
                                paint_avatar(ui, r, Some(user.avatar_or_default(48)), &name);
                                ui.label(RichText::new(&name).font(strong(16.0)).color(t.header_primary));
                                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                    let (r, b) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click());
                                    let b = b.on_hover_cursor(egui::CursorIcon::PointingHand);
                                    ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(14.0), if b.hovered() { t.header_primary } else { t.interactive_normal });
                                    close = b.on_hover_text("Close").clicked();
                                });
                            });
                        });
                    TopBottomPanel::bottom("request_preview_bar")
                        .show_separator_line(false)
                        .frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 16.0, right: 16.0, top: 4.0, bottom: 16.0 }))
                        .show_inside(ui, |ui| preview_answer = super::chat::request_bar(ui, &t).map(|a| (pid, a)));
                    CentralPanel::default().frame(Frame::none().fill(t.page(t.bg_primary))).show_inside(ui, |ui| {
                        let mut actions = Vec::new();
                        let mut editing = None;
                        self.message_list(ui, &channel, &name, &mut editing, &mut actions);
                        for a in actions {
                            self.apply_action(a);
                        }
                    });
                });
            if close {
                self.request_preview = None;
            }
        }
        TopBottomPanel::top("requests_header")
            .exact_height(48.0)
            .frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin::symmetric(16.0, 0.0)))
            .show_inside(ui, |ui| {
                let full = ui.max_rect().expand2(vec2(16.0, 0.0));
                ui.painter().hline(full.x_range(), full.bottom() - 0.5, Stroke::new(1.0_f32, t.border_subtle));
                ui.horizontal_centered(|ui| {
                    ui.spacing_mut().item_spacing.x = 8.0;
                    ui.label(RichText::new(icon::MAIL).font(icon_font(18.0)).color(t.text_muted));
                    ui.label(RichText::new("Message Requests").font(strong(16.0)).color(t.header_primary));
                    let (dot, _) = ui.allocate_exact_size(vec2(12.0, 32.0), Sense::hover());
                    ui.painter().circle_filled(dot.center(), 2.0, t.interactive_muted);
                    ui.spacing_mut().item_spacing.x = 16.0;
                    let spam_label = if spam > 0 { format!("Spam ({spam})") } else { "Spam".into() };
                    for (label, on) in [("Requests".to_string(), false), (spam_label, true)] {
                        let kind = if spam_tab == on { Pill::Selected } else { Pill::Normal };
                        if pill(ui, &t, &label, kind, 0).clicked() {
                            switch_tab = Some(on);
                        }
                    }
                });
            });
        let mut action: Option<(Id, Option<bool>)> = None;
        let now = now_ms();
        CentralPanel::default().frame(Frame::none().fill(t.page(t.bg_primary)).inner_margin(Margin { left: 14.0, right: 16.0, top: 16.0, bottom: 0.0 })).show_inside(ui, |ui| {
            ui.spacing_mut().item_spacing.y = 0.0;
            let title = if spam_tab { format!("Spam – {}", reqs.len()) } else { format!("Pending requests – {}", reqs.len()) };
            let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::hover());
            ui.painter().text(pos2(r.left() + 10.0, r.center().y), Align2::LEFT_CENTER, title, FontId::proportional(14.0), t.text_muted);
            if reqs.is_empty() {
                ui.add_space(60.0);
                ui.vertical_centered(|ui| {
                    let msg = if spam_tab { "No spam here. Nice." } else { "There are no pending message requests. Here's Wumpus for now." };
                    ui.label(RichText::new(msg).size(15.0).color(t.text_muted));
                });
                return;
            }
            ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
                ui.spacing_mut().item_spacing.y = 0.0;
                for c in &reqs {
                    let user = c.recipients.first().cloned().unwrap_or_default();
                    let name = user.display_name().to_string();
                    let preview = self.request_previews.get(&c.id).map(|m| m.content.clone()).filter(|s| !s.is_empty());
                    let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 62.0), Sense::click());
                    let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                    let hovered = ui.rect_contains_pointer(rect);
                    if self.request_preview == Some(c.id) {
                        ui.painter().rect_filled(rect, 8.0, t.bg_selected);
                    } else if hovered {
                        ui.painter().rect_filled(rect, 8.0, t.bg_hover);
                    }
                    let av = Rect::from_min_size(pos2(rect.left() + 10.0, rect.center().y - 16.0), vec2(32.0, 32.0));
                    paint_avatar(ui, av, Some(super::avatar_uri(&user, 64, hovered)), &name);
                    if let Some(deco) = super::decoration_uri(&user, hovered) {
                        egui::Image::new(deco).paint_at(ui, av.expand(3.2));
                    }
                    // Decline / Accept DM, right-aligned.
                    let accept_r = Rect::from_min_size(pos2(rect.right() - 10.0 - 100.0, rect.center().y - 16.0), vec2(100.0, 32.0));
                    let decline_r = Rect::from_min_size(pos2(accept_r.left() - 8.0 - 76.0, accept_r.top()), vec2(76.0, 32.0));
                    let p = ui.painter_at(Rect::from_min_max(rect.min, pos2(decline_r.left() - 8.0, rect.bottom())));
                    let name_y = rect.center().y - 9.0;
                    let mut x = super::paint_text_emoji(ui, &p, pos2(av.right() + 12.0, name_y), &name, strong(16.0), t.header_primary).right();
                    if let Some((tag, badge)) = user.server_tag() {
                        x += 4.0 + paint_tag_chip(ui, &p, x + 4.0, name_y, &tag, badge.as_deref(), &t);
                    }
                    x = p.text(pos2(x + 6.0, name_y + 1.0), Align2::LEFT_CENTER, &user.username, FontId::proportional(14.0), t.text_muted).right();
                    let since = c
                        .is_message_request_timestamp
                        .as_deref()
                        .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
                        .map(|d| d.timestamp_millis().max(0) as u64)
                        .or_else(|| c.last_message_id.map(|m| m.timestamp_ms()));
                    if let Some(at) = since.filter(|at| *at <= now) {
                        let ago = match ago(now - at).as_str() {
                            "just now" => "just now".to_string(),
                            a => format!("{a} ago"),
                        };
                        p.text(pos2(x + 6.0, name_y + 1.0), Align2::LEFT_CENTER, ago, FontId::proportional(12.0), t.text_muted);
                    }
                    let sub = preview.as_deref().and_then(|s| s.lines().next()).unwrap_or("Sent you a message");
                    super::paint_text_emoji(ui, &p, pos2(av.right() + 12.0, rect.center().y + 10.0), sub, FontId::proportional(14.0), t.text_muted);
                    let decline = ui.interact(decline_r, egui::Id::new(("req_decline", c.id.0)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                    ui.painter().rect(decline_r, 8.0, if decline.hovered() { overlay(0.2) } else { overlay(0.12) }, Stroke::new(1.0_f32, overlay(0.04)));
                    ui.painter().text(decline_r.center(), Align2::CENTER_CENTER, "Decline", strong(14.0), t.header_primary);
                    let accept = ui.interact(accept_r, egui::Id::new(("req_accept", c.id.0)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                    ui.painter().rect_filled(accept_r, 8.0, if accept.hovered() { BRAND_HOVER } else { BRAND });
                    ui.painter().text(accept_r.center(), Align2::CENTER_CENTER, "Accept DM", strong(14.0), Color32::WHITE);
                    if decline.clicked() {
                        action = Some((c.id, Some(false)));
                    } else if accept.clicked() {
                        action = Some((c.id, Some(true)));
                    } else if resp.clicked() {
                        action = Some((c.id, None));
                    }
                }
            });
        });
        if let Some(on) = switch_tab {
            self.requests_spam = on;
        }
        match action.or(preview_answer.map(|(ch, a)| (ch, Some(a)))) {
            Some((ch, Some(accept))) => {
                self.request_preview = None;
                self.answer_request(ch, accept);
            }
            Some((ch, None)) => self.request_preview = Some(ch),
            None => {}
        }
    }
}

/// "Looking for accounts you've blocked or ignored? Go to settings" (×).
fn blocked_notice_ui(ui: &mut Ui, t: &Theme) -> Option<FriendAction> {
    let mut action = None;
    let w = ui.available_width() - 16.0 - 4.0;
    ui.horizontal(|ui| {
        ui.add_space(16.0);
        let (rect, _) = ui.allocate_exact_size(vec2(w, 52.0), Sense::hover());
        ui.painter().rect_filled(rect, 4.0, t.bg_secondary);
        let c = pos2(rect.left() + 16.0 + 10.0, rect.center().y);
        ui.painter().circle_filled(c, 9.0, t.interactive_normal);
        ui.painter().text(c, Align2::CENTER_CENTER, "i", strong(13.0), t.bg_secondary);
        let font = strong(14.0);
        let r = ui.painter().text(pos2(rect.left() + 48.0, rect.center().y), Align2::LEFT_CENTER, "Looking for accounts you’ve blocked or ignored? ", font.clone(), t.header_primary);
        let g = ui.painter().layout_no_wrap("Go to settings".into(), font, t.text_link);
        let link = Rect::from_min_size(pos2(r.right(), rect.center().y - g.size().y / 2.0), g.size());
        let lr = ui.interact(link, egui::Id::new("blocked_notice_link"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        if lr.hovered() {
            ui.painter().hline(link.x_range(), link.bottom(), Stroke::new(1.0_f32, t.text_link));
        }
        ui.painter().galley(link.min, g, t.text_link);
        if lr.clicked() {
            action = Some(FriendAction::Tab(FriendsTab::Blocked));
        }
        let x = Rect::from_center_size(pos2(rect.right() - 26.0, rect.center().y), vec2(24.0, 24.0));
        let xr = ui.interact(x, egui::Id::new("blocked_notice_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(13.0), if xr.hovered() { t.header_primary } else { t.interactive_normal });
        if xr.on_hover_text("Dismiss").clicked() {
            action = Some(FriendAction::DismissNotice);
        }
    });
    action
}

/// What Discord's "Accept friend request?" says (its en-GB strings).
const STRANGER_TITLE: &str = "Accept friend request?";
const STRANGER_BODY: &str = "This may be someone you don\u{2019}t know. You don\u{2019}t share any mutual friends or small mutual servers with them.";

impl RustCord {
    /// Discord's "Accept friend request?" pop-up. Accepting a request from a
    /// stranger (no mutual friends or small mutual servers) is refused with
    /// error 80013 until it is confirmed; Accept sends it again with
    /// `confirm_stranger_request`. Measured on Discord web (2026-11-23): 400 px
    /// wide, 12 px corners, a 20/24 semibold title 24 px in, the 16/20 text
    /// 8 px under it, a 40 px close button 8 px from the corner, and Cancel /
    /// Accept (40 px tall, 8 px apart) sharing the width. Enter accepts; Esc,
    /// ✕ or a click on the dimmed window cancels.
    pub fn stranger_confirm_ui(&mut self, ctx: &egui::Context) {
        let Some(user) = self.stranger_confirm else { return };
        let t = self.theme.clone();
        const W: f32 = 398.0;
        // The Accept button holds the keyboard focus: Enter presses it (and the
        // message box, which sends on Enter, doesn't have it meanwhile).
        let ok_id = egui::Id::new("stranger_confirm_ok");
        let mut cancel = ctx.input(|i| i.key_pressed(Key::Escape));
        let mut confirm = ctx.memory(|m| m.has_focus(ok_id)) && ctx.input(|i| i.key_pressed(Key::Enter));
        cancel |= super::guild_pages::modal_frame(ctx, &t, "stranger_confirm", W, |ui| {
            let mut job = egui::text::LayoutJob::single_section(
                STRANGER_BODY.into(),
                egui::TextFormat { font_id: FontId::proportional(16.0), color: t.header_secondary, line_height: Some(20.0), ..Default::default() },
            );
            job.wrap.max_width = W - 48.0;
            let body = ui.fonts(|f| f.layout_job(job));
            let h = 24.0 + 24.0 + 8.0 + body.size().y + 8.0 + 16.0 + 40.0 + 8.0 + 16.0;
            let (r, _) = ui.allocate_exact_size(vec2(W, h), Sense::hover());
            ui.painter().text(pos2(r.left() + 24.0, r.top() + 36.0), Align2::LEFT_CENTER, STRANGER_TITLE, strong(20.0), t.header_primary);
            let x = Rect::from_min_size(pos2(r.right() - 8.0 - 40.0, r.top() + 8.0), vec2(40.0, 40.0));
            let xr = ui.interact(x, egui::Id::new("stranger_confirm_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            if xr.hovered() {
                ui.painter().rect_filled(x, 8.0, t.bg_hover);
            }
            ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(14.0), if xr.hovered() { t.header_primary } else { t.interactive_normal });
            cancel |= xr.clicked();
            ui.painter().galley(pos2(r.left() + 24.0, r.top() + 56.0), body, t.header_secondary);
            let bw = (W - 48.0 - 8.0) / 2.0;
            let no = Rect::from_min_size(pos2(r.left() + 24.0, r.bottom() - 24.0 - 40.0), vec2(bw, 40.0));
            let yes = no.translate(vec2(bw + 8.0, 0.0));
            let nr = ui.interact(no, egui::Id::new("stranger_confirm_cancel"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            ui.painter().rect(no, 8.0, overlay(if nr.hovered() { 0.2 } else { 0.12 }), Stroke::new(1.0_f32, crate::style::rgba(151, 151, 159, 10)));
            ui.painter().text(no.center(), Align2::CENTER_CENTER, "Cancel", crate::style::medium(16.0), t.header_primary);
            cancel |= nr.clicked();
            let yr = ui.interact(yes, ok_id, Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            ui.painter().rect(yes, 8.0, if yr.hovered() { BRAND_HOVER } else { BRAND }, Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
            ui.painter().text(yes.center(), Align2::CENTER_CENTER, "Accept", crate::style::medium(16.0), Color32::WHITE);
            confirm |= yr.clicked();
        });
        if confirm && crate::diagnostics::dev_var("RUSTCORD_DEV_VIEW").as_deref() == Ok("stranger-confirm") {
            ctx.memory_mut(|m| m.surrender_focus(ok_id));
            self.stranger_confirm = None;
            self.toast("Accepted (test): nothing sent.", false);
        } else if confirm {
            ctx.memory_mut(|m| m.surrender_focus(ok_id));
            self.stranger_confirm = None;
            log::info!("friends: accepting {user}'s request (confirmed as a stranger's)");
            self.backend.send(crate::backend::Command::AcceptStranger { user });
        } else if cancel {
            ctx.memory_mut(|m| m.surrender_focus(ok_id));
            self.stranger_confirm = None;
        } else {
            ctx.memory_mut(|m| m.request_focus(ok_id));
        }
    }
}