Skip to content

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

57.0 KB
Raw Blame
//! Discord's badges as `/users/{id}/badges` describes them (names, tiers,
//! progress, rarity, artwork): the badge row on profiles and its tooltips
//! ("Nitro Platinum. Subscriber since 03/09/2025"), and the "Your badges"
//! window with its tier track, progress and "Customise Your Badges" (show,
//! hide and reorder; saved with PATCH /users/@me/badges/settings).

use crate::app::RustCord;
use crate::style::{icon, icon_font, overlay, Theme};
use discord::model::Id;
use eframe::egui::{self, pos2, vec2, Align2, Color32, CursorIcon, FontId, Frame, Key, Margin, Order, Rect, RichText, Rounding, ScrollArea, Sense, Stroke, Ui};
use serde_json::Value;
use std::collections::HashSet;

#[derive(Clone, Debug, Default)]
pub struct BadgeTier {
    pub key: String,
    pub name: String,
    pub rarity: u8,
    pub icon: Option<String>,
    pub owned: bool,
    pub milestone: String,
}

#[derive(Clone, Debug, Default)]
pub struct BadgeInfo {
    pub id: u32,
    pub name: String,
    pub description: String,
    pub info_label: String,
    pub rarity: u8,
    pub icon: Option<String>,
    pub big_icon: Option<String>,
    pub big_icon_animated: Option<String>,
    pub earnable: bool,
    pub owned: bool,
    pub hidden: bool,
    pub current_tier: Option<String>,
    pub next_tier: Option<String>,
    pub tier_obtained: Vec<(String, String)>,
    pub obtained_at: Option<String>,
    pub tiers: Vec<BadgeTier>,
    /// (current, floor, threshold, helper text)
    pub progress: Option<(f64, f64, f64, String)>,
}

fn s(v: &Value, k: &str) -> String {
    v[k].as_str().unwrap_or("").to_string()
}

fn opt(v: &Value, k: &str) -> Option<String> {
    v[k].as_str().filter(|x| !x.is_empty()).map(String::from)
}

impl BadgeInfo {
    pub fn parse(v: &Value) -> Option<BadgeInfo> {
        let id = v["badge_id"].as_u64()? as u32;
        let tiers = v["tiers"]
            .as_array()
            .into_iter()
            .flatten()
            .map(|t| BadgeTier {
                key: s(t, "key"),
                name: s(t, "name"),
                rarity: t["rarity"].as_u64().unwrap_or(0) as u8,
                icon: opt(t, "simple_icon_raster_url").or_else(|| opt(t, "simple_icon_url")),
                owned: t["owned"].as_bool().unwrap_or(false),
                milestone: s(t, "milestone_text"),
            })
            .collect();
        let progress = v["progress"].as_array().and_then(|p| p.first()).map(|p| {
            (p["current"].as_f64().unwrap_or(0.0), p["floor"].as_f64().unwrap_or(0.0), p["threshold"].as_f64().unwrap_or(1.0), s(p, "progress_helper_text"))
        });
        Some(BadgeInfo {
            id,
            name: s(v, "name"),
            description: s(v, "description"),
            info_label: s(v, "info_label"),
            rarity: v["rarity"].as_u64().unwrap_or(0) as u8,
            icon: opt(v, "simple_icon_raster_url").or_else(|| opt(v, "simple_icon_url")),
            big_icon: opt(v, "complex_icon_static_url").or_else(|| opt(v, "simple_icon_url")),
            big_icon_animated: opt(v, "complex_icon_animated_url"),
            earnable: v["is_earnable"].as_bool().unwrap_or(false),
            owned: v["owned"].as_bool().unwrap_or(false),
            hidden: v["hidden"].as_bool().unwrap_or(false),
            current_tier: opt(v, "current_tier"),
            next_tier: opt(v, "next_tier"),
            tier_obtained: v["tier_obtained_at"].as_object().map(|m| m.iter().map(|(k, d)| (k.clone(), d.as_str().unwrap_or("").to_string())).collect()).unwrap_or_default(),
            obtained_at: opt(v, "obtained_at"),
            tiers,
            progress,
        })
    }

    fn tier(&self, key: Option<&str>) -> Option<&BadgeTier> {
        let key = key?;
        self.tiers.iter().find(|t| t.key == key)
    }

    /// "Nitro Platinum", "Game Variety Explorer" (the name and its tier).
    pub fn title(&self) -> String {
        match self.tier(self.current_tier.as_deref()).filter(|t| !t.name.is_empty()) {
            Some(t) => format!("{} {}", self.name, t.name),
            None => self.name.clone(),
        }
    }

    /// The small icon, in the current tier's look.
    pub fn small_icon(&self) -> Option<String> {
        self.tier(self.current_tier.as_deref()).and_then(|t| t.icon.clone()).or_else(|| self.icon.clone())
    }
}

/// Discord's rarity (1 common, 2 rare, 3 epic, 5 mythic): the chip's label,
/// fill, text colour and border ring (from its --badge-* tokens).
struct Rarity {
    label: &'static str,
    fill: Color32,
    text: Color32,
    ring: (Color32, Color32),
}

fn rarity(r: u8) -> Rarity {
    let c = |r, g, b| Color32::from_rgb(r, g, b);
    match r {
        0 | 1 => Rarity { label: "COMMON", fill: crate::style::rgba(151, 151, 159, 61), text: c(201, 202, 206), ring: (c(129, 130, 138), c(129, 130, 138)) },
        2 => Rarity { label: "RARE", fill: crate::style::rgba(88, 101, 242, 61), text: c(160, 169, 250), ring: (c(88, 101, 242), c(45, 53, 173)) },
        3 | 4 => Rarity { label: "EPIC", fill: crate::style::rgba(160, 86, 242, 61), text: c(202, 158, 249), ring: (c(255, 76, 210), c(160, 86, 242)) },
        _ => Rarity { label: "MYTHIC", fill: crate::style::rgba(254, 110, 13, 61), text: c(254, 146, 66), ring: (c(255, 224, 71), c(254, 110, 13)) },
    }
}

fn date(iso: &str) -> String {
    chrono::DateTime::parse_from_rfc3339(iso).map(|d| d.with_timezone(&chrono::Local).format("%d/%m/%y").to_string()).unwrap_or_default()
}

/// Badge ids (Discord's enum): Nitro, Server Boosting, Quests, Orbs, Gifting,
/// the four "levelled" activity badges and Staff.
const PREMIUM_TENURE: u32 = 1;
const GUILD_BOOSTER: u32 = 12;
const QUEST_COMPLETED: u32 = 14;
const ORB_PROFILE: u32 = 16;
const GIFTING: u32 = 17;
const STAFF: u32 = 22;
/// Badges that get Discord's blue "new" dot until you've looked at them.
const INDICATOR_BADGES: [u32; 4] = [18, 19, 20, 21];

/// Badges Discord won't let you hide ("Badge is always visible").
fn always_visible(id: u32) -> bool {
    matches!(id, STAFF | PREMIUM_TENURE)
}

/// The tier a badge shows: the current one, or the next while locked.
fn shown_tier(b: &BadgeInfo) -> Option<&BadgeTier> {
    let key = if b.owned { b.current_tier.as_deref() } else { b.next_tier.as_deref() };
    key.and_then(|k| b.tiers.iter().find(|t| t.key == k)).or_else(|| b.tiers.first())
}

