Skip to content

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

243 KB
Raw Blame
//! Profiles: the popout, the DM panel's card, the full profile window, your
//! own account menu, and the quick switcher.
//!
//! Sizes, colours and behaviour are Discord's web client's, read from its
//! DOM, stylesheets and profile modules (last on 2026-12-01).

use super::chat::UiAction;
use super::motion::{self, Motion};
use super::profile_theme as theme;
use super::{paint_avatar, paint_status_dot, status_label, SizedOffScreen};
use crate::app::RustCord;
use crate::store::ChannelRow;
use crate::style::{bold, icon, icon_font, overlay};
use discord::model::{channel_kind, Id, Message, User};
use discord::settings_proto::CustomStatus;
use eframe::egui::{
    self, epaint::Shadow, pos2, vec2, Align2, Button, Color32, FontId, Frame, Key, Margin, Order, Rect, RichText,
    Rounding, ScrollArea, Sense, Stroke, TextEdit, Ui,
};

/// Popouts and the account card (a profile theme adds its 2 px border on
/// each side; the DM panel's card is 304 with 2 px padding).
const POPOUT_W: f32 = 300.0;
/// Banner height of the small cards and of the full profile.
const BANNER_H: f32 = 105.0;
const FULL_BANNER_H: f32 = 140.0;

/// Full profile tabs (`FullProfile::tab`).
pub const TAB_ACTIVITY: u8 = 0;
pub const TAB_FRIENDS: u8 = 1;
pub const TAB_SERVERS: u8 = 2;
pub const TAB_BOARD: u8 = 3;
/// A bot's profile: its bio, roles and dates.
pub const TAB_BIO: u8 = 4;
/// Not chosen yet: the profile's first tab, as Discord opens it (the Board
/// when they have one, else Activity).
pub const TAB_FIRST: u8 = u8::MAX;

fn rgb(c: u32) -> Color32 {
    Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)
}

/// Discord's plain dark / light theme, for the text on themed profiles.
fn plain_theme(dark: bool) -> &'static crate::style::Theme {
    static THEMES: std::sync::OnceLock<[crate::style::Theme; 2]> = std::sync::OnceLock::new();
    &THEMES.get_or_init(|| [crate::style::Theme::preset("dark"), crate::style::Theme::preset("light")])[usize::from(!dark)]
}

/// Discord's --background-surface-highest, one step above the theme's
/// floating surface (status bubbles sit on it).
fn surface_highest(t: &crate::style::Theme) -> Color32 {
    if t.light {
        return Color32::WHITE;
    }
    let c = t.bg_floating;
    Color32::from_rgb(c.r().saturating_add(5), c.g().saturating_add(5), c.b().saturating_add(6))
}

/// Keeps the full profile directly above its dimmed backdrop. egui raises
/// a layer you press on (a click outside the profile, to close it, raised
/// the backdrop), and layers raised in the same frame keep their old order:
/// the next full profile opened under its own backdrop, a grey screen.
fn above_backdrop(ui: &Ui) {
    ui.ctx().set_sublayer(egui::LayerId::new(Order::Foreground, egui::Id::new("full_profile_bg")), ui.layer_id());
}

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

/// A rounded rect filled with Discord's profile gradient: `top` down to
/// `solid` px (the banner's height), then fading to `bottom` at the foot.
/// (egui meshes can't round, so the rounded foot is the solid end colour.)
fn gradient_rrect(out: &mut Vec<egui::Shape>, rect: Rect, rounding: Rounding, solid: f32, top: Color32, bottom: Color32) {
    out.push(egui::Shape::rect_filled(rect, rounding, top));
    let r = rounding.sw.max(rounding.se);
    let foot = Rect::from_min_max(pos2(rect.left(), rect.bottom() - (2.0 * r).max(1.0)), rect.max);
    out.push(egui::Shape::rect_filled(foot, Rounding { nw: 0.0, ne: 0.0, ..rounding }, bottom));
    let start = (rect.top() + solid).min(rect.bottom() - r);
    let mut mesh = egui::Mesh::default();
    for (y, c) in [(start, top), (rect.bottom() - r, bottom)] {
        mesh.colored_vertex(pos2(rect.left(), y), c);
        mesh.colored_vertex(pos2(rect.right(), y), c);
    }
    mesh.add_triangle(0, 1, 2);
    mesh.add_triangle(1, 2, 3);
    out.push(egui::Shape::mesh(mesh));
}

/// A rounded rect that fades from `top` to `rest` over its first `fade` px
/// (the full profile's window on a profile theme).
fn fade_rrect(out: &mut Vec<egui::Shape>, rect: Rect, r: f32, fade: f32, top: Color32, rest: Color32) {
    out.push(egui::Shape::rect_filled(rect, r, rest));
    let head = Rect::from_min_max(rect.min, pos2(rect.right(), rect.top() + (2.0 * r).max(1.0)));
    out.push(egui::Shape::rect_filled(head, Rounding { nw: r, ne: r, sw: 0.0, se: 0.0 }, top));
    let mut mesh = egui::Mesh::default();
    for (y, c) in [(rect.top() + r, top), ((rect.top() + fade).min(rect.bottom() - r), rest)] {
        mesh.colored_vertex(pos2(rect.left(), y), c);
        mesh.colored_vertex(pos2(rect.right(), y), c);
    }
    mesh.add_triangle(0, 1, 2);
    mesh.add_triangle(1, 2, 3);
    out.push(egui::Shape::mesh(mesh));
}

/// Discord's blurred banner behind a themed full profile: the picture across
/// the window's width at `alpha`, gone 280 px down. A 64 px copy stretched
/// that far is as soft as Discord's 15 px blur, and costs nothing.
fn paint_backdrop(ui: &Ui, rect: Rect, r: f32, banner: &str, alpha: f32) {
    let small = banner.replace("size=600", "size=64").replace(".gif?", ".png?");
    let Ok(egui::load::TexturePoll::Ready { texture }) = egui::Image::new(small).texture_options(super::SMOOTH).load_for_size(ui.ctx(), vec2(64.0, 64.0)) else { return };
    let (tw, th) = (texture.size.x.max(1.0), texture.size.y.max(1.0));
    let full_h = rect.width() * th / tw;
    let depth = 280.0_f32.min(rect.height());
    let shade = |y: f32| crate::style::rgba(255, 255, 255, (alpha * (1.0 - y / depth) * 255.0) as u8);
    let mut mesh = egui::Mesh::with_texture(texture.id);
    // A point `y` down from the top, as the picture covers it there.
    let vertex = |x: f32, y: f32| egui::epaint::Vertex { pos: pos2(x, rect.top() + y), uv: pos2((x - rect.left()) / rect.width(), (y / full_h).min(1.0)), color: shade(y) };
    // The band between the rounded corners, then the full width below them.
    for (x0, x1, y0, y1) in [(rect.left() + r, rect.right() - r, 0.0, r), (rect.left(), rect.right(), r, depth)] {
        let at = mesh.vertices.len() as u32;
        for (x, y) in [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] {
            mesh.vertices.push(vertex(x, y));
        }
        mesh.add_triangle(at, at + 1, at + 2);
        mesh.add_triangle(at + 1, at + 2, at + 3);
    }
    // The two rounded corners themselves, as quarter circles: the picture
    // reaches the rounded edge and stops there (left out, the corners were
    // darker squares).
    if r > 0.0 {
        const STEPS: u32 = 8;
        for (cx, from) in [(rect.left() + r, std::f32::consts::PI), (rect.right() - r, 1.5 * std::f32::consts::PI)] {
            let centre = mesh.vertices.len() as u32;
            mesh.vertices.push(vertex(cx, r));
            for i in 0..=STEPS {
                let a = from + i as f32 / STEPS as f32 * std::f32::consts::FRAC_PI_2;
                mesh.vertices.push(vertex(cx + r * a.cos(), r + r * a.sin()));
            }
            for i in 0..STEPS {
                mesh.add_triangle(centre, centre + 1 + i, centre + 2 + i);
            }
        }
    }
    ui.painter().add(egui::Shape::mesh(mesh));
}

/// A round arrow (Discord's "Returning after …" icon), drawn: the icon font
/// has none.
fn paint_return_icon(painter: &egui::Painter, rect: Rect, color: Color32) {
    let (c, r) = (rect.center(), rect.width() * 0.36);
    let stroke = Stroke::new(1.3_f32, color);
    let at = |deg: f32| c + r * vec2(deg.to_radians().cos(), deg.to_radians().sin());
    let arc: Vec<egui::Pos2> = (0..=14).map(|i| at(-40.0 + i as f32 * 20.0)).collect();
    painter.add(egui::Shape::line(arc, stroke));
    let tip = at(-40.0);
    painter.add(egui::Shape::convex_polygon(vec![tip + vec2(2.6, 0.6), tip + vec2(-2.2, 0.8), tip + vec2(0.4, -3.0)], color, Stroke::NONE));
}

/// Card background with its drop shadow underneath (a Frame's own shadow
/// would be painted over a background RustCord sets afterwards).
fn with_shadow(card: egui::Shape, rect: Rect) -> egui::Shape {
    egui::Shape::Vec(vec![egui::Shape::Rect(shadow().as_shape(rect, Rounding::same(12.0))), card])
}

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

/// "01:06", like Discord's song timer (hours only when needed).
fn clock(ms: u64) -> String {
    let s = ms / 1000;
    if s >= 3600 {
        format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
    } else {
        format!("{:02}:{:02}", s / 60, s % 60)
    }
}

/// Discord's name for a Nitro tenure badge ("premium_tenure_12_month_v2").
fn nitro_tier(badge_id: &str) -> Option<&'static str> {
    if badge_id == "premium" {
        return Some("Nitro");
    }
    let months: u32 = badge_id.strip_prefix("premium_tenure_")?.split('_').next()?.parse().ok()?;
    Some(match months {
        0..=2 => "Nitro Bronze",
        3..=5 => "Nitro Silver",
        6..=11 => "Nitro Gold",
        12..=23 => "Nitro Platinum",
        24..=35 => "Nitro Diamond",
        36..=59 => "Nitro Emerald",
        60..=71 => "Nitro Ruby",
        _ => "Nitro Opal",
    })
}

/// A badge's tooltip: the badge larger, its name and what it says.
fn badge_tooltip(ui: &mut Ui, t: &crate::style::Theme, b: &discord::model::ProfileBadge) {
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing.x = 10.0;
        ui.add(egui::Image::new(b.icon_url()).fit_to_exact_size(vec2(32.0, 32.0)));
        ui.vertical(|ui| {
            ui.spacing_mut().item_spacing.y = 2.0;
            match nitro_tier(&b.id) {
                Some(tier) => {
                    ui.label(bold(tier).size(14.0).color(t.header_primary));
                    ui.label(RichText::new(&b.description).size(12.5).color(t.text_normal));
                }
                None => {
                    ui.label(bold(&b.description).size(13.5).color(t.header_primary));
                }
            }
        });
    });
}

/// Discord's role pill (web module 166005, read 2026-12-01): 24 px tall with
/// 8 px corners, a 1 px `edge` and no fill; a 12 px colour dot, the name in
/// 12 px, then the role's icon. Allocated as one measured widget so wrapping
/// rows break cleanly. A `removable` one ends in a 24 px × button instead of
/// its 8 px of padding; returns whether that was clicked.
fn role_chip(ui: &mut Ui, t: &crate::style::Theme, r: &discord::model::Role, removable: bool, salt: Id, edge: Color32) -> bool {
    let galley = ui.painter().layout_no_wrap(r.name.clone(), FontId::proportional(12.0), t.text_normal);
    let role_icon = r.icon_url().or_else(|| r.unicode_emoji.as_deref().map(crate::emoji::twemoji_url));
    let width = 7.0 + 12.0 + 4.0 + galley.size().x + if role_icon.is_some() { 16.0 } else { 0.0 } + if removable { 24.0 } else { 9.0 };
    let max = ui.max_rect().width();
    let (rect, _) = ui.allocate_exact_size(vec2(width.min(max), 24.0), Sense::hover());
    let p = ui.painter_at(rect);
    p.rect_stroke(rect.shrink(0.5), 8.0, Stroke::new(1.0_f32, edge));
    let dot = pos2(rect.left() + 13.0, rect.center().y);
    let color = if r.color == 0 { t.interactive_normal } else { rgb(r.color) };
    p.circle_filled(dot, 6.0, color);
    let x = rect.left() + 23.0;
    p.galley(pos2(x, rect.center().y - galley.size().y / 2.0), galley.clone(), t.text_normal);
    if let Some(u) = role_icon {
        egui::Image::new(u).paint_at(ui, Rect::from_center_size(pos2(x + galley.size().x + 10.0, rect.center().y), vec2(12.0, 12.0)));
    }
    if !removable {
        return false;
    }
    // The ×: a 12 px icon in the pill's last 24 px, subtle until pointed at.
    let slot = Rect::from_min_max(pos2(rect.right() - 24.0, rect.top()), rect.max);
    let b = ui.interact(slot, egui::Id::new(("role_x", salt.0, r.id.0)), Sense::click());
    p.text(slot.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(8.0), if b.hovered() { t.header_primary } else { subtle(t) });
    b.on_hover_text("Remove role").on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
}

/// The badge chip's "+N": Discord's 20 px slot with the count centred in it.
fn more_badges(ui: &mut Ui, t: &crate::style::Theme, hidden: usize) -> egui::Response {
    let galley = ui.painter().layout_no_wrap(format!("+{hidden}"), FontId::proportional(14.0), t.header_primary);
    let (r, resp) = ui.allocate_exact_size(vec2((galley.size().x + 4.0).max(20.0), 20.0), Sense::click());
    let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
    ui.painter().galley(r.center() - galley.size() / 2.0, galley, t.header_primary);
    resp
}

/// What the card asks the caller to do.
#[derive(Default)]
struct CardOut {
    message: bool,
    edit_profile: bool,
    /// Your own status bubble was clicked.
    edit_status: bool,
    /// Avatar / banner clicked: show it in the viewer.
    view: Option<crate::features::MediaView>,
    /// Server tag clicked: (server, where).
    tag: Option<(Id, egui::Pos2)>,
    /// Role to give (true) or take away: (server, role, add).
    role_change: Option<(Id, Id, bool)>,
    /// One of your badges clicked: (all badges, which).
    badges: Option<(Vec<discord::model::ProfileBadge>, usize)>,
    /// Avatar clicked in a small card: open the full profile.
    expand: bool,
    /// Game Collection clicked: open the full profile on its Board.
    board: bool,
    /// "Listen Along" clicked on someone's Spotify.
    listen_along: bool,
    /// Your server tag's ▾ clicked (where).
    tag_picker: Option<egui::Pos2>,
    /// The banner's Add Friend (true) / Remove Friend (false).
    friend: Option<bool>,
    /// "N Mutual Friends" / "N Mutual Servers" clicked: that full-profile tab.
    mutual_tab: Option<u8>,
    /// The full profile's note changed: save this.
    note: Option<String>,
    /// "Add Note" clicked on a small card: the full profile, on its note.
    note_focus: bool,
    /// "More" clicked: open its menu here.
    more: Option<egui::Pos2>,
    /// "React to status" clicked: the emoji picker here, for this status.
    status_react: Option<(egui::Pos2, String)>,
    /// "Reply to status" clicked (the status).
    status_reply: Option<String>,
    /// One of an app's command buttons clicked.
    command: Option<String>,
}

/// How Discord quotes a custom status in the DM a reaction or reply to it
/// becomes: a small italic line saying what happened, the status, then what
/// you sent.
fn status_quote(verb: &str, name: &str, status: &str) -> String {
    let mut quote = format!("> -# *{verb} to {name}'s status*\n");
    if !status.is_empty() {
        quote.push_str(&format!("> {status}\n"));
    }
    quote
}

/// Which card `profile_card` draws; Discord's layouts differ a little.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CardKind {
    /// Someone's 300 px popout, "Message @…" at the bottom.
    Popout,
    /// Your own card above the account menu.
    Account,
    /// The DM side panel's card.
    Panel,
    /// The big profile window.
    Full,
}

/// Discord's ChatIcon (the full profile's "Message" button), in white.
/// Discord's PaperPlusIcon and PaperIcon (the note button: no note yet, a
/// note), in white to be tinted.
const PAPER_PLUS_SVG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"><path fill="#fff" fill-rule="evenodd" d="M5 2a3 3 0 0 0-3 3v14a3 3 0 0 0 3 3h9c.1 0 .12-.11.04-.15a3 3 0 0 1-2.03-3.16c.04-.34-.2-.69-.55-.69H6a1 1 0 1 1 0-2h9.5a.5.5 0 0 0 .5-.5V15a3 3 0 0 1 .19-1.05c.15-.4-.11-.95-.54-.95H6a1 1 0 1 1 0-2h12a1 1 0 0 1 .88.52c.13.24.35.48.62.52A3 3 0 0 1 21.83 14v.02c.02.06.17.05.17-.02V5a3 3 0 0 0-3-3H5Zm1 4a1 1 0 0 0 0 2h5a1 1 0 1 0 0-2H6Z"/><path fill="#fff" d="M19 14a1 1 0 0 1 1 1v3h3a1 1 0 1 1 0 2h-3v3a1 1 0 1 1-2 0v-3h-3a1 1 0 1 1 0-2h3v-3a1 1 0 0 1 1-1Z"/></svg>"##;
const PAPER_SVG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"><path fill="#fff" fill-rule="evenodd" clip-rule="evenodd" d="M5 2a3 3 0 0 0-3 3v14a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3V5a3 3 0 0 0-3-3H5Zm1 4a1 1 0 0 0 0 2h5a1 1 0 1 0 0-2H6Zm-1 6a1 1 0 0 1 1-1h12a1 1 0 1 1 0 2H6a1 1 0 0 1-1-1Zm1 4a1 1 0 1 0 0 2h12a1 1 0 1 0 0-2H6Z"/></svg>"##;

const CHAT_SVG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"><path fill="#fff" d="M12 22a10 10 0 1 0-8.45-4.64c.13.19.11.44-.04.61l-2.06 2.37A1 1 0 0 0 2.2 22H12Z"/></svg>"##;

/// Discord's UserCheckIcon (the banner's "Friend" button), in white.
pub(super) const USER_CHECK_SVG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"><path fill="#fff" d="M12 10a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM11.53 11A9.53 9.53 0 0 0 2 20.53c0 .81.66 1.47 1.47 1.47h.22c.24 0 .44-.17.5-.4.29-1.12.84-2.17 1.32-2.91.14-.21.43-.1.4.15l-.26 2.61c-.02.3.2.55.5.55h6.4a.5.5 0 0 0 .35-.85l-.02-.03a3 3 0 1 1 4.24-4.24l.53.52c.2.2.5.2.7 0l1.8-1.8c.17-.17.2-.43.06-.62A9.52 9.52 0 0 0 12.47 11h-.94Z"/><path fill="#fff" d="M23.7 17.7a1 1 0 1 0-1.4-1.4L18 20.58l-2.3-2.3a1 1 0 0 0-1.4 1.42l3 3a1 1 0 0 0 1.4 0l5-5Z"/></svg>"##;

/// Whether the account's language is British English (Discord's dates and
/// spellings differ from its default, US English).
fn british() -> bool {
    discord::http::account_locale().as_deref() == Some("en-GB")
}

/// Discord's short date (Member Since): "Oct 18, 2024", or "18 Oct 2024"
/// ("16 Sept 2019") in British English.
fn short_date(ms: u64) -> String {
    let Some(d) = chrono::DateTime::from_timestamp_millis(ms as i64).map(|d| d.with_timezone(&chrono::Local)) else {
        return String::new();
    };
    short_date_in(d.date_naive(), british())
}

fn short_date_in(d: chrono::NaiveDate, british: bool) -> String {
    use chrono::Datelike;
    if british {
        let month = if d.month() == 9 { "Sept".to_string() } else { d.format("%b").to_string() };
        format!("{} {month} {}", d.day(), d.year())
    } else {
        format!("{} {}, {}", d.format("%b"), d.day(), d.year())
    }
}

/// One account under a full profile's Connections, as Discord draws it
/// (web module 364152, measured 2026-11-27): the platform's logo on a 24 px
/// white tile (its name on hover), then the account name with ↗, a link
/// when the platform has profile pages, "Member since …" and what the
/// platform shares, in 10 px.
fn connection_row(ui: &mut Ui, t: &crate::style::Theme, a: &discord::model::ConnectedAccount) {
    use super::brand_icons::{self as brand, Fact};
    const NAME_H: f32 = 18.0;
    let meta = a.metadata.as_ref();
    let since = meta.and_then(|m| m.get("created_at")).and_then(|v| v.as_str()).and_then(|s| {
        chrono::DateTime::parse_from_rfc3339(s).ok().map(|d| d.timestamp_millis()).or_else(|| {
            chrono::NaiveDateTime::parse_from_str(s.get(..19).unwrap_or(s), "%Y-%m-%dT%H:%M:%S").ok().map(|d| d.and_utc().timestamp_millis())
        })
    });
    let facts = brand::facts(&a.kind, meta);
    let facts_h = if facts.is_empty() {
        0.0
    } else if facts.iter().any(|f| matches!(f, Fact::Item { .. })) {
        22.0
    } else {
        16.0
    };
    let info_h = NAME_H + if since.is_some() { 16.0 } else { 0.0 } + if facts.is_empty() { 0.0 } else { 4.0 + facts_h };
    let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), info_h.max(24.0)), Sense::hover());
    let p = ui.painter();

    // The tile: white, 1 px --border-subtle, 8 px corners, an 18 px logo.
    let tile = Rect::from_min_size(row.min, vec2(24.0, 24.0));
    p.rect(tile, 8.0, Color32::WHITE, Stroke::new(1.0_f32, t.border_subtle));
    if let Some(src) = brand::tile(&a.kind) {
        egui::Image::new(src).paint_at(ui, Rect::from_center_size(tile.center(), vec2(18.0, 18.0)));
    }
    ui.interact(tile, egui::Id::new(("conn_tile", &a.kind, &a.id)), Sense::hover()).on_hover_text(brand::platform_name(&a.kind));

    // (Short rows sit centred on the tile.)
    let x = row.left() + 32.0;
    let mut y = row.top() + ((24.0 - info_h) / 2.0).max(0.0);
    let link = a.link();
    let icon_w = if link.is_some() { 2.0 + 16.0 } else { 0.0 };
    let max_w = (row.right() - x - icon_w).max(20.0);
    let mut job = egui::text::LayoutJob::simple_singleline(a.name.clone(), FontId::proportional(14.0), t.text_normal);
    job.wrap = egui::text::TextWrapping { max_width: max_w, max_rows: 1, break_anywhere: true, overflow_character: Some('…') };
    let galley = p.layout_job(job);
    let elided = galley.elided;
    let name_r = Rect::from_min_size(pos2(x, y + (NAME_H - galley.size().y) / 2.0), galley.size());
    let name_w = name_r.width();
    p.galley(name_r.min, galley, t.text_normal);
    let hit = Rect::from_min_size(pos2(x, y), vec2(name_w + icon_w, NAME_H));
    let id = egui::Id::new(("conn_name", &a.kind, &a.id));
    match link {
        Some(url) => {
            let resp = ui.interact(hit, id, Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            let ext = Rect::from_min_size(pos2(x + name_w + 2.0, y + 1.0), vec2(16.0, 16.0));
            egui::Image::new(brand::link_external()).tint(t.text_normal).paint_at(ui, ext);
            if resp.hovered() {
                ui.painter().hline(name_r.left()..=name_r.right(), name_r.bottom() - 1.5, Stroke::new(1.0_f32, t.text_normal));
            }
            let resp = if elided { resp.on_hover_text(&a.name) } else { resp };
            if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                ui.ctx().open_url(egui::OpenUrl::new_tab(url));
            }
        }
        None if elided => {
            ui.interact(hit, id, Sense::hover()).on_hover_text(&a.name);
        }
        None => {}
    }
    y += NAME_H;
    let p = ui.painter();
    if let Some(ms) = since {
        p.text(pos2(x, y), Align2::LEFT_TOP, format!("Member since {}", short_date(ms.max(0) as u64)), FontId::proportional(12.0), t.text_normal);
        y += 16.0;
    }
    if facts.is_empty() {
        return;
    }
    // Each fact 4 px down, 8 px after the one before; Steam's items carry
    // their game's 18 px icon. Numbers are the same weight as their words,
    // except in an item.
    y += 4.0;
    let small = FontId::proportional(10.0);
    let semibold = FontId::new(10.0, egui::FontFamily::Name(crate::style::BOLD.into()));
    let mid = y + facts_h / 2.0 + 2.0;
    let mut cx = x;
    for f in &facts {
        match f {
            Fact::Count(n, label) => {
                let g = p.layout_no_wrap(format!("{n} {label}"), small.clone(), t.text_normal);
                let w = g.size().x;
                p.galley(pos2(cx, mid - g.size().y / 2.0), g, t.text_normal);
                cx += w + 8.0;
            }
            Fact::Item { icon, count, label } => {
                if let Some(src) = brand::tile(icon) {
                    egui::Image::new(src).paint_at(ui, Rect::from_min_size(pos2(cx, mid - 9.0), vec2(18.0, 18.0)));
                }
                cx += 22.0;
                let n = p.layout_no_wrap(count.clone(), semibold.clone(), t.text_normal);
                let nw = n.size().x;
                p.galley(pos2(cx, mid - n.size().y / 2.0), n, t.text_normal);
                let w = p.layout_no_wrap(format!(" {label}"), small.clone(), t.text_normal);
                let ww = w.size().x;
                p.galley(pos2(cx + nw, mid - w.size().y / 2.0), w, t.text_normal);
                cx += nw + ww + 8.0;
            }
            Fact::Tag { label, positive } => {
                let (fill, text) = if *positive { (Color32::from_rgb(0, 128, 67), Color32::WHITE) } else { (crate::style::rgba(151, 151, 159, 31), t.text_normal) };
                let g = p.layout_no_wrap(label.to_string(), small.clone(), text);
                let pill = Rect::from_min_size(pos2(cx, mid - 7.0), vec2(g.size().x + 16.0, 14.0));
                p.rect_filled(pill, 12.0, fill);
                p.galley(pos2(pill.left() + 8.0, mid - g.size().y / 2.0), g, text);
                cx = pill.right() + 8.0;
            }
        }
    }
}

/// Discord's --shadow-border + --shadow-high under a 300 px card.
fn with_popout_shadow(card: egui::Shape, rect: Rect) -> egui::Shape {
    let high = Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) };
    egui::Shape::Vec(vec![egui::Shape::Rect(high.as_shape(rect, Rounding::same(8.0))), card])
}

/// One of the round buttons in a card's banner (32 px, black 56% with a
/// white-8% edge, like Discord's).
fn banner_button(ui: &mut Ui, rect: Rect, id: egui::Id, glyph: Option<&str>, tip: &str) -> egui::Response {
    card_button(ui, rect, id, glyph, tip, true)
}

/// A 32 px icon button: round in a banner, or Discord's square secondary
/// button (--background-mod-subtle, 8 px corners) in the full profile.
fn card_button(ui: &mut Ui, rect: Rect, id: egui::Id, glyph: Option<&str>, tip: &str, round: bool) -> egui::Response {
    let resp = ui.interact(rect, id, Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    if round {
        ui.painter().circle(rect.center(), 16.0, Color32::from_black_alpha(143), Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
    } else {
        let fill = if resp.hovered() { overlay(0.2) } else { overlay(0.12) };
        ui.painter().rect(rect, 8.0, fill, Stroke::new(1.0_f32, crate::style::rgba(151, 151, 159, 10)));
    }
    match glyph {
        Some(g) => {
            ui.painter().text(rect.center(), Align2::CENTER_CENTER, g, icon_font(16.0), Color32::WHITE);
        }
        None => {
            egui::Image::new(egui::ImageSource::Bytes { uri: "bytes://user-check.svg".into(), bytes: egui::load::Bytes::Static(USER_CHECK_SVG.as_bytes()) })
                .paint_at(ui, Rect::from_center_size(rect.center(), vec2(16.0, 16.0)));
        }
    }
    resp.on_hover_text(tip)
}

/// A profile's open "More" menu (Discord's user-profile-overflow-menu).
pub struct ProfileMore {
    pub user: User,
    pub guild: Option<Id>,
    pub pos: egui::Pos2,
    pub opened: u64,
    /// The open submenu and the top of its row.
    sub: Option<(MoreSub, f32)>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum MoreSub {
    Invite,
    Copy,
}

enum SwitchTo {
    Channel(Id),
    User(Id),
    Guild(Id),
}

impl RustCord {
    /// (emoji, text) custom status for a user.
    /// (emoji image URL, text) of a user's custom status.
    pub(crate) fn custom_status_of(&self, user: Id) -> Option<(Option<String>, String)> {
        if Some(user) == self.store.me_id() {
            return self.store.my_custom.as_ref().map(|c| (self.my_status_emoji(), c.text.clone()));
        }
        let cs = self.store.presences.get(&user)?.custom_status()?.clone();
        let emoji = cs.emoji.and_then(|e| match (e.id, e.name) {
            (Some(id), _) => Some(super::emoji_img(id, e.animated, 48)),
            (None, Some(n)) => Some(crate::emoji::twemoji_url(&n)),
            _ => None,
        });
        Some((emoji, cs.state.unwrap_or_default()))
    }

    /// Image for your own custom status emoji (custom emoji by ID, else Unicode).
    pub(crate) fn my_status_emoji(&self) -> Option<String> {
        let c = self.store.my_custom.as_ref()?;
        match (c.emoji_id, c.emoji_name.as_deref()) {
            (Some(id), _) => {
                // The settings don't say whether it's animated; your servers might.
                let animated = self.store.guilds.values().flat_map(|g| g.guild.emojis.iter()).any(|e| e.id == Some(id) && e.animated);
                Some(super::emoji_img(id, animated, 48))
            }
            (None, Some(n)) => Some(crate::emoji::twemoji_url(n)),
            _ => None,
        }
    }

    /// Nitro profile theme: (top, bottom, primary) colours of the card.
    /// Measured against Discord: the card is the primary→accent gradient under
    /// a 60% black overlay; border and button use the colours themselves.
    /// The colours a card's text uses: over a profile theme Discord draws it
    /// in its plain (untinted) text colours, whatever client theme the app
    /// has (Vesktop, 2026-11-22: bio and names (247,250,252), not blue-tinted).
    fn card_text_theme(&self, user: Id, guild: Option<Id>) -> crate::style::Theme {
        let mut t = self.theme.clone();
        // A themed profile is on Discord's dark or light theme, as its
        // primary colour decides, whatever theme the app has.
        if let Some((primary, _)) = self.theme_colors(user, guild) {
            let dark = theme::is_dark(primary);
            let plain = plain_theme(dark);
            t.header_primary = plain.header_primary;
            t.interactive_normal = plain.interactive_normal;
            t.text_link = plain.text_link;
            t.light = plain.light;
            // Its text is white (black when light) at Discord's set
            // strengths: 96 % default, 88 % subtle, 76 % muted.
            let ink = |a: u8| if dark { crate::style::rgba(255, 255, 255, a) } else { crate::style::rgba(0, 0, 0, a) };
            t.text_normal = ink(245);
            t.header_secondary = ink(224);
            t.text_muted = ink(194);
        }
        t
    }

    /// The profile theme's two colours (0xRRGGBB), when themes are shown.
    fn theme_colors(&self, user: Id, guild: Option<Id>) -> Option<(u32, u32)> {
        self.profile_for(user, guild)?.theme_colors().filter(|_| super::PROFILE_THEMES.load(std::sync::atomic::Ordering::Relaxed))
    }

    fn card_theme(&self, user: Id, guild: Option<Id>) -> Option<(Color32, Color32, Color32)> {
        let (a, b) = self.theme_colors(user, guild)?;
        // Discord's --profile-gradient-overlay-color: 60 % black, or white.
        let over = if theme::is_dark(a) { Color32::BLACK } else { Color32::WHITE };
        let dim = |c: u32| rgb(c).lerp_to_gamma(over, 0.6);
        Some((dim(a), dim(b), rgb(a)))
    }

    /// A surface colour inside a themed card: Discord mixes the theme's base
    /// colour into its plain dark (or light) surfaces, one part in three.
    fn themed_surface(&self, user: Id, guild: Option<Id>, plain_dark: u32) -> Option<Color32> {
        let (primary, _) = self.theme_colors(user, guild)?;
        let dark = theme::is_dark(primary);
        let surface = if dark { rgb(plain_dark) } else { Color32::WHITE };
        Some(surface.lerp_to_gamma(theme::base_color(primary, dark), 1.0 / 3.0))
    }

    /// Which cached profile to show for `user` in `guild`: that exact one,
    /// else the same person's global or another server's profile.
    fn profile_key_for(&self, user: Id, guild: Option<Id>) -> Option<(Id, Option<Id>)> {
        let ok = |k: &(Id, Option<Id>)| self.profiles.get(k).is_some_and(|r| r.is_ok());
        if ok(&(user, guild)) {
            return Some((user, guild));
        }
        if ok(&(user, None)) {
            return Some((user, None));
        }
        self.profiles.iter().find(|((u, _), r)| *u == user && r.is_ok()).map(|(k, _)| *k)
    }

    pub(crate) fn profile_for(&self, user: Id, guild: Option<Id>) -> Option<&discord::model::UserProfile> {
        self.profiles.get(&self.profile_key_for(user, guild)?).and_then(|r| r.as_ref().ok())
    }

    /// The raw (undimmed) theme colours: (primary, accent).
    fn theme_raw(&self, user: Id, guild: Option<Id>) -> Option<(Color32, Color32)> {
        let (a, b) = self.theme_colors(user, guild)?;
        Some((rgb(a), rgb(b)))
    }

    /// Colour under the top of the card (avatar ring, status bubble).
    fn card_background(&self, user: Id, guild: Option<Id>) -> Color32 {
        self.card_theme(user, guild).map(|(top, _, _)| top).unwrap_or(self.theme.bg_secondary_alt)
    }

    /// A big card's background: the profile theme's gradient (the colour
    /// itself down to `solid`, the banner's height), inside a `border` in the
    /// undimmed colours when there is one; or the plain surface.
    fn card_shapes(&self, rect: Rect, user: Id, guild: Option<Id>, rounding: Rounding, border: f32, solid: f32) -> egui::Shape {
        let (Some((top, bottom, _)), Some((primary, accent))) = (self.card_theme(user, guild), self.theme_raw(user, guild)) else {
            return egui::Shape::Vec(vec![
                egui::Shape::rect_filled(rect, rounding, self.theme.bg_secondary_alt),
                egui::Shape::rect_stroke(rect, rounding, Stroke::new(1.0_f32, self.theme.border_subtle)),
            ]);
        };
        let mut shapes = Vec::new();
        if border > 0.0 {
            gradient_rrect(&mut shapes, rect, rounding, solid, primary, accent);
        }
        let inner = |r: f32| (r - border).max(0.0);
        let inside = Rounding { nw: inner(rounding.nw), ne: inner(rounding.ne), sw: inner(rounding.sw), se: inner(rounding.se) };
        gradient_rrect(&mut shapes, rect.shrink(border), inside, solid, top, bottom);
        egui::Shape::Vec(shapes)
    }

    /// Friend (opens "Remove Friend", asked twice) / Add Friend / request
    /// sent, as a banner circle or the full profile's square button.
    fn friend_button(&self, ui: &mut Ui, rect: Rect, user: Id, kind: CardKind, out: &mut CardOut) {
        let t = &self.theme;
        let round = kind != CardKind::Full;
        // (Per card: the popout and the DM panel can show the same person at once.)
        let fid = egui::Id::new(("profile_friend", user.0, kind as u8));
        match self.store.relationships.get(&user).map(|r| r.kind) {
            Some(1) => {
                let resp = card_button(ui, rect, fid, None, "Friend", round);
                // Discord's menu beside the button, 8 px away: "Remove Friend"
                // (which asks before it does anything).
                let menu = fid.with("menu");
                if resp.clicked() {
                    ui.memory_mut(|m| m.toggle_popup(menu));
                }
                if ui.memory(|m| m.is_popup_open(menu)) {
                    let mut picked = false;
                    let area = egui::Area::new(menu).order(Order::Foreground).fixed_pos(pos2(rect.right() + 8.0, rect.top())).constrain(true).show(ui.ctx(), |ui| {
                        super::ctx_menu_frame(t).show(ui, |ui| {
                            ui.set_width(128.0);
                            picked = super::ctx_row(ui, t, None, "Remove Friend", None, false, true).clicked();
                        });
                    });
                    if picked {
                        out.friend = Some(false);
                        ui.memory_mut(|m| m.close_popup());
                    } else if !resp.clicked() && (area.response.clicked_elsewhere() || ui.input(|i| i.key_pressed(Key::Escape))) {
                        ui.memory_mut(|m| m.close_popup());
                    }
                }
            }
            Some(4) => {
                card_button(ui, rect, fid, Some(icon::USER_PLUS), "Friend Request Sent", round);
            }
            Some(2) => {}
            _ => {
                if card_button(ui, rect, fid, Some(icon::USER_PLUS), "Add Friend", round).clicked() {
                    out.friend = Some(true);
                }
            }
        }
    }

    /// Background of the 300 px cards (popout, your account card, the DM
    /// panel): Discord's --background-surface-high, or the theme's top.
    fn popout_background(&self, user: Id, guild: Option<Id>) -> Color32 {
        self.card_theme(user, guild).map(|(top, _, _)| top).unwrap_or(self.theme.surface_high)
    }

    /// Those cards' shapes: 8 px corners and Discord's 1 px white-8% ring,
    /// or the profile theme's gradient inside its 2 px border.
    fn popout_shapes(&self, rect: Rect, user: Id, guild: Option<Id>) -> egui::Shape {
        let (Some((top, bottom, _)), Some((primary, accent))) = (self.card_theme(user, guild), self.theme_raw(user, guild)) else {
            // The ring as a 1 px larger fill underneath: exactly one pixel wide.
            return egui::Shape::Vec(vec![
                egui::Shape::rect_filled(rect.expand(1.0), 9.0, crate::style::rgba(255, 255, 255, 20)),
                egui::Shape::rect_filled(rect, 8.0, self.theme.surface_high),
            ]);
        };
        // Discord: the colours themselves as a 2 px frame, the card inside
        // under the overlay; both solid down to the banner's height.
        let mut shapes = Vec::new();
        gradient_rrect(&mut shapes, rect, Rounding::same(8.0), BANNER_H, primary, accent);
        gradient_rrect(&mut shapes, rect.shrink(2.0), Rounding::same(6.0), BANNER_H, top, bottom);
        egui::Shape::Vec(shapes)
    }

    /// Padding between a 300 px card's edge and its banner: the theme's
    /// 2 px border (the DM panel always has it).
    fn popout_inset(&self, user: Id, guild: Option<Id>) -> f32 {
        if self.card_theme(user, guild).is_some() {
            2.0
        } else {
            0.0
        }
    }

    /// Discord's "👤 1 Mutual Friend • 6 Mutual Servers" (web module 791556):
    /// each part underlined on hover, in 14 px, or 12 px when both are
    /// there; the first three friends' faces, or with no friends in common
    /// the first three servers' icons. The row is 4 px above and below its
    /// tallest part: the text's line (16 or 18 px), the faces (16) or the
    /// server icons (19, with their ring). Returns the full-profile tab that
    /// was clicked.
    fn mutuals_row(&self, ui: &mut Ui, users: &[User], guilds: &[Id], friends: usize, servers: usize, bg: Color32) -> Option<u8> {
        let t = &self.theme;
        let mut open = None;
        let size = if friends > 0 && servers > 0 { 12.0 } else { 14.0 };
        let icons: Vec<(Option<String>, String)> = guilds
            .iter()
            .filter_map(|g| self.store.guilds.get(g))
            .take(3)
            .map(|g| (g.guild.icon_url(32), super::acronym(&g.guild.name)))
            .collect();
        let line: f32 = if size == 12.0 { 16.0 } else { 18.0 };
        let pictures: f32 = if friends > 0 { 16.0 } else if !icons.is_empty() { 19.0 } else { 0.0 };
        let row_h = line.max(pictures) + 8.0;
        ui.allocate_ui_with_layout(vec2(ui.available_width(), row_h), egui::Layout::left_to_right(egui::Align::Center), |ui| {
            ui.set_min_height(row_h);
            ui.spacing_mut().item_spacing.x = 0.0;
            let part = |ui: &mut Ui, avatars: &[User], servers: &[(Option<String>, String)], text: String| -> bool {
                let galley = ui.painter().layout_no_wrap(text, FontId::proportional(size), t.header_secondary);
                let n = avatars.len().max(servers.len()).min(3);
                // (16 px pictures overlapping by 3, then 4 px.)
                let av_w = if n > 0 { 16.0 + (n - 1) as f32 * 13.0 + 4.0 } else { 0.0 };
                let (r, resp) = ui.allocate_exact_size(vec2(av_w + galley.size().x, row_h), Sense::click());
                let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                for (i, u) in avatars.iter().take(3).enumerate() {
                    let a = Rect::from_min_size(pos2(r.left() + i as f32 * 13.0, r.center().y - 8.0), vec2(16.0, 16.0));
                    if i > 0 {
                        ui.painter().circle_filled(a.center(), 9.5, bg);
                    }
                    paint_avatar(ui, a, u.avatar_url(32), u.display_name());
                }
                for (i, (icon, letters)) in servers.iter().take(3).enumerate() {
                    let a = Rect::from_min_size(pos2(r.left() + i as f32 * 13.0, r.center().y - 8.0), vec2(16.0, 16.0));
                    if i > 0 {
                        ui.painter().rect_filled(a.expand(1.5), 5.0, bg);
                    }
                    match icon {
                        Some(u) => egui::Image::new(u.clone()).rounding(4.0).paint_at(ui, a),
                        None => {
                            ui.painter().rect_filled(a, 4.0, overlay(0.16));
                            ui.painter().text(a.center(), Align2::CENTER_CENTER, letters.chars().next().unwrap_or(' '), FontId::proportional(8.0), t.text_normal);
                        }
                    }
                }
                let pos = pos2(r.left() + av_w, r.center().y - galley.size().y / 2.0);
                let text_rect = Rect::from_min_size(pos, galley.size());
                ui.painter().galley(pos, galley, t.header_secondary);
                if resp.hovered() {
                    ui.painter().hline(text_rect.x_range(), text_rect.bottom() - 1.5, Stroke::new(1.0_f32, t.header_secondary));
                }
                resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
            };
            if friends > 0 && part(ui, users, &[], format!("{friends} Mutual Friend{}", if friends == 1 { "" } else { "s" })) {
                open = Some(TAB_FRIENDS);
            }
            // (A 4 px dot, 6 px either side.)
            if friends > 0 && servers > 0 {
                let (d, _) = ui.allocate_exact_size(vec2(16.0, row_h), Sense::hover());
                ui.painter().circle_filled(d.center(), 2.0, t.header_secondary);
            }
            let shown: &[(Option<String>, String)] = if friends > 0 { &[] } else { &icons };
            if servers > 0 && part(ui, &[], shown, format!("{servers} Mutual Server{}", if servers == 1 { "" } else { "s" })) {
                open = Some(TAB_SERVERS);
            }
        });
        open
    }

    /// A bio cut to Discord's three lines, with "View Full Bio" under it
    /// when there's more (returns whether that was clicked).
    fn clamped_bio(&self, ui: &mut Ui, t: &crate::style::Theme, guild: Option<Id>, bio: &str, actions: &mut Vec<UiAction>) -> bool {
        // Three of Discord's 18 px lines.
        const LINES: f32 = 54.0;
        let fake = Message { guild_id: guild, ..Default::default() };
        let top = ui.cursor().min;
        let w = ui.available_width();
        let mut child = ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_min_size(top, vec2(w, 4000.0))).layout(egui::Layout::top_down(egui::Align::Min)));
        child.set_clip_rect(Rect::from_min_size(top, vec2(w, LINES)).intersect(ui.clip_rect()));
        self.render_bio(&mut child, &fake, bio, t.text_normal, actions);
        let full = child.min_rect().height();
        ui.allocate_exact_size(vec2(w, full.min(LINES)), Sense::hover());
        if full <= LINES + 1.0 {
            return false;
        }
        ui.add_space(8.0);
        let galley = ui.painter().layout_no_wrap("View Full Bio".into(), FontId::proportional(12.0), t.header_primary);
        let (r, resp) = ui.allocate_exact_size(vec2(galley.size().x, 17.0), Sense::click());
        let pos = pos2(r.left(), r.center().y - galley.size().y / 2.0);
        let text_rect = Rect::from_min_size(pos, galley.size());
        ui.painter().galley(pos, galley, t.header_primary);
        if resp.hovered() {
            ui.painter().hline(text_rect.x_range(), text_rect.bottom() - 1.5, Stroke::new(1.0_f32, t.header_primary));
        }
        resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
    }

    /// One activity as Discord shows it: art, title lines and, for songs and
    /// other timed activities, a progress bar with elapsed / total time (or
    /// "for 12m"). Someone else's Spotify gets "Listen Along"; returns
    /// whether that was clicked.
    pub(crate) fn activity_card(&self, ui: &mut Ui, a: &discord::model::Activity, owner: Id, compact: bool) -> bool {
        let t = &self.theme;
        let mut listen = false;
        // Just a name (a bot's "Watching ETH: $2,236"): one line, no empty art box.
        let bare = a.large_image_url().is_none() && a.details.is_none() && a.state.is_none() && a.timestamps.as_ref().and_then(|ts| ts.start).is_none();
        if bare {
            let text = match a.kind {
                2 => format!("Listening to {}", a.name),
                3 => format!("Watching {}", a.name),
                1 => format!("Streaming {}", a.name),
                5 => format!("Competing in {}", a.name),
                _ => format!("Playing {}", a.name),
            };
            Frame::none().fill(overlay(if compact { 0.12 } else { 0.06 })).rounding(8.0).inner_margin(Margin::symmetric(10.0, 8.0)).show(ui, |ui| {
                ui.set_width(ui.available_width());
                ui.horizontal(|ui| {
                    ui.spacing_mut().item_spacing.x = 8.0;
                    ui.label(RichText::new(icon::GAME).font(icon_font(14.0)).color(t.interactive_normal));
                    ui.add(egui::Label::new(RichText::new(text).size(13.0).color(t.text_normal)).truncate());
                });
            });
            return false;
        }
        let (art_size, pad, round) = if compact { (56.0, 10.0, 8.0) } else { (80.0, 16.0, 12.0) };
        let stroke = if compact { Stroke::NONE } else { Stroke::new(1.0_f32, t.border_subtle) };
        Frame::none().fill(overlay(if compact { 0.12 } else { 0.06 })).stroke(stroke).rounding(round).inner_margin(Margin::same(pad)).show(ui, |ui| {
            ui.set_width(ui.available_width());
            let spotify = a.kind == 2 && a.party.as_ref().and_then(|p| p.id.as_deref()).is_some_and(|p| p.starts_with("spotify:"));
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 6.0;
                let heading = match a.kind {
                    2 => format!("Listening to {}", a.name),
                    3 => format!("Watching {}", a.name),
                    1 => format!("Streaming {}", a.name),
                    5 => format!("Competing in {}", a.name),
                    _ => "Playing".to_string(),
                };
                ui.label(bold(heading).size(12.0).color(t.header_secondary));
                if spotify {
                    if let Some(src) = super::brand_icons::connection("spotify") {
                        ui.add(egui::Image::new(src).fit_to_exact_size(vec2(14.0, 14.0)));
                    }
                }
            });
            ui.add_space(6.0);
            let now = now_ms();
            let span = a.timestamps.as_ref().and_then(|ts| Some((ts.start?, ts.end?))).filter(|(s, e)| e > s);
            ui.horizontal_top(|ui| {
                ui.spacing_mut().item_spacing.x = 12.0;
                let (art, art_resp) = ui.allocate_exact_size(vec2(art_size, art_size), Sense::hover());
                // The activity's own picture; without one, the game's icon
                // (as Discord shows a plain "Playing"), the small picture
                // promoted, then a controller.
                let app_icon = || {
                    a.application_id.and_then(|id| match self.apps.get(&id) {
                        Some(info) => info.icon_url(),
                        None => {
                            self.apps_wanted.borrow_mut().insert(id);
                            None
                        }
                    })
                };
                let assets = a.assets.as_ref();
                let (large, small) = match (a.large_image_url(), a.small_image_url()) {
                    (Some(l), s) => (Some(l), s),
                    (None, Some(s)) => (Some(s), None),
                    (None, None) => (app_icon(), None),
                };
                match large {
                    Some(u) => egui::Image::new(u).rounding(6.0).paint_at(ui, art),
                    None => {
                        ui.painter().rect_filled(art, 6.0, overlay(0.16));
                        ui.painter().text(art.center(), Align2::CENTER_CENTER, icon::GAME, icon_font(art_size * 0.4), t.interactive_normal);
                    }
                }
                // Discord's small picture: a circle over the bottom-right
                // corner, ringed in the card's colour.
                let badge = art_size * 0.35;
                let badge_rect = Rect::from_center_size(art.right_bottom() - vec2(badge * 0.3, badge * 0.3), vec2(badge, badge));
                if let Some(u) = &small {
                    ui.painter().circle_filled(badge_rect.center(), badge / 2.0 + 2.0, if t.light { t.bg_secondary } else { t.bg_floating });
                    egui::Image::new(u.as_str()).rounding(badge / 2.0).paint_at(ui, badge_rect);
                }
                let over_small = small.is_some() && ui.rect_contains_pointer(badge_rect.expand(2.0));
                let tip = if over_small { assets.and_then(|x| x.small_text.as_deref()) } else { assets.and_then(|x| x.large_text.as_deref()) };
                if let Some(tip) = tip.filter(|s| !s.is_empty()) {
                    art_resp.on_hover_text(tip);
                }
                ui.vertical(|ui| {
                    ui.set_width(ui.available_width());
                    ui.spacing_mut().item_spacing.y = 2.0;
                    let title = if a.kind == 0 { a.name.clone() } else { a.details.clone().unwrap_or_else(|| a.name.clone()) };
                    ui.add(egui::Label::new(bold(title).size(14.0).color(t.header_primary)).truncate());
                    if a.kind == 0 {
                        if let Some(d) = &a.details {
                            ui.add(egui::Label::new(RichText::new(d).size(12.5).color(t.text_normal)).truncate());
                        }
                    }
                    if let Some(s) = &a.state {
                        // Spotify separates artists with ';'.
                        let s = if spotify { s.replace(';', ",") } else { s.clone() };
                        ui.add(egui::Label::new(RichText::new(s).size(12.5).color(t.text_normal)).truncate());
                    }
                    match span {
                        Some((start, end)) => {
                            ui.add_space(6.0);
                            let total = end - start;
                            let done = now.saturating_sub(start).min(total);
                            let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 14.0), Sense::hover());
                            let font = FontId::proportional(11.5);
                            let p = ui.painter();
                            let left = p.layout_no_wrap(clock(done), font.clone(), t.text_normal);
                            let right = p.layout_no_wrap(clock(total), font, t.text_normal);
                            let bar = Rect::from_min_max(
                                pos2(row.left() + left.size().x + 8.0, row.center().y - 2.0),
                                pos2(row.right() - right.size().x - 8.0, row.center().y + 2.0),
                            );
                            p.galley(pos2(row.left(), row.center().y - left.size().y / 2.0), left, t.text_normal);
                            p.galley(pos2(row.right() - right.size().x, row.center().y - right.size().y / 2.0), right, t.text_normal);
                            if bar.width() > 4.0 {
                                p.rect_filled(bar, 2.0, overlay(0.2));
                                let filled = Rect::from_min_size(bar.min, vec2(bar.width() * done as f32 / total as f32, bar.height()));
                                p.rect_filled(filled, 2.0, t.header_primary);
                            }
                            // Tick on the next whole second only while a timer is on screen.
                            ui.ctx().request_repaint_after(std::time::Duration::from_millis(1000 - (now - start) % 1000));
                        }
                        None => {
                            if let Some(start) = a.timestamps.as_ref().and_then(|ts| ts.start).filter(|s| now > *s) {
                                let mins = (now - start) / 60_000;
                                let text = if mins >= 60 { format!("for {}h {}m", mins / 60, mins % 60) } else { format!("for {}m", mins.max(1)) };
                                ui.label(RichText::new(text).size(12.5).color(t.text_muted));
                            }
                        }
                    }
                });
            });
            if spotify && a.sync_id.is_some() && Some(owner) != self.store.me_id() {
                ui.add_space(8.0);
                let on = self.listen_along.as_ref().is_some_and(|(u, _)| *u == owner);
                let label = if on { "Stop Listening Along" } else { "Listen Along" };
                let b = ui.add_sized(
                    [ui.available_width(), 32.0],
                    Button::new(RichText::new(format!("{}  {label}", icon::HEADPHONES)).font(icon_font(13.0)).color(t.header_primary)).fill(overlay(if on { 0.24 } else { 0.16 })).rounding(8.0),
                );
                listen = b.clicked();
            }
        });
        listen
    }

    /// Discord's "Game Collection" row on a small card (40 px, mod 16 %, 8 px
    /// corners): up to four 24 px icons, the fourth dimmed under "+N" when
    /// there are more. Returns whether it was clicked (it opens the Board).
    fn game_collection(&self, ui: &mut Ui, t: &crate::style::Theme, games: &[Id], themed: bool, label_px: f32) -> bool {
        const SLOTS: usize = 4;
        let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::click());
        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
        // --background-surface-higher; on a profile theme, mod 16 %.
        let fill = match (themed, resp.hovered()) {
            (true, hovered) => overlay(if hovered { 0.24 } else { 0.16 }),
            (false, false) => self.theme.bg_floating,
            (false, true) => surface_highest(&self.theme),
        };
        ui.painter().rect_filled(r, 8.0, fill);
        ui.painter().text(r.left_center() + vec2(8.0, 0.0), Align2::LEFT_CENTER, "Game Collection", crate::style::medium(label_px), t.header_primary);
        let shown = games.len().min(SLOTS);
        let more = games.len() - shown;
        let mut x = r.right() - 8.0 - shown as f32 * 28.0 + 4.0;
        for (i, game) in games.iter().enumerate() {
            let app = self.apps.get(game);
            if app.is_none() {
                self.apps_wanted.borrow_mut().insert(*game);
            }
            if i >= SLOTS {
                continue;
            }
            let slot = Rect::from_min_size(pos2(x, r.center().y - 12.0), vec2(24.0, 24.0));
            x += 28.0;
            let last = more > 0 && i == SLOTS - 1;
            ui.painter().rect_filled(slot, 4.0, if themed { crate::style::rgba(255, 255, 255, 61) } else { overlay(0.24) });
            if let Some(u) = app.and_then(|a| a.icon_url()) {
                let icon = egui::Image::new(u).rounding(4.0);
                if last { icon.tint(crate::style::rgba(255, 255, 255, 128)) } else { icon }.paint_at(ui, slot);
            }
            if last {
                ui.painter().rect_filled(slot, 4.0, Color32::from_black_alpha(153));
                ui.painter().text(slot.center(), Align2::CENTER_CENTER, format!("+{more}"), crate::style::medium(12.0), Color32::from_rgb(224, 224, 227));
            } else if let Some(a) = app {
                ui.interact(slot, ui.id().with(("game_collection_icon", game.0, i)), Sense::hover()).on_hover_text(&a.name);
            }
        }
        resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
    }

    /// Start (or stop) listening along to `user`'s Spotify.
    pub(crate) fn toggle_listen_along(&mut self, user: Id) {
        if self.listen_along.as_ref().is_some_and(|(u, _)| *u == user) {
            self.listen_along = None;
            return;
        }
        let Some(a) = self.spotify_of(user) else { return };
        let Some(track) = a.sync_id.clone() else { return };
        let position_ms = a.timestamps.as_ref().and_then(|ts| ts.start).map(|s| now_ms().saturating_sub(s)).unwrap_or(0);
        self.backend.send(crate::backend::Command::SpotifyPlay { track: track.clone(), position_ms });
        self.listen_along = Some((user, track));
    }

    fn spotify_of(&self, user: Id) -> Option<discord::model::Activity> {
        self.store
            .presences
            .get(&user)?
            .activities
            .iter()
            .find(|a| a.kind == 2 && a.sync_id.is_some() && a.party.as_ref().and_then(|p| p.id.as_deref()).is_some_and(|p| p.starts_with("spotify:")))
            .cloned()
    }

    /// Listen Along keeps following: when their song changes, play the new
    /// one; when they stop listening, so do you. Cheap; runs every frame.
    pub(crate) fn listen_along_tick(&mut self) {
        let Some((user, last)) = self.listen_along.clone() else { return };
        match self.spotify_of(user) {
            None => {
                self.listen_along = None;
                self.toast("They stopped listening to Spotify.", false);
            }
            Some(a) if a.sync_id.as_deref() != Some(last.as_str()) => {
                let track = a.sync_id.clone().unwrap_or_default();
                let position_ms = a.timestamps.as_ref().and_then(|ts| ts.start).map(|s| now_ms().saturating_sub(s)).unwrap_or(0);
                self.backend.send(crate::backend::Command::SpotifyPlay { track: track.clone(), position_ms });
                self.listen_along = Some((user, track));
            }
            Some(_) => {}
        }
    }

    /// How far inside a floating card's edge its banner sits: Discord keeps
    /// the card's border (2px theme gradient, or the 1px hairline) all the
    /// way round, over the banner too.
    fn card_inset(&self, user: Id, guild: Option<Id>) -> f32 {
        if self.card_theme(user, guild).is_some() {
            2.0
        } else {
            1.0
        }
    }

    /// The card itself. `dm_draft` is the "Message @user" box (others only).
    /// `inset` keeps the banner inside the card's border (0 when flush).
    #[allow(clippy::too_many_arguments)]
    fn profile_card(&self, ui: &mut Ui, w: f32, user: &User, guild: Option<Id>, bg: Color32, dm_draft: Option<&mut String>, kind: CardKind, inset: f32, actions: &mut Vec<UiAction>) -> CardOut {
        let card_t = self.card_text_theme(user.id, guild);
        let t = &card_t;
        let mut out = CardOut::default();
        let expandable = kind != CardKind::Full;
        let data = self.profiles.get(&(user.id, guild));
        // While this server's profile loads, show what RustCord already knows about
        // them (banner, bio, badges, theme from another server or their
        // global profile) instead of an empty card; roles wait for the real one.
        let exact = data.and_then(|r| r.as_ref().ok());
        let profile = exact.or_else(|| self.profile_for(user.id, guild));
        // Prefer the profile's user object but keep cosmetics the message had.
        let original = user;
        let mut user = profile.map(|p| p.user.clone()).filter(|u| !u.username.is_empty()).unwrap_or_else(|| original.clone());
        if user.avatar_decoration_data.is_none() {
            user.avatar_decoration_data = original.avatar_decoration_data.clone();
        }
        if user.primary_guild.is_none() {
            user.primary_guild = original.primary_guild.clone();
        }
        let is_me = Some(user.id) == self.store.me_id();
        let member = exact.and_then(|p| p.guild_member.clone());
        // In a server the name wears the style they set for that server.
        if let Some(style) = member.as_ref().and_then(|m| m.display_name_styles.clone()).or_else(|| self.store.member_style(guild, user.id).cloned()) {
            user.display_name_styles = Some(style);
        }

        ui.set_width(w);
        // Banner.
        // The full profile (not expandable) is bigger, like Discord's. The
        // small cards' 105 px banner sits inside their padding.
        let (banner_h, av_size) = if expandable { (BANNER_H + inset, 80.0) } else { (FULL_BANNER_H, 120.0) };
        let (slot, _) = ui.allocate_exact_size(vec2(w, banner_h), Sense::hover());
        let banner = Rect::from_min_max(slot.min + vec2(inset, inset), pos2(slot.right() - inset, slot.bottom()));
        // Painted strictly inside its slot (a cover-cropped GIF never spills
        // over the card's border).
        let corner = match kind {
            CardKind::Full => (16.0 - inset).max(0.0),
            CardKind::Panel => 4.0,
            _ => (8.0 - inset).max(0.0),
        };
        let top = Rounding { nw: corner, ne: corner, sw: 0.0, se: 0.0 };
        let banner_color = profile
            .and_then(|p| p.accent_color())
            .map(rgb)
            .or_else(|| profile.and_then(|p| p.theme_colors().filter(|_| super::PROFILE_THEMES.load(std::sync::atomic::Ordering::Relaxed))).map(|(a, _)| rgb(a)))
            // Discord: the avatar's dominant colour (its 128 px WebP), dark
            // grey (primary-800) until that's known.
            .or_else(|| avatar_palette(ui.ctx(), &user))
            .unwrap_or(Color32::from_rgb(0x1e, 0x1f, 0x22));
        ui.painter().rect_filled(banner, top, banner_color);
        // (Not clickable: Discord's banners open nothing, on any card.)
        if let Some(url) = profile.and_then(|p| p.banner_url()) {
            super::paint_cover(ui, banner, &super::anim(&url), top);
        }
        // Round buttons in the banner's corner: Friend / Add Friend (other
        // people's small cards) and More (copy ID / username).
        // (The full profile has its buttons under the badges instead.)
        if kind != CardKind::Full && kind != CardKind::Account {
            let (top, right) = if kind == CardKind::Panel { (slot.top() + 10.0, slot.right() - 10.0) } else { (slot.top() + 8.0, slot.right() - 12.0) };
            let more = Rect::from_min_size(pos2(right - 32.0, top), vec2(32.0, 32.0));
            // (Apps can't be friends: theirs has "More" alone.)
            if !is_me && !user.bot {
                let friend = Rect::from_min_size(pos2(more.left() - 40.0, top), vec2(32.0, 32.0));
                self.friend_button(ui, friend, user.id, kind, &mut out);
            }
            // (Discord's menu opens beside the button, 8 px away.)
            if banner_button(ui, more, egui::Id::new(("profile_more", user.id.0, kind as u8)), Some(icon::MORE), "More").clicked() {
                out.more = Some(pos2(more.right() + 8.0, more.top()));
            }
        }

        // Avatar with ring, status dot and decoration (animated avatars play
        // here). Click to see it full size.
        // Discord: the popout's avatar 16 px in and 61 px down (a theme's
        // 2 px frame widens the card rather than moving what's in it), the
        // DM panel's 59 px down and 18 px in.
        let av_min = match kind {
            CardKind::Full => slot.min + vec2(32.0, 80.0),
            CardKind::Panel => slot.min + vec2(18.0, 59.0),
            // Your account card (Vesktop, 2026-11-22): 16 px in, 60 px down.
            CardKind::Account => slot.min + vec2(16.0, 60.0),
            CardKind::Popout => slot.min + vec2(16.0, 61.0),
        };
        let av = Rect::from_min_size(av_min, vec2(av_size, av_size));
        ui.painter().circle_filled(av.center(), av_size / 2.0 + 6.0, bg);
        paint_avatar(ui, av, Some(super::anim(&user.avatar_animated(160))), user.display_name());
        // Like Discord: in a small card the avatar opens the full profile;
        // in the full profile it shows the picture.
        let av_resp = ui.interact(av, egui::Id::new(("avatar_zoom", user.id.0, expandable, kind as u8)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        if expandable && av_resp.hovered() {
            // Discord dims the avatar under the pointer (black 40 %).
            ui.painter().circle_filled(av.center(), av_size / 2.0, Color32::from_black_alpha(102));
        }
        if av_resp.clicked() {
            if expandable {
                out.expand = true;
            } else {
                let big = user.avatar_animated(1024);
                out.view = Some(crate::features::MediaView { image: big.clone(), video: None, link: big, size: Some((1024.0, 1024.0)) });
            }
        }
        // Profiles always play the decoration, like Discord's.
        if let Some(deco) = super::decoration_uri(&user, true) {
            egui::Image::new(deco).paint_at(ui, av.expand(av.width() * 0.1));
        }
        let dot = av_size * 0.1;
        paint_status_dot(ui, av.right_bottom() - vec2(av_size * 0.15, av_size * 0.15), dot, self.store.dot_status(user.id), bg);

        // Custom status: Discord's thought bubble beside the avatar (the
        // highest surface, 16 px corners, a 20 px and a 10 px circle rising
        // from its corner; two lines at most). Yours opens the "Set a custom
        // status" dialog (or offers to add one).
        let status = self.custom_status_of(user.id).filter(|(e, t)| e.is_some() || !t.is_empty());
        if status.is_some() || is_me {
            let themed = self.theme_colors(user.id, guild).is_some();
            let inner = slot.min + vec2(inset, inset);
            // Where Discord puts it, and how wide it may get.
            let (left, top, widest) = match kind {
                CardKind::Popout => (inner.x + 105.0, inner.y + BANNER_H - 7.0, 181.0),
                CardKind::Panel => (inner.x + 109.0, inner.y + BANNER_H - 7.0, 181.0),
                CardKind::Full => (slot.left() + 172.0, slot.top() + FULL_BANNER_H - 8.0, w - 172.0 - 16.0),
                CardKind::Account => (av.right() + 14.0, banner.bottom() - 10.0, w - av_size - 46.0),
            };
            let hovered = is_me && ui.rect_contains_pointer(Rect::from_min_size(pos2(left, top), vec2(widest, 36.0)));
            let said = status.as_ref().map(|(_, text)| text.clone());
            let (emoji, text, color) = match status {
                Some((e, text)) => (e, text, t.text_normal),
                None => (None, "Add Status".to_string(), if hovered { t.text_normal } else { t.text_muted }),
            };
            // An emoji alone is 32 px; beside text it is 16 px and 4 px away.
            let emoji_w = match (&emoji, text.is_empty()) {
                (Some(_), true) => 32.0,
                (Some(_), false) => 20.0,
                (None, _) => 0.0,
            };
            let mut job = egui::text::LayoutJob::simple(text, FontId::proportional(14.0), color, (widest - 26.0 - emoji_w).max(40.0));
            job.wrap.max_rows = 2;
            job.wrap.overflow_character = Some('…');
            let galley = ui.painter().layout_job(job);
            let content_h = if emoji_w == 32.0 { 32.0 } else { galley.rows.len().max(1) as f32 * 18.0 };
            let bubble = Rect::from_min_size(pos2(left, top), vec2((galley.size().x + emoji_w + 26.0).clamp(42.0, widest), content_h + 18.0));
            let fill = self.themed_surface(user.id, guild, 0x2c2d32).unwrap_or_else(|| surface_highest(&self.theme));
            let fill = if hovered && ui.rect_contains_pointer(bubble) { fill.lerp_to_gamma(if t.light { Color32::BLACK } else { Color32::WHITE }, 0.04) } else { fill };
            // --border-muted, or --border-strong on a profile theme.
            let edge = Stroke::new(1.0_f32, if themed { crate::style::rgba(150, 150, 159, 112) } else { t.border_subtle });
            let p = ui.painter();
            p.add(Shadow { offset: vec2(0.0, 1.0), blur: 4.0, spread: 0.0, color: Color32::from_black_alpha(36) }.as_shape(bubble, Rounding::same(16.0)));
            p.circle(bubble.min + vec2(2.0, -10.0), 4.5, fill, edge);
            p.rect(bubble.shrink(0.5), 16.0, fill, edge);
            // The larger circle merges into the bubble: its fill covers the
            // bubble's edge, and the bubble's inside covers the rest of it.
            p.circle(bubble.min + vec2(20.0, 2.0), 9.5, fill, edge);
            p.rect_filled(bubble.shrink(1.0), 15.0, fill);
            let (mut x, y) = (bubble.left() + 13.0, bubble.top() + 9.0);
            if let Some(e) = &emoji {
                let px = if emoji_w == 32.0 { 32.0 } else { 16.0 };
                egui::Image::new(e.as_str()).paint_at(ui, Rect::from_min_size(pos2(x, y + (content_h.min(18.0).max(px) - px) / 2.0), vec2(px, px)));
                x += emoji_w;
            }
            ui.painter().galley(pos2(x, y + (content_h - galley.size().y) / 2.0), galley, color);
            if is_me && ui.interact(bubble, egui::Id::new(("status_bubble", user.id.0, kind as u8)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                out.edit_status = true;
            }
            // Someone else's: Discord's React / Reply bar rides the bubble's
            // top-right corner while the pointer is on either (60 × 30, two
            // 26 × 24 buttons).
            if let (false, false, Some(said)) = (is_me, user.bot, said) {
                let bar = Rect::from_min_size(pos2(bubble.right() - 68.0, bubble.top() - 16.0), vec2(60.0, 30.0));
                if ui.rect_contains_pointer(bubble.union(bar)) {
                    ui.painter().rect(bar.shrink(0.5), 15.0, fill, edge);
                    for (i, (glyph, tip)) in [(icon::EMOJI, "React to status"), (icon::REPLY, "Reply to status")].into_iter().enumerate() {
                        let cell = Rect::from_min_size(pos2(bar.left() + 3.0 + i as f32 * 28.0, bar.top() + 3.0), vec2(26.0, 24.0));
                        let resp = ui.interact(cell, egui::Id::new(("status_bar", user.id.0, kind as u8, i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                        if resp.hovered() {
                            ui.painter().rect_filled(cell, 8.0, overlay(0.16));
                        }
                        super::paint_icon(ui.painter(), Rect::from_center_size(cell.center(), vec2(16.0, 16.0)), glyph, t.header_primary);
                        if resp.on_hover_text(tip).clicked() {
                            if i == 0 {
                                out.status_react = Some((cell.left_bottom(), said.clone()));
                            } else {
                                out.status_reply = Some(said.clone());
                            }
                        }
                    }
                }
            }
        }
        // Discord: the name's line 91 px under the popout avatar's top (the
        // 140 px header, 8 px, the body's 4 px), 140 in the full profile.
        let name_drop = match kind {
            CardKind::Account => 93.0,
            CardKind::Full => 140.0,
            // (The DM panel: 95 px, its header being 144 px.)
            CardKind::Panel => 95.0,
            CardKind::Popout => 91.0,
        };
        ui.add_space((av.top() + name_drop - ui.cursor().top()).max(0.0));

        // Body padding: 16 px (+ the card's) in the small cards, 32 / 24 in
        // the full profile.
        let (pad_l, pad_r) = if expandable { (16.0 + inset, 16.0 + inset) } else { (32.0, 24.0) };
        // (The full profile's sections continue below the card: no bottom margin.)
        let pad_b = match kind {
            CardKind::Account => 0.0,
            CardKind::Full => 0.0,
            // (12 px under the footer, the card's 4 px, a theme's frame.)
            CardKind::Popout => 16.0 + inset,
            CardKind::Panel => 16.0,
        };
        Frame::none().inner_margin(Margin { left: pad_l, right: pad_r, top: 0.0, bottom: pad_b }).show(ui, |ui| {
            ui.set_width(w - pad_l - pad_r);
            ui.spacing_mut().item_spacing.y = 0.0;
            // Everything between the header and the message box.
            let mut sections = |ui: &mut Ui| {
            let display = member.as_ref().and_then(|m| m.nick.clone()).unwrap_or_else(|| user.display_name().to_string());
            let name_h = match kind {
                CardKind::Full => 32.0,
                CardKind::Account => 22.0,
                _ => 24.0,
            };
            let (name_rect, _) = ui.allocate_exact_size(vec2(w - pad_l - pad_r, name_h), Sense::hover());
            let name_font = FontId::new(if expandable { 20.0 } else { 24.0 }, egui::FontFamily::Name(crate::style::BOLD.into()));
            // (A pixel above centre on the small cards: where Chrome sets a
            // 20 px line of gg sans in its 24 px box.)
            let lift = if expandable && kind != CardKind::Account { 1.0 } else { 0.0 };
            let drawn = super::paint_styled_name(&ui.painter_at(name_rect), name_rect.left_center() - vec2(0.0, lift), Align2::LEFT_CENTER, &display, name_font, &user, t.header_primary);
            let small = expandable && kind != CardKind::Account;
            // Like Discord: on a small card the name (underlined under the
            // pointer) and the username open the full profile.
            if small {
                let resp = ui.interact(drawn, egui::Id::new(("profile_name", user.id.0, kind as u8)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                if resp.hovered() {
                    ui.painter().hline(drawn.x_range(), drawn.bottom() - 2.0, Stroke::new(1.5_f32, t.header_primary));
                }
                out.expand |= resp.clicked();
            }
            // An app's "APP" tag sits beside its name.
            let mut beside = drawn.right() + 4.0;
            if kind != CardKind::Account {
                if let Some(right) = super::paint_bot_badge(ui.painter(), beside, name_rect.center().y, &user, t) {
                    beside = right + 4.0;
                }
            }
            // Discord's note button (web module 243166) sits beside the name
            // while the pointer is on the profile: a paper with a plus, or
            // without one when you've written a note (which its tooltip
            // shows); it opens the full profile at the note.
            let note = Rect::from_min_size(pos2(beside, name_rect.center().y - 12.0), vec2(24.0, 24.0));
            let on_card = ui.ctx().pointer_hover_pos().is_some_and(|p| ui.clip_rect().contains(p) && ui.ctx().layer_id_at(p) == Some(ui.layer_id()));
            if small && !is_me && !user.bot && note.right() <= name_rect.right() && on_card {
                let written = match self.api_results.get(&format!("note:{}", user.id)) {
                    Some(Ok(v)) => v["note"].as_str().filter(|n| !n.is_empty()).map(str::to_string),
                    _ => None,
                };
                let resp = ui.interact(note, egui::Id::new(("profile_add_note", user.id.0, kind as u8)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                let (uri, svg) = if written.is_some() { ("bytes://paper.svg", PAPER_SVG) } else { ("bytes://paper-plus.svg", PAPER_PLUS_SVG) };
                let tint = if resp.hovered() { t.header_primary } else { t.interactive_normal };
                egui::Image::new(egui::ImageSource::Bytes { uri: uri.into(), bytes: egui::load::Bytes::Static(svg.as_bytes()) })
                    .tint(tint)
                    .paint_at(ui, Rect::from_center_size(note.center(), vec2(16.0, 16.0)));
                let tip = written.unwrap_or_else(|| "Add Note (only visible to you)".into());
                out.note_focus |= resp.on_hover_text(tip).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
            }
            // Server tag chip + badges chip.
            // Like Discord: six badges, then "+N" (hover lists the rest).
            const SHOWN: usize = 6;
            let badges: Vec<_> = profile.map(|p| p.badges.iter().chain(p.guild_badges.iter()).cloned().collect()).unwrap_or_default();
            // The badge API's list is drawn with its own icons, other pictures
            // than the profile's: the profile's stay until those have loaded,
            // so the row doesn't go blank when the list arrives.
            let rich_badges: Option<Vec<super::badges::BadgeInfo>> = if badges.is_empty() {
                None
            } else {
                self.badges_of(user.id)
                    .map(|all| all.into_iter().filter(|b| b.owned && !b.hidden).collect::<Vec<_>>())
                    .filter(|rich| super::badges::icons_loaded(ui.ctx(), rich.iter().take(SHOWN), vec2(20.0, 20.0)))
            };
            // RustCord's own badge (from its registry), after Discord's.
            let rustcord = if user.bot || user.system { None } else { self.rustcord_member(user.id) };
            let tag = user.server_tag();
            // Your own full profile: a ▾ to choose which server's tag you wear.
            let pick_tag = is_me && !expandable;
            let badge_count = rich_badges.as_ref().filter(|r| !r.is_empty()).map_or(badges.len(), |r| r.len());
            // Discord's badge chip: --background-mod-subtle with a faint edge,
            // 8 px corners, 20 px badges 2 px apart (an app's have no chip).
            // The chips' 1 px edge is Discord's --border-muted: plain to see on
            // a plain card, faint on a profile theme (which is on Discord's
            // dark theme, where that border nearly vanishes).
            let chip_edge = if self.theme_colors(user.id, guild).is_some() { crate::style::rgba(151, 151, 159, 10) } else { crate::style::rgba(151, 151, 159, 41) };
            let badge_frame = if user.bot {
                Frame::none().inner_margin(Margin::symmetric(0.0, 2.0))
            } else {
                Frame::none().fill(overlay(0.12)).stroke(Stroke::new(1.0_f32, chip_edge)).rounding(8.0).inner_margin(Margin { left: 4.0, right: 4.0, top: 2.0, bottom: 2.0 })
            };
            let badges_w = {
                let n = badge_count.min(SHOWN) as f32;
                let more = if badge_count > SHOWN { 22.0 } else { 0.0 };
                let own = if rustcord.is_some() { 26.0 } else { 0.0 };
                (n * 22.0 - 2.0).max(0.0) + more + own + if user.bot { 0.0 } else { 10.0 }
            };
            if user.bot && small {
                ui.add_space(8.0);
            }
            // Username, pronouns, server tag and badges share one wrapping
            // row, as in Discord (6 px apart; rows 2 px apart, 4 in the full
            // profile): a short name has its tag and badges beside it.
            {
                ui.horizontal_wrapped(|ui| {
                    // (Discord's gap: 6 px with pronouns in the row, 9.33 without.)
                    let pronouns = profile.and_then(|p| p.pronouns());
                    let apart = if pronouns.is_some() || kind == CardKind::Account { 6.0 } else { 9.33 };
                    ui.spacing_mut().item_spacing = vec2(apart, match kind {
                        CardKind::Full => 4.0,
                        CardKind::Account => 3.0,
                        _ => 2.0,
                    });
                    let text = |ui: &mut Ui, s: String, after: f32| -> egui::Response {
                        let mut job = egui::text::LayoutJob::simple_singleline(s, FontId::proportional(14.0), t.header_primary);
                        job.wrap = egui::text::TextWrapping::truncate_at_width(ui.max_rect().width() - after);
                        let g = ui.painter().layout_job(job);
                        let (r, resp) = ui.allocate_exact_size(vec2(g.size().x + after, 24.0), Sense::hover());
                        ui.painter().galley(pos2(r.left(), r.center().y - g.size().y / 2.0), g, t.header_primary);
                        resp
                    };
                    // Apps still have a discriminator: "Arcane#7800".
                    let handle = match user.discriminator.as_deref().filter(|d| user.bot && *d != "0" && !d.is_empty()) {
                        Some(d) => format!("{}#{d}", user.username),
                        None => user.username.clone(),
                    };
                    let username = text(ui, handle, 0.0);
                    if small {
                        out.expand |= ui.interact(username.rect, egui::Id::new(("profile_username", user.id.0, kind as u8)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                    }
                    if let Some(pr) = pronouns {
                        // (Discord's 4 px dot, in the text colour.)
                        let (d, _) = ui.allocate_exact_size(vec2(6.0, 24.0), Sense::hover());
                        ui.painter().circle_filled(d.center(), 2.0, t.header_primary);
                        text(ui, pr.to_string(), 2.0).on_hover_text("Pronouns");
                    }
                    // (Your account card keeps its chips on their own row.)
                    if kind == CardKind::Account && (tag.is_some() || !badges.is_empty() || rustcord.is_some() || user.bot || user.system) {
                        ui.end_row();
                    }
                    if let Some((tag, badge)) = tag {
                        if let (Some(pos), Some(g)) = (self.profile_tag_chip(ui, t, &tag, badge, chip_edge), user.server_tag_guild()) {
                            out.tag = Some((g, pos));
                        }
                    }
                    if pick_tag {
                        let (r, resp) = ui.allocate_exact_size(vec2(22.0, 20.0), Sense::click());
                        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                        if resp.hovered() || self.tag_picker.is_some() {
                            ui.painter().rect_filled(r, 4.0, overlay(0.16));
                        }
                        let label = if user.server_tag().is_some() { icon::CHEVRON_DOWN } else { icon::ADD };
                        ui.painter().text(r.center(), Align2::CENTER_CENTER, label, icon_font(10.0), t.interactive_normal);
                        if resp.on_hover_text("Server tag").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            out.tag_picker = Some(r.left_bottom());
                        }
                    }
                    if kind == CardKind::Account {
                        super::bot_badge(ui, t, &user);
                    }
                    if !badges.is_empty() || rustcord.is_some() {
                        // (A frame doesn't wrap by itself: start the next row when it won't fit.)
                        if ui.cursor().left() > ui.max_rect().left() + 1.0 && ui.available_size_before_wrap().x < badges_w {
                            ui.end_row();
                        }
                        let rustcord_badge = |ui: &mut Ui| {
                            if let Some(m) = &rustcord {
                                if ui.cursor().left() > ui.max_rect().left() + 1.0 {
                                    ui.add_space(4.0);
                                }
                                let r = ui.add(egui::Image::new(super::badges::rustcord_icon()).fit_to_exact_size(vec2(20.0, 20.0)).rounding(5.0).sense(Sense::hover()));
                                r.on_hover_ui(|ui| super::badges::rustcord_tooltip(ui, t, m));
                            }
                        };
                        // (Discord's chip starts 1 px left of what's in the row.)
                        if !user.bot {
                            ui.add_space(-1.0);
                        }
                        badge_frame.show(ui, |ui| {
                            ui.horizontal(|ui| {
                                ui.spacing_mut().item_spacing.x = 2.0;
                                // Discord's badge API (tiers, "Nitro Platinum. Subscriber since …"
                                // tooltips, your shown / hidden choice), once it's loaded.
                                if let Some(rich) = rich_badges.as_ref().filter(|r| !r.is_empty()) {
                                    for b in rich.iter().take(SHOWN) {
                                        let Some(icon) = b.small_icon() else { continue };
                                        let r = ui.add(egui::Image::new(icon).fit_to_exact_size(vec2(20.0, 20.0)).sense(Sense::click()));
                                        if r.hovered() {
                                            super::badges::tooltip_above(ui, r.rect, t, b);
                                        }
                                        let r = r.on_hover_cursor(egui::CursorIcon::PointingHand);
                                        if r.clicked() && is_me {
                                            // (Discord opens "Your badges" on the one clicked.)
                                            ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("badge_window_sel"), b.id));
                                            out.badges = Some((badges.clone(), 0));
                                        }
                                    }
                                    if rich.len() > SHOWN {
                                        let r = more_badges(ui, t, rich.len() - SHOWN);
                                        let r = r.on_hover_ui(|ui| {
                                            ui.spacing_mut().item_spacing.y = 6.0;
                                            for b in &rich[SHOWN..] {
                                                super::badges::tooltip_row(ui, t, b);
                                            }
                                        });
                                        if is_me && r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                            out.badges = Some((badges.clone(), 0));
                                        }
                                    }
                                    rustcord_badge(ui);
                                    return;
                                }
                                for (i, b) in badges.iter().take(SHOWN).enumerate() {
                                    let r = ui.add(egui::Image::new(b.icon_url()).fit_to_exact_size(vec2(20.0, 20.0)).sense(Sense::click()));
                                    let r = r.on_hover_ui(|ui| badge_tooltip(ui, t, b)).on_hover_cursor(egui::CursorIcon::PointingHand);
                                    if r.clicked() {
                                        // Yours open Discord's "Your badges" window; others' open their link.
                                        if is_me {
                                            out.badges = Some((badges.clone(), i));
                                        } else if let Some(link) = &b.link {
                                            ui.ctx().open_url(egui::OpenUrl::new_tab(link));
                                        }
                                    }
                                }
                                if badges.len() > SHOWN {
                                    // Discord: "+N" lists the rest, each with its icon; yours opens the badge window.
                                    let r = more_badges(ui, t, badges.len() - SHOWN);
                                    let r = r.on_hover_ui(|ui| {
                                        ui.spacing_mut().item_spacing.y = 6.0;
                                        for b in &badges[SHOWN..] {
                                            ui.horizontal(|ui| {
                                                ui.add(egui::Image::new(b.icon_url()).fit_to_exact_size(vec2(18.0, 18.0)));
                                                ui.label(RichText::new(&b.description).size(13.0).color(t.header_primary));
                                            });
                                        }
                                    });
                                    if is_me && r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                        out.badges = Some((badges.clone(), SHOWN));
                                    }
                                }
                                rustcord_badge(ui);
                            });
                        });
                    }
                });
            }

            match data {
                // Still loading: Discord's placeholder lines where the rest will be.
                None if profile.is_none() => {
                    ui.add_space(12.0);
                    for part in [0.62, 0.9, 0.74] {
                        let (r, _) = ui.allocate_exact_size(vec2(ui.available_width() * part, 12.0), Sense::hover());
                        ui.painter().rect_filled(r, 6.0, overlay(0.1));
                        ui.add_space(8.0);
                    }
                }
                None => {}
                Some(Err(e)) => {
                    ui.label(RichText::new(format!("Couldn't load the full profile: {e}")).size(12.0).color(t.text_muted));
                }
                Some(Ok(_)) => {}
            }

            // The full profile: Message, Friend and More under the badges.
            if kind == CardKind::Full && !is_me {
                ui.add_space(24.0);
                ui.horizontal(|ui| {
                    ui.spacing_mut().item_spacing.x = 8.0;
                    let stranger = self.store.relationships.get(&user.id).is_none_or(|r| r.kind == 0);
                    // A primary button: 12 px in, a 16 px icon, 4 px, 14 px medium.
                    let primary = |ui: &mut Ui, glyph: &str, text: &str| -> egui::Response {
                        let label = ui.painter().layout_no_wrap(text.into(), crate::style::medium(14.0), Color32::WHITE);
                        let (r, resp) = ui.allocate_exact_size(vec2(12.0 + 16.0 + 4.0 + label.size().x + 12.0, 32.0), Sense::click());
                        // Brand, or the theme's own button colour (darker under the pointer).
                        let brand = self.theme_colors(user.id, guild).map_or(Color32::from_rgb(0x58, 0x65, 0xf2), |(primary, _)| theme::button_color(primary));
                        let fill = if resp.hovered() { brand.lerp_to_gamma(Color32::BLACK, 0.19) } else { brand };
                        ui.painter().rect(r, 8.0, fill, Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
                        let slot = Rect::from_center_size(pos2(r.left() + 20.0, r.center().y), vec2(16.0, 16.0));
                        if glyph == icon::MESSAGE {
                            egui::Image::new(egui::ImageSource::Bytes { uri: "bytes://chat.svg".into(), bytes: egui::load::Bytes::Static(CHAT_SVG.as_bytes()) }).paint_at(ui, slot);
                        } else {
                            super::paint_icon(ui.painter(), slot, glyph, Color32::WHITE);
                        }
                        ui.painter().galley(pos2(r.left() + 32.0, r.center().y - label.size().y / 2.0), label, Color32::WHITE);
                        resp.on_hover_cursor(egui::CursorIcon::PointingHand)
                    };
                    if stranger {
                        if primary(ui, icon::USER_PLUS, "Add Friend").clicked() {
                            out.friend = Some(true);
                        }
                        let (mr, _) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::hover());
                        out.message |= card_button(ui, mr, egui::Id::new(("profile_message_full", user.id.0)), Some(icon::MESSAGE), "Message", false).clicked();
                    } else {
                        out.message |= primary(ui, icon::MESSAGE, "Message").clicked();
                        let (fr, _) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::hover());
                        self.friend_button(ui, fr, user.id, kind, &mut out);
                    }
                    let (mr, _) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::hover());
                    if card_button(ui, mr, egui::Id::new(("profile_more_full", user.id.0)), Some(icon::MORE), "More", false).clicked() {
                        out.more = Some(pos2(mr.right() + 8.0, mr.top()));
                    }
                });
            }

            // "1 Mutual Friend • 6 Mutual Servers" under the badges.
            if expandable && !is_me {
                if let Some(p) = profile {
                    let friends = p.mutual_friends_count.map_or(p.mutual_friends.len(), |n| n as usize);
                    let servers = p.mutual_guilds.len();
                    if friends > 0 || servers > 0 {
                        ui.add_space(if kind == CardKind::Panel { 8.0 } else { 12.0 });
                        let guilds: Vec<Id> = p.mutual_guilds.iter().map(|g| g.id).collect();
                        if let Some(tab) = self.mutuals_row(ui, &p.mutual_friends, &guilds, friends, servers, bg) {
                            out.mutual_tab = Some(tab);
                        }
                    }
                }
            }

            // An app's popout offers "Add App": Discord's 32 px secondary
            // button (a 16 px plus, 4 px, 14 px medium), to its authorisation page.
            if small && user.bot && !user.system {
                ui.add_space(12.0);
                let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());
                ui.painter().rect(r.shrink(0.5), 8.0, overlay(if resp.hovered() { 0.2 } else { 0.12 }), Stroke::new(1.0_f32, t.border_subtle));
                let label = ui.painter().layout_no_wrap("Add App".into(), crate::style::medium(14.0), t.header_primary);
                let x = r.center().x - (20.0 + label.size().x) / 2.0;
                super::paint_icon(ui.painter(), Rect::from_min_size(pos2(x, r.center().y - 8.0), vec2(16.0, 16.0)), icon::ADD, t.header_primary);
                ui.painter().galley(pos2(x + 20.0, r.center().y - label.size().y / 2.0), label, t.header_primary);
                if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                    ui.ctx().open_url(egui::OpenUrl::new_tab(format!("https://discord.com/oauth2/authorize?client_id={}", user.id)));
                }
            }

            if let Some(bio) = profile.and_then(|p| p.bio()) {
                if expandable {
                    // Three lines, then "View Full Bio" (the full profile).
                    ui.add_space(match kind {
                        CardKind::Panel => 20.0,
                        CardKind::Account => 7.0,
                        _ => 12.0,
                    });
                    out.expand |= self.clamped_bio(ui, t, guild, bio, actions);
                } else {
                    ui.add_space(24.0);
                    let fake = Message { guild_id: guild, ..Default::default() };
                    self.render_bio(ui, &fake, bio, t.text_normal, actions);
                }
            }

            // Game Collection: favourite / played games as icons, three then "+N".
            // An app's commands, a few as buttons like Discord's (from the
            // command list of where you are, once it has arrived): clicking
            // one starts it in the message box.
            if small && user.bot {
                let commands = self.app_command_names(user.id, guild);
                if !commands.is_empty() {
                    ui.add_space(12.0);
                    let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 16.0), Sense::hover());
                    ui.painter().text(r.left_center(), Align2::LEFT_CENTER, "Commands", FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.header_primary);
                    ui.add_space(8.0);
                    ui.horizontal_wrapped(|ui| {
                        ui.spacing_mut().item_spacing = vec2(6.0, 6.0);
                        for name in commands.iter().take(4) {
                            let label = ui.painter().layout_no_wrap(format!("/{name}"), crate::style::medium(14.0), t.header_primary);
                            let (r, resp) = ui.allocate_exact_size(vec2((label.size().x + 24.0).min(ui.max_rect().width()), 32.0), Sense::click());
                            ui.painter().rect(r.shrink(0.5), 8.0, overlay(if resp.hovered() { 0.2 } else { 0.12 }), Stroke::new(1.0_f32, t.border_subtle));
                            ui.painter_at(r).galley(pos2(r.left() + 12.0, r.center().y - label.size().y / 2.0), label, t.header_primary);
                            if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                out.command = Some(name.clone());
                            }
                        }
                    });
                }
            }
            // The DM panel has "Member Since" here (the popouts don't have it;
            // the full profile's is further down).
            if kind == CardKind::Panel {
                ui.add_space(20.0);
                let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 16.0), Sense::hover());
                ui.painter().text(r.left_center(), Align2::LEFT_CENTER, "Member Since", FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.header_primary);
                ui.add_space(8.0);
                value(ui, t, &short_date(user.id.timestamp_ms()));
            }
            let games = profile.map(|p| p.game_ids()).unwrap_or_default();
            if !games.is_empty() && small {
                // (12 px apart in a popout; the panel's sections are 20 apart
                // and its label a size larger.)
                let panel = kind == CardKind::Panel;
                ui.add_space(if panel { 20.0 } else { 12.0 });
                out.board |= self.game_collection(ui, t, &games, self.theme_colors(user.id, guild).is_some(), if panel { 14.0 } else { 12.0 });
            }
            // (Your account card's own layout; the full profile has the Board instead.)
            if !games.is_empty() && kind == CardKind::Account {
                let account = true;
                let (shown, icon_px, label_px) = if account { (4, 24.0, 12.0) } else { (3, 28.0, 13.0) };
                ui.add_space(if account { 12.0 } else { 10.0 });
                let hovered_id = egui::Id::new(("game_collection_hover", user.id.0, expandable));
                let lit = expandable && ui.data(|d| d.get_temp::<bool>(hovered_id).unwrap_or(false));
                let margin = if account { Margin::symmetric(8.0, 7.5) } else { Margin::symmetric(10.0, 8.0) };
                let gc = Frame::none().fill(overlay(if lit { 0.18 } else { 0.12 })).rounding(8.0).inner_margin(margin).show(ui, |ui| {
                    ui.set_width(ui.available_width());
                    ui.horizontal(|ui| {
                        ui.label(bold("Game Collection").size(label_px).color(t.header_primary));
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            ui.spacing_mut().item_spacing.x = 4.0;
                            if games.len() > shown {
                                let rest: Vec<String> = games[shown..].iter().map(|g| self.apps.get(g).map(|a| a.name.clone()).unwrap_or_default()).collect();
                                let (r, resp) = ui.allocate_exact_size(vec2(icon_px, icon_px), Sense::hover());
                                ui.painter().rect_filled(r, 6.0, overlay(0.2));
                                ui.painter().text(r.center(), Align2::CENTER_CENTER, format!("+{}", games.len() - shown), FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.header_primary);
                                resp.on_hover_text(rest.join("\n"));
                            }
                            // Right-to-left: draw the first ones in reverse so they read left→right.
                            for g in games.iter().take(shown).rev() {
                                let (r, resp) = ui.allocate_exact_size(vec2(icon_px, icon_px), Sense::hover());
                                match self.apps.get(g) {
                                    Some(app) => {
                                        match app.icon_url() {
                                            Some(u) => {
                                                egui::Image::new(u).rounding(6.0).paint_at(ui, r);
                                            }
                                            None => {
                                                ui.painter().rect_filled(r, 6.0, overlay(0.2));
                                                ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::GAME, icon_font(14.0), t.interactive_normal);
                                            }
                                        }
                                        resp.on_hover_text(&app.name);
                                    }
                                    None => {
                                        ui.painter().rect_filled(r, 6.0, overlay(0.2));
                                        self.apps_wanted.borrow_mut().insert(*g);
                                    }
                                }
                            }
                            for g in games.iter().skip(shown) {
                                if !self.apps.contains_key(g) {
                                    self.apps_wanted.borrow_mut().insert(*g);
                                }
                            }
                        });
                    });
                });
                // Like Discord: in a small card it opens the full profile's Board.
                if expandable {
                    let r = ui.interact(gc.response.rect, hovered_id.with("click"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                    ui.data_mut(|d| d.insert_temp(hovered_id, r.hovered()));
                    out.board |= r.clicked();
                }
            }

            // What they're doing right now (Discord's popout shows the first
            // activity: a song with its progress, a game…).
            if expandable {
                let acts = self.store.presences.get(&user.id).map(|p| p.activities.iter().filter(|a| a.kind != 4).cloned().collect::<Vec<_>>()).unwrap_or_default();
                if let Some(a) = acts.first() {
                    ui.add_space(10.0);
                    out.listen_along |= self.activity_card(ui, a, user.id, true);
                }
            }

            // "Member Since" is in Discord's DM side panel, not the popouts.
            // Discord's full profile: the Discord logo + date, then the
            // server's icon + the date they joined it.
            if kind == CardKind::Full && guild.is_none() {
                // Discord's full profile: a 12 px medium header, the date under it.
                ui.add_space(24.0);
                heading(ui, t, "Member Since");
                ui.add_space(8.0);
                value(ui, t, &short_date(user.id.timestamp_ms()));
            } else if kind == CardKind::Full {
                // In a server: Discord's logo + date, the server's icon + when they joined.
                ui.add_space(24.0);
                heading(ui, t, "Member Since");
                ui.add_space(8.0);
                ui.horizontal(|ui| {
                    ui.spacing_mut().item_spacing.x = 4.0;
                    let (logo, lr) = ui.allocate_exact_size(vec2(16.0, 18.0), Sense::hover());
                    egui::Image::new(super::brand_icons::discord_logo(0xdbdee1)).paint_at(ui, Rect::from_center_size(logo.center(), vec2(16.0, 16.0)));
                    lr.on_hover_text("Discord");
                    ui.label(RichText::new(short_date(user.id.timestamp_ms())).size(14.0).color(t.text_normal));
                    let joined = member.as_ref().and_then(|m| m.joined_at.as_deref()).and_then(|j| chrono::DateTime::parse_from_rfc3339(j).ok());
                    if let (Some(d), Some(gs)) = (joined, guild.and_then(|g| self.store.guilds.get(&g))) {
                        // Discord's divider: a 4 px dot in the subtle colour, 8 px either side.
                        ui.add_space(4.0);
                        let (dot, _) = ui.allocate_exact_size(vec2(4.0, 18.0), Sense::hover());
                        ui.painter().circle_filled(dot.center(), 2.0, subtle(t));
                        ui.add_space(4.0);
                        let (icon_r, ir) = ui.allocate_exact_size(vec2(16.0, 18.0), Sense::hover());
                        let icon_r = Rect::from_center_size(icon_r.center(), vec2(16.0, 16.0));
                        match gs.guild.icon_url(32) {
                            Some(u) => egui::Image::new(u).rounding(4.0).paint_at(ui, icon_r),
                            None => {
                                ui.painter().rect_filled(icon_r, 4.0, overlay(0.16));
                                ui.painter().text(icon_r.center(), Align2::CENTER_CENTER, super::acronym(&gs.guild.name).chars().next().unwrap_or(' '), FontId::proportional(9.0), t.text_normal);
                            }
                        }
                        ir.on_hover_text(&gs.guild.name);
                        ui.label(RichText::new(short_date(d.timestamp_millis().max(0) as u64)).size(14.0).color(t.text_normal));
                    }
                });
            }

            // The full profile's Friends Since: after Member Since, before Roles.
            if kind == CardKind::Full {
                let since = self.store.relationships.get(&user.id).filter(|r| r.kind == 1).and_then(|r| r.since.as_deref()).and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok());
                if let Some(since) = since {
                    ui.add_space(24.0);
                    heading(ui, t, "Friends Since");
                    ui.add_space(8.0);
                    value(ui, t, &short_date(since.timestamp_millis().max(0) as u64));
                }
            }

            // Roles: Discord's chips (colour dot, name, role icon), three then
            // "+N"; with Manage Roles, × removes one and + adds one below yours.
            let roles = member.as_ref().map(|m| m.roles.clone()).unwrap_or_default();
            let all_roles: Vec<discord::model::Role> = guild.and_then(|g| self.store.guilds.get(&g)).map(|g| g.guild.roles.clone()).unwrap_or_default();
            let mut guild_roles: Vec<_> = all_roles.iter().filter(|r| roles.contains(&r.id)).cloned().collect();
            guild_roles.sort_by_key(|r| std::cmp::Reverse(r.position));
            let manage = guild.filter(|g| self.store.has_perm(*g, discord::model::permissions::MANAGE_ROLES));
            let top = guild.map(|g| self.store.my_top_role(g)).unwrap_or(0);
            let can_edit = |r: &discord::model::Role| manage.is_some() && !r.managed && (r.position as i64) < top;
            if member.is_some() && (!guild_roles.is_empty() || manage.is_some()) {
                // Discord: a person's popout lists them without a heading;
                // an app's and the full profile say "Roles".
                if kind == CardKind::Full {
                    ui.add_space(24.0);
                    heading(ui, t, "Roles");
                    ui.add_space(6.0);
                } else if user.bot {
                    ui.add_space(12.0);
                    ui.label(bold("Roles").size(12.0).color(t.header_primary));
                    ui.add_space(10.0);
                } else {
                    ui.add_space(14.0);
                }
                let open_id = egui::Id::new(("roles_open", user.id.0, guild.map(|g| g.0)));
                let adding_id = egui::Id::new(("roles_adding", user.id.0, guild.map(|g| g.0)));
                let show_all = !expandable || ui.data(|d| d.get_temp::<bool>(open_id).unwrap_or(false));
                let mut adding = ui.data(|d| d.get_temp::<bool>(adding_id).unwrap_or(false));
                // The pills' 1 px edge: white 8 % on a profile theme.
                let edge = if self.theme_colors(user.id, guild).is_some() { crate::style::rgba(255, 255, 255, 20) } else { t.border_subtle };
                ui.horizontal_wrapped(|ui| {
                    ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
                    let shown = if show_all { guild_roles.len() } else { 3 };
                    for r in guild_roles.iter().take(shown) {
                        if role_chip(ui, t, r, can_edit(r), user.id, edge) {
                            if let Some(g) = guild {
                                out.role_change = Some((g, r.id, false));
                            }
                        }
                    }
                    // "+N" and "+": the same pill, the text in the subtle colour.
                    let pill = |ui: &mut Ui, text: &str, tip: &str| -> bool {
                        let galley = ui.painter().layout_no_wrap(text.to_string(), FontId::proportional(12.0), subtle(t));
                        let (rect, resp) = ui.allocate_exact_size(vec2(galley.size().x + 16.0, 24.0), Sense::click());
                        let fill = if resp.hovered() { overlay(0.12) } else { Color32::TRANSPARENT };
                        ui.painter().rect(rect.shrink(0.5), 8.0, fill, Stroke::new(1.0_f32, edge));
                        ui.painter().galley(pos2(rect.left() + 7.0, rect.center().y - galley.size().y / 2.0), galley, subtle(t));
                        resp.on_hover_text(tip).on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
                    };
                    if guild_roles.len() > 3 && !show_all && pill(ui, &format!("+{}", guild_roles.len() - 3), "Show all roles") {
                        ui.data_mut(|d| d.insert_temp(open_id, true));
                    }
                    // Add: a bare 24 px plus, no pill around it.
                    if manage.is_some() {
                        let (slot, resp) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click());
                        ui.painter().text(slot.center(), Align2::CENTER_CENTER, icon::ADD, icon_font(11.0), if resp.hovered() { t.header_primary } else { t.interactive_normal });
                        if resp.on_hover_text("Add Role").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            adding = !adding;
                            ui.data_mut(|d| d.insert_temp(adding_id, adding));
                        }
                    }
                });
                // Role picker: roles they don't have that you can give.
                if adding {
                    let mut options: Vec<&discord::model::Role> =
                        all_roles.iter().filter(|r| !roles.contains(&r.id) && Some(r.id) != guild && can_edit(r)).collect();
                    options.sort_by_key(|r| std::cmp::Reverse(r.position));
                    Frame::none().fill(t.bg_floating).rounding(8.0).stroke(Stroke::new(1.0_f32, t.border_subtle)).inner_margin(4.0).show(ui, |ui| {
                        ui.set_width(ui.available_width());
                        ScrollArea::vertical().max_height(160.0).show(ui, |ui| {
                            if options.is_empty() {
                                ui.label(RichText::new("No roles you can add.").size(13.0).color(t.text_muted));
                            }
                            for r in options {
                                let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 28.0), Sense::click());
                                let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                                if resp.hovered() {
                                    ui.painter().rect_filled(row, 4.0, overlay(0.16));
                                }
                                ui.painter().circle_filled(row.left_center() + vec2(12.0, 0.0), 5.0, if r.color == 0 { t.interactive_normal } else { rgb(r.color) });
                                ui.painter().text(row.left_center() + vec2(24.0, 0.0), Align2::LEFT_CENTER, &r.name, FontId::proportional(13.0), t.text_normal);
                                if resp.clicked() {
                                    if let Some(g) = guild {
                                        out.role_change = Some((g, r.id, true));
                                    }
                                    ui.data_mut(|d| d.insert_temp(adding_id, false));
                                }
                            }
                        });
                    });
                }
            }

            };
            // Like Discord: a popout taller than the window (20 px to spare)
            // scrolls between its header and its message box.
            if kind == CardKind::Popout {
                let room = (ui.ctx().screen_rect().height() - 20.0 - (BANNER_H + 43.0 + inset) - (16.0 + 46.0 + 16.0 + inset)).max(120.0);
                ScrollArea::vertical().id_salt(("profile_popout_body", user.id.0)).max_height(room).auto_shrink([false, true]).show(ui, |ui| sections(ui));
            } else {
                sections(ui);
            }
            if expandable && kind != CardKind::Account {
                ui.add_space(if dm_draft.is_some() { 16.0 } else { 12.0 });
            }
            if is_me {
                // Your own popout has the button; the account menu has a row instead.
                if dm_draft.is_some() {
                    // Themed profiles get a button in the theme's colour, like Discord.
                    let fill = self.card_theme(user.id, guild).map(|(_, _, primary)| primary).unwrap_or(t.accent);
                    // A 32 px primary button: a 16 px pencil, 4 px, 14 px medium.
                    let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());
                    let fill = if resp.hovered() { fill.lerp_to_gamma(Color32::BLACK, 0.19) } else { fill };
                    ui.painter().rect(r.shrink(0.5), 8.0, fill, Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
                    let label = ui.painter().layout_no_wrap("Edit Profile".into(), crate::style::medium(14.0), Color32::WHITE);
                    let x = r.center().x - (20.0 + label.size().x) / 2.0;
                    super::paint_icon(ui.painter(), Rect::from_min_size(pos2(x, r.center().y - 8.0), vec2(16.0, 16.0)), icon::EDIT, Color32::WHITE);
                    ui.painter().galley(pos2(x + 20.0, r.center().y - label.size().y / 2.0), label, Color32::WHITE);
                    out.edit_profile = resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                }
            } else if let Some(draft) = dm_draft {
                let id = egui::Id::new(("profile_dm", user.id.0));
                // ("Reply to status" turns the box into the reply's.)
                let replying = ui.data(|d| d.get_temp::<String>(egui::Id::new(("status_reply", user.id.0)))).is_some();
                // (By the name they go by here: their server nickname, like Discord's.)
                let name = member.as_ref().and_then(|m| m.nick.as_deref()).unwrap_or(user.display_name());
                let hint = if replying { format!("Reply to {name}'s status") } else { format!("Message @{name}") };
                let focused = ui.memory(|m| m.has_focus(id));
                let enter = focused && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter));
                // Discord's box, 8 px corners: black 12 % inside a 1 px edge
                // (46 px), or white 12 % without one on a profile theme
                // (44 px). The text is 15 px inside, the emoji button 12.
                let themed = self.theme_colors(user.id, guild).is_some();
                let edge = if themed { 0.0 } else { 1.0 };
                let (bx, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0 + 2.0 * edge), Sense::hover());
                if themed {
                    ui.painter().rect_filled(bx, 8.0, crate::style::rgba(255, 255, 255, 31));
                } else {
                    ui.painter().rect(bx.shrink(0.5), 8.0, Color32::from_black_alpha(31), Stroke::new(1.0_f32, t.border_subtle));
                }
                let text_rect = Rect::from_min_max(pos2(bx.left() + 15.0 + edge, bx.top() + 1.0), pos2(bx.right() - 48.0, bx.bottom() - 1.0));
                let mut field = ui.new_child(egui::UiBuilder::new().max_rect(text_rect).layout(egui::Layout::left_to_right(egui::Align::Center)));
                field.add(
                    TextEdit::multiline(draft)
                        .id(id)
                        .frame(false)
                        .desired_rows(1)
                        .margin(Margin::ZERO)
                        .font(FontId::proportional(16.0))
                        .desired_width(text_rect.width()),
                );
                // The placeholder (14 px) on the box's middle, like Discord's;
                // egui would set it at the top of the 16 px text's line.
                if draft.is_empty() {
                    let g = ui.painter().layout_no_wrap(hint, FontId::proportional(14.0), t.text_muted);
                    ui.painter().with_clip_rect(text_rect).galley(pos2(text_rect.left(), bx.center().y - g.size().y / 2.0), g, t.text_muted);
                }
                let eb = Rect::from_min_size(pos2(bx.right() - 12.0 - edge - 32.0, bx.center().y - 16.0), vec2(32.0, 32.0));
                let er = ui.interact(eb, id.with("emoji"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                if er.hovered() {
                    ui.painter().rect_filled(eb, 8.0, overlay(0.12));
                }
                ui.painter().text(eb.center(), Align2::CENTER_CENTER, icon::EMOJI, icon_font(18.0), if er.hovered() { t.interactive_hover } else { t.interactive_normal });
                if er.clicked() {
                    ui.memory_mut(|m| m.request_focus(id));
                }
                out.message |= enter;
            }
        });
        out
    }

    /// The full profile's last section, Discord's "Note (only visible to
    /// you)": click to write one. Returns the note to save, once you click
    /// away from a changed one (`PUT /users/@me/notes/{id}`).
    fn note_section(&self, ui: &mut Ui, t: &crate::style::Theme, user: &User, guild: Option<Id>) -> Option<String> {
        ui.add_space(24.0);
        heading(ui, t, "Note (only visible to you)");
        ui.add_space(4.0);
        let saved = match self.api_results.get(&format!("note:{}", user.id)) {
            Some(Ok(v)) => v["note"].as_str().unwrap_or("").to_string(),
            _ => String::new(),
        };
        let nid = egui::Id::new(("profile_note", user.id.0));
        let mut text: String = ui.data(|d| d.get_temp(nid)).unwrap_or_else(|| saved.clone());
        let hint = RichText::new("Click to add a note").font(FontId::new(14.0, egui::FontFamily::Name(crate::style::ITALIC.into()))).color(t.text_muted);
        let te = egui::TextEdit::multiline(&mut text)
            .id(nid.with("edit"))
            .frame(false)
            .desired_rows(1)
            .desired_width(ui.available_width())
            .font(FontId::proportional(14.0))
            .text_color(t.text_normal)
            .hint_text(hint)
            .char_limit(256)
            .margin(vec2(0.0, 0.0))
            .show(ui);
        // Opened by a small card's "Add Note": start writing here.
        let wanted = egui::Id::new("profile_note_focus");
        if ui.data(|d| d.get_temp::<bool>(wanted).unwrap_or(false)) && self.profiles.contains_key(&(user.id, guild)) {
            ui.data_mut(|d| d.remove::<bool>(wanted));
            te.response.request_focus();
            te.response.scroll_to_me(Some(egui::Align::Center));
        }
        if te.response.has_focus() {
            ui.data_mut(|d| d.insert_temp(nid, text));
            return None;
        }
        ui.data_mut(|d| d.remove::<String>(nid));
        (te.response.lost_focus() && text.trim() != saved.trim()).then(|| text.trim().to_string())
    }

    /// Panel on the right of a 1:1 DM, like Discord's user profile sidebar.
    pub fn dm_profile_panel(&mut self, ui: &mut Ui, user: &User) {
        self.want_profile(user.id, None);
        let effect = self.want_profile_effect(user.id, None);
        if Some(user.id) != self.store.me_id() && !user.bot {
            self.api_get_once(&format!("note:{}", user.id), format!("/users/@me/notes/{}", user.id));
        }
        let t = self.theme.clone();
        let bg = self.popout_background(user.id, None);
        // Discord's redesigned sidebar: a card floating 8 px in from the chat
        // (2 px padding inside), "View Full Profile" pinned at its foot.
        let card = ui.max_rect().shrink(8.0);
        ui.painter().add(self.popout_shapes(card, user.id, None));
        let mut actions = Vec::new();
        let mut full_profile = false;
        let mut view = None;
        let mut tag_click = None;
        let (mut board, mut listen) = (false, false);
        let (mut friend, mut mutual_tab, mut more) = (None, None, None);
        let (mut status_react, mut status_reply) = (None, None);
        let footer = Rect::from_min_max(pos2(card.left() + 2.0, card.bottom() - 74.0), card.max - vec2(2.0, 2.0));
        let body = Rect::from_min_max(card.min, pos2(card.right(), footer.top()));
        let mut inner = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::top_down(egui::Align::Min)));
        inner.set_clip_rect(body.intersect(ui.clip_rect()));
        ScrollArea::vertical().auto_shrink([false, false]).show(&mut inner, |ui| {
            ui.spacing_mut().item_spacing.y = 0.0;
            let out = self.profile_card(ui, card.width(), user, None, bg, None, CardKind::Panel, 2.0, &mut actions);
            view = out.view;
            full_profile |= out.expand || out.note_focus;
            if out.note_focus {
                ui.data_mut(|d| d.insert_temp(egui::Id::new("profile_note_focus"), true));
            }
            tag_click = out.tag;
            board |= out.board;
            listen |= out.listen_along;
            friend = out.friend;
            mutual_tab = out.mutual_tab;
            more = out.more;
            status_react = out.status_react;
            status_reply = out.status_reply;
        });
        // (The panel's effect starts over for each person it shows.)
        if let Some(sku) = effect {
            let hovered = ui.rect_contains_pointer(card);
            self.paint_profile_effect(ui, card.shrink(2.0), sku, user.id.0, CardKind::Panel as u8, hovered);
        }
        // 40 px, 16 px in: --background-mod-subtle with a faint edge.
        let button = Rect::from_min_max(footer.min + vec2(16.0, 16.0), footer.max - vec2(16.0, 16.0));
        let resp = ui.interact(button, egui::Id::new(("dm_view_full_profile", user.id.0)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        ui.painter().rect(
            button,
            8.0,
            if resp.hovered() { overlay(0.2) } else { overlay(0.12) },
            Stroke::new(1.0_f32, crate::style::rgba(151, 151, 159, 10)),
        );
        ui.painter().text(button.center(), Align2::CENTER_CENTER, "View Full Profile", crate::style::medium(16.0), t.header_primary);
        full_profile |= resp.clicked();
        for a in actions {
            if let UiAction::Reveal(id, k) = a {
                self.revealed.insert((id, k));
            }
        }
        if let Some(add) = friend {
            self.friend_click(user, add);
        }
        if let Some((at, status)) = status_react {
            self.open_emoji_picker(crate::features::PickerTarget::StatusReact { user: user.id, status }, at);
        }
        if let Some(status) = status_reply {
            self.reply_to_status_in_dm(user.id, &status);
        }
        if let Some(at) = more {
            // (The panel is at the window's edge: the menu opens leftwards.)
            self.toggle_profile_more(user.clone(), None, at - vec2(8.0 + 32.0 + 8.0 + 170.0, 0.0));
        }
        if let Some(tab) = mutual_tab {
            self.open_full_profile_on(user.clone(), None, tab);
        } else if full_profile {
            self.open_full_profile(user.clone(), None);
        }
        if board {
            self.open_full_profile_on(user.clone(), None, TAB_BOARD);
        }
        if listen {
            self.toggle_listen_along(user.id);
        }
        if view.is_some() {
            self.viewer = view;
        }
        if let Some((g, at)) = tag_click {
            self.open_tag_popout(g, at);
        }
    }

    pub fn profile_ui(&mut self, ctx: &egui::Context) {
        let Some(p) = &self.profile else { return };
        let (user, guild, pos, opened) = (p.user.clone(), p.guild, p.pos, p.opened_frame);
        let effect = self.want_profile_effect(user.id, guild);
        if Some(user.id) != self.store.me_id() && !user.bot {
            self.api_get_once(&format!("note:{}", user.id), format!("/users/@me/notes/{}", user.id));
        }
        let bg = self.popout_background(user.id, guild);
        // A menu of the card's that is open now takes this frame's clicks
        // and Escape (even the one that closes it).
        let menu_open = self.profile_more.is_some() || self.remove_friend.is_some() || self.tag_popout.is_some() || ctx.memory(|m| m.any_popup_open());
        let mut draft = self.profile.as_mut().map(|p| std::mem::take(&mut p.dm_draft)).unwrap_or_default();
        let mut actions = Vec::new();
        let mut out = CardOut::default();
        let area = egui::Area::new(egui::Id::new("profile_popout"))
            .order(Order::Foreground)
            .fixed_pos(pos)
            .constrain(true)
            .show(ctx, |ui| {
                // Discord's popout slides 10 px towards what it opened from
                // (the click, left or right of it); again for the next person.
                let leftwards = ctx.input(|i| i.pointer.press_origin()).is_some_and(|click| click.x > pos.x + POPOUT_W / 2.0);
                motion::tag(ui, Motion::Slide(vec2(if leftwards { -10.0 } else { 10.0 }, 0.0)), user.id.0 ^ guild.map_or(0, |g| g.0.rotate_left(1)));
                let bg_slot = ui.painter().add(egui::Shape::Noop);
                let inset = self.popout_inset(user.id, guild);
                let frame = Frame::none().rounding(8.0).show(ui, |ui| {
                    out = self.profile_card(ui, POPOUT_W + 2.0 * inset, &user, guild, bg, Some(&mut draft), CardKind::Popout, inset, &mut actions);
                });
                let rect = frame.response.rect;
                ui.painter().set(bg_slot, with_popout_shadow(self.popout_shapes(rect, user.id, guild), rect));
                // (Inside a profile theme's frame, like Discord's.)
                if let Some(sku) = effect {
                    let hovered = ui.rect_contains_pointer(rect);
                    self.paint_profile_effect(ui, rect.shrink(inset), sku, opened, CardKind::Popout as u8, hovered);
                }
            });
        if out.edit_status {
            self.profile = None;
            self.open_custom_status_dialog();
        }
        if let Some(at) = out.more.take() {
            self.toggle_profile_more(user.clone(), guild, at);
        }
        if let Some((at, status)) = out.status_react.take() {
            self.open_emoji_picker(crate::features::PickerTarget::StatusReact { user: user.id, status }, at);
        }
        if let Some(status) = out.status_reply.take() {
            ctx.data_mut(|d| d.insert_temp(egui::Id::new(("status_reply", user.id.0)), status));
            ctx.memory_mut(|m| m.request_focus(egui::Id::new(("profile_dm", user.id.0))));
        }
        if let Some(name) = out.command.take() {
            if let Some(ch) = self.current_channel {
                *self.drafts.entry(ch).or_default() = format!("/{name} ");
                self.compose.focus_composer = true;
            }
            self.profile = None;
            return;
        }
        // An app's commands come with the server's (or the DM's) command list.
        if user.bot {
            match guild {
                Some(g) => self.api_get_once(&format!("apps:g:{g}"), format!("/guilds/{g}/application-command-index")),
                None => {
                    if let Some(ch) = self.current_channel.filter(|_| self.current_guild.is_none()) {
                        self.api_get_once(&format!("apps:c:{ch}"), format!("/channels/{ch}/application-command-index"));
                    }
                }
            }
        }
        if out.expand || out.note_focus {
            if out.note_focus {
                ctx.data_mut(|d| d.insert_temp(egui::Id::new("profile_note_focus"), true));
            }
            self.profile = None;
            self.open_full_profile(user, guild);
            return;
        }
        if out.board {
            self.profile = None;
            self.open_full_profile_on(user, guild, TAB_BOARD);
            return;
        }
        if out.listen_along {
            self.toggle_listen_along(user.id);
        }
        if let Some(add) = out.friend {
            self.friend_click(&user, add);
        }
        if let Some(tab) = out.mutual_tab {
            self.profile = None;
            self.open_full_profile_on(user, guild, tab);
            return;
        }
        if let Some(v) = out.view.take() {
            self.viewer = Some(v);
            return;
        }
        if let Some((g, at)) = out.tag.take() {
            self.open_tag_popout(g, at);
            return;
        }
        if let Some((g, role, add)) = out.role_change.take() {
            self.backend.send(crate::backend::Command::MemberRole { guild: g, user: user.id, role, add });
        }
        if let Some(b) = out.badges.take() {
            self.profile = None;
            self.badges_view = Some(b);
            return;
        }
        if let Some(p) = self.profile.as_mut() {
            p.dm_draft = draft;
        }
        for a in actions {
            if let UiAction::Reveal(id, k) = a {
                self.revealed.insert((id, k));
            }
        }
        if out.message {
            let reply_id = egui::Id::new(("status_reply", user.id.0));
            let replying = ctx.data(|d| d.get_temp::<String>(reply_id));
            let text = self.profile.as_ref().map(|p| p.dm_draft.trim().to_string()).unwrap_or_default();
            match replying {
                // A reply to their status goes out from here; you stay where you are.
                Some(status) => {
                    if !text.is_empty() {
                        ctx.data_mut(|d| d.remove::<String>(reply_id));
                        if let Some(p) = self.profile.as_mut() {
                            p.dm_draft.clear();
                        }
                        self.status_interaction(user.id, &status, "Replied", &text);
                    }
                }
                None => {
                    if let Some(p) = self.profile.as_mut() {
                        p.dm_draft.clear();
                    }
                    self.open_dm_with(user.id, text);
                }
            }
        } else if out.edit_profile {
            self.profile = None;
            self.settings_open = true;
        } else if !menu_open && self.profile_more.is_none() && ((area.response.clicked_elsewhere() && ctx.cumulative_pass_nr() > opened + 1) || ctx.input(|i| i.key_pressed(Key::Escape))) {
            self.profile = None;
        }
    }

    // ---- removing a friend -----------------------------------------------------

    /// A card's friend button: adding goes out at once; removing asks first.
    fn friend_click(&mut self, user: &User, add: bool) {
        if add {
            self.relationship(user.id, true, "User Profile");
        } else {
            self.remove_friend = Some((user.id, user.username.clone()));
        }
    }

    /// Discord's "Remove 'name'" dialog: Cancel, or the red "Remove Friend".
    pub fn remove_friend_ui(&mut self, ctx: &egui::Context) {
        let Some((user, name)) = self.remove_friend.clone() else { return };
        let t = self.theme.clone();
        const W: f32 = 398.0;
        let mut cancel = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape));
        let mut confirm = false;
        cancel |= super::guild_pages::modal_frame(ctx, &t, "remove_friend", W, |ui| {
            // "Are you sure you want to remove **name** from your friends?"
            let plain = egui::TextFormat { font_id: FontId::proportional(16.0), color: t.header_secondary, line_height: Some(20.0), ..Default::default() };
            let strong = egui::TextFormat { font_id: FontId::new(16.0, egui::FontFamily::Name(crate::style::BOLD.into())), ..plain.clone() };
            let mut job = egui::text::LayoutJob::default();
            job.append("Are you sure you want to remove ", 0.0, plain.clone());
            job.append(&name, 0.0, strong);
            job.append(" from your friends?", 0.0, plain);
            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());
            let title = FontId::new(20.0, egui::FontFamily::Name(crate::style::STRONG.into()));
            ui.painter().with_clip_rect(r.shrink2(vec2(24.0, 0.0)).with_max_x(r.right() - 56.0)).text(pos2(r.left() + 24.0, r.top() + 36.0), Align2::LEFT_CENTER, format!("Remove '{name}'"), title, 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("remove_friend_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("remove_friend_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();
            // Discord's critical button (red-430, darker under the pointer).
            let yr = ui.interact(yes, egui::Id::new("remove_friend_ok"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            let red = if yr.hovered() { Color32::from_rgb(0xb4, 0x22, 0x2c) } else { Color32::from_rgb(0xd2, 0x2d, 0x39) };
            ui.painter().rect(yes, 8.0, red, Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
            ui.painter().text(yes.center(), Align2::CENTER_CENTER, "Remove Friend", crate::style::medium(16.0), Color32::WHITE);
            confirm |= yr.clicked();
        });
        // (Above the full profile, which keeps itself on top.)
        for id in [egui::Id::new(("remove_friend", "dim")), egui::Id::new("remove_friend")] {
            ctx.move_to_top(egui::LayerId::new(Order::Foreground, id));
        }
        if confirm {
            self.remove_friend = None;
            self.relationship(user, false, "User Profile");
        } else if cancel {
            self.remove_friend = None;
        }
    }

    // ---- the "More" menu ------------------------------------------------------

    fn toggle_profile_more(&mut self, user: User, guild: Option<Id>, pos: egui::Pos2) {
        self.profile_more = match self.profile_more.take() {
            Some(open) if open.user.id == user.id => None,
            _ => Some(ProfileMore { user, guild, pos, opened: self.ctx.cumulative_pass_nr(), sub: None }),
        };
    }

    /// Discord's profile "More" menu: View Full Profile and Invite to Server;
    /// Block; Copy User Info (ID, profile link, avatar and banner links).
    /// Submenus open beside their row under the pointer.
    /// A Recent Activity song's ⋯ menu (Discord's activity context menu
    /// for someone else's song): "Play on Spotify", which opens the track.
    pub fn recent_activity_menu_ui(&mut self, ctx: &egui::Context) {
        let menu_id = egui::Id::new("recent_activity_menu");
        let Some((_, pos, track, opened)) = ctx.data(|d| d.get_temp::<(u64, egui::Pos2, String, u64)>(menu_id)) else { return };
        if self.full_profile.is_none() {
            ctx.data_mut(|d| d.remove::<(u64, egui::Pos2, String, u64)>(menu_id));
            return;
        }
        let t = self.theme.clone();
        let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
        let area = egui::Area::new(menu_id).order(Order::Foreground).fixed_pos(pos).constrain(true).show(ctx, |ui| {
            ui.ctx().move_to_top(ui.layer_id());
            super::ctx_menu_frame(&t).show(ui, |ui| {
                ui.set_width(152.0);
                ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                if super::ctx_row(ui, &t, None, "Play on Spotify", None, false, true).clicked() {
                    ui.ctx().open_url(egui::OpenUrl::new_tab(&track));
                    close = true;
                }
            });
        });
        // (Not the click on ⋯ that opened it.)
        if close || (area.response.clicked_elsewhere() && ctx.cumulative_pass_nr() > opened + 1) {
            ctx.data_mut(|d| d.remove::<(u64, egui::Pos2, String, u64)>(menu_id));
        }
    }

    pub fn profile_more_ui(&mut self, ctx: &egui::Context) {
        use discord::model::permissions::CREATE_INSTANT_INVITE;
        let Some(menu) = self.profile_more.as_ref() else { return };
        let (user, guild, pos, opened, was_sub) = (menu.user.clone(), menu.guild, menu.pos, menu.opened, menu.sub);
        let t = self.theme.clone();
        let is_me = Some(user.id) == self.store.me_id();
        let blocked = self.store.relationships.get(&user.id).is_some_and(|r| r.kind == 2);
        let profile = self.profile_for(user.id, guild);
        let banner = profile.and_then(|p| p.banner_url()).map(|u| u.replace("size=600", "size=1024"));
        // Servers you may invite people to and they aren't in already.
        let shared: Vec<Id> = profile.map(|p| p.mutual_guilds.iter().map(|g| g.id).collect()).unwrap_or_default();
        let servers: Vec<(Id, String)> = if is_me || user.bot {
            Vec::new()
        } else {
            let open = |g: &Id| !shared.contains(g) && self.store.has_perm(*g, CREATE_INSTANT_INVITE) && self.store.first_text_channel(Some(*g)).is_some();
            self.store.guild_order.iter().filter(|g| open(g)).filter_map(|g| Some((*g, self.store.guilds.get(g)?.guild.name.clone()))).collect()
        };

        let ignored = self.store.relationships.get(&user.id).is_some_and(|r| r.user_ignored);
        enum Pick {
            View,
            Share,
            Invite(Id),
            Ignore(bool),
            Block(bool),
            Copy(String, &'static str),
        }
        let mut pick = None;
        let mut sub = was_sub;
        let mut plain_hovered = false;
        let area = egui::Area::new(egui::Id::new("profile_more_menu")).order(Order::Foreground).fixed_pos(pos).constrain(true).show(ctx, |ui| {
            super::ctx_menu_frame(&t).show(ui, |ui| {
                ui.set_width(152.0);
                ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                let mut row = |ui: &mut Ui, label: &str, danger: bool, opens: Option<MoreSub>| -> bool {
                    // (A row stays lit while its submenu is open.)
                    let lit = ui.painter().add(egui::Shape::Noop);
                    let r = super::ctx_row(ui, &t, None, label, opens.map(|_| icon::CHEVRON), danger, true);
                    match opens {
                        Some(which) => {
                            if r.hovered() || r.clicked() {
                                sub = Some((which, r.rect.top()));
                            } else if sub.is_some_and(|(s, _)| s == which) {
                                ui.painter().set(lit, egui::Shape::rect_filled(r.rect, 4.0, t.bg_hover));
                            }
                            false
                        }
                        None => {
                            plain_hovered |= r.hovered();
                            r.clicked()
                        }
                    }
                };
                if row(ui, "View Full Profile", false, None) {
                    pick = Some(Pick::View);
                }
                if !user.bot && row(ui, "Share Profile", false, None) {
                    pick = Some(Pick::Share);
                }
                if !servers.is_empty() {
                    row(ui, "Invite to Server", false, Some(MoreSub::Invite));
                }
                if !is_me {
                    super::ctx_separator(ui, &t);
                    if !user.bot && !blocked && row(ui, if ignored { "Unignore" } else { "Ignore" }, false, None) {
                        pick = Some(Pick::Ignore(!ignored));
                    }
                    if row(ui, if blocked { "Unblock" } else { "Block" }, true, None) {
                        pick = Some(Pick::Block(!blocked));
                    }
                }
                super::ctx_separator(ui, &t);
                row(ui, "Copy User Info", false, Some(MoreSub::Copy));
            });
        });
        ctx.move_to_top(area.response.layer_id);
        let main = area.response.rect;
        if plain_hovered {
            sub = None;
        }
        let mut sub_rect = None;
        if let Some((which, top)) = sub {
            let width = if which == MoreSub::Invite { 264.0 } else { 172.0 };
            // To the right when there's room, else on the left.
            let right = main.right() - 4.0 + width + 16.0 <= ctx.screen_rect().right();
            let (pivot, at) = if right { (Align2::LEFT_TOP, pos2(main.right() - 4.0, top - 9.0)) } else { (Align2::RIGHT_TOP, pos2(main.left() + 4.0, top - 9.0)) };
            let shown = egui::Area::new(egui::Id::new(("profile_more_sub", which as u8))).order(Order::Foreground).pivot(pivot).fixed_pos(at).constrain(true).show(ctx, |ui| {
                super::ctx_menu_frame(&t).show(ui, |ui| {
                    ui.set_width(width);
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    match which {
                        MoreSub::Invite => {
                            ScrollArea::vertical().max_height(340.0).show(ui, |ui| {
                                for (id, name) in &servers {
                                    if super::ctx_row(ui, &t, None, name, None, false, true).clicked() {
                                        pick = Some(Pick::Invite(*id));
                                    }
                                }
                            });
                        }
                        MoreSub::Copy => {
                            let mut copy = |ui: &mut Ui, label: &str, text: String, done: &'static str| {
                                if super::ctx_row(ui, &t, None, label, None, false, true).clicked() {
                                    pick = Some(Pick::Copy(text, done));
                                }
                            };
                            copy(ui, "Copy User ID", user.id.to_string(), "User ID copied.");
                            copy(ui, "Copy Profile Link", format!("https://discord.com/users/{}", user.id), "Profile link copied.");
                            if user.avatar.is_some() {
                                copy(ui, "Copy Avatar Image Link", user.avatar_animated(1024), "Avatar link copied.");
                            }
                            if let Some(b) = &banner {
                                copy(ui, "Copy Banner Image Link", b.clone(), "Banner link copied.");
                            }
                        }
                    }
                });
            });
            ctx.move_to_top(shown.response.layer_id);
            sub_rect = Some(shown.response.rect);
        }

        let inside = |p: egui::Pos2| main.contains(p) || sub_rect.is_some_and(|r| r.contains(p));
        let outside = ctx.cumulative_pass_nr() > opened + 1 && ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !inside(p)));
        let escape = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape));
        if outside || escape || pick.is_some() {
            self.profile_more = None;
        } else if let Some(m) = self.profile_more.as_mut() {
            m.sub = sub;
        }
        match pick {
            Some(Pick::View) => {
                self.profile = None;
                self.open_full_profile(user, guild);
            }
            Some(Pick::Share) => {
                // (The dialog takes over from the card it was opened on.)
                self.profile = None;
                self.full_profile = None;
                self.start_share(format!("https://discord.com/users/{}", user.id));
            }
            Some(Pick::Ignore(on)) => self.backend.send(crate::backend::Command::Ignore { user: user.id, on }),
            Some(Pick::Invite(server)) => self.invite_from_profile(user.id, server),
            Some(Pick::Block(on)) => self.set_blocked(user.id, on),
            Some(Pick::Copy(text, done)) => {
                ctx.copy_text(text);
                self.toast(done, false);
            }
            None => {}
        }
    }

    /// Discord's reaction or reply to someone's custom status: a message in
    /// your DM with them that quotes the status (`verb` is "Reacted" or
    /// "Replied"), sent without leaving where you are.
    pub(crate) fn status_interaction(&mut self, user: Id, status: &str, verb: &str, input: &str) {
        let name = self.store.users.get(&user).map(|u| u.display_name().to_string()).unwrap_or_default();
        let content = status_quote(verb, &name, status) + input;
        let dm = self.store.channels.values().find(|c| c.kind == channel_kind::DM && c.recipients.first().is_some_and(|u| u.id == user)).map(|c| c.id);
        let nonce = Id(Id::from_timestamp_ms(chrono::Utc::now().timestamp_millis().max(0) as u64).0 | (user.0 & 0xFFF)).to_string();
        self.backend.send(crate::backend::Command::SendInvite { user, dm, content, nonce });
        self.toast(if verb == "Replied" { "Reply sent." } else { "Reaction sent." }, false);
    }

    /// "Reply to status" where there's no message box on the card (the DM
    /// panel, the full profile): the quote goes into your DM's message box.
    fn reply_to_status_in_dm(&mut self, user: Id, status: &str) {
        let name = self.store.users.get(&user).map(|u| u.display_name().to_string()).unwrap_or_default();
        let dm = self.store.channels.values().find(|c| c.kind == channel_kind::DM && c.recipients.first().is_some_and(|u| u.id == user)).map(|c| c.id);
        self.full_profile = None;
        match dm {
            Some(ch) => {
                self.current_guild = None;
                self.select_channel(Some(ch));
                let draft = self.drafts.entry(ch).or_default();
                *draft = status_quote("Replied", &name, status) + draft;
                self.compose.focus_composer = true;
            }
            None => self.open_dm_with(user, String::new()),
        }
    }

    /// The names of `app`'s slash commands where you are, as far as the
    /// command list of this server (or DM) has arrived.
    fn app_command_names(&self, app: Id, guild: Option<Id>) -> Vec<String> {
        let here = match (guild, self.current_channel) {
            (Some(g), _) => format!("apps:g:{g}"),
            (None, Some(ch)) => format!("apps:c:{ch}"),
            (None, None) => String::new(),
        };
        let app = app.to_string();
        let mut names: Vec<String> = Vec::new();
        for key in [here.as_str(), "apps:me"] {
            let Some(Ok(index)) = self.api_results.get(key) else { continue };
            for cmd in index["application_commands"].as_array().into_iter().flatten() {
                let name = cmd["name"].as_str().unwrap_or_default();
                if cmd["application_id"].as_str() == Some(app.as_str()) && cmd["type"].as_u64().unwrap_or(1) == 1 && !name.is_empty() && !names.iter().any(|n| n == name) {
                    names.push(name.to_string());
                }
            }
        }
        names
    }

    /// "Invite to Server": make an invite to `server` (Discord's defaults:
    /// seven days, no limit) and send it to them once it exists.
    fn invite_from_profile(&mut self, user: Id, server: Id) {
        let Some(channel) = self.store.first_text_channel(Some(server)) else { return };
        self.profile_invites.push((channel, user));
        self.backend.send(crate::backend::Command::CreateInvite { channel, max_age: 604_800, max_uses: 0, temporary: false });
    }

    /// The invite asked for by [`Self::invite_from_profile`] arrived (or didn't).
    pub(crate) fn send_profile_invite(&mut self, user: Id, link: Result<String, String>) {
        let link = match link {
            Ok(link) => link,
            Err(e) => return self.toast(format!("Couldn't create an invite: {e}"), true),
        };
        let dm = self.store.channels.values().find(|c| c.kind == channel_kind::DM && c.recipients.first().is_some_and(|u| u.id == user)).map(|c| c.id);
        let nonce = Id(Id::from_timestamp_ms(chrono::Utc::now().timestamp_millis().max(0) as u64).0 | (user.0 & 0xFFF)).to_string();
        self.backend.send(crate::backend::Command::SendInvite { user, dm, content: link, nonce });
        self.toast("Invite sent.", false);
    }

    // ---- account menu (your own card + status) ------------------------------

    pub fn account_menu_ui(&mut self, ctx: &egui::Context) {
        let Some(menu) = &self.account_menu else { return };
        let Some(me) = self.store.me.clone() else { return };
        let t = self.theme.clone();
        let (anchor, opened, mut status_open, mut switch_open) = (menu.pos, menu.opened_frame, menu.status_open, menu.switch_open);
        let bg = self.popout_background(me.id, None);
        let current = if self.store.my_status.is_empty() { "online".to_string() } else { self.store.my_status.clone() };
        let bold14 = FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
        let label14 = crate::style::medium(14.0);
        let subtle = if t.light { t.header_secondary } else { Color32::from_rgb(0xb5, 0xba, 0xc1) };
        let mut orbs_open = menu.orbs_open;
        // Your Orbs balance (Discord's GET /users/@me/virtual-currency/balance).
        let orbs: Option<u64> = self.api_results.get("orbs-balance").and_then(|r| r.as_ref().ok()).and_then(|v| v["balance"].as_u64());
        // Not answered yet (it's asked for the first time the menu opens).
        let orbs_loading = !self.api_results.contains_key("orbs-balance");

        let mut actions = Vec::new();
        let mut out = CardOut::default();
        let mut set_status: Option<String> = None;
        let mut copy_id = false;
        let mut switch_pick = None;
        let accounts = super::switch_accounts::listed_accounts(self);
        let active_account = self.account.or(Some(me.id));
        let mut open_badges = false;
        let my_badges: Vec<discord::model::ProfileBadge> =
            self.profiles.get(&(me.id, None)).and_then(|r| r.as_ref().ok()).map(|p| p.badges.clone()).unwrap_or_default();
        let mut flyout_at: Option<egui::Pos2> = None;
        // One menu row: icon (or status dot), label, optional chevron.
        let row = |ui: &mut Ui, glyph: Option<&str>, dot: Option<&str>, label: &str, chevron: bool, color: Color32| -> egui::Response {
            let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());
            let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
            if resp.hovered() {
                ui.painter().rect_filled(r, 8.0, overlay(0.16));
            }
            if let Some(g) = glyph {
                super::paint_icon(ui.painter(), Rect::from_center_size(r.left_center() + vec2(16.0, 0.0), vec2(16.0, 16.0)), g, color);
            }
            if let Some(s) = dot {
                paint_status_dot(ui, r.left_center() + vec2(16.0, 0.0), 5.0, s, Color32::TRANSPARENT);
            }
            ui.painter().text(r.left_center() + vec2(32.0, 0.0), Align2::LEFT_CENTER, label, label14.clone(), color);
            if chevron {
                super::paint_icon(ui.painter(), Rect::from_center_size(r.right_center() - vec2(16.0, 0.0), vec2(16.0, 16.0)), icon::CHEVRON_SMALL_RIGHT, color);
            }
            resp
        };
        // A rounded group of rows with hairlines between them.
        let group = |ui: &mut Ui, add: &mut dyn FnMut(&mut Ui)| {
            Frame::none().fill(overlay(0.12)).rounding(8.0).inner_margin(8.0).show(ui, |ui| {
                // The card's 16px margins and this frame's own 8px.
                ui.set_width(POPOUT_W - 32.0 - 16.0);
                ui.spacing_mut().item_spacing.y = 0.0;
                add(ui);
            });
        };
        // 8 px, a hairline (4 px in from the rows' ends), 8 px.
        let divider = |ui: &mut Ui| {
            ui.add_space(8.0);
            let y = ui.cursor().top() + 0.5;
            let x = ui.max_rect().x_range();
            ui.painter().hline(egui::Rangef::new(x.min + 4.0, x.max - 4.0), y, Stroke::new(1.0_f32, t.border_subtle));
            ui.add_space(9.0);
        };

        let area = egui::Area::new(egui::Id::new("account_menu"))
            .order(Order::Foreground)
            .pivot(Align2::LEFT_BOTTOM)
            .fixed_pos(anchor - vec2(0.0, 8.0))
            .constrain(true)
            .sized_off_screen(ctx)
            .show(ctx, |ui| {
                // (Discord's opens above its anchor: it comes down into place.)
                motion::tag(ui, Motion::Slide(vec2(0.0, -10.0)), 0);
                let bg_slot = ui.painter().add(egui::Shape::Noop);
                let inset = self.popout_inset(me.id, None);
                // Like Discord's: its foot stays just above your panel, it is
                // no taller than the room above (12 px to spare), and what
                // doesn't fit scrolls (a short window used to push it down).
                let room = (anchor.y - 8.0 - ctx.screen_rect().top() - 12.0).max(160.0);
                let frame = Frame::none().rounding(8.0).show(ui, |ui| {
                    ScrollArea::vertical().id_salt("account_menu_scroll").max_height(room).min_scrolled_height(room).auto_shrink([true, true]).show(ui, |ui| {
                        out = self.profile_card(ui, POPOUT_W, &me, None, bg, None, CardKind::Account, inset, &mut actions);
                        Frame::none().inner_margin(Margin { left: 16.0, right: 16.0, top: 9.0, bottom: 22.0 }).show(ui, |ui| {
                            ui.spacing_mut().item_spacing.y = 12.0;
                            group(ui, &mut |ui| {
                                let r = row(ui, Some(icon::EDIT), None, "Edit Profile", false, subtle);
                                if r.clicked() {
                                    out.edit_profile = true;
                                }
                                if r.hovered() {
                                    status_open = false;
                                    switch_open = false;
                                    orbs_open = false;
                                }
                                divider(ui);
                                let shown = current.as_str();
                                let dot = if shown == "invisible" { "offline" } else { shown };
                                let r = row(ui, None, Some(dot), status_label(shown), true, subtle);
                                if r.hovered() || r.clicked() {
                                    status_open = true;
                                    switch_open = false;
                                    orbs_open = false;
                                    flyout_at = Some(r.rect.right_top());
                                } else if status_open {
                                    flyout_at = Some(r.rect.right_top());
                                }
                                // Discord's "Badges" row: the "Your badges" window.
                                if !my_badges.is_empty() {
                                    divider(ui);
                                    let r = row(ui, Some(icon::BADGE), None, "Badges", false, subtle);
                                    if r.clicked() {
                                        open_badges = true;
                                    }
                                    if r.hovered() {
                                        status_open = false;
                                        switch_open = false;
                                        orbs_open = false;
                                    }
                                }
                                // Discord's "560 Orbs" row: your balance; its flyout is the wallet.
                                if let Some(n) = orbs {
                                    divider(ui);
                                    let r = row(ui, Some(icon::ORBS), None, &format!("{} Orbs", group_thousands(n)), true, subtle);
                                    if r.hovered() || r.clicked() {
                                        orbs_open = true;
                                        status_open = false;
                                        switch_open = false;
                                        flyout_at = Some(r.rect.right_top());
                                    } else if orbs_open {
                                        flyout_at = Some(r.rect.right_top());
                                    }
                                } else if orbs_loading {
                                    // Its place is kept while the balance loads, with a
                                    // placeholder line for the amount: the rows below
                                    // would jump when it came.
                                    divider(ui);
                                    let r = row(ui, Some(icon::ORBS), None, "", false, subtle);
                                    let line = Rect::from_min_size(r.rect.left_center() + vec2(32.0, -6.0), vec2(72.0, 12.0));
                                    ui.painter().rect_filled(line, 6.0, overlay(0.1));
                                    if r.hovered() {
                                        status_open = false;
                                        switch_open = false;
                                        orbs_open = false;
                                    }
                                }
                            });
                            group(ui, &mut |ui| {
                                let r = row(ui, Some(icon::USER_CIRCLE_FILLED), None, "Switch Accounts", true, subtle);
                                if r.hovered() || r.clicked() {
                                    switch_open = true;
                                    status_open = false;
                                    orbs_open = false;
                                    flyout_at = Some(r.rect.right_top());
                                } else if switch_open {
                                    flyout_at = Some(r.rect.right_top());
                                }
                                divider(ui);
                                let r = row(ui, Some(icon::ID), None, "Copy User ID", false, subtle);
                                if r.clicked() {
                                    copy_id = true;
                                }
                                if r.hovered() {
                                    status_open = false;
                                    switch_open = false;
                                    orbs_open = false;
                                }
                            });
                        });
                    });
                });
                let rect = frame.response.rect;
                ui.painter().set(bg_slot, with_popout_shadow(self.popout_shapes(rect, me.id, None), rect));
            });

        // Flyouts to the right of their row, like Discord's.
        let mut flyout_rect = None;
        let mut open_page: Option<crate::features::StorePage> = None;
        if let (Some(at), true, Some(n)) = (flyout_at, orbs_open, orbs) {
            let fly = egui::Area::new(egui::Id::new("orbs_flyout"))
                .order(Order::Tooltip)
                .fixed_pos(at + vec2(16.0, -16.0))
                .constrain(true)
                .show(ctx, |ui| {
                    Frame::none()
                        .fill(t.surface_high)
                        .rounding(8.0)
                        .stroke(Stroke::new(1.0_f32, t.border_subtle))
                        .shadow(shadow())
                        .inner_margin(Margin::same(16.0))
                        .show(ui, |ui| {
                            ui.set_width(308.0);
                            ui.spacing_mut().item_spacing.y = 0.0;
                            ui.horizontal(|ui| {
                                ui.add_space(44.0);
                                ui.label(RichText::new(group_thousands(n)).font(FontId::new(32.0, egui::FontFamily::Name(crate::style::STRONG.into()))).color(t.header_primary));
                            });
                            ui.add_space(16.0);
                            ui.horizontal(|ui| {
                                ui.spacing_mut().item_spacing.x = 12.0;
                                for (glyph, label, page) in [(icon::QUESTS, "Quests", crate::features::StorePage::Quests), (icon::SHOP, "Shop", crate::features::StorePage::Shop)] {
                                    let (r, resp) = ui.allocate_exact_size(vec2(148.0, 40.0), Sense::click());
                                    ui.painter().rect_filled(r, 8.0, overlay(if resp.hovered() { 0.2 } else { 0.12 }));
                                    let galley = ui.painter().layout_no_wrap(label.to_string(), crate::style::medium(16.0), t.header_primary);
                                    let x = r.center().x - (galley.size().x + 26.0) / 2.0;
                                    super::paint_icon(ui.painter(), Rect::from_center_size(pos2(x + 9.0, r.center().y), vec2(18.0, 18.0)), glyph, t.header_primary);
                                    ui.painter().galley(pos2(x + 26.0, r.center().y - galley.size().y / 2.0), galley, t.header_primary);
                                    if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                        open_page = Some(page);
                                    }
                                }
                            });
                        });
                });
            flyout_rect = Some(fly.response.rect);
        }
        if let (Some(at), true) = (flyout_at, status_open || switch_open) {
            let fly = egui::Area::new(egui::Id::new("account_flyout"))
                .order(Order::Tooltip)
                .fixed_pos(at + vec2(12.0, -8.0))
                .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(if switch_open { 8.0 } else { 6.0 })
                        .show(ui, |ui| {
                            ui.set_width(if switch_open { super::switch_accounts::FLYOUT_W - 18.0 } else { 250.0 });
                            ui.spacing_mut().item_spacing.y = 0.0;
                            if status_open {
                                for (s, label, hint) in [
                                    ("online", "Online", ""),
                                    ("idle", "Idle", ""),
                                    ("dnd", "Do Not Disturb", "You will not receive desktop notifications"),
                                    ("invisible", "Invisible", "You will appear offline"),
                                ] {
                                    let h = if hint.is_empty() { 36.0 } else { 52.0 };
                                    let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());
                                    let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                                    if resp.hovered() {
                                        ui.painter().rect_filled(r, 6.0, overlay(0.16));
                                    }
                                    let top = if hint.is_empty() { r.center().y } else { r.top() + 17.0 };
                                    paint_status_dot(ui, pos2(r.left() + 18.0, top), 5.0, if s == "invisible" { "offline" } else { s }, Color32::TRANSPARENT);
                                    ui.painter().text(pos2(r.left() + 36.0, top), Align2::LEFT_CENTER, label, bold14.clone(), t.header_primary);
                                    if !hint.is_empty() {
                                        ui.painter().text(pos2(r.left() + 36.0, top + 18.0), Align2::LEFT_CENTER, hint, FontId::proportional(12.0), t.text_muted);
                                    }
                                    if current == s {
                                        ui.painter().text(pos2(r.right() - 14.0, top), Align2::CENTER_CENTER, icon::CHECK, icon_font(12.0), t.accent);
                                    }
                                    if resp.clicked() {
                                        set_status = Some(s.to_string());
                                    }
                                }
                            } else {
                                switch_pick = super::switch_accounts::flyout_rows(ui, &t, &accounts, active_account);
                            }
                        });
                });
            flyout_rect = Some(fly.response.rect);
        }

        if let Some(m) = self.account_menu.as_mut() {
            m.status_open = status_open;
            m.switch_open = switch_open;
            m.orbs_open = orbs_open;
        }
        if orbs.is_none() && !self.api_results.contains_key("orbs-balance") && !self.api_busy("orbs-balance") {
            self.api("orbs-balance", reqwest::Method::GET, "/users/@me/virtual-currency/balance", None);
        }
        for a in actions {
            if let UiAction::Reveal(id, k) = a {
                self.revealed.insert((id, k));
            }
        }
        let custom_now = self.store.my_custom.clone();
        // Clicks inside the menu or its flyout don't close it.
        let clicked_outside = ctx.input(|i| {
            i.pointer.any_click()
                && i.pointer.interact_pos().is_some_and(|p| !area.response.rect.contains(p) && !flyout_rect.is_some_and(|f| f.contains(p)))
        });
        if let Some(page) = open_page {
            self.account_menu = None;
            self.current_guild = None;
            self.open_store_page(page);
        } else if let Some(s) = set_status {
            self.set_status(&s, custom_now);
            self.account_menu = None;
        } else if let Some(pick) = switch_pick {
            self.account_menu = None;
            match pick {
                super::switch_accounts::FlyoutPick::Switch(id) => self.switch_account(id),
                super::switch_accounts::FlyoutPick::Manage => self.open_manage_accounts(),
            }
        } else if open_badges {
            self.account_menu = None;
            self.badges_view = Some((my_badges, 0));
        } else if copy_id {
            ctx.copy_text(me.id.to_string());
            self.toast("User ID copied.", false);
            self.account_menu = None;
        } else if out.expand {
            self.account_menu = None;
            self.open_full_profile(me.clone(), None);
        } else if out.board {
            self.account_menu = None;
            self.open_full_profile_on(me.clone(), None, TAB_BOARD);
        } else if let Some(v) = out.view.take() {
            self.account_menu = None;
            self.viewer = Some(v);
        } else if let Some((g, at)) = out.tag.take() {
            self.open_tag_popout(g, at);
        } else if let Some(b) = out.badges.take() {
            self.account_menu = None;
            self.badges_view = Some(b);
        } else if out.edit_status {
            self.open_custom_status_dialog();
        } else if out.edit_profile {
            self.account_menu = None;
            self.settings_open = true;
        } else if (clicked_outside && ctx.cumulative_pass_nr() > opened + 1) || ctx.input(|i| i.key_pressed(Key::Escape)) {
            self.account_menu = None;
        }
    }

    /// Discord's "Set a custom status" dialog (keeps the current emoji).
    pub fn custom_status_dialog_ui(&mut self, ctx: &egui::Context) {
        let Some(mut text) = self.custom_status_dialog.take() else { return };
        let t = self.theme.clone();
        let emoji = self.my_status_emoji();
        let name = self.store.me.as_ref().map(|u| u.display_name().to_string()).unwrap_or_default();
        let screen = ctx.screen_rect();
        // The dimmed app takes the pointer: a click off the dialog stops here.
        egui::Area::new(egui::Id::new("status_dim")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha(150));
        });
        let (mut save, mut cancel, mut clear) = (false, ctx.input(|i| i.key_pressed(Key::Escape)), false);
        // (Before the field below can change it.)
        let unchanged = text == self.store.my_custom.as_ref().map(|c| c.text.as_str()).unwrap_or_default();
        let area = egui::Area::new(egui::Id::new("custom_status_dialog"))
            .order(Order::Tooltip)
            .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0))
            .show(ctx, |ui| {
                Frame::none()
                    .fill(t.bg_floating)
                    .rounding(12.0)
                    .stroke(Stroke::new(1.0_f32, t.border_subtle))
                    .shadow(shadow())
                    .inner_margin(Margin::symmetric(20.0, 18.0))
                    .show(ui, |ui| {
                        ui.set_width(400.0);
                        ui.label(bold("Set a custom status").size(20.0).color(t.header_primary));
                        ui.add_space(14.0);
                        ui.label(bold(format!("What's cookin', {name}?")).size(13.0).color(t.header_secondary));
                        ui.add_space(6.0);
                        Frame::none().fill(t.input_bg).rounding(8.0).stroke(Stroke::new(1.0_f32, t.border_subtle)).inner_margin(Margin::symmetric(10.0, 6.0)).show(ui, |ui| {
                            ui.horizontal(|ui| {
                                let (r, _) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::hover());
                                match &emoji {
                                    Some(e) => {
                                        egui::Image::new(e.as_str()).paint_at(ui, r);
                                    }
                                    None => {
                                        ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::EMOJI, icon_font(18.0), t.interactive_normal);
                                    }
                                }
                                let field = ui.add(
                                    TextEdit::singleline(&mut text)
                                        .frame(false)
                                        .hint_text("Support has arrived!")
                                        .desired_width(ui.available_width() - 24.0)
                                        .char_limit(128),
                                );
                                field.request_focus();
                                save |= field.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
                                let (x, b) = ui.allocate_exact_size(vec2(20.0, 20.0), Sense::click());
                                let b = b.on_hover_cursor(egui::CursorIcon::PointingHand);
                                ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(10.0), if b.hovered() { t.header_primary } else { t.interactive_normal });
                                clear |= b.on_hover_text("Clear status").clicked();
                            });
                        });
                        ui.add_space(18.0);
                        ui.horizontal(|ui| {
                            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                save |= ui.add(Button::new(bold("Save").size(14.0).color(Color32::WHITE)).fill(t.accent).rounding(8.0).min_size(vec2(96.0, 36.0))).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                                cancel |= ui.add(Button::new(RichText::new("Cancel").size(14.0).color(t.header_primary)).frame(false)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                            });
                        });
                    });
            });
        // Clicking off the dialog closes it, unless a new status is typed in.
        cancel |= unchanged && super::pressed_outside(ctx, area.response.rect);
        let st = if self.store.my_status.is_empty() { "online".to_string() } else { self.store.my_status.clone() };
        if save {
            let now = self.store.my_custom.clone();
            let text = text.trim().to_string();
            let keep_emoji = now.as_ref().is_some_and(|c| c.emoji_id.is_some() || c.emoji_name.is_some());
            let cs = (!text.is_empty() || keep_emoji).then(|| CustomStatus {
                text,
                emoji_name: now.as_ref().and_then(|c| c.emoji_name.clone()),
                emoji_id: now.as_ref().and_then(|c| c.emoji_id),
                expires_at_ms: None,
            });
            self.set_status(&st, cs);
        } else if clear {
            self.set_status(&st, None);
        } else if !cancel {
            self.custom_status_dialog = Some(text);
        }
    }

    // ---- quick switcher -------------------------------------------------------

    // ---- full profile ---------------------------------------------------------

    pub fn open_full_profile(&mut self, user: User, guild: Option<Id>) {
        self.open_full_profile_on(user, guild, TAB_FIRST);
    }

    /// The full profile, opened on a given tab (`TAB_*`).
    pub fn open_full_profile_on(&mut self, user: User, guild: Option<Id>, tab: u8) {
        self.want_profile(user.id, guild);
        self.tag_picker = None;
        self.full_profile = Some(crate::features::FullProfile { user, guild, tab, opened_frame: self.ctx.cumulative_pass_nr() });
    }

    /// Discord's full profile window: the card (bigger, with Member Since,
    /// Friends Since and Connections) on the left; Activity, Mutual Friends
    /// and Mutual Servers tabs on the right. The avatar here opens the picture.
    pub fn full_profile_ui(&mut self, ctx: &egui::Context) {
        let Some(fp) = &self.full_profile else { return };
        if fp.user.bot {
            return self.bot_profile_ui(ctx);
        }
        let (user, guild, mut tab, opened) = (fp.user.clone(), fp.guild, fp.tab, fp.opened_frame);
        if Some(user.id) != self.store.me_id() {
            self.api_get_once(&format!("note:{}", user.id), format!("/users/@me/notes/{}", user.id));
        }
        self.api_get_once(&format!("outbox:{}", user.id), format!("/content-inventory/users/{}/outbox", user.id));
        let effect = self.want_profile_effect(user.id, guild);
        let t = self.theme.clone();
        let screen = ctx.screen_rect();
        let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
        egui::Area::new(egui::Id::new("full_profile_bg")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            let (r, resp) = ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(r, 0.0, Color32::from_black_alpha(184));
            close |= resp.clicked() && ctx.cumulative_pass_nr() > opened + 1;
        });
        // Discord's sizes (its modal-v2 CSS, read 2026-11-23): the whole window
        // below 929 px wide / 785 px tall, else 962 wide (48 px clear each
        // side) and up to 800 tall (48 px clear above and below); 16 px corners
        // only when it floats; 32 px padding, 48 from 1025 px wide. A short
        // window's content clears the title bar (Discord's desktop app does).
        let (vw, vh) = (screen.width(), screen.height());
        let (narrow, short) = (vw < 929.0, vh < 785.0);
        let size = vec2(if narrow { vw } else { 962.0_f32.min(vw - 96.0) }, if short { vh } else { 800.0_f32.min(vh - 96.0) });
        let modal = Rect::from_center_size(screen.center(), size);
        let corner = if narrow || short { 0.0 } else { 16.0 };
        let pad = if vw >= 1025.0 { 48.0 } else { 32.0 };
        let bar = if short { super::TITLE_BAR } else { 0.0 };
        let profile_w = (if narrow { 0.455 * vw } else { 0.455 * vw - 43.68 }).clamp(300.0, 400.0);
        let profile = self.profiles.get(&(user.id, guild)).and_then(|r| r.as_ref().ok()).cloned();
        let bg = self.popout_background(user.id, guild);
        // On a profile theme the whole window is in the theme's colours:
        // its text follows the theme, not the app.
        let ct = self.card_text_theme(user.id, guild);
        let themed = self.theme_colors(user.id, guild).is_some();
        let mut actions = Vec::new();
        let mut out = CardOut::default();
        let (mut message, mut open_guild, mut open_user) = (false, None, None);
        let mut add_connection = false;
        let mut listen = false;
        let is_me = Some(user.id) == self.store.me_id();
        egui::Area::new(egui::Id::new("full_profile")).order(Order::Foreground).fixed_pos(modal.min).show(ctx, |ui| {
            // To the front as it opens, and not after: layers that all ask
            // for the top keep their old order among themselves, so a tag
            // card or menu opened from here a second time stayed behind it.
            if ui.ctx().cumulative_pass_nr() <= opened + 1 {
                ui.ctx().move_to_top(ui.layer_id());
            }
            above_backdrop(ui);
            // The layer must cover the window: egui routes the mouse wheel by
            // area rects, and the columns below are child UIs that don't grow it.
            ui.expand_to_include_rect(modal);
            // (Discord's modal: fades in growing from 70 %.)
            motion::tag(ui, Motion::Modal, 0);
            // Discord's 16 px window: --background-base-lower, or on a profile
            // theme the theme's own window colour, darkest at the top (the
            // 60 % overlay at 80 % strength, 20 % from 300 px down) with the
            // banner faintly behind it.
            ui.painter().add(egui::Shape::Rect(shadow().as_shape(modal, Rounding::same(corner))));
            match self.theme_colors(user.id, guild) {
                Some((primary, secondary)) => {
                    let dark = theme::is_dark(primary);
                    let base = theme::modal_background(primary, secondary, dark);
                    let mut shapes = Vec::new();
                    fade_rrect(&mut shapes, modal, corner, 300.0, theme::modal_shade(base, dark, 0.8), theme::modal_shade(base, dark, 0.2));
                    ui.painter().extend(shapes);
                    if let Some(banner) = profile.as_ref().and_then(|p| p.banner_url()) {
                        paint_backdrop(ui, modal, corner, &banner, if dark { 0.3 } else { 0.4 });
                    }
                }
                None => {
                    ui.painter().rect_filled(modal, corner, t.bg_primary);
                }
            }
            // Close: a 32 px secondary button 8 px from the corner.
            if !narrow || !short {
                // 1 px border-normal on the sides that don't touch the window's edge.
                let stroke = Stroke::new(1.0_f32, super::modal_border(&t));
                if !narrow && !short {
                    ui.painter().rect_stroke(modal, corner, stroke);
                } else if !narrow {
                    ui.painter().vline(modal.left() + 0.5, modal.y_range(), stroke);
                    ui.painter().vline(modal.right() - 0.5, modal.y_range(), stroke);
                } else {
                    ui.painter().hline(modal.x_range(), modal.top() + 0.5, stroke);
                    ui.painter().hline(modal.x_range(), modal.bottom() - 0.5, stroke);
                }
            }
            let x = Rect::from_min_size(pos2(modal.right() - 40.0, modal.top() + 8.0 + bar), vec2(32.0, 32.0));
            let xr = ui.interact(x, egui::Id::new("full_profile_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            ui.painter().rect(x, 8.0, if xr.hovered() { overlay(0.2) } else { overlay(0.12) }, Stroke::new(1.0_f32, crate::style::rgba(151, 151, 159, 10)));
            ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(14.0), t.header_primary);
            close |= xr.clicked();

            // The card: 400 px, 49 px in, down to the window's bottom edge
            // (rounded at the top only), its content scrolling inside.
            let card_w = profile_w;
            let edge = if narrow { 0.0 } else { 1.0 };
            let left = Rect::from_min_max(modal.min + vec2(pad + edge, pad + edge + bar), pos2(modal.left() + pad + edge + card_w, modal.bottom()));
            // The card: --shadow-medium under it; plain, --background-surface-high
            // with a faint outline.
            let card_top = Rounding { nw: 16.0, ne: 16.0, sw: 0.0, se: 0.0 };
            ui.painter().with_clip_rect(modal).add(Shadow { offset: vec2(0.0, 4.0), blur: 8.0, spread: 0.0, color: Color32::from_black_alpha(41) }.as_shape(left, card_top));
            if self.card_theme(user.id, guild).is_none() {
                ui.painter().rect(left, card_top, t.surface_high, Stroke::new(1.0_f32, overlay(0.04)));
            }
            let mut cui = ui.new_child(egui::UiBuilder::new().max_rect(left).layout(egui::Layout::top_down(egui::Align::Min)));
            ScrollArea::vertical().id_salt("full_profile_left").auto_shrink([false, false]).show(&mut cui, |ui| {
                ui.spacing_mut().item_spacing.y = 0.0;
                let slot = ui.painter().add(egui::Shape::Noop);
                let card = ui.scope(|ui| {
                    let inset = self.card_inset(user.id, guild);
                    out = self.profile_card(ui, card_w, &user, guild, bg, None, CardKind::Full, inset, &mut actions);
                    // (Message / Friend / More are in the card, under the badges.)
                    Frame::none().inner_margin(Margin { left: 32.0, right: 24.0, top: 0.0, bottom: 32.0 }).show(ui, |ui| {
                        ui.spacing_mut().item_spacing.y = 0.0;
                        let accounts = profile.as_ref().map(|p| p.connected_accounts.clone()).unwrap_or_default();
                        if !accounts.is_empty() || is_me {
                            ui.add_space(24.0);
                            heading(ui, &ct, "Connections");
                            ui.add_space(12.0);
                            for (i, a) in accounts.iter().enumerate() {
                                if i > 0 {
                                    ui.add_space(16.0);
                                }
                                connection_row(ui, &ct, a);
                            }
                            if !accounts.is_empty() {
                                ui.add_space(16.0);
                            }
                            if is_me {
                                let r = ui.add(egui::Label::new(RichText::new(format!("{}  Add Connection", icon::ADD)).font(icon_font(14.0)).color(ct.text_link)).selectable(false).sense(Sense::click()));
                                if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                    add_connection = true;
                                }
                            }
                        }
                        if !is_me {
                            if let Some(note) = self.note_section(ui, &ct, &user, guild) {
                                out.note = Some(note);
                            }
                        }
                    });
                });
                // A profile theme's gradient (the plain card is the column's
                // fill): down to the window's edge however little is in it.
                let rect = card.response.rect;
                let rect = rect.with_max_y(rect.bottom().max(left.bottom()));
                if self.card_theme(user.id, guild).is_some() {
                    let top = Rounding { nw: 16.0, ne: 16.0, sw: 0.0, se: 0.0 };
                    ui.painter().set(slot, self.card_shapes(rect, user.id, guild, top, 0.0, FULL_BANNER_H));
                }
                // (Over the column itself: it stays put while the card scrolls.)
                if let Some(sku) = effect {
                    let hovered = ui.rect_contains_pointer(left);
                    self.paint_profile_effect(ui, left, sku, opened, CardKind::Full as u8, hovered);
                }
                // Dev aid: open scrolled to the bottom (screenshots can't scroll).
                if crate::diagnostics::dev_var_os("RUSTCORD_DEV_PROFILE_BOTTOM").is_some() {
                    ui.scroll_to_cursor(Some(egui::Align::BOTTOM));
                }
            });

            // Right: tabs.
            let right = Rect::from_min_max(pos2(left.right() + 32.0, left.top() + 20.0), pos2(modal.right() - pad - edge, modal.bottom() - 16.0));
            let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::top_down(egui::Align::Min)));
            let friends_n = profile.as_ref().map(|p| p.mutual_friends_count.unwrap_or(p.mutual_friends.len() as u32)).unwrap_or(0);
            let servers_n = profile.as_ref().map(|p| p.mutual_guilds.len()).unwrap_or(0);
            let plural = |n: usize, one: &str, many: &str| match n {
                0 => format!("No {many}"),
                1 => format!("1 {one}"),
                _ => format!("{n} {many}"),
            };
            // Discord's tabs: Board (their game widgets) when they have any,
            // Activity, then the mutuals for other people.
            let has_board = profile.as_ref().is_some_and(|p| p.widgets.iter().any(|w| !w.data.games.is_empty()));
            let mut labels: Vec<(u8, String)> = Vec::new();
            if has_board {
                labels.push((TAB_BOARD, "Board".to_string()));
            }
            labels.push((TAB_ACTIVITY, "Activity".to_string()));
            if !is_me {
                labels.push((TAB_FRIENDS, plural(friends_n as usize, "Mutual Friend", "Mutual Friends")));
                labels.push((TAB_SERVERS, plural(servers_n, "Mutual Server", "Mutual Servers")));
            }
            // Asked for the Board (or no tab yet) before the profile arrived:
            // keep that until RustCord knows what there is.
            if !labels.iter().any(|(k, _)| *k == tab) && !(matches!(tab, TAB_BOARD | TAB_FIRST) && profile.is_none()) {
                tab = if tab == TAB_FIRST { labels[0].0 } else { TAB_ACTIVITY };
            }
            rui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 24.0;
                for (kind, label) in labels.iter() {
                    let selected = tab == *kind;
                    let g = ui.painter().layout_no_wrap(label.clone(), FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into())), Color32::PLACEHOLDER);
                    let (r, resp) = ui.allocate_exact_size(vec2(g.size().x, 30.0), Sense::click());
                    // Discord: the selected tab in the strong text colour, over
                    // a 2 px bar that also shows under the pointer; its 14 px
                    // line of text at the top of the 30 px tab.
                    let mark = ct.header_primary;
                    let fg = if selected {
                        mark
                    } else if resp.hovered() {
                        ct.header_primary
                    } else {
                        subtle(&ct)
                    };
                    ui.painter().galley(pos2(r.left(), r.top() + 7.0 - g.size().y / 2.0), g, fg);
                    if selected || resp.hovered() {
                        ui.painter().rect_filled(Rect::from_min_max(pos2(r.left(), r.bottom() - 2.0), r.right_bottom()), Rounding { nw: 2.0, ne: 2.0, sw: 0.0, se: 0.0 }, mark);
                    }
                    if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                        tab = *kind;
                    }
                }
            });
            let y = rui.cursor().top();
            rui.painter().hline(right.x_range(), y - 0.5, Stroke::new(1.0_f32, t.border_subtle));
            // (8 px to the panel, whose content starts 10 px in; the row
            // above already left this layout's own 3 px.)
            rui.add_space(18.0 - rui.spacing().item_spacing.y);
            let name = user.display_name().to_string();
            ScrollArea::vertical().id_salt("full_profile_right").auto_shrink([false, false]).show(&mut rui, |ui| {
                ui.set_width(right.width());
                match tab {
                    TAB_BOARD => {
                        if let Some(p) = &profile {
                            self.board_ui(ui, &ct, p);
                        } else {
                            ui.add_space(40.0);
                            ui.vertical_centered(|ui| ui.spinner());
                        }
                    }
                    TAB_FRIENDS => {
                        let list = profile.as_ref().map(|p| p.mutual_friends.clone()).unwrap_or_default();
                        if list.is_empty() {
                            ui.add_space(60.0);
                            ui.vertical_centered(|ui| ui.label(RichText::new("No mutual friends").size(15.0).color(t.text_muted)));
                        }
                        // Discord's rows: 48 px (2 px apart), a 40 px avatar
                        // 4 px in, the name in 16 px medium and, when they
                        // have one, their status under it.
                        ui.spacing_mut().item_spacing.y = 2.0;
                        for f in list {
                            let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 48.0), Sense::click());
                            if resp.hovered() {
                                ui.painter().rect_filled(row, 4.0, overlay(0.12));
                            }
                            let av = Rect::from_min_size(pos2(row.left() + 4.0, row.top() + 4.0), vec2(40.0, 40.0));
                            paint_avatar(ui, av, Some(f.avatar_or_default(80)), f.display_name());
                            paint_status_dot(ui, av.right_bottom() - vec2(5.0, 5.0), 5.0, self.store.dot_status(f.id), if themed { theme::modal_background(self.theme_colors(user.id, guild).map_or(0, |c| c.0), self.theme_colors(user.id, guild).map_or(0, |c| c.1), !ct.light) } else { t.bg_primary });
                            let p = ui.painter_at(row);
                            let status = self.custom_status_of(f.id).filter(|(emoji, text)| emoji.is_some() || !text.is_empty());
                            let x = av.right() + 10.0;
                            let name_y = if status.is_some() { row.center().y - 8.0 } else { row.center().y };
                            // Their name in their own style, their server tag beside it.
                            let name = super::paint_styled_name(&p, pos2(x, name_y), Align2::LEFT_CENTER, f.display_name(), crate::style::medium(16.0), &f, ct.text_normal);
                            if let Some((tag, badge)) = f.server_tag() {
                                super::paint_tag_chip(ui, &p, name.right() + 4.0, name_y, &tag, badge.as_deref(), &ct);
                            }
                            if let Some((emoji, text)) = status {
                                let mut sx = x;
                                if let Some(e) = emoji {
                                    egui::Image::new(e).paint_at(ui, Rect::from_min_size(pos2(sx, row.center().y + 3.0), vec2(14.0, 14.0)));
                                    sx += 18.0;
                                }
                                p.text(pos2(sx, row.center().y + 10.0), Align2::LEFT_CENTER, text, crate::style::medium(12.0), ct.text_normal);
                            }
                            if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                open_user = Some(f);
                            }
                        }
                    }
                    TAB_SERVERS => {
                        let list = profile.as_ref().map(|p| p.mutual_guilds.clone()).unwrap_or_default();
                        if let Some(g) = self.mutual_servers_ui(ui, &ct, &list) {
                            open_guild = Some(g);
                        }
                    }
                    _ => {
                        let acts: Vec<discord::model::Activity> = self.store.presences.get(&user.id).map(|p| p.activities.iter().filter(|a| a.kind != 4).cloned().collect()).unwrap_or_default();
                        let recent: Vec<serde_json::Value> = match self.api_results.get(&format!("outbox:{}", user.id)) {
                            Some(Ok(v)) => v["entries"].as_array().cloned().unwrap_or_default(),
                            _ => Vec::new(),
                        };
                        for a in &acts {
                            listen |= self.activity_card(ui, a, user.id, false);
                            ui.add_space(12.0);
                        }
                        if !recent.is_empty() {
                            self.recent_activity_ui(ui, &ct, &recent);
                        }
                        if acts.is_empty() && recent.is_empty() {
                            ui.add_space((right.height() * 0.3).max(40.0));
                            ui.vertical_centered(|ui| {
                                ui.label(bold(format!("{name} doesn’t have any activity to share here")).size(17.0).color(t.header_primary));
                                ui.add_space(6.0);
                                ui.label(RichText::new("No activity shared yet – drop them a friendly hello to start chatting").size(14.0).color(t.text_normal));
                                if !is_me {
                                    ui.add_space(16.0);
                                    let b = Button::new(RichText::new(format!("{}  Message", icon::MESSAGE)).font(icon_font(14.0)).color(t.header_primary)).fill(overlay(0.16)).rounding(8.0).min_size(vec2(0.0, 32.0));
                                    message |= ui.add(b).clicked();
                                }
                            });
                        }
                    }
                }
            });
        });
        for a in actions {
            if let UiAction::Reveal(id, k) = a {
                self.revealed.insert((id, k));
            }
        }
        if let Some(fp) = self.full_profile.as_mut() {
            fp.tab = tab;
        }
        if listen || out.listen_along {
            self.toggle_listen_along(user.id);
        }
        if let Some(n) = out.note.take() {
            self.api_results.insert(format!("note:{}", user.id), Ok(serde_json::json!({ "note": n })));
            self.api("note:save", reqwest::Method::PUT, format!("/users/@me/notes/{}", user.id), Some(serde_json::json!({ "note": n })));
        }
        if let Some(at) = out.more.take() {
            self.toggle_profile_more(user.clone(), guild, at);
        }
        if let Some((at, status)) = out.status_react.take() {
            self.open_emoji_picker(crate::features::PickerTarget::StatusReact { user: user.id, status }, at);
        }
        if let Some(status) = out.status_reply.take() {
            self.reply_to_status_in_dm(user.id, &status);
            return;
        }
        // The card's Message / Friend buttons.
        message |= out.message;
        if let Some(add) = out.friend.take() {
            self.friend_click(&user, add);
        }
        if let Some(at) = out.tag_picker.take() {
            self.tag_picker = if self.tag_picker.is_some() { None } else { Some(at + vec2(0.0, 6.0)) };
        }
        if is_me {
            self.tag_picker_ui(ctx);
        }
        if let Some(v) = out.view.take() {
            self.viewer = Some(v);
        } else if let Some((g, at)) = out.tag.take() {
            self.open_tag_popout(g, at);
        } else if let Some(b) = out.badges.take() {
            self.full_profile = None;
            self.badges_view = Some(b);
        } else if let Some((g, role, add)) = out.role_change.take() {
            self.backend.send(crate::backend::Command::MemberRole { guild: g, user: user.id, role, add });
        } else if out.edit_status {
            self.full_profile = None;
            self.open_custom_status_dialog();
        } else if add_connection {
            self.full_profile = None;
            self.settings_open = true;
            self.settings_tab = crate::app::SettingsTab::Connections;
        } else if message {
            self.full_profile = None;
            self.open_dm_with(user.id, String::new());
        } else if let Some(g) = open_guild {
            self.full_profile = None;
            self.select_guild(Some(g));
        } else if let Some(u) = open_user {
            self.open_full_profile(u, None);
        } else if close && self.viewer.is_none() && self.tag_popout.is_none() && self.profile_more.is_none() && self.remove_friend.is_none() && !ctx.data(|d| d.get_temp::<(u64, egui::Pos2, String, u64)>(egui::Id::new("recent_activity_menu")).is_some()) {
            self.full_profile = None;
        }
    }

    /// Mutual server rows as Discord draws them: 48 px (2 px apart), a 40 px
    /// icon with 12 px corners 4 px in, the name in 16 px medium, their
    /// nickname there under it in 12 px. Returns a clicked server.
    fn mutual_servers_ui(&self, ui: &mut Ui, t: &crate::style::Theme, list: &[discord::model::MutualGuild]) -> Option<Id> {
        let mut clicked = None;
        if list.is_empty() {
            ui.add_space(60.0);
            ui.vertical_centered(|ui| ui.label(RichText::new("No servers in common").size(15.0).color(t.text_muted)));
        }
        ui.spacing_mut().item_spacing.y = 2.0;
        for mg in list {
            let Some(gs) = self.store.guilds.get(&mg.id) else { continue };
            let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 48.0), Sense::click());
            if resp.hovered() {
                ui.painter().rect_filled(row, 4.0, overlay(0.12));
            }
            let icon_rect = Rect::from_min_size(pos2(row.left() + 4.0, row.top() + 4.0), vec2(40.0, 40.0));
            match gs.guild.icon_url(80) {
                Some(u) => egui::Image::new(u).rounding(12.0).paint_at(ui, icon_rect),
                None => {
                    ui.painter().rect_filled(icon_rect, 12.0, overlay(0.16));
                    ui.painter().text(icon_rect.center(), Align2::CENTER_CENTER, super::acronym(&gs.guild.name), FontId::proportional(13.0), t.text_normal);
                }
            }
            let p = ui.painter_at(row);
            let x = icon_rect.right() + 10.0;
            let ny = if mg.nick.is_some() { row.center().y - 8.0 } else { row.center().y };
            super::paint_text_emoji(ui, &p, pos2(x, ny), &gs.guild.name, crate::style::medium(16.0), t.text_normal);
            if let Some(n) = &mg.nick {
                p.text(pos2(x, row.center().y + 10.0), Align2::LEFT_CENTER, n, crate::style::medium(12.0), t.text_normal);
            }
            if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                clicked = Some(mg.id);
            }
        }
        clicked
    }

    /// The Board tab as Discord draws it: a card per game widget (mod 16 %,
    /// 16 px corners, 12 / 16 / 16 px padding) under a 14 px medium title.
    /// Covers are 3:4, a quarter of the card wide, 16 px apart: the
    /// favourite beside its name, note and tags; "Games in Rotation" one to
    /// a row beside its name; the rest as a grid.
    fn board_ui(&self, ui: &mut Ui, t: &crate::style::Theme, p: &discord::model::UserProfile) {
        ui.spacing_mut().item_spacing.y = 0.0;
        let cover = |ui: &mut Ui, game: Id, size: egui::Vec2| -> egui::Response {
            let (r, resp) = ui.allocate_exact_size(size, Sense::hover());
            ui.painter().add(Shadow { offset: vec2(0.0, 3.0), blur: 12.0, spread: 0.0, color: Color32::from_black_alpha(41) }.as_shape(r, Rounding::same(8.0)));
            let app = self.apps.get(&game);
            // (Asked for again when all RustCord has is from before covers were fetched.)
            if app.is_none_or(|a| a.game_cover.is_none()) {
                self.apps_wanted.borrow_mut().insert(game);
            }
            match app {
                Some(app) => match app.cover_url() {
                    Some(u) => super::paint_cover(ui, r, &u, Rounding::same(8.0)),
                    None => {
                        ui.painter().rect_filled(r, 8.0, overlay(0.16));
                        ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::GAME, icon_font(size.x * 0.35), t.interactive_normal);
                    }
                },
                None => {
                    ui.painter().rect_filled(r, 8.0, overlay(0.12));
                }
            }
            resp
        };
        let name_of = |game: Id| self.apps.get(&game).map(|a| a.name.clone()).unwrap_or_default();
        for w in p.widgets.iter().filter(|w| !w.data.games.is_empty()) {
            let kind = w.data.kind.as_str();
            let title = match kind {
                "favorite_games" if british() => "Favourite Game".to_string(),
                "favorite_games" => "Favorite Game".to_string(),
                "current_games" => "Games in Rotation".to_string(),
                "played_games" => "Games I Like".to_string(),
                "want_to_play_games" => "Want to Play".to_string(),
                other => other
                    .split('_')
                    .map(|w| {
                        let mut c = w.chars();
                        c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default()
                    })
                    .collect::<Vec<_>>()
                    .join(" "),
            };
            Frame::none()
                .fill(overlay(0.16))
                .stroke(Stroke::new(1.0_f32, crate::style::rgba(151, 151, 159, 10)))
                .rounding(16.0)
                .inner_margin(Margin { left: 16.0, right: 16.0, top: 12.0, bottom: 16.0 })
                .show(ui, |ui| {
                    ui.set_width(ui.available_width());
                    ui.spacing_mut().item_spacing.y = 0.0;
                    let (head, _) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::hover());
                    ui.painter().text(head.left_center(), Align2::LEFT_CENTER, &title, crate::style::medium(14.0), t.text_normal);
                    ui.add_space(8.0);
                    let cw = ((ui.available_width() - 48.0) / 4.0).max(40.0);
                    let size = vec2(cw, cw * 4.0 / 3.0);
                    // A cover with what's said about the game beside it, centred on the cover.
                    let beside = |ui: &mut Ui, g: &discord::model::ProfileGame, rich: bool| {
                        let top = ui.cursor().min;
                        cover(ui, g.game_id, size);
                        let x = top.x + cw + 16.0;
                        let note = g.comment.as_deref().filter(|c| rich && !c.trim().is_empty());
                        let tags: Vec<String> = if rich {
                            // Discord sends ids ("open_to_play"): "Open to play".
                            g.tags.iter().map(|tag| { let words = tag.replace('_', " "); let mut c = words.chars(); c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default() }).collect()
                        } else {
                            Vec::new()
                        };
                        let lines = 18.0 + if note.is_some() { 22.0 } else { 0.0 } + if tags.is_empty() { 0.0 } else { 28.0 };
                        let mut y = top.y + (size.y - lines) / 2.0;
                        let p = ui.painter().with_clip_rect(Rect::from_min_max(pos2(x, top.y), pos2(ui.max_rect().right(), top.y + size.y)));
                        p.text(pos2(x, y + 9.0), Align2::LEFT_CENTER, name_of(g.game_id), crate::style::medium(14.0), t.text_normal);
                        y += 22.0;
                        if let Some(c) = note {
                            p.text(pos2(x, y + 9.0), Align2::LEFT_CENTER, format!("“ {}", c.trim()), FontId::proportional(14.0), t.text_muted);
                            y += 22.0;
                        }
                        let mut tx = x;
                        for tag in tags {
                            let r = p.text(pos2(tx, y + 4.0 + 10.0), Align2::LEFT_CENTER, tag, FontId::proportional(12.0), t.text_normal);
                            tx = r.right() + 12.0;
                        }
                    };
                    match kind {
                        "favorite_games" | "current_games" => {
                            for (i, g) in w.data.games.iter().enumerate() {
                                if i > 0 {
                                    ui.add_space(12.0);
                                }
                                beside(ui, g, kind == "favorite_games");
                            }
                        }
                        _ => {
                            // One measured widget per cover so rows wrap.
                            ui.horizontal_wrapped(|ui| {
                                ui.spacing_mut().item_spacing = vec2(16.0, 16.0);
                                for g in &w.data.games {
                                    let name = name_of(g.game_id);
                                    let resp = cover(ui, g.game_id, size - vec2(0.01, 0.0));
                                    if !name.is_empty() {
                                        resp.on_hover_text(name);
                                    }
                                }
                            });
                        }
                    }
                });
            ui.add_space(12.0);
        }
    }

    /// Discord's profile for bots and apps: one column with the banner across
    /// the top, Message and "Add App" beside the avatar, then Bio and Mutual
    /// Servers tabs (not the two-column user profile).
    fn bot_profile_ui(&mut self, ctx: &egui::Context) {
        let Some(fp) = &self.full_profile else { return };
        let (user, guild, mut tab, opened) = (fp.user.clone(), fp.guild, fp.tab, fp.opened_frame);
        if tab != TAB_SERVERS {
            tab = TAB_BIO;
        }
        let t = self.theme.clone();
        let screen = ctx.screen_rect();
        let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
        egui::Area::new(egui::Id::new("full_profile_bg")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            let (r, resp) = ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(r, 0.0, Color32::from_black_alpha(184));
            close |= resp.clicked() && ctx.cumulative_pass_nr() > opened + 1;
        });
        let data = self.profiles.get(&(user.id, guild));
        let profile = data.and_then(|r| r.as_ref().ok()).cloned();
        let loading = data.is_none();
        let u = profile.as_ref().map(|p| p.user.clone()).filter(|u| !u.username.is_empty()).unwrap_or_else(|| user.clone());
        let modal = Rect::from_center_size(screen.center(), vec2(600.0_f32.min(screen.width() - 40.0), (screen.height() - 80.0).min(620.0)));
        let bg = self.card_background(user.id, guild);
        let inset = self.card_inset(user.id, guild);
        let (mut message, mut add_app, mut open_guild, mut view) = (false, false, None, None);
        let mut actions = Vec::new();
        egui::Area::new(egui::Id::new("full_profile")).order(Order::Foreground).fixed_pos(modal.min).show(ctx, |ui| {
            if ui.ctx().cumulative_pass_nr() <= opened + 1 {
                ui.ctx().move_to_top(ui.layer_id());
            }
            above_backdrop(ui);
            ui.expand_to_include_rect(modal);
            motion::tag(ui, Motion::Modal, 0);
            let border = if self.card_theme(user.id, guild).is_some() { 2.0 } else { 0.0 };
            ui.painter().add(with_shadow(self.card_shapes(modal, user.id, guild, Rounding::same(12.0), border, 212.0), modal));
            // Banner.
            let banner = Rect::from_min_max(modal.min + vec2(inset, inset), pos2(modal.right() - inset, modal.top() + 212.0));
            let corner = Rounding { nw: 12.0 - inset, ne: 12.0 - inset, sw: 0.0, se: 0.0 };
            let color = profile.as_ref().and_then(|p| p.accent_color()).map(rgb).unwrap_or_else(|| crate::style::color_for(u.display_name()));
            ui.painter().rect_filled(banner, corner, color);
            if let Some(url) = profile.as_ref().and_then(|p| p.banner_url()) {
                super::paint_cover(ui, banner, &super::anim(&url), corner);
            }
            // Close, over the banner.
            let x = Rect::from_center_size(pos2(banner.right() - 24.0, banner.top() + 24.0), vec2(30.0, 30.0));
            let xr = ui.interact(x, egui::Id::new("bot_profile_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            ui.painter().circle_filled(x.center(), 15.0, Color32::from_black_alpha(if xr.hovered() { 190 } else { 140 }));
            ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(12.0), Color32::WHITE);
            close |= xr.clicked();
            // Avatar half over the banner.
            let av = Rect::from_center_size(pos2(banner.left() + 24.0 + 60.0, banner.bottom()), vec2(120.0, 120.0));
            ui.painter().circle_filled(av.center(), 66.0, bg);
            paint_avatar(ui, av, Some(super::anim(&u.avatar_animated(240))), u.display_name());
            if ui.interact(av, egui::Id::new(("bot_avatar", u.id.0)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                let big = u.avatar_animated(1024);
                view = Some(crate::features::MediaView { image: big.clone(), video: None, link: big, size: Some((1024.0, 1024.0)) });
            }
            paint_status_dot(ui, av.right_bottom() - vec2(18.0, 18.0), 12.0, self.store.dot_status(u.id), bg);
            // Message and Add App, right-aligned under the banner.
            let by = banner.bottom() + 14.0;
            let add_g = ui.painter().layout_no_wrap(format!("{}  Add App", icon::ADD), icon_font(14.0), t.header_primary);
            let add_r = Rect::from_min_max(pos2(modal.right() - 24.0 - add_g.size().x - 28.0, by), pos2(modal.right() - 24.0, by + 34.0));
            let add_resp = ui.interact(add_r, egui::Id::new("bot_add_app"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            ui.painter().rect_filled(add_r, 8.0, overlay(if add_resp.hovered() { 0.24 } else { 0.16 }));
            ui.painter().galley(add_r.center() - add_g.size() / 2.0, add_g, t.header_primary);
            add_app = add_resp.clicked();
            let msg_r = Rect::from_min_max(pos2(add_r.left() - 8.0 - 34.0, by), pos2(add_r.left() - 8.0, by + 34.0));
            let msg_resp = ui.interact(msg_r, egui::Id::new("bot_message"), Sense::click()).on_hover_text("Message").on_hover_cursor(egui::CursorIcon::PointingHand);
            ui.painter().rect_filled(msg_r, 8.0, overlay(if msg_resp.hovered() { 0.24 } else { 0.16 }));
            ui.painter().text(msg_r.center(), Align2::CENTER_CENTER, icon::MESSAGE, icon_font(15.0), t.header_primary);
            message = msg_resp.clicked();

            // Name, username, tabs, content.
            let body = Rect::from_min_max(pos2(modal.left() + 24.0, banner.bottom() + 70.0), pos2(modal.right() - 24.0, modal.bottom() - 20.0));
            let mut bui = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::top_down(egui::Align::Min)));
            let ui = &mut bui;
            ui.spacing_mut().item_spacing.y = 4.0;
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 8.0;
                let display = profile.as_ref().and_then(|p| p.guild_member.as_ref()).and_then(|m| m.nick.clone()).unwrap_or_else(|| u.display_name().to_string());
                ui.label(RichText::new(display).font(FontId::new(24.0, egui::FontFamily::Name(crate::style::BOLD.into()))).color(t.header_primary));
                super::bot_badge(ui, &t, &u);
            });
            let handle = match u.discriminator.as_deref().filter(|d| *d != "0" && !d.is_empty()) {
                Some(d) => format!("{}#{d}", u.username),
                None => u.username.clone(),
            };
            ui.label(RichText::new(handle).size(14.0).color(t.header_primary));
            ui.add_space(14.0);
            let servers_n = profile.as_ref().map(|p| p.mutual_guilds.len()).unwrap_or(0);
            let servers_label = if servers_n == 1 { "1 Mutual Server".to_string() } else { format!("{servers_n} Mutual Servers") };
            let labels = [(TAB_BIO, "Bio".to_string()), (TAB_SERVERS, servers_label)];
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 24.0;
                for (kind, label) in labels.iter() {
                    let selected = tab == *kind;
                    let g = ui.painter().layout_no_wrap(label.clone(), FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into())), Color32::PLACEHOLDER);
                    let (r, resp) = ui.allocate_exact_size(vec2(g.size().x, 26.0), Sense::click());
                    let fg = if selected || resp.hovered() { t.header_primary } else { t.interactive_normal };
                    ui.painter().galley(pos2(r.left(), r.top()), g, fg);
                    if selected {
                        ui.painter().rect_filled(Rect::from_min_max(pos2(r.left(), r.bottom() - 2.0), r.right_bottom()), 1.0, t.header_primary);
                    }
                    if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                        tab = *kind;
                    }
                }
            });
            let y = ui.cursor().top();
            ui.painter().hline(body.x_range(), y, Stroke::new(1.0_f32, t.border_subtle));
            ui.add_space(12.0);
            ScrollArea::vertical().id_salt("bot_profile_body").auto_shrink([false, false]).show(ui, |ui| {
                ui.set_width(body.width());
                if loading {
                    ui.add_space(20.0);
                    ui.vertical_centered(|ui| ui.spinner());
                    return;
                }
                if tab == TAB_SERVERS {
                    let list = profile.as_ref().map(|p| p.mutual_guilds.clone()).unwrap_or_default();
                    open_guild = self.mutual_servers_ui(ui, &t, &list);
                    return;
                }
                if let Some(bio) = profile.as_ref().and_then(|p| p.bio()) {
                    let fake = Message { guild_id: guild, ..Default::default() };
                    self.render_markdown_sized(ui, &fake, bio, 14.0, t.text_normal, &mut actions);
                    ui.add_space(14.0);
                }
                ui.label(bold("Member Since").size(12.0).color(t.header_secondary));
                ui.add_space(2.0);
                let mut since = short_date(u.id.timestamp_ms());
                let joined = profile.as_ref().and_then(|p| p.guild_member.as_ref()).and_then(|m| m.joined_at.as_deref()).and_then(|j| chrono::DateTime::parse_from_rfc3339(j).ok());
                if let (Some(d), Some(gs)) = (joined, guild.and_then(|g| self.store.guilds.get(&g))) {
                    since = format!("{since}  •  {} {}", gs.guild.name, short_date(d.timestamp_millis().max(0) as u64));
                }
                ui.label(RichText::new(since).size(14.0).color(t.text_normal));
                let roles = profile.as_ref().and_then(|p| p.guild_member.as_ref()).map(|m| m.roles.clone()).unwrap_or_default();
                let mut guild_roles: Vec<discord::model::Role> =
                    guild.and_then(|g| self.store.guilds.get(&g)).map(|g| g.guild.roles.iter().filter(|r| roles.contains(&r.id)).cloned().collect()).unwrap_or_default();
                guild_roles.sort_by_key(|r| std::cmp::Reverse(r.position));
                if !guild_roles.is_empty() {
                    ui.add_space(14.0);
                    ui.label(bold("Roles").size(12.0).color(t.header_secondary));
                    ui.add_space(4.0);
                    ui.horizontal_wrapped(|ui| {
                        ui.spacing_mut().item_spacing = vec2(6.0, 6.0);
                        for r in &guild_roles {
                            role_chip(ui, &t, r, false, u.id, t.border_subtle);
                        }
                    });
                }
            });
        });
        for a in actions {
            if let UiAction::Reveal(id, k) = a {
                self.revealed.insert((id, k));
            }
        }
        if let Some(fp) = self.full_profile.as_mut() {
            fp.tab = tab;
        }
        if let Some(v) = view {
            self.viewer = Some(v);
        } else if add_app {
            ctx.open_url(egui::OpenUrl::new_tab(format!("https://discord.com/oauth2/authorize?client_id={}", user.id)));
        } else if message {
            self.full_profile = None;
            self.open_dm_with(user.id, String::new());
        } else if let Some(g) = open_guild {
            self.full_profile = None;
            self.select_guild(Some(g));
        } else if close && self.viewer.is_none() {
            self.full_profile = None;
        }
    }

    /// Wear `choice`'s Server Tag next to your name (None: no tag):
    /// `PUT /users/@me/clan`. Shown right away; the gateway's USER_UPDATE
    /// confirms it.
    pub fn set_server_tag(&mut self, choice: Option<Id>) {
        let (body, pg) = match choice {
            Some(g) => {
                // The server card if fetched, else the tag on the server itself.
                let gp = self.guild_profiles.get(&g).and_then(|r| r.as_ref().ok());
                let own = self.store.guilds.get(&g).and_then(|gs| gs.guild.profile.as_ref());
                let pg = discord::model::PrimaryGuild {
                    identity_guild_id: Some(g),
                    identity_enabled: Some(true),
                    tag: gp.and_then(|p| p.tag.clone()).or_else(|| own.and_then(|p| p.tag.clone())),
                    badge: gp.and_then(|p| p.badge_hash.clone()).or_else(|| own.and_then(|p| p.badge.clone())),
                };
                (serde_json::json!({ "identity_guild_id": g.to_string(), "identity_enabled": true }), Some(pg))
            }
            None => (serde_json::json!({ "identity_guild_id": serde_json::Value::Null, "identity_enabled": false }), None),
        };
        self.api("set_server_tag", reqwest::Method::PUT, "/users/@me/clan", Some(body));
        if let Some(me) = self.store.me.as_mut() {
            me.primary_guild = pg.clone();
            me.clan = pg;
        }
        if let Some(fp) = self.full_profile.as_mut().filter(|fp| Some(fp.user.id) == self.store.me.as_ref().map(|m| m.id)) {
            if let Some(me) = &self.store.me {
                fp.user.primary_guild = me.primary_guild.clone();
                fp.user.clan = me.clan.clone();
            }
        }
        let mine = self.store.me.as_ref().map(|m| m.id);
        for ((u, _), p) in self.profiles.iter_mut() {
            if Some(*u) == mine {
                if let Ok(p) = p {
                    p.user.primary_guild = self.store.me.as_ref().and_then(|m| m.primary_guild.clone());
                    p.user.clan = self.store.me.as_ref().and_then(|m| m.clan.clone());
                }
            }
        }
    }

    /// Your server tag dropdown (own full profile): the servers you're in
    /// that have a tag, and "None". Picking one is `PUT /users/@me/clan`.
    fn tag_picker_ui(&mut self, ctx: &egui::Context) {
        // A failed save: say so (the next USER_UPDATE or profile fetch fixes the chip).
        if self.api_result("set_server_tag").is_some_and(|r| r.is_err()) {
            if let Some(Err(e)) = self.api_take("set_server_tag") {
                self.toast(format!("Couldn't change your server tag: {e}"), true);
            }
        }
        let Some(at) = self.tag_picker else { return };
        let Some(me) = self.store.me.clone() else { return };
        let t = self.theme.clone();
        let current = me.server_tag_guild();
        let candidates: Vec<Id> =
            self.store.guild_order.iter().copied().filter(|g| self.store.guilds.get(g).is_some_and(|gs| gs.guild.features.as_ref().is_some_and(|f| f.iter().any(|f| f == "GUILD_TAGS")))).collect();
        // Each server's tag text and badge come from its guild profile.
        for g in &candidates {
            let asked = egui::Id::new(("tag_picker_asked", g.0));
            if !self.guild_profiles.contains_key(g) && !ctx.data(|d| d.get_temp::<bool>(asked).unwrap_or(false)) {
                ctx.data_mut(|d| d.insert_temp(asked, true));
                self.backend.send(crate::backend::Command::FetchGuildProfile(*g));
            }
        }
        let mut pick: Option<Option<Id>> = None;
        let area = egui::Area::new(egui::Id::new("tag_picker")).order(Order::Tooltip).fixed_pos(at).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(6.0).show(ui, |ui| {
                ui.set_width(260.0);
                ui.spacing_mut().item_spacing.y = 0.0;
                ui.label(bold("Server Tag").size(12.0).color(t.header_secondary));
                ui.add_space(6.0);
                ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
                    let row = |ui: &mut Ui, selected: bool| -> (Rect, egui::Response) {
                        let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click());
                        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                        if resp.hovered() || selected {
                            ui.painter().rect_filled(r, 6.0, overlay(if selected { 0.12 } else { 0.16 }));
                        }
                        if selected {
                            ui.painter().text(r.right_center() - vec2(12.0, 0.0), Align2::CENTER_CENTER, icon::CHECK, icon_font(12.0), t.accent);
                        }
                        (r, resp)
                    };
                    for g in &candidates {
                        let Some(gs) = self.store.guilds.get(g) else { continue };
                        let gp = self.guild_profiles.get(g).and_then(|r| r.as_ref().ok());
                        let tag = gp.and_then(|p| p.tag.clone()).filter(|t| !t.is_empty());
                        if gp.is_some() && tag.is_none() {
                            continue;
                        }
                        let (r, resp) = row(ui, current == Some(*g));
                        let icon_rect = Rect::from_center_size(r.left_center() + vec2(18.0, 0.0), vec2(24.0, 24.0));
                        match gs.guild.icon_url(48) {
                            Some(u) => egui::Image::new(u).rounding(7.0).paint_at(ui, icon_rect),
                            None => {
                                ui.painter().rect_filled(icon_rect, 7.0, overlay(0.16));
                                ui.painter().text(icon_rect.center(), Align2::CENTER_CENTER, super::acronym(&gs.guild.name), FontId::proportional(9.0), t.text_normal);
                            }
                        }
                        let name_max = r.width() - 140.0;
                        // One line, "…" when it doesn't fit.
                        let mut job = egui::text::LayoutJob::simple_singleline(gs.guild.name.clone(), FontId::proportional(14.0), t.header_primary);
                        job.wrap = egui::text::TextWrapping::truncate_at_width(name_max);
                        let galley = ui.painter().layout_job(job);
                        ui.painter().galley(pos2(icon_rect.right() + 10.0, r.center().y - galley.size().y / 2.0), galley, t.header_primary);
                        match &tag {
                            Some(text) => {
                                let badge = gp.and_then(|p| p.badge_hash.as_ref()).map(|b| format!("https://cdn.discordapp.com/guild-tag-badges/{g}/{b}.png?size=32"));
                                super::paint_tag_chip(ui, ui.painter(), r.right() - 30.0 - 70.0, r.center().y, text, badge.as_deref(), &t);
                            }
                            None => {
                                ui.painter().text(r.right_center() - vec2(34.0, 0.0), Align2::RIGHT_CENTER, "…", FontId::proportional(13.0), t.text_muted);
                            }
                        }
                        if resp.clicked() && tag.is_some() {
                            pick = Some(Some(*g));
                        }
                    }
                    if candidates.is_empty() {
                        ui.label(RichText::new("None of your servers has a tag yet.").size(13.0).color(t.text_muted));
                        ui.add_space(6.0);
                    }
                    let (r, resp) = row(ui, current.is_none());
                    ui.painter().text(r.left_center() + vec2(10.0, 0.0), Align2::LEFT_CENTER, "Don't show a tag", FontId::proportional(14.0), t.header_primary);
                    if resp.clicked() {
                        pick = Some(None);
                    }
                });
            });
        });
        if let Some(choice) = pick {
            self.tag_picker = None;
            self.set_server_tag(choice);
        } else if ctx.input(|i| i.pointer.any_click()) && !ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| area.response.rect.contains(p) || (p - at).length() < 24.0) {
            self.tag_picker = None;
        }
    }

    pub fn switcher_ui(&mut self, ctx: &egui::Context) {
        let Some(mut query) = self.switcher.take() else { return };
        let t = self.theme.clone();
        let q = query.trim().to_lowercase();

        // (label, sub, avatar url, target)
        let mut items: Vec<(String, String, Option<String>, SwitchTo)> = Vec::new();
        for id in self.store.dm_list() {
            if let Some(c) = self.store.channels.get(&id) {
                let avatar = (c.kind == channel_kind::DM).then(|| c.recipients.first().map(|u| u.avatar_or_default(64))).flatten();
                items.push((self.store.label(c), "Direct Message".into(), avatar, SwitchTo::Channel(id)));
            }
        }
        for r in self.store.relationships.values().filter(|r| r.kind == 1) {
            if let Some(u) = self.store.users.get(&r.id) {
                items.push((u.display_name().to_string(), u.username.clone(), Some(u.avatar_or_default(64)), SwitchTo::User(u.id)));
            }
        }
        for gid in &self.store.guild_order {
            let Some(g) = self.store.guilds.get(gid) else { continue };
            items.push((g.guild.name.clone(), "Server".into(), g.guild.icon_url(64), SwitchTo::Guild(*gid)));
            for row in self.store.channel_rows(*gid) {
                if let ChannelRow::Channel { id, name, kind, .. } = row {
                    if channel_kind::is_text(kind) {
                        items.push((format!("#{name}"), g.guild.name.clone(), None, SwitchTo::Channel(id)));
                    }
                }
            }
        }
        items.retain(|(l, s, ..)| q.is_empty() || l.to_lowercase().contains(&q) || s.to_lowercase().contains(&q));
        items.truncate(60);

        let mut chosen: Option<usize> = None;
        let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
        egui::Window::new("switcher")
            .title_bar(false)
            .collapsible(false)
            .resizable(false)
            .anchor(Align2::CENTER_TOP, vec2(0.0, 90.0))
            .fixed_size([560.0, 0.0])
            .frame(Frame::window(&ctx.style()).fill(t.bg_secondary).inner_margin(16.0).rounding(8.0))
            .show(ctx, |ui| {
                ui.label(bold("Search for servers, channels or DMs").size(13.0).color(t.header_secondary));
                ui.add_space(6.0);
                let r = ui.add(TextEdit::singleline(&mut query).hint_text("Where would you like to go?").desired_width(f32::INFINITY).font(FontId::proportional(18.0)).margin(vec2(10.0, 10.0)));
                r.request_focus();
                if ui.input(|i| i.key_pressed(Key::Enter)) && !items.is_empty() {
                    chosen = Some(0);
                }
                ui.add_space(8.0);
                ScrollArea::vertical().max_height(360.0).show(ui, |ui| {
                    for (i, (label, sub, avatar, _)) in items.iter().enumerate() {
                        let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());
                        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                        if resp.hovered() || (i == 0 && !q.is_empty()) {
                            ui.painter().rect_filled(rect, 4.0, t.bg_hover);
                        }
                        let av = Rect::from_center_size(pos2(rect.left() + 18.0, rect.center().y), vec2(22.0, 22.0));
                        if avatar.is_some() || sub == "Direct Message" {
                            paint_avatar(ui, av, avatar.clone(), label);
                        } else {
                            super::paint_hashtag(ui.painter(), Rect::from_center_size(av.center(), vec2(18.0, 18.0)), t.text_muted);
                        }
                        ui.painter().text(pos2(rect.left() + 38.0, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(15.0), t.header_primary);
                        ui.painter().text(rect.right_center() - vec2(10.0, 0.0), Align2::RIGHT_CENTER, sub, FontId::proportional(12.0), t.text_muted);
                        if resp.clicked() {
                            chosen = Some(i);
                        }
                    }
                });
                // The click on "Find or start a conversation" that opened this is still
                // this frame's click: it used to close the switcher at once.
                let opened = ui.data(|d| d.get_temp::<u64>(egui::Id::new("switcher_opened"))).unwrap_or(0);
                let fresh = ui.ctx().cumulative_pass_nr() <= opened + 1;
                if !fresh && ui.input(|i| i.pointer.any_click()) && !ui.rect_contains_pointer(ui.max_rect()) {
                    close = true;
                }
            });

        if let Some(i) = chosen {
            match items.swap_remove(i).3 {
                SwitchTo::Channel(id) => {
                    let guild = self.store.channels.get(&id).and_then(|c| c.guild_id);
                    self.current_guild = guild;
                    self.select_channel(Some(id));
                }
                SwitchTo::User(id) => self.open_dm_with(id, String::new()),
                SwitchTo::Guild(id) => self.select_guild(Some(id)),
            }
            return;
        }
        if !close {
            self.switcher = Some(query);
        }
    }
}