/// The "Your badges" window and its "Customise your badges" card.
pub struct BadgeWindow {
    pub sel: Option<u32>,
    pub customize: bool,
    pub order: Vec<u32>,
    pub hidden: HashSet<u32>,
    pub dirty: bool,
    /// The tile being dragged in the customise card, and where it was grabbed.
    pub drag: Option<(u32, egui::Vec2)>,
    /// A tile's "⋯" menu: badge and where it hangs.
    pub menu: Option<(u32, egui::Pos2, u64)>,
}

impl BadgeWindow {
    fn new(sel: Option<u32>) -> Self {
        BadgeWindow { sel, customize: false, order: Vec::new(), hidden: HashSet::new(), dirty: false, drag: None, menu: None }
    }
}

/// Which "new" dots you've seen (Discord keeps them in its own local store;
/// here a small file next to the other settings).
fn seen_store() -> &'static std::sync::Mutex<Option<HashSet<u32>>> {
    static SEEN: std::sync::OnceLock<std::sync::Mutex<Option<HashSet<u32>>>> = std::sync::OnceLock::new();
    SEEN.get_or_init(|| std::sync::Mutex::new(None))
}

fn seen_ids(dir: Option<&std::path::Path>) -> HashSet<u32> {
    let mut g = seen_store().lock().unwrap_or_else(|e| e.into_inner());
    if g.is_none() {
        let loaded = dir.and_then(|d| std::fs::read_to_string(d.join("badges-seen.json")).ok()).and_then(|s| serde_json::from_str::<Vec<u32>>(&s).ok()).unwrap_or_default();
        *g = Some(loaded.into_iter().collect());
    }
    g.clone().unwrap_or_default()
}

fn mark_seen(dir: Option<&std::path::Path>, id: u32) {
    let mut set = seen_ids(dir);
    if !INDICATOR_BADGES.contains(&id) || !set.insert(id) {
        return;
    }
    if let Some(d) = dir {
        let mut v: Vec<u32> = set.iter().copied().collect();
        v.sort_unstable();
        let _ = std::fs::write(d.join("badges-seen.json"), serde_json::to_string(&v).unwrap_or_default());
    }
    *seen_store().lock().unwrap_or_else(|e| e.into_inner()) = Some(set);
}

/// A badge's large art (animated when Discord has it).
fn art_uri(b: &BadgeInfo) -> Option<String> {
    b.big_icon_animated.as_deref().and_then(|u| crate::video::frame_uri(u, super::animating())).or_else(|| b.big_icon.clone()).or_else(|| b.small_icon())
}

/// Whether the small icons of `badges` are ready to draw at `size`, starting
/// the loads of those that aren't. One that failed counts as ready: it won't
/// come, and mustn't hold the others back.
pub fn icons_loaded<'a>(ctx: &egui::Context, badges: impl Iterator<Item = &'a BadgeInfo>, size: egui::Vec2) -> bool {
    use egui::load::TexturePoll;
    // (Every icon is asked for, not just up to the first that isn't ready.)
    badges
        .filter_map(BadgeInfo::small_icon)
        .map(|icon| !matches!(egui::Image::new(icon).load_for_size(ctx, size), Ok(TexturePoll::Pending { .. })))
        .fold(true, |all, ready| all && ready)
}

/// Paint `src` inside `rect` keeping its aspect ratio (CSS object-fit: contain).
fn paint_contain(ui: &Ui, src: &str, rect: Rect, tint: Color32) {
    let size = egui::Image::new(src.to_string()).load_for_size(ui.ctx(), rect.size()).ok().and_then(|p| p.size());
    let r = match size {
        Some(s) if s.x > 0.0 && s.y > 0.0 => {
            let k = (rect.width() / s.x).min(rect.height() / s.y);
            Rect::from_center_size(rect.center(), s * k)
        }
        _ => rect,
    };
    egui::Image::new(src.to_string()).tint(tint).paint_at(ui, r);
}

/// Discord's display face, ABC Ginto Nord: Bold on a badge's hover card
/// (Black Italic on the Nitro badge's), Bold Italic in the badges window.
fn ginto(size: f32, face: &'static str) -> FontId {
    FontId::new(size, egui::FontFamily::Name(face.into()))
}

/// ABC Ginto Nord's line gap, in ems. egui counts a font's line gap in its
/// row height; a browser's line box leaves it out.
const GINTO_LINE_GAP: f32 = 0.2;

/// `text` wrapped at `width` with each row centred, laid out the way CSS
/// does: rows `height` apart (whatever the font's own row height), the
/// letters centred in each. Returns the galley and how far below the top of
/// its first line box to paint it; its x is the centre.
fn centred_lines(ui: &Ui, text: &str, font: FontId, color: Color32, height: f32, width: f32) -> (std::sync::Arc<egui::Galley>, f32) {
    let gap = if matches!(&font.family, egui::FontFamily::Name(name) if name.starts_with("ginto")) { GINTO_LINE_GAP * font.size } else { 0.0 };
    let own = ui.fonts(|f| f.row_height(&font)) - gap;
    let mut job = egui::text::LayoutJob::simple(text.to_string(), font, color, width);
    job.halign = egui::Align::Center;
    job.sections[0].format.line_height = Some(height);
    (ui.painter().layout_job(job), (height - own) / 2.0)
}

/// Discord's text-subtle (#b5bac1 on dark themes).
fn subtle(t: &Theme) -> Color32 {
    if t.light {
        t.text_muted
    } else {
        Color32::from_rgb(0xb5, 0xba, 0xc1)
    }
}

/// A badge's tooltip, Discord's "mini premium tooltip" (web modules 328464
/// and 56810, read 2026-12-01): 200 px wide with 12 px at the sides and 16
/// above and below (24 below when there is no info line); the badge's big
/// art 64 px tall, drawn 1.4 × when it is the animated one; then, centred
/// and 4 px apart: the badge's name (14/18 medium, subtle), its tier in
/// 16 px ABC Ginto Nord capitals, and the info line (14/18 medium, subtle).
/// A badge without tiers has its name as the title. The Nitro badge has
/// "Nitro <tier>" as its title, in italics, and no name line.
pub fn tooltip(ui: &mut Ui, t: &Theme, b: &BadgeInfo) {
    // (The popup frame pads 12 × 16.)
    ui.set_width(176.0);
    ui.spacing_mut().item_spacing.y = 0.0;
    let (art, _) = ui.allocate_exact_size(vec2(176.0, 64.0), Sense::hover());
    let grown = b.big_icon_animated.is_some() && super::animating();
    if let Some(a) = art_uri(b) {
        paint_contain(ui, &a, Rect::from_center_size(art.center(), art.size() * if grown { 1.4 } else { 1.0 }), Color32::WHITE);
    }
    ui.add_space(12.0);
    let nitro = b.id == PREMIUM_TENURE;
    let tier = b.tier(b.current_tier.as_deref()).map(|tier| tier.name.clone()).filter(|name| !name.is_empty() && !nitro);
    let whole = b.title();
    let line = |ui: &mut Ui, text: &str, font: FontId, color: Color32, height: f32| {
        let (galley, down) = centred_lines(ui, text, font, color, height, 176.0);
        let (r, _) = ui.allocate_exact_size(vec2(176.0, galley.rows.len().max(1) as f32 * height), Sense::hover());
        ui.painter().galley(pos2(r.center().x, r.top() + down), galley, color);
    };
    let (eyebrow, title) = match &tier {
        Some(tier) => (Some(b.name.as_str()), tier.as_str()),
        None if nitro => (None, whole.as_str()),
        None => (None, b.name.as_str()),
    };
    if let Some(name) = eyebrow {
        line(ui, name, crate::style::medium(14.0), subtle(t), 18.0);
    }
    // (Discord keeps this gap when there is no name above the title.)
    ui.add_space(4.0);
    let face = if nitro { crate::style::GINTO_BLACK_ITALIC } else { crate::style::GINTO_BOLD };
    line(ui, &title.to_uppercase(), ginto(16.0, face), t.header_primary, 16.0);
    if b.info_label.is_empty() {
        ui.add_space(8.0);
    } else {
        ui.add_space(4.0);
        line(ui, &b.info_label, crate::style::medium(14.0), subtle(t), 18.0);
    }
}