/// 58020 -> "58,020" (Discord's en-GB number format).
fn group_thousands(n: u64) -> String {
    let digits = n.to_string();
    let mut out = String::new();
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(c);
    }
    out
}

/// A user's avatar colour as Discord picks it for a banner-less profile
/// (see `palette`); asks for the picture until it's decoded.
fn avatar_palette(ctx: &egui::Context, user: &User) -> Option<Color32> {
    let uri = match &user.avatar {
        Some(h) => format!("https://cdn.discordapp.com/avatars/{}/{h}.webp?size=128", user.id),
        None => user.avatar_or_default(128),
    };
    if let Some([r, g, b]) = crate::palette::get(&uri) {
        return Some(Color32::from_rgb(r, g, b));
    }
    let _ = ctx.try_load_image(&uri, egui::SizeHint::default());
    None
}

/// A full-profile section heading as Discord sets it: 12 px medium on a
/// 16 px line, in the subtle colour.
fn heading(ui: &mut Ui, t: &crate::style::Theme, text: &str) {
    let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 16.0), Sense::hover());
    ui.painter().text(r.left_center(), Align2::LEFT_CENTER, text, crate::style::medium(12.0), subtle(t));
}

/// What stands under a heading: 14 px on an 18 px line.
fn value(ui: &mut Ui, t: &crate::style::Theme, text: &str) {
    let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover());
    ui.painter().text(r.left_center(), Align2::LEFT_CENTER, text, FontId::proportional(14.0), t.text_normal);
}

/// Discord's text-subtle: #b5bac1 on dark themes; on a profile theme (whose
/// see-through text [`RustCord::card_text_theme`] sets) its 88 % ink.
fn subtle(t: &crate::style::Theme) -> Color32 {
    if t.text_normal.a() < 255 {
        t.header_secondary
    } else if t.light {
        t.text_muted
    } else {
        Color32::from_rgb(0xb5, 0xba, 0xc1)
    }
}

/// How long ago, as Discord says it on an activity ("6h ago", and "6 hours
/// ago" for its tooltip): seconds under a minute, minutes under an hour,
/// hours under twelve, days under nine, weeks under four, then months of
/// 30 days; each rounded to the nearest.
fn ago(secs: i64) -> (String, String) {
    const MINUTE: i64 = 60;
    const HOUR: i64 = 3600;
    const DAY: i64 = 86_400;
    let secs = secs.max(0);
    let nearest = |unit: i64| (secs as f64 / unit as f64).round() as i64;
    let (n, short, long) = if secs < MINUTE {
        (secs, "s", "second")
    } else if secs < HOUR {
        (nearest(MINUTE), "m", "minute")
    } else if secs < 12 * HOUR {
        (nearest(HOUR), "h", "hour")
    } else if secs < 9 * DAY {
        (nearest(DAY), "d", "day")
    } else if secs < 28 * DAY {
        (nearest(7 * DAY), "w", "week")
    } else {
        (nearest(30 * DAY), "mo", "month")
    };
    (format!("{n}{short} ago"), format!("{n} {long}{} ago", if n == 1 { "" } else { "s" }))
}