/// [`tooltip`] where Discord puts it: above the badge, centred on it, with
/// its 16 × 8 caret pointing down at it (surface-high, 1 px border-subtle,
/// 8 px corners, 0 12 24 rgba(0,0,0,.24) shadow).
pub fn tooltip_above(ui: &Ui, anchor: Rect, t: &Theme, b: &BadgeInfo) {
    // (Its caret's tip stops 3 px above the badge.)
    let tip_bottom = anchor.top() - 11.0;
    let area = egui::Area::new(egui::Id::new(("badge_tooltip", b.id)))
        .order(Order::Tooltip)
        .pivot(Align2::CENTER_BOTTOM)
        .fixed_pos(pos2(anchor.center().x, tip_bottom))
        .constrain(true)
        .interactable(false)
        .show(ui.ctx(), |ui| {
            Frame::none()
                .fill(t.surface_high)
                .rounding(8.0)
                .shadow(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) })
                .inner_margin(Margin { left: 12.0, right: 12.0, top: 16.0, bottom: 16.0 })
                .show(ui, |ui| tooltip(ui, t, b));
        });
    // Its border is inside the 200 px (a frame's own straddles the edge),
    // and the caret is drawn over the bottom of it.
    let r = area.response.rect;
    let cx = anchor.center().x.clamp(r.left() + 14.0, r.right() - 14.0);
    let p = ui.ctx().layer_painter(area.response.layer_id);
    p.rect_stroke(r.shrink(0.5), 8.0, Stroke::new(1.0_f32, t.border_subtle));
    let pts = vec![pos2(cx - 8.0, r.bottom() - 1.0), pos2(cx + 8.0, r.bottom() - 1.0), pos2(cx, r.bottom() + 7.0)];
    p.add(egui::Shape::convex_polygon(pts, t.surface_high, Stroke::NONE));
    p.line_segment([pos2(cx - 8.0, r.bottom() - 0.5), pos2(cx, r.bottom() + 7.5)], Stroke::new(1.0_f32, t.border_subtle));
    p.line_segment([pos2(cx + 8.0, r.bottom() - 0.5), pos2(cx, r.bottom() + 7.5)], Stroke::new(1.0_f32, t.border_subtle));
}

/// A compact line for a badge (the "+N" list): icon and "Name Tier".
pub fn tooltip_row(ui: &mut Ui, t: &Theme, b: &BadgeInfo) {
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing.x = 8.0;
        if let Some(i) = b.small_icon() {
            ui.add(egui::Image::new(i).fit_to_exact_size(vec2(20.0, 20.0)));
        }
        ui.label(RichText::new(b.title()).font(crate::style::medium(14.0)).color(t.header_primary));
    });
}

/// RustCord's own badge: the app's "R".
pub fn rustcord_icon() -> egui::ImageSource<'static> {
    egui::ImageSource::Bytes { uri: "bytes://rustcord-badge.png".into(), bytes: egui::load::Bytes::Static(include_bytes!("../../assets/icon-256.png")) }
}

/// "3 days", "2 months", "1 year 4 months": how long ago `joined` was.
pub fn tenure(joined: u64, now: u64) -> String {
    let days = now.saturating_sub(joined) / 86_400;
    let plural = |n: u64, unit: &str| format!("{n} {unit}{}", if n == 1 { "" } else { "s" });
    match days {
        0 => "today".to_string(),
        1..=29 => plural(days, "day"),
        30..=364 => plural(days / 30, "month"),
        _ => {
            let (years, months) = (days / 365, days % 365 / 30);
            if months == 0 { plural(years, "year") } else { format!("{} {}", plural(years, "year"), plural(months, "month")) }
        }
    }
}

/// The RustCord badge's tooltip: "RustCord", "User since 13/07/26 (4 months)",
/// and whether they're on it right now.
pub fn rustcord_tooltip(ui: &mut Ui, t: &Theme, m: &crate::registry::Membership) {
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing.x = 10.0;
        ui.add(egui::Image::new(rustcord_icon()).fit_to_exact_size(vec2(32.0, 32.0)));
        ui.vertical(|ui| {
            ui.spacing_mut().item_spacing.y = 2.0;
            ui.label(crate::style::bold("RustCord").size(14.0).color(t.header_primary));
            let now = chrono::Utc::now().timestamp().max(0) as u64;
            let since = chrono::DateTime::from_timestamp(m.joined as i64, 0).map(|d| d.with_timezone(&chrono::Local).format("%d/%m/%y").to_string()).unwrap_or_default();
            let held = tenure(m.joined, now);
            let line = if held == "today" { format!("User since {since} (joined today)") } else { format!("User since {since} ({held})") };
            ui.label(RichText::new(line).size(12.5).color(t.text_normal));
            if m.online {
                ui.label(RichText::new("Using RustCord right now").size(12.5).color(Color32::from_rgb(0x43, 0xa2, 0x5a)));
            }
        });
    });
}

/// Discord's secondary button: mod 12 % (16 % hovered), a faint 1 px edge,
/// 8 px corners, 14/18 medium white label.
fn secondary_button(ui: &mut Ui, rect: Rect, id: egui::Id, label: &str) -> egui::Response {
    let r = ui.interact(rect, id, Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
    ui.painter().rect(rect, 8.0, overlay(if r.hovered() { 0.16 } else { 0.12 }), Stroke::new(1.0_f32, crate::style::rgba(143, 143, 152, 10)));
    ui.painter().text(rect.center(), Align2::CENTER_CENTER, label, crate::style::medium(14.0), Color32::from_rgb(251, 251, 251));
    r
}

/// The rarity chip: 18 px pill, 8 px padding, a 12 px icon and the name in
/// 12/16 semibold capitals, with Discord's 1 px gradient ring.
fn rarity_chip(ui: &Ui, left: f32, y: f32, r: &Rarity) -> f32 {
    let font = FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into()));
    let g = ui.painter().layout_no_wrap(r.label.to_string(), font, r.text);
    let w = 8.0 + 12.0 + 4.0 + g.size().x + 8.0;
    let chip = Rect::from_min_size(pos2(left, y - 9.0), vec2(w, 18.0));
    let p = ui.painter();
    p.rect_filled(chip, 9.0, r.fill);
    // The ring: start colour on the left half, end colour on the right.
    let left_half = p.with_clip_rect(Rect::from_min_max(chip.min, pos2(chip.center().x, chip.bottom())));
    left_half.rect_stroke(chip.shrink(0.5), 9.0, Stroke::new(1.0_f32, r.ring.0));
    let right_half = p.with_clip_rect(Rect::from_min_max(pos2(chip.center().x, chip.top()), chip.max));
    right_half.rect_stroke(chip.shrink(0.5), 9.0, Stroke::new(1.0_f32, r.ring.1));
    // A small rounded triangle (Discord's rarity glyph).
    let c = pos2(chip.left() + 14.0, y + 0.5);
    p.add(egui::Shape::convex_polygon(vec![c + vec2(0.0, -4.5), c + vec2(5.0, 4.0), c + vec2(-5.0, 4.0)], r.text, Stroke::new(1.0_f32, r.text)));
    p.galley(pos2(chip.left() + 24.0, y - g.size().y / 2.0), g, r.text);
    w
}

impl RustCord {
    /// Someone's badges from Discord's badge API (fetched once; None until then).
    pub fn badges_of(&self, user: Id) -> Option<Vec<BadgeInfo>> {
        let tag = format!("badges:{user}");
        if !self.api_results.contains_key(&tag) && !self.api_pending.contains(&tag) {
            self.badges_wanted.borrow_mut().push(user);
            return None;
        }
        match self.api_results.get(&tag)? {
            Ok(v) => Some(v["badges"].as_array().into_iter().flatten().filter_map(BadgeInfo::parse).collect()),
            Err(_) => None,
        }
    }

    /// Fetch the badges asked for during the frame.
    pub fn fetch_wanted_badges(&mut self) {
        let wanted: Vec<Id> = std::mem::take(&mut *self.badges_wanted.borrow_mut());
        for u in wanted {
            let me = self.store.me_id() == Some(u);
            let path = if me { "/users/@me/badges".to_string() } else { format!("/users/{u}/badges") };
            self.api_get_once(&format!("badges:{u}"), path);
        }
    }

    /// The window (opened from the account menu's "Badges" or your badge row).
    pub fn badges_ui(&mut self, ctx: &egui::Context) {
        // Old entry points still open it this way.
        if self.badges_view.take().is_some() && self.badge_window.is_none() {
            let sel = ctx.data_mut(|d| d.remove_temp::<u32>(egui::Id::new("badge_window_sel")));
            self.badge_window = Some(BadgeWindow::new(sel));
        }
        match self.api_take("badges:save") {
            Some(Ok(_)) => {
                if let Some(me) = self.store.me_id() {
                    self.api_results.remove(&format!("badges:{me}"));
                }
                self.toast("Badges saved.", false);
            }
            Some(Err(e)) => self.toast(format!("Couldn't save your badges: {e}"), true),
            None => {}
        }
        let Some(me) = self.store.me_id() else { return };
        if self.badge_window.is_none() {
            return;
        }
        let all = self.badges_of(me);
        self.fetch_wanted_badges();
        let customize = self.badge_window.as_ref().is_some_and(|w| w.customize);
        if customize {
            self.badges_customize_ui(ctx, all);
        } else {
            self.badges_directory_ui(ctx, all);
        }
    }