/// "Returning after 2 months" (days when it's under a month).
fn returning_after(last_played: chrono::DateTime<chrono::Utc>, now: chrono::DateTime<chrono::Utc>) -> String {
    use chrono::Datelike;
    let mut months = (now.year() - last_played.year()) * 12 + now.month() as i32 - last_played.month() as i32;
    if now.day() < last_played.day() {
        months -= 1;
    }
    let (n, unit) = if months > 0 { (months as i64, "month") } else { ((now - last_played).num_days().max(0), "day") };
    format!("Returning after {n} {unit}{}", if n == 1 { "" } else { "s" })
}

impl RustCord {
    /// Discord's "Recent activity": a 12 px medium label, then a card each
    /// (mod 16 %, 12 px corners and padding, 8 px apart): a 60 px picture
    /// with 8 px corners, the title in 14 px semibold (a song's artists under
    /// it) and a 12 px line of what's notable: 🎮 "3w ago", ⚡ "3x Streak",
    /// 🔥 "Trending", ↻ "Returning after 2 months", "5h Marathon",
    /// 🌱 "New Player". Games and listening sessions; times count from the
    /// entry's id.
    fn recent_activity_ui(&self, ui: &mut Ui, t: &crate::style::Theme, entries: &[serde_json::Value]) {
        ui.spacing_mut().item_spacing.y = 0.0;
        ui.label(RichText::new("Recent activity").font(crate::style::medium(12.0)).color(subtle(t)));
        ui.add_space(8.0);
        let now = chrono::Utc::now();
        for e in entries {
            let id = e["id"].as_str().and_then(|s| s.parse::<u64>().ok()).map(Id);
            let age = id.map(|id| now.timestamp() - (id.timestamp_ms() / 1000) as i64);
            // (title, line under it, picture, the game's app, time icon, a
            // song's Spotify pages: track, album, artist)
            let (title, under, picture, app, glyph, spotify) = match e["extra"]["type"].as_str() {
                Some("played_game_extra") => {
                    let app = e["extra"]["application_id"].as_str().and_then(|s| s.parse::<u64>().ok()).map(Id);
                    (e["extra"]["game_name"].as_str().unwrap_or("").to_string(), None, None, app, icon::GAME_CONTROLLER, None)
                }
                Some("listened_session_extra") => {
                    let media = &e["extra"]["entries"][0]["media"];
                    // (Discord names the first artist only.)
                    let artist = media["artists"][0]["name"].as_str().filter(|a| !a.is_empty()).map(str::to_string);
                    let page = |kind: &str, id: &serde_json::Value| id.as_str().filter(|i| !i.is_empty()).map(|i| format!("https://open.spotify.com/{kind}/{i}"));
                    let pages = (page("track", &media["external_id"]), page("album", &media["external_parent_id"]), page("artist", &media["artists"][0]["external_id"]));
                    (media["title"].as_str().unwrap_or("").to_string(), artist, media["image_url"].as_str().map(str::to_string), None, icon::MUSIC, Some(pages))
                }
                _ => continue,
            };
            let (card, _) = ui.allocate_exact_size(vec2(ui.available_width(), 84.0), Sense::hover());
            ui.painter().rect_filled(card, 12.0, overlay(0.16));
            let art = Rect::from_min_size(card.min + vec2(12.0, 12.0), vec2(60.0, 60.0));
            let known = app.and_then(|a| self.apps.get(&a));
            match picture.or_else(|| known.and_then(|info| info.icon_url())) {
                Some(u) => egui::Image::new(u).rounding(8.0).paint_at(ui, art),
                None => {
                    ui.painter().rect_filled(art, 8.0, overlay(0.12));
                    if known.is_some() || app.is_none() {
                        super::paint_icon(ui.painter(), Rect::from_center_size(art.center(), vec2(28.0, 28.0)), glyph, t.interactive_normal);
                    }
                }
            }
            if let Some(a) = app.filter(|_| known.is_none()) {
                self.apps_wanted.borrow_mut().insert(a);
            }
            // A song's cover, title and artist open its album, the track and
            // the artist on Spotify (Discord's web player links).
            let key = id.map_or(0, |i| i.0);
            let link = |ui: &mut Ui, rect: Rect, url: Option<&String>, what: &str, underline: Option<Color32>| {
                let Some(url) = url else { return };
                let resp = ui.interact(rect, egui::Id::new(("recent_link", key, what.to_string())), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                if let (true, Some(c)) = (resp.hovered(), underline) {
                    ui.painter().hline(rect.x_range(), rect.bottom() - 1.0, Stroke::new(1.0_f32, c));
                }
                if resp.clicked() {
                    ui.ctx().open_url(egui::OpenUrl::new_tab(url));
                }
            };
            if let Some((_, album, _)) = &spotify {
                link(ui, art, album.as_ref(), "album", None);
            }
            // The text block (title, artists, badges 4 px apart) is centred on the picture.
            let x = art.right() + 12.0;
            let clip = ui.painter().with_clip_rect(Rect::from_min_max(pos2(x, card.top()), pos2(card.right() - 36.0, card.bottom())));
            let block = 18.0 + if under.is_some() { 16.0 } else { 0.0 } + 4.0 + 16.0;
            let mut y = art.center().y - block / 2.0;
            let title_rect = clip.text(pos2(x, y + 9.0), Align2::LEFT_CENTER, &title, FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.text_normal);
            if let Some((track, _, _)) = &spotify {
                link(ui, title_rect.intersect(clip.clip_rect()), track.as_ref(), "track", Some(t.text_normal));
            }
            y += 18.0;
            if let Some(artists) = &under {
                let artist_rect = clip.text(pos2(x, y + 8.0), Align2::LEFT_CENTER, artists, FontId::proportional(12.0), t.text_normal);
                if let Some((_, _, artist)) = &spotify {
                    link(ui, artist_rect.intersect(clip.clip_rect()), artist.as_ref(), "artist", Some(t.text_normal));
                }
                y += 16.0;
            }
            // Discord's ⋯ (16 px, 12 px from the corner): for a song, "Play on Spotify".
            if let Some(track) = spotify.as_ref().and_then(|(track, _, _)| track.clone()) {
                let dots = Rect::from_min_size(pos2(card.right() - 32.0, card.top() + 12.0), vec2(16.0, 16.0));
                let resp = ui.interact(dots, egui::Id::new(("recent_more", key)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("More");
                super::paint_icon(ui.painter(), dots, icon::MORE, if resp.hovered() { t.header_primary } else { t.interactive_normal });
                let menu_id = egui::Id::new("recent_activity_menu");
                if resp.clicked() {
                    let open = ui.ctx().data(|d| d.get_temp::<(u64, egui::Pos2, String, u64)>(menu_id)).is_some_and(|(k, ..)| k == key);
                    let frame = ui.ctx().cumulative_pass_nr();
                    ui.ctx().data_mut(|d| if open { d.remove::<(u64, egui::Pos2, String, u64)>(menu_id) } else { d.insert_temp(menu_id, (key, pos2(dots.right() + 8.0, dots.top()), track, frame)) });
                }
            }
            // Each piece: a 12 px icon, 4 px, its text; 8 px apart.
            let y = y + 4.0 + 8.0;
            let mut px = x;
            let mut piece = |glyph: Option<&str>, text: &str, tip: Option<String>| {
                let slot = Rect::from_min_size(pos2(px, y - 6.0), vec2(12.0, 12.0));
                // (Icons and text both in the subtle colour, as Discord's profile has them.)
                match glyph {
                    Some(g) => super::paint_icon(ui.painter(), slot, g, subtle(t)),
                    None => paint_return_icon(ui.painter(), slot, subtle(t)),
                }
                let g = ui.painter().layout_no_wrap(text.to_string(), FontId::proportional(12.0), subtle(t));
                let r = Rect::from_min_size(pos2(px, y - 8.0), vec2(16.0 + g.size().x, 16.0));
                ui.painter().galley(pos2(px + 16.0, y - g.size().y / 2.0), g, subtle(t));
                if let Some(tip) = tip {
                    ui.interact(r, egui::Id::new(("recent_piece", id.map(|i| i.0), text.to_string())), Sense::hover()).on_hover_text(tip);
                }
                px = r.right() + 8.0;
            };
            if let Some((short, long)) = age.map(ago) {
                piece(Some(glyph), &short, Some(long));
            }
            // In Discord's order (web module 322789): New Player, Streak,
            // Trending, Returning, Marathon.
            let traits = e["traits"].as_array().map(Vec::as_slice).unwrap_or_default();
            let of = |kind: u64| traits.iter().find(|tr| tr["type"].as_u64() == Some(kind));
            if of(1).and_then(|tr| tr["first_time"].as_bool()) == Some(true) {
                piece(Some(icon::SPROUT), "New Player", None);
            }
            // A streak counts from three days, while the entry is under two days old.
            if let Some(n) = of(8).and_then(|tr| tr["streak_count_days"].as_u64()).filter(|n| *n >= 3 && age.is_some_and(|a| a <= 48 * 3600)) {
                piece(Some(icon::BOLT), &format!("{n}x Streak"), Some(format!("{n}-day streak\nPlayed {n} days in a row")));
            }
            if of(9).and_then(|tr| tr["trending"].as_u64()).unwrap_or(0) > 0 {
                piece(Some(icon::FLAME), "Trending", None);
            }
            if let Some(last) = of(5).and_then(|tr| tr["resurrected_last_played"].as_str()).and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) {
                piece(None, &returning_after(last.with_timezone(&chrono::Utc), now), None);
            }
            if of(6).and_then(|tr| tr["marathon"].as_bool()) == Some(true) {
                let hours = (of(2).and_then(|tr| tr["duration_seconds"].as_f64()).unwrap_or(0.0) / 3600.0).round() as u64;
                if hours > 0 {
                    piece(Some(icon::BOLT), &format!("{hours}h Marathon"), Some(format!("Played for {hours}h")));
                }
            }
            ui.add_space(8.0);
        }
    }
}

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

    #[test]
    fn status_replies_quote_like_discord() {
        // Discord: `> -# *Replied to NAME's status*\n> STATUS\nINPUT`.
        assert_eq!(status_quote("Replied", "ferris", ".gg/example") + "nice", "> -# *Replied to ferris's status*\n> .gg/example\nnice");
        // An emoji-only status has nothing to quote.
        assert_eq!(status_quote("Reacted", "ferris", "") + "🔥", "> -# *Reacted to ferris's status*\n🔥");
    }

    #[test]
    fn dates_follow_the_account_language() {
        let d = chrono::NaiveDate::from_ymd_opt(2024, 10, 18).unwrap();
        assert_eq!(short_date_in(d, false), "Oct 18, 2024");
        assert_eq!(short_date_in(d, true), "18 Oct 2024");
        assert_eq!(short_date_in(chrono::NaiveDate::from_ymd_opt(2019, 9, 16).unwrap(), true), "16 Sept 2019");
    }

    #[test]
    fn ago_rounds_like_discord() {
        assert_eq!(ago(42).0, "42s ago");
        assert_eq!(ago(90 * 60).0, "2h ago");
        // Past twelve hours it counts days.
        assert_eq!(ago(20 * 3600), ("1d ago".to_string(), "1 day ago".to_string()));
        assert_eq!(ago(8 * 86_400).0, "8d ago");
        assert_eq!(ago(22 * 86_400).0, "3w ago");
        assert_eq!(ago(70 * 86_400), ("2mo ago".to_string(), "2 months ago".to_string()));
    }

    #[test]
    fn returning_counts_whole_months() {
        let at = |s: &str| chrono::DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&chrono::Utc);
        // (Counted to today, as Discord does: last played 19 Sept read
        // "Returning after 2 months" on 1 Dec.)
        assert_eq!(returning_after(at("2026-09-19T16:01:38Z"), at("2026-11-07T13:49:38Z")), "Returning after 1 month");
        assert_eq!(returning_after(at("2026-09-19T16:01:38Z"), at("2026-12-01T00:00:00Z")), "Returning after 2 months");
        assert_eq!(returning_after(at("2026-11-20T00:00:00Z"), at("2026-12-01T00:00:00Z")), "Returning after 11 days");
    }
}