    /// Discord's "Your badges" directory (measured 2026-11-22): 680 × 560 on
    /// surface-high with a 1 px border-normal and 12 px corners; a 264 px list
    /// on the left, the selected badge on the right (base-lower).
    fn badges_directory_ui(&mut self, ctx: &egui::Context, all: Option<Vec<BadgeInfo>>) {
        let t = self.theme.clone();
        let dir = self.config_dir.clone();
        let seen = seen_ids(dir.as_deref());
        let Some(win) = self.badge_window.as_mut() else { return };
        let owned: Vec<BadgeInfo> = all.as_ref().map(|a| a.iter().filter(|b| b.owned).cloned().collect()).unwrap_or_default();
        let unlockable: Vec<BadgeInfo> = all.as_ref().map(|a| a.iter().filter(|b| !b.owned && b.earnable).cloned().collect()).unwrap_or_default();
        if win.sel.is_none() {
            win.sel = owned.first().or(unlockable.first()).map(|b| b.id);
        }
        let selected = all.as_ref().and_then(|a| a.iter().find(|b| Some(b.id) == win.sel).cloned());
        if let Some(b) = &selected {
            mark_seen(dir.as_deref(), b.id);
        }
        let (mut close, mut open_customize) = (ctx.input(|i| i.key_pressed(Key::Escape)), false);
        let mut pick: Option<u32> = None;
        let mut cta: Option<u32> = None;
        let screen = ctx.screen_rect();
        egui::Area::new(egui::Id::new("badges_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(160));
        });
        let area = egui::Area::new(egui::Id::new("badges_window")).order(Order::Tooltip).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
            let (whole, _) = ui.allocate_exact_size(vec2(680.0, 560.0), Sense::hover());
            let p = ui.painter().clone();
            p.add(egui::epaint::Shadow { offset: vec2(0.0, 4.0), blur: 8.0, spread: 0.0, color: Color32::from_black_alpha(41) }.as_shape(whole, 12.0));
            p.rect_filled(whole, 12.0, t.surface_high);
            // Right: the details panel's own background.
            let left = Rect::from_min_size(whole.min, vec2(264.0, whole.height()));
            let right = Rect::from_min_max(pos2(left.right() + 1.0, whole.top()), whole.max);
            p.rect_filled(right, Rounding { nw: 0.0, sw: 0.0, ne: 12.0, se: 12.0 }, t.bg_primary);
            p.vline(left.right() + 0.5, whole.y_range(), Stroke::new(1.0_f32, crate::style::rgba(143, 143, 152, 10)));
            p.rect_stroke(whole.expand(0.5), 12.5, Stroke::new(1.0_f32, super::modal_border(&t)));

            // ---- left: your badges, the ones to unlock, Customise ----
            let x0 = left.left() + 24.0;
            let mut y = left.top() + 24.0;
            p.text(pos2(x0, y + 12.0), Align2::LEFT_CENTER, "Your badges", FontId::new(20.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.header_primary);
            y += 24.0 + 8.0;
            let sub = p.layout(
                "Browse your badges and discover new ones you can unlock.".into(),
                crate::style::medium(14.0),
                subtle(&t),
                216.0,
            );
            let sub_h = sub.size().y;
            p.galley(pos2(x0, y), sub, subtle(&t));
            y += sub_h + 24.0;
            let mut grid = |ui: &mut Ui, list: &[BadgeInfo], top: f32| -> f32 {
                for (i, b) in list.iter().enumerate() {
                    let (col, row) = ((i % 4) as f32, (i / 4) as f32);
                    let r = Rect::from_min_size(pos2(x0 + col * 56.0, top + row * 56.0), vec2(48.0, 48.0));
                    let resp = ui.interact(r, egui::Id::new(("badge_tile", b.id)), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                    let is_sel = Some(b.id) == win.sel;
                    let edge = if is_sel { Color32::from_rgb(116, 135, 248) } else { crate::style::rgba(143, 143, 152, 10) };
                    ui.painter().rect(r, 8.0, overlay(if resp.hovered() { 0.16 } else { 0.12 }), Stroke::new(1.0_f32, edge));
                    let icon = if b.owned { b.small_icon() } else { shown_tier(b).and_then(|t| t.icon.clone()).or_else(|| b.icon.clone()) };
                    if let Some(i) = icon {
                        egui::Image::new(i).paint_at(ui, Rect::from_center_size(r.center(), vec2(24.0, 24.0)));
                    }
                    if !is_sel && INDICATOR_BADGES.contains(&b.id) && !seen.contains(&b.id) {
                        ui.painter().circle_filled(pos2(r.right() - 8.0, r.top() + 8.0), 3.0, Color32::from_rgb(88, 101, 242));
                    }
                    if resp.clicked() {
                        pick = Some(b.id);
                    }
                }
                let rows = list.len().div_ceil(4) as f32;
                top + rows * 56.0 - 8.0
            };
            match &all {
                None => {
                    ui.put(Rect::from_min_size(pos2(x0, y), vec2(216.0, 32.0)), egui::Spinner::new());
                }
                Some(_) => {
                    let bottom = grid(ui, &owned, y);
                    if !unlockable.is_empty() {
                        let ly = bottom + 24.0;
                        p.text(pos2(x0, ly + 9.0), Align2::LEFT_CENTER, "Available to unlock", crate::style::medium(14.0), t.text_normal);
                        grid(ui, &unlockable, ly + 18.0 + 12.0);
                    }
                }
            }
            // Bottom: a hairline, then the 232 × 32 button 16 px in.
            let bar_top = left.bottom() - 65.0;
            p.hline(left.x_range(), bar_top + 0.5, Stroke::new(1.0_f32, t.border_subtle));
            let btn = Rect::from_min_size(pos2(left.left() + 16.0, bar_top + 17.0), vec2(232.0, 32.0));
            open_customize = secondary_button(ui, btn, egui::Id::new("badges_customise"), "Customise Your Badges").clicked();

            // ---- right: the selected badge ----
            let close_r = Rect::from_min_size(pos2(right.right() - 48.0, right.top() + 16.0), vec2(32.0, 32.0));
            if let Some(b) = &selected {
                let inner = Rect::from_min_max(pos2(right.left() + 24.0, right.top()), pos2(right.right() - 24.0, right.bottom()));
                let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::top_down(egui::Align::Min)));
                rui.set_clip_rect(right.shrink(1.0));
                ScrollArea::vertical().id_salt("badge_details").auto_shrink([false, false]).show(&mut rui, |ui| {
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    ui.add_space(16.0 + 24.0);
                    let row = |ui: &mut Ui, h: f32| ui.allocate_exact_size(vec2(right.width(), h), Sense::hover()).0;
                    // The art, 180 × 150.
                    let art = row(ui, 150.0);
                    if let Some(a) = art_uri(b) {
                        paint_contain(ui, &a, Rect::from_center_size(art.center(), vec2(180.0, 150.0)), Color32::WHITE);
                    }
                    // Name: ABC Ginto Nord Bold Italic, 24/26 capitals.
                    let (title, down) = centred_lines(ui, &b.title().to_uppercase(), ginto(24.0, crate::style::GINTO_BOLD_ITALIC), Color32::WHITE, 26.0, inner.width());
                    let tr = row(ui, 26.0 * title.rows.len().max(1) as f32);
                    ui.painter().galley(pos2(tr.center().x, tr.top() + down), title, Color32::WHITE);
                    ui.add_space(5.0);
                    // "Subscriber since … • Unlocked … • [RARE]"
                    let line = row(ui, 18.0);
                    let mut parts: Vec<String> = Vec::new();
                    if !b.info_label.is_empty() {
                        parts.push(b.info_label.clone());
                    }
                    let unlocked = b.current_tier.as_ref().and_then(|k| b.tier_obtained.iter().find(|(t, _)| t == k)).map(|(_, d)| d.clone()).or_else(|| b.obtained_at.clone());
                    if let Some(d) = unlocked.filter(|_| b.owned) {
                        parts.push(format!("Unlocked {}", date(&d)));
                    }
                    let rar = rarity(shown_tier(b).map_or(b.rarity, |t| t.rarity.max(1)));
                    let font = crate::style::medium(12.0);
                    let galleys: Vec<_> = parts.iter().map(|s| ui.painter().layout_no_wrap(s.clone(), font.clone(), subtle(&t))).collect();
                    let chip_font = FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into()));
                    let chip_w = 24.0 + ui.painter().layout_no_wrap(rar.label.to_string(), chip_font, rar.text).size().x + 8.0;
                    let dots = galleys.len() as f32 * 11.0;
                    let total = galleys.iter().map(|g| g.size().x).sum::<f32>() + dots + chip_w;
                    let mut x = line.center().x - total / 2.0;
                    let cy = line.center().y;
                    for g in galleys {
                        let w = g.size().x;
                        ui.painter().galley(pos2(x, cy - g.size().y / 2.0), g, subtle(&t));
                        x += w + 4.0;
                        ui.painter().circle_filled(pos2(x + 1.5, cy), 1.5, subtle(&t));
                        x += 7.0;
                    }
                    rarity_chip(ui, x, cy, &rar);
                    ui.add_space(24.0);
                    // The card: mod 8 %, 12 px corners, 16 px padding.
                    let card_w = inner.width();
                    {
                        Frame::none().fill(overlay(0.08)).rounding(12.0).inner_margin(Margin::same(16.0)).outer_margin(Margin { left: 24.0, right: 24.0, top: 0.0, bottom: 0.0 }).show(ui, |ui| {
                            ui.set_width(card_w - 32.0);
                            ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                            let w = card_w - 32.0;
                            if let Some((cur, floor, threshold, helper)) = &b.progress {
                                let (lr, _) = ui.allocate_exact_size(vec2(w, 18.0), Sense::hover());
                                ui.painter().text(lr.left_center(), Align2::LEFT_CENTER, "Your progress", crate::style::medium(14.0), t.text_normal);
                                ui.add_space(16.0);
                                let (pr, _) = ui.allocate_exact_size(vec2(w, 35.0), Sense::hover());
                                let now_art = b.small_icon();
                                let next_art = b.tier(b.next_tier.as_deref()).and_then(|t| t.icon.clone());
                                let mut l = pr.left();
                                if let Some(i) = now_art {
                                    egui::Image::new(i).paint_at(ui, Rect::from_min_size(pos2(l, pr.top()), vec2(35.0, 35.0)));
                                    l += 35.0 + 12.0;
                                }
                                let rgt = if next_art.is_some() { pr.right() - 35.0 - 12.0 } else { pr.right() };
                                if let Some(i) = next_art {
                                    egui::Image::new(i).paint_at(ui, Rect::from_min_size(pos2(pr.right() - 35.0, pr.top()), vec2(35.0, 35.0)));
                                }
                                ui.painter().text(pos2(l, pr.top() + 9.0), Align2::LEFT_CENTER, helper, crate::style::medium(14.0), t.text_normal);
                                let bar = Rect::from_min_max(pos2(l, pr.top() + 26.0), pos2(rgt, pr.top() + 32.0));
                                ui.painter().rect_filled(bar, 3.0, overlay(0.2));
                                let frac = ((cur - floor) / (threshold - floor).max(1.0)).clamp(0.0, 1.0) as f32;
                                ui.painter().rect_filled(Rect::from_min_size(bar.min, vec2(bar.width() * frac, bar.height())), 3.0, Color32::from_rgb(88, 101, 242));
                                ui.add_space(16.0);
                                let (sep, _) = ui.allocate_exact_size(vec2(w, 1.0), Sense::hover());
                                ui.painter().hline(sep.x_range(), sep.center().y, Stroke::new(1.0_f32, t.border_subtle));
                                ui.add_space(16.0);
                            }
                            // Description and the badge's button.
                            let label = match (b.id, b.owned) {
                                (STAFF, _) => Some("Work with Us"),
                                (PREMIUM_TENURE, true) => Some("Nitro Home"),
                                (PREMIUM_TENURE, false) => Some("Get Nitro"),
                                (GUILD_BOOSTER, true) => Some("Manage Boosts"),
                                (GUILD_BOOSTER, false) => Some("Boost a server"),
                                (ORB_PROFILE, _) => Some("Orbs Shop"),
                                (QUEST_COMPLETED, _) => Some("Quests Home"),
                                (GIFTING, _) => Some("Send Gift"),
                                _ => None,
                            };
                            let btn_w = label.map_or(0.0, |l| ui.painter().layout_no_wrap(l.to_string(), crate::style::medium(14.0), Color32::WHITE).size().x + 24.0);
                            let desc = if b.description.is_empty() { b.name.clone() } else { b.description.clone() };
                            let text_w = if label.is_some() { w - btn_w - 16.0 } else { w };
                            let g = ui.painter().layout(desc, crate::style::medium(14.0), t.text_normal, text_w);
                            let h = g.size().y.max(if label.is_some() { 32.0 } else { 0.0 });
                            let (dr, _) = ui.allocate_exact_size(vec2(w, h), Sense::hover());
                            ui.painter().galley(pos2(dr.left(), dr.center().y - g.size().y / 2.0), g, t.text_normal);
                            if let Some(l) = label {
                                let br = Rect::from_min_size(pos2(dr.right() - btn_w, dr.center().y - 16.0), vec2(btn_w, 32.0));
                                if secondary_button(ui, br, egui::Id::new(("badge_cta", b.id)), l).clicked() {
                                    cta = Some(b.id);
                                }
                            }
                            // The tier timeline: columns 77 wide, 4 apart, rows 88 apart.
                            if !b.tiers.is_empty() {
                                ui.add_space(24.0);
                                for chunk in b.tiers.chunks(4) {
                                    let (rr, _) = ui.allocate_exact_size(vec2(w, 88.0), Sense::hover());
                                    let span = chunk.len() as f32 * 77.0 + (chunk.len() as f32 - 1.0) * 4.0;
                                    let x0 = rr.center().x - span / 2.0;
                                    for (i, tier) in chunk.iter().enumerate() {
                                        let cx = x0 + i as f32 * 81.0 + 38.5;
                                        if let Some(icon) = &tier.icon {
                                            let tint = if tier.owned { Color32::WHITE } else { crate::style::rgba(255, 255, 255, 102) };
                                            egui::Image::new(icon.as_str()).tint(tint).paint_at(ui, Rect::from_center_size(pos2(cx, rr.top() + 16.0), vec2(32.0, 32.0)));
                                        }
                                        let name_c = if tier.owned { t.text_normal } else { t.text_muted };
                                        let tf = FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into()));
                                        ui.painter().text(pos2(cx, rr.top() + 44.0), Align2::CENTER_CENTER, &tier.name, tf, name_c);
                                        if !tier.milestone.is_empty() {
                                            let mg = ui.painter().layout_no_wrap(tier.milestone.clone(), FontId::proportional(12.0), subtle(&t));
                                            let lock_w = if tier.owned { 0.0 } else { 10.0 };
                                            let mx = cx - (mg.size().x + lock_w) / 2.0;
                                            let my = rr.top() + 60.0;
                                            if !tier.owned {
                                                ui.painter().text(pos2(mx + 4.0, my), Align2::CENTER_CENTER, "\u{E72E}", icon_font(8.0), t.text_muted);
                                            }
                                            ui.painter().galley(pos2(mx + lock_w, my - mg.size().y / 2.0), mg, subtle(&t));
                                        }
                                    }
                                }
                            }
                        });
                    }
                    ui.add_space(24.0);
                });
            }
            // Close: 32 × 32, 8 px corners, a 16 px ×.
            let xr = ui.interact(close_r, egui::Id::new("badges_close"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            if xr.hovered() {
                ui.painter().rect_filled(close_r, 8.0, overlay(0.12));
            }
            super::paint_icon(ui.painter(), Rect::from_center_size(close_r.center(), vec2(16.0, 16.0)), icon::CLOSE, if xr.hovered() { t.header_primary } else { t.interactive_normal });
            close |= xr.clicked();
        });
        close |= super::pressed_outside(ctx, area.response.rect);
        let Some(win) = self.badge_window.as_mut() else { return };
        if let Some(id) = pick {
            win.sel = Some(id);
        }
        if open_customize {
            win.customize = true;
            win.order.clear();
            win.hidden.clear();
            win.dirty = false;
        }
        if let Some(id) = cta {
            self.badge_window = None;
            match id {
                STAFF => ctx.open_url(egui::OpenUrl::new_tab("https://discord.com/careers")),
                GUILD_BOOSTER => {
                    self.settings_open = true;
                    self.settings_tab = crate::app::SettingsTab::ServerBoost;
                }
                ORB_PROFILE => self.open_store_page(crate::features::StorePage::Shop),
                QUEST_COMPLETED => self.open_store_page(crate::features::StorePage::Quests),
                _ => self.open_store_page(crate::features::StorePage::Nitro),
            }
            return;
        }
        if close {
            self.badge_window = None;
        }
    }

    /// Discord's "Customise your badges" card (read 2026-11-22): 360 wide on
    /// surface-higher, 12 px corners, 16 px padding; Nitro icon + title 16/20
    /// semibold, the hint 12/16, then six 48 px tiles a row (28 px icons) you
    /// drag to reorder; a tile's "⋯" (on hover) opens View Badge Details /
    /// Move to Front / Move to Back / Hide Badge. Hidden ones fade to 30 % with
    /// an eye-slash. Changes wait for the unsaved-changes bar, like Discord's
    /// profile editor.
    fn badges_customize_ui(&mut self, ctx: &egui::Context, all: Option<Vec<BadgeInfo>>) {
        let t = self.theme.clone();
        let Some(win) = self.badge_window.as_mut() else { return };
        let owned: Vec<BadgeInfo> = all.as_ref().map(|a| a.iter().filter(|b| b.owned).cloned().collect()).unwrap_or_default();
        if win.order.is_empty() && !owned.is_empty() {
            win.order = owned.iter().map(|b| b.id).collect();
            win.hidden = owned.iter().filter(|b| b.hidden).map(|b| b.id).collect();
        }
        // Discord's order: Staff first, then what's shown (your order), then the hidden ones.
        let by_id = |id: u32| owned.iter().find(|b| b.id == id).cloned();
        let fixed: Vec<BadgeInfo> = win.order.iter().copied().filter(|id| *id == STAFF).filter_map(by_id).collect();
        let shown: Vec<BadgeInfo> = win.order.iter().copied().filter(|id| *id != STAFF && !win.hidden.contains(id)).filter_map(by_id).collect();
        let hidden_list: Vec<BadgeInfo> = win.order.iter().copied().filter(|id| *id != STAFF && win.hidden.contains(id)).filter_map(by_id).collect();
        let tiles: Vec<(BadgeInfo, bool, bool)> = fixed
            .iter()
            .map(|b| (b.clone(), false, false))
            .chain(shown.iter().map(|b| (b.clone(), true, false)))
            .chain(hidden_list.iter().map(|b| (b.clone(), false, true)))
            .collect();
        let (dirty, drag, menu) = (win.dirty, win.drag, win.menu);
        let now = ctx.cumulative_pass_nr();
        let (mut view_badges, mut close) = (false, false);
        let mut new_drag = drag;
        let mut drop_at: Option<(u32, usize)> = None;
        let mut open_menu: Option<(u32, egui::Pos2)> = None;
        let mut menu_act: Option<(u32, u8)> = None;
        let (mut save, mut reset) = (false, false);
        let mut dragging_tile: Option<(BadgeInfo, Rect)> = None;
        let screen = ctx.screen_rect();
        egui::Area::new(egui::Id::new("badges_dim")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            let r = ui.allocate_exact_size(screen.size(), Sense::click()).1;
            ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha(160));
            close |= r.clicked() && !dirty;
        });
        let area = egui::Area::new(egui::Id::new("badges_customise_card")).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(egui::epaint::Shadow { offset: vec2(0.0, 2.0), blur: 4.0, spread: 0.0, color: Color32::from_black_alpha(51) })
                .inner_margin(Margin::same(16.0))
                .show(ui, |ui| {
                    ui.set_width(328.0);
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    let (hr, _) = ui.allocate_exact_size(vec2(328.0, 20.0), Sense::hover());
                    super::paint_icon(ui.painter(), Rect::from_min_size(pos2(hr.left(), hr.top() + 2.0), vec2(16.0, 16.0)), icon::NITRO, t.text_normal);
                    ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, "Customise your badges", FontId::new(16.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.header_primary);
                    ui.add_space(4.0);
                    ui.add(egui::Label::new(RichText::new("Drag to reorder and hide the ones that you don\u{2019}t want others to see.").size(12.0).color(subtle(&t))).wrap());
                    ui.add_space(16.0);
                    let rows = tiles.len().div_ceil(6).max(1) as f32;
                    let (grid, _) = ui.allocate_exact_size(vec2(328.0, rows * 56.0 - 8.0), Sense::hover());
                    let slot = |i: usize| Rect::from_min_size(grid.min + vec2((i % 6) as f32 * 56.0, (i / 6) as f32 * 56.0), vec2(48.0, 48.0));
                    let pointer = ui.input(|i| i.pointer.interact_pos());
                    let mut dragged_paint: Option<(BadgeInfo, Rect)> = None;
                    for (i, (b, movable, hidden)) in tiles.iter().enumerate() {
                        let r = slot(i);
                        let sense = if *movable { Sense::click_and_drag() } else { Sense::click() };
                        let resp = ui.interact(r, egui::Id::new(("badge_ctile", b.id)), sense);
                        let resp = if *movable { resp.on_hover_cursor(CursorIcon::Grab) } else { resp };
                        if resp.drag_started() && *movable {
                            new_drag = Some((b.id, pointer.map_or(vec2(24.0, 24.0), |p| p - r.min)));
                        }
                        let dragging = drag.is_some_and(|(id, _)| id == b.id);
                        if dragging {
                            if let Some(p) = pointer {
                                let off = drag.map_or(vec2(24.0, 24.0), |(_, o)| o);
                                dragged_paint = Some((b.clone(), Rect::from_min_size(p - off, vec2(48.0, 48.0))));
                                // Where it would land: the nearest movable slot.
                                let first = fixed.len();
                                let target = (first..first + shown.len()).min_by(|a, c| slot(*a).center().distance(p).total_cmp(&slot(*c).center().distance(p))).unwrap_or(first);
                                if resp.drag_stopped() || !ui.input(|i| i.pointer.primary_down()) {
                                    drop_at = Some((b.id, target - first));
                                }
                            }
                            // An empty slot where it was.
                            ui.painter().rect_stroke(r, 8.0, Stroke::new(1.0_f32, crate::style::rgba(143, 143, 152, 40)));
                            continue;
                        }
                        // (By position: the "⋯" over the corner takes the hover itself.)
                        let over = drag.is_none() && pointer.is_some_and(|p| r.expand(2.0).contains(p) || Rect::from_center_size(pos2(r.right() - 6.0, r.top() + 6.0), vec2(24.0, 24.0)).contains(p));
                        let hot = over || menu.is_some_and(|(id, _, _)| id == b.id);
                        let tile = if hot { r.expand(2.0) } else { r };
                        ui.painter().rect(tile, 8.0, overlay(0.12), Stroke::new(1.0_f32, crate::style::rgba(143, 143, 152, 10)));
                        if let Some(i) = b.small_icon() {
                            let s = if hot { 30.0 } else { 28.0 };
                            let tint = if *hidden { crate::style::rgba(255, 255, 255, 77) } else { Color32::WHITE };
                            egui::Image::new(i).tint(tint).paint_at(ui, Rect::from_center_size(r.center(), vec2(s, s)));
                        }
                        if *hidden {
                            super::paint_icon(ui.painter(), Rect::from_min_size(pos2(r.left() + 24.0, r.top() + 4.0), vec2(20.0, 20.0)), icon::EYE_SLASH, t.text_normal);
                        }
                        // The "⋯" button: 24 px round, over the top-right corner.
                        if hot {
                            let mr = Rect::from_center_size(pos2(r.right() - 6.0, r.top() + 6.0), vec2(24.0, 24.0));
                            let mresp = ui.interact(mr, egui::Id::new(("badge_ctile_more", b.id)), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                            ui.painter().circle_filled(mr.center(), 12.0, t.bg_floating.lerp_to_gamma(Color32::WHITE, 0.05));
                            ui.painter().text(mr.center(), Align2::CENTER_CENTER, icon::MORE, icon_font(12.0), t.text_normal);
                            if mresp.clicked() {
                                open_menu = Some((b.id, mr.center()));
                            }
                        }
                    }
                    dragging_tile = dragged_paint;
                    ui.add_space(16.0);
                    let (vb, _) = ui.allocate_exact_size(vec2(328.0, 32.0), Sense::hover());
                    view_badges = secondary_button(ui, vb, egui::Id::new("badges_view"), "View Badges").clicked();
                });
        });
        // The tile under the pointer while it's dragged, above everything.
        if let Some((b, r)) = dragging_tile {
            egui::Area::new(egui::Id::new("badge_drag_tile")).order(Order::Tooltip).fixed_pos(r.min - vec2(2.0, 2.0)).interactable(false).show(ctx, |ui| {
                ui.ctx().move_to_top(ui.layer_id());
                let (tr, _) = ui.allocate_exact_size(vec2(52.0, 52.0), Sense::hover());
                ui.painter().add(egui::epaint::Shadow { offset: vec2(0.0, 4.0), blur: 12.0, spread: 0.0, color: Color32::from_black_alpha(90) }.as_shape(tr, 8.0));
                ui.painter().rect(tr, 8.0, t.bg_floating.lerp_to_gamma(Color32::WHITE, 0.08), Stroke::new(1.0_f32, crate::style::rgba(143, 143, 152, 40)));
                if let Some(i) = b.small_icon() {
                    egui::Image::new(i).paint_at(ui, Rect::from_center_size(tr.center(), vec2(30.0, 30.0)));
                }
            });
            ctx.set_cursor_icon(CursorIcon::Grabbing);
        }
        // The tile's menu (Discord's context menu, the badge's name on top).
        let mut menu_rect = None;
        if let Some((id, at, opened)) = menu {
            let b = owned.iter().find(|b| b.id == id).cloned();
            if let Some(b) = b {
                let is_hidden = self.badge_window.as_ref().is_some_and(|w| w.hidden.contains(&id));
                let m = egui::Area::new(egui::Id::new("badge_tile_menu")).order(Order::Tooltip).fixed_pos(at).constrain(true).show(ctx, |ui| {
                    ui.ctx().move_to_top(ui.layer_id());
                    super::ctx_menu_frame(&t).show(ui, |ui| {
                        ui.set_width(161.0);
                        ui.spacing_mut().item_spacing.y = 0.0;
                        let (hr, _) = ui.allocate_exact_size(vec2(161.0, 36.0), Sense::hover());
                        ui.painter().text(pos2(hr.left() + 8.0, hr.center().y), Align2::LEFT_CENTER, &b.name, crate::style::medium(14.0), t.text_muted);
                        if super::ctx_row(ui, &t, Some(icon::CIRCLE_INFO), "View Badge Details", None, false, true).clicked() {
                            menu_act = Some((id, 0));
                        }
                        let movable = id != STAFF && !is_hidden;
                        if super::ctx_row(ui, &t, Some(icon::ARROW_LEFT), "Move to Front", None, false, movable).clicked() {
                            menu_act = Some((id, 1));
                        }
                        if super::ctx_row(ui, &t, Some(icon::ARROW_RIGHT), "Move to Back", None, false, movable).clicked() {
                            menu_act = Some((id, 2));
                        }
                        let can_hide = !always_visible(id);
                        let (glyph, label) = if is_hidden { ("\u{E7B3}", "Show Badge") } else { (icon::EYE_SLASH, "Hide Badge") };
                        let r = super::ctx_row(ui, &t, Some(glyph), label, None, false, can_hide);
                        let r = if can_hide { r } else { r.on_hover_text(if id == STAFF { "Badge is always visible and appears first" } else { "Badge is always visible" }) };
                        if r.clicked() {
                            menu_act = Some((id, 3));
                        }
                    });
                });
                menu_rect = Some(m.response.rect);
                let pressed_off = ctx.input(|i| i.pointer.any_pressed()) && ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !m.response.rect.contains(p));
                if (pressed_off && now > opened + 1) || ctx.input(|i| i.key_pressed(Key::Escape)) {
                    if let Some(w) = self.badge_window.as_mut() {
                        w.menu = None;
                    }
                }
            }
        }
        // Discord's unsaved-changes bar under it all.
        if dirty {
            let w = 700.0_f32.min(screen.width() - 40.0);
            let bar = Rect::from_min_size(pos2(screen.center().x - w / 2.0, screen.bottom() - 20.0 - 54.0), vec2(w, 54.0));
            egui::Area::new(egui::Id::new("badges_save_bar")).order(Order::Tooltip).fixed_pos(bar.min).show(ctx, |ui| {
                let (r, _) = ui.allocate_exact_size(bar.size(), Sense::click());
                let p = ui.painter();
                p.add(egui::epaint::Shadow { offset: vec2(0.0, 2.0), blur: 10.0, spread: 0.0, color: Color32::from_black_alpha(51) }.as_shape(r, 8.0));
                p.rect(r, 8.0, t.bg_secondary, Stroke::new(1.0_f32, t.border_subtle));
                p.text(pos2(r.left() + 16.0, r.center().y), Align2::LEFT_CENTER, "Careful \u{2014} you have unsaved changes!", crate::style::medium(16.0), Color32::WHITE);
                let sg = p.layout_no_wrap("Save Changes".into(), crate::style::medium(14.0), Color32::WHITE);
                let sr = Rect::from_min_size(pos2(r.right() - 10.0 - (sg.size().x + 32.0), r.center().y - 16.0), vec2(sg.size().x + 32.0, 32.0));
                let sresp = ui.interact(sr, egui::Id::new("badges_save"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                let green = Color32::from_rgb(0, 133, 69);
                ui.painter().rect_filled(sr, 8.0, if sresp.hovered() { green.lerp_to_gamma(Color32::BLACK, 0.12) } else { green });
                ui.painter().galley(sr.center() - sg.size() / 2.0, sg, Color32::WHITE);
                let rg = ui.painter().layout_no_wrap("Reset".into(), crate::style::medium(14.0), Color32::from_rgb(140, 160, 253));
                let rr = Rect::from_min_size(pos2(sr.left() - 16.0 - rg.size().x, r.center().y - rg.size().y / 2.0), rg.size());
                let rresp = ui.interact(rr.expand(4.0), egui::Id::new("badges_reset"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                if rresp.hovered() {
                    ui.painter().hline(rr.x_range(), rr.bottom(), Stroke::new(1.0_f32, Color32::from_rgb(140, 160, 253)));
                }
                ui.painter().galley(rr.min, rg, Color32::from_rgb(140, 160, 253));
                save = sresp.clicked();
                reset = rresp.clicked();
            });
        }
        close |= !dirty && ctx.input(|i| i.key_pressed(Key::Escape)) && menu.is_none();
        let _ = (area, menu_rect);
        let Some(win) = self.badge_window.as_mut() else { return };
        win.drag = new_drag;
        if let Some((id, at)) = open_menu {
            win.menu = Some((id, at, now));
        }
        if let Some((id, target)) = drop_at {
            // Reorder among the shown (movable) badges.
            let mut shown_ids: Vec<u32> = win.order.iter().copied().filter(|i| *i != STAFF && !win.hidden.contains(i)).collect();
            if let Some(from) = shown_ids.iter().position(|x| *x == id) {
                let moved = shown_ids.remove(from);
                shown_ids.insert(target.min(shown_ids.len()), moved);
                if from != target {
                    win.dirty = true;
                }
            }
            let rest: Vec<u32> = win.order.iter().copied().filter(|i| *i == STAFF || win.hidden.contains(i)).collect();
            win.order = rest.iter().copied().filter(|i| *i == STAFF).chain(shown_ids).chain(rest.iter().copied().filter(|i| *i != STAFF)).collect();
            win.drag = None;
        }
        if let Some((id, act)) = menu_act {
            win.menu = None;
            match act {
                0 => {
                    win.customize = false;
                    win.sel = Some(id);
                }
                1 | 2 => {
                    win.order.retain(|x| *x != id);
                    let at = if act == 1 { win.order.iter().position(|x| *x != STAFF).unwrap_or(win.order.len()) } else { win.order.len() };
                    win.order.insert(at, id);
                    win.dirty = true;
                }
                _ => {
                    if !win.hidden.remove(&id) {
                        win.hidden.insert(id);
                    }
                    win.dirty = true;
                }
            }
        }
        if reset {
            win.order.clear();
            win.hidden.clear();
            win.dirty = false;
        }
        if view_badges {
            win.customize = false;
            win.menu = None;
        }
        if save {
            let display: Vec<u32> = win.order.iter().copied().filter(|id| *id != STAFF && !win.hidden.contains(id)).collect();
            let hidden: Vec<u32> = win.order.iter().copied().filter(|id| win.hidden.contains(id)).collect();
            win.dirty = false;
            win.order.clear();
            win.hidden.clear();
            self.api("badges:save", reqwest::Method::PATCH, "/users/@me/badges/settings", Some(serde_json::json!({ "display_order": display, "hidden_badges": hidden })));
        }
        if close {
            self.badge_window = None;
        }
    }
}