Skip to content

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

119 KB
Raw Blame
//! The Server Boosts page, as Discord draws it: "Levels" and "Additional
//! Perks" cards on the left; on the right the Server Boosts counts (people who
//! manage the server) or the video and "Become a Server Booster" card
//! (everyone else), then Recent Activity.
//!
//! It is fed by the three requests Discord's own page makes: the perk catalog
//! (`/store/published-listings/skus` for Discord's boost-perk application),
//! what the server has switched on (`/guilds/{id}/powerups`) and every boost
//! (`/guilds/{id}/premium/subscriptions`). Sizes, colours, texts and the
//! rules for each state were read from Discord web.
//!
//! Boosting, and switching a perk on or off, are purchases / server changes
//! Discord confirms in its own dialogs: those buttons are drawn the same and
//! open the matching page on discord.com.

use super::guild_pages::{boost_level, has_feature, modal_frame, rgb, strong};
use crate::app::RustCord;
use crate::style::{icon, icon_font, medium, rgba, Theme};
use chrono::{DateTime, Local};
use discord::model::{permissions, Guild, Id, User};
use eframe::egui::{
    self, load::Bytes, pos2, text::LayoutJob, vec2, Align2, CentralPanel, Color32, FontId, Frame, Galley, Pos2, Rect, Rounding,
    ScrollArea, Sense, Shadow, SidePanel, Stroke, TextFormat, TopBottomPanel, Ui,
};
use reqwest::Method;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

/// Discord's application that sells the boost perks.
const POWERUPS_APP: &str = "1340102344645283891";
const SKU_LEVELS: [&str; 3] = ["1341586379779604621", "1341586379779604622", "1341586379779604623"];
const SKU_SERVER_TAG: &str = "1351706802684952639";
const SKU_ROLE_STYLES: &str = "1354906318279807056";
/// Custom Invite Link: also part of Level 3.
const SKU_INVITE_LINK: &str = "1387197800336330924";
/// The Server Tag badge packs, in the order Discord lists them (one card).
const SKU_BADGE_PACKS: [&str; 4] = ["1466209416931055898", "1395150519886024775", "1466209416922667288", "1395150923734581339"];
const SKU_UPLOADS_250: &str = "1479204648718958665";
const SKU_GUILD_THEME: &str = "1493634428604252161";
/// Boosts each level costs on its own (2, then 5 more, then 7 more).
const LEVEL_COST: [u32; 3] = [2, 5, 7];
/// What a boost-bought server feature costs (Discord's table).
const FEATURE_COST: [(&str, u32); 6] = [
    ("GUILD_TAGS", 3),
    ("ENHANCED_ROLE_COLORS", 3),
    ("GUILD_TAGS_BADGE_PACK_PETS", 3),
    ("GUILD_TAGS_BADGE_PACK_FLEX", 5),
    ("GUILD_TAGS_BADGE_PACK_PLANT", 3),
    ("GUILD_TAGS_BADGE_PACK_CREEPY_CRAWLIES", 2),
];
const FAQ_URL: &str = "https://support.discord.com/hc/en-us/articles/360028038352";
const VIDEO_URL: &str = "https://cdn.discordapp.com/assets/content/f0b9a61f96ee69dc341c22c04fe6458660d9317caae3d381c05cf8348fca5b95.mp4";
const BADGE_PACKS_IMAGE: &str = "https://cdn.discordapp.com/assets/content/8dd1f75ba9ef2e0587c9963de0964edc7577f98385e85372e9dc600d353dd3b1.png";

/// Discord's --guild-boosting-pink-refresh.
const PINK: Color32 = Color32::from_rgb(255, 76, 210);
const BRAND: Color32 = Color32::from_rgb(88, 101, 242);
const BRAND_HOVER: Color32 = Color32::from_rgb(68, 82, 187);
const BRAND_ACTIVE: Color32 = Color32::from_rgb(58, 72, 163);
/// --status-positive / --text-feedback-positive.
const POSITIVE: Color32 = Color32::from_rgb(61, 158, 96);
const POSITIVE_TEXT: Color32 = Color32::from_rgb(94, 180, 121);
/// --text-feedback-warning / --status-warning / --icon-feedback-critical.
const WARNING_TEXT: Color32 = Color32::from_rgb(234, 152, 0);
const WARNING: Color32 = Color32::from_rgb(253, 184, 51);
const CRITICAL: Color32 = Color32::from_rgb(248, 126, 122);

const SIDEBAR_W: f32 = 376.0;
const CARD_R: f32 = 16.0;
/// A level card: 16 + 38 (progress) + 240 (content) + borders.
const LEVEL_H: f32 = 296.0;

// ---- icons ----------------------------------------------------------------

/// Discord's 24 px icons used on the page: (name, [(even-odd fill, path)]).
const ICONS: &[(&str, &[(bool, &str)])] = &[
    (
        "gem",
        &[
            (false, "M11.02 1.36c.56-.48 1.4-.48 1.96 0l6.48 5.45c.34.29.54.71.54 1.16v8.23c-.05.38-.24.74-.54 1l-6.48 5.44c-.53.45-1.3.48-1.86.09l-.1-.09-6.48-5.45c-.3-.25-.49-.6-.53-1L4 16.04V7.97c0-.45.2-.87.54-1.16l6.48-5.45ZM6.36 7.89a1 1 0 0 0-.36.76v6.7c0 .29.13.57.36.76l5 4.2a1 1 0 0 0 1.28 0l5-4.2a1 1 0 0 0 .36-.77V8.65a1 1 0 0 0-.36-.76l-5-4.2a1 1 0 0 0-1.28 0l-5 4.2Z"),
            (false, "M11.36 6.3a1 1 0 0 1 1.28 0l3 2.52a1 1 0 0 1 .36.76v4.84a1 1 0 0 1-.36.76l-3 2.53a1 1 0 0 1-1.28 0l-3-2.53a1 1 0 0 1-.36-.76V9.58a1 1 0 0 1 .36-.76l3-2.53Z"),
        ],
    ),
    ("gem-slash", &[(false, "M20 16.03v.17c-.05.38-.24.74-.54 1l-6.48 5.44c-.53.45-1.3.48-1.86.09l-.1-.09-2.94-2.47 1.41-1.42 1.87 1.57a1 1 0 0 0 1.28 0l5-4.21a1 1 0 0 0 .36-.76v-5.1l2-2v7.78Zm-4-1.61a1 1 0 0 1-.36.76l-3 2.53a1 1 0 0 1-1.28 0l-.45-.38L16 12.24v2.18ZM11.02 1.36c.56-.48 1.4-.48 1.96 0l2.94 2.47-1.41 1.42-1.87-1.57a1 1 0 0 0-1.28 0l-5 4.21a1 1 0 0 0-.36.76v5.1l-2 2V7.98c0-.45.2-.87.54-1.16l6.48-5.45Zm.34 4.93a1 1 0 0 1 1.28 0l.45.38L8 11.76V9.58a1 1 0 0 1 .36-.76l3-2.53ZM22.7 1.3a1 1 0 0 1 0 1.4l-20 20a1 1 0 0 1-1.4-1.4l20-20a1 1 0 0 1 1.4 0Z")]),
    ("emoji", &[(true, "M12 23a11 11 0 1 0 0-22 11 11 0 0 0 0 22ZM6.5 13a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm11 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm-9.8 1.17a1 1 0 0 1 1.39.27 3.5 3.5 0 0 0 5.82 0 1 1 0 0 1 1.66 1.12 5.5 5.5 0 0 1-9.14 0 1 1 0 0 1 .27-1.4Z")]),
    (
        "sticker",
        &[
            (true, "M6 2h12a4 4 0 0 1 4 4v7.5a.5.5 0 0 1-.5.5H19a5 5 0 0 0-5 5v2.5a.5.5 0 0 1-.5.5H6a4 4 0 0 1-4-4V6a4 4 0 0 1 4-4Zm.5 8a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM19 8.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Zm-9.91 2.94a1 1 0 0 0-1.66 1.12 5.5 5.5 0 0 0 9.14 0 1 1 0 0 0-1.66-1.12 3.5 3.5 0 0 1-5.82 0Z"),
            (false, "M21.66 16c.03 0 .05.03.04.06a3 3 0 0 1-.58.82l-4.24 4.24a3 3 0 0 1-.82.58.04.04 0 0 1-.06-.04V19a3 3 0 0 1 3-3h2.66Z"),
        ],
    ),
    (
        "soundboard",
        &[
            (false, "M14.24 1.03a1 1 0 0 1 .73 1.21l-1 4a1 1 0 1 1-1.94-.48l1-4a1 1 0 0 1 1.21-.73ZM20.7 4.7a1 1 0 0 0-1.4-1.4l-4 4a1 1 0 0 0 1.4 1.4l4-4Z"),
            (true, "M15.14 20.14c1.78-1.78.7-5.75-2.42-8.86-3.11-3.12-7.08-4.2-8.86-2.42A3.13 3.13 0 0 0 3 11V11l-1.16 8.92a2 2 0 0 0 2.24 2.24L13 21c.86-.04 1.6-.32 2.14-.86Zm-1.3-3.4a9.61 9.61 0 0 0-2.53-4.05 9.61 9.61 0 0 0-4.05-2.53c-1.27-.35-1.82-.05-1.99.11-.16.17-.46.72-.11 2a9.61 9.61 0 0 0 2.53 4.04 9.61 9.61 0 0 0 4.05 2.53c1.27.35 1.82.05 1.99-.11.16-.17.46-.72.11-2Z"),
            (false, "M7.05 3.32a1 1 0 0 1 1.9-.64l1 3a1 1 0 0 1-1.9.64l-1-3ZM22.97 9.76a1 1 0 0 0-1.21-.73l-4 1a1 1 0 1 0 .48 1.94l4-1a1 1 0 0 0 .73-1.21ZM20.68 16.95a1 1 0 0 0 .64-1.9l-3-1a1 1 0 0 0-.64 1.9l3 1Z"),
        ],
    ),
    ("gif", &[(true, "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-3H5Zm2.18 13.87a2.9 2.9 0 0 1-1.66-.49 3.18 3.18 0 0 1-1.12-1.35A4.88 4.88 0 0 1 4 12c0-.75.14-1.42.42-2 .29-.59.7-1.04 1.24-1.37a3.7 3.7 0 0 1 1.95-.5c.64 0 1.21.14 1.72.4.5.28.89.67 1.15 1.16l-1.22.88a1.76 1.76 0 0 0-1.64-1.02c-.66 0-1.17.22-1.52.65a2.74 2.74 0 0 0-.53 1.8c0 .78.18 1.39.53 1.81.35.42.86.64 1.52.64.3 0 .57-.06.81-.16.25-.12.45-.27.58-.47v-.93H7.3v-1.4h3.24v4.23H9.27l-.2-.71c-.43.57-1.06.86-1.89.86Zm6.34-.15h-1.57V8.28h1.57v7.44Zm1.51 0h1.57v-2.83h2.76v-1.42H16.6V9.7H20V8.28h-4.97v7.44Z")]),
    ("audio", &[(false, "M12 3a9 9 0 0 0-8.95 10h1.87a5 5 0 0 1 4.1 2.13l1.37 1.97a3.1 3.1 0 0 1-.17 3.78 2.85 2.85 0 0 1-3.55.74 11 11 0 1 1 10.66 0c-1.27.71-2.73.23-3.55-.74a3.1 3.1 0 0 1-.17-3.78l1.38-1.97a5 5 0 0 1 4.1-2.13h1.86A9 9 0 0 0 12 3Z")]),
    (
        "stream",
        &[
            (true, "M2 5a3 3 0 0 1 3-3h14a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3V5Zm16 3a1 1 0 0 0-.3-.7l-3-3a1 1 0 1 0-1.4 1.4L14.58 7H13a6 6 0 0 0-6 6 1 1 0 1 0 2 0 4 4 0 0 1 4-4h1.59l-1.3 1.3a1 1 0 0 0 1.42 1.4l3-3A1 1 0 0 0 18 8Z"),
            (false, "M13 19.5c0 .28.22.5.5.5H15a1 1 0 1 1 0 2H9a1 1 0 1 1 0-2h1.5a.5.5 0 0 0 .5-.5v-2c0-.28.22-.5.5-.5h1c.28 0 .5.22.5.5v2Z"),
        ],
    ),
    ("upload", &[(false, "M13 16V5.41l3.3 3.3a1 1 0 1 0 1.4-1.42l-5-5a1 1 0 0 0-1.4 0l-5 5a1 1 0 0 0 1.4 1.42L11 5.4V16a1 1 0 1 0 2 0ZM3 20a1 1 0 1 0 0 2h18a1 1 0 1 0 0-2H3Z")]),
    ("role-icon", &[(false, "M20.3 5.41h-.39c-.84 0-1.52-.65-1.52-1.46v-.3c0-.9-.77-1.65-1.71-1.65H7.31c-.94 0-1.71.74-1.71 1.65v.3c0 .81-.68 1.46-1.52 1.46H3.7c-.94 0-1.7.73-1.7 1.64v3.52l.01.49c.05 3.11.94 4.69 2.92 6.63C6.72 19.46 11.58 22 11.99 22c.41 0 5.27-2.54 7.06-4.31 1.98-1.95 2.92-3.53 2.92-6.63L22 7.05c0-.9-.76-1.64-1.7-1.64Zm-8.32.03a3.15 3.15 0 1 1-.01 6.3 3.15 3.15 0 0 1 .01-6.3Zm4.52 11.67c-.97.68-2.86 1.62-3.87 2.11-.42.2-.91.2-1.33 0a40.17 40.17 0 0 1-3.82-2.1.87.87 0 0 1-.37-.85c.42-2.69 2.46-3.21 4.89-3.21 2.43 0 4.4.68 4.87 3.08a.97.97 0 0 1-.38.98l.01-.01Z")]),
    (
        "banner",
        &[
            (false, "M4 8v7.5a.5.5 0 0 1-.5.5H3a1 1 0 0 1-1-1V8a6 6 0 0 1 6-6h7a1 1 0 0 1 1 1v.5a.5.5 0 0 1-.5.5H8a4 4 0 0 0-4 4Z"),
            (true, "M6 9a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3V9Zm13.8 9.79L16.82 15a2 2 0 0 0-3.14 0l-2.09 2.65-.13-.16a1.5 1.5 0 0 0-2.36.05l-.95 1.26a.75.75 0 0 0 .6 1.2h10.46c.62 0 .97-.72.59-1.21ZM11.73 8.3c.57-.56 1.52-.01 1.33.77a.8.8 0 0 0 .55.96c.77.22.77 1.3 0 1.53a.8.8 0 0 0-.55.96c.19.77-.76 1.32-1.33.76a.8.8 0 0 0-1.1 0c-.58.56-1.53.01-1.33-.76a.8.8 0 0 0-.56-.96c-.77-.22-.77-1.31 0-1.53a.8.8 0 0 0 .56-.96c-.2-.78.75-1.33 1.32-.77.31.3.8.3 1.11 0Z"),
        ],
    ),
    ("star", &[(false, "M10.81 2.86c.38-1.15 2-1.15 2.38 0l1.89 5.83h6.12c1.2 0 1.71 1.54.73 2.25l-4.95 3.6 1.9 5.82a1.25 1.25 0 0 1-1.93 1.4L12 18.16l-4.95 3.6c-.98.7-2.3-.25-1.92-1.4l1.89-5.82-4.95-3.6a1.25 1.25 0 0 1 .73-2.25h6.12l1.9-5.83Z")]),
    ("check", &[(true, "M12 23a11 11 0 1 0 0-22 11 11 0 0 0 0 22Zm5.7-13.3a1 1 0 0 0-1.4-1.4L10 14.58l-2.3-2.3a1 1 0 0 0-1.4 1.42l3 3a1 1 0 0 0 1.4 0l7-7Z")]),
    ("error", &[(true, "M12 23a11 11 0 1 0 0-22 11 11 0 0 0 0 22Zm1.44-15.94L13.06 14a1.06 1.06 0 0 1-2.12 0l-.38-6.94a1 1 0 0 1 1-1.06h.88a1 1 0 0 1 1 1.06Zm-.19 10.69a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0Z")]),
    ("play", &[(false, "M9.25 3.35C7.87 2.45 6 3.38 6 4.96v14.08c0 1.58 1.87 2.5 3.25 1.61l10.85-7.04a1.9 1.9 0 0 0 0-3.22L9.25 3.35Z")]),
    ("close", &[(false, "M19.3 20.7a1 1 0 0 0 1.4-1.4L13.42 12l7.3-7.3a1 1 0 0 0-1.42-1.4L12 10.58l-7.3-7.3a1 1 0 0 0-1.4 1.42L10.58 12l-7.3 7.3a1 1 0 1 0 1.42 1.4L12 13.42l7.3 7.3Z")]),
];

/// The icon `name` as a white SVG (tinted when drawn, so one texture serves
/// every colour).
fn icon_source(name: &str) -> Option<egui::ImageSource<'static>> {
    use std::sync::{Mutex, OnceLock};
    static CACHE: OnceLock<Mutex<HashMap<&'static str, Arc<[u8]>>>> = OnceLock::new();
    let (key, paths) = ICONS.iter().find(|(n, _)| *n == name)?;
    let cache = CACHE.get_or_init(Default::default);
    let cached = cache.lock().ok().and_then(|c| c.get(key).cloned());
    let bytes = match cached {
        Some(b) => b,
        None => {
            let mut svg = String::from("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"#ffffff\">");
            for (even_odd, d) in paths.iter() {
                let rule = if *even_odd { " fill-rule=\"evenodd\" clip-rule=\"evenodd\"" } else { "" };
                svg.push_str(&format!("<path{rule} d=\"{d}\"/>"));
            }
            svg.push_str("</svg>");
            let bytes: Arc<[u8]> = Arc::from(svg.into_bytes());
            if let Ok(mut c) = cache.lock() {
                c.insert(key, bytes.clone());
            }
            bytes
        }
    };
    Some(egui::ImageSource::Bytes { uri: format!("bytes://boosts-{key}.svg").into(), bytes: Bytes::Shared(bytes) })
}

/// Paint icon `name` in a `size` px box whose top-left is `at`.
fn paint_icon(ui: &Ui, name: &str, at: Pos2, size: f32, color: Color32) {
    if let Some(src) = icon_source(name) {
        egui::Image::new(src).tint(color).show_loading_spinner(false).paint_at(ui, Rect::from_min_size(at, vec2(size, size)));
    }
}

/// The pixel-art gem of level `n` (0-2).
fn level_gem(n: usize) -> egui::ImageSource<'static> {
    const GEMS: [(&str, &[u8]); 3] = [
        ("bytes://boosts-level1.svg", include_bytes!("../../assets/boosts/level1.svg")),
        ("bytes://boosts-level2.svg", include_bytes!("../../assets/boosts/level2.svg")),
        ("bytes://boosts-level3.svg", include_bytes!("../../assets/boosts/level3.svg")),
    ];
    let (uri, bytes) = GEMS[n.min(2)];
    egui::ImageSource::Bytes { uri: uri.into(), bytes: Bytes::Static(bytes) }
}

/// The thumbnail of Discord's "How do Boosts work?" video (scaled down from
/// the 1920 x 1080 original).
fn video_thumbnail() -> egui::ImageSource<'static> {
    egui::ImageSource::Bytes { uri: "bytes://boosts-video.jpg".into(), bytes: Bytes::Static(include_bytes!("../../assets/boosts/how-boosts-work.jpg")) }
}

// ---- data -----------------------------------------------------------------

/// One thing Boosts unlock (Discord: a "powerup").
#[derive(Clone, Debug, PartialEq)]
pub struct Powerup {
    pub sku: String,
    pub level: bool,
    pub title: String,
    pub description: String,
    pub cost: u32,
    /// The powerup that has to be on first.
    pub dependency: Option<String>,
    pub image: Option<String>,
}

/// A card under "Additional Perks".
#[derive(Clone, Debug, PartialEq)]
pub enum Listing {
    Perk(Powerup),
    /// The Server Tag badge packs share one card.
    BadgePacks(Vec<Powerup>),
}

/// How a powerup is on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
    Inactive,
    /// Switched on with Boosts.
    Active,
    /// Comes with a level the server has.
    Level,
    /// Discord gave the server Level 3 (PREMIUM_TIER_3_OVERRIDE).
    Override,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
    Gave,
    /// Ending within three days, at this time (ms).
    Expiring(i64),
    Expired,
}

/// One line of Recent Activity.
#[derive(Clone, Debug)]
pub struct Activity {
    pub user: User,
    pub phase: Phase,
    /// What Discord sorts by, and the date it shows (ms).
    pub at: i64,
}

/// What Discord sent for one server's page, parsed.
#[derive(Clone, Debug, Default)]
pub struct BoostsData {
    guild: Id,
    /// Which of the three answers this was built from.
    stamp: [bool; 3],
    pub levels: Vec<Powerup>,
    pub perks: Vec<Listing>,
    /// Powerups switched on: SKU → when it ends (ms), if it's running out.
    pub unlocked: HashMap<String, Option<i64>>,
    /// `unlocked` came from Discord (false: not loaded, or the request failed).
    pub unlocked_known: bool,
    pub activity: Vec<Activity>,
    /// Boosts that aren't ended or ending.
    pub lasting: u32,
    /// You boost this server.
    pub boosting: bool,
}

/// A pop-up over the page.
#[derive(Clone, Debug, PartialEq)]
enum Modal {
    /// A level's "View Perks" (0-2).
    Level(usize),
    /// A perk, by SKU.
    Perk(String),
    /// The Server Tag badge packs.
    Packs,
    /// "Disable {perk}?"
    Disable(String),
    /// "{perk} enabled!"
    Enabled(String),
    /// The server hasn't the Boosts this perk costs.
    NeedBoosts(String),
    /// "Boost This Server": use one of your unused Boosts.
    Boost,
}

#[derive(Default)]
pub struct BoostsState {
    data: Option<BoostsData>,
    /// How far the Levels row is scrolled sideways.
    levels_scroll: f32,
    /// The pop-up that is open, and the server it is for.
    modal: Option<(Id, Modal)>,
    /// A perk being switched on (true) or off, until Discord answers.
    toggling: Option<(String, bool)>,
}

fn subs_tag(g: Id) -> String {
    format!("gp:boosts:{g}")
}

fn catalog_tag(g: Id) -> String {
    format!("gp:boost-catalog:{g}")
}

fn unlocked_tag(g: Id) -> String {
    format!("gp:boost-unlocked:{g}")
}

/// The levels and perks Discord sold on 2026-11-22: shown until its catalog
/// arrives (and in the demo, which has none).
fn builtin_catalog() -> (Vec<Powerup>, Vec<Powerup>) {
    let p = |sku: &str, level: bool, title: &str, description: &str, cost: u32, dependency: Option<&str>, image: Option<&str>| Powerup {
        sku: sku.into(),
        level,
        title: title.into(),
        description: description.into(),
        cost,
        dependency: dependency.map(String::from),
        image: image.map(String::from),
    };
    let levels = vec![
        p(SKU_LEVELS[0], true, "Level 1", "", 2, None, None),
        p(SKU_LEVELS[1], true, "Level 2", "", 5, Some(SKU_LEVELS[0]), None),
        p(SKU_LEVELS[2], true, "Level 3", "", 7, Some(SKU_LEVELS[1]), None),
    ];
    let perks = vec![
        p(
            SKU_SERVER_TAG,
            false,
            "Server Tag",
            "Let your members represent your server everywhere on Discord.",
            3,
            None,
            Some("https://cdn.discordapp.com/assets/content/478ce7fb9a64e4d6c4792c82d93f724c2aa0444ac2dfc3e2dfdf43dd11a39c79.png"),
        ),
        p(
            SKU_ROLE_STYLES,
            false,
            "Enhanced Role Styles",
            "Make certain roles stand out with animated, vibrant gradients.",
            3,
            None,
            Some("https://cdn.discordapp.com/assets/content/93c84331a5f11ba05946bce6fb4f85594d98cb52c8452e9b6869291da41cf62c.png"),
        ),
        p(SKU_BADGE_PACKS[1], false, "Pets Badge Pack", "", 3, Some(SKU_SERVER_TAG), None),
        p(SKU_BADGE_PACKS[3], false, "Flex Badge Pack", "", 5, Some(SKU_SERVER_TAG), None),
        p(SKU_BADGE_PACKS[2], false, "Plant Badge Pack", "", 3, Some(SKU_SERVER_TAG), None),
        p(SKU_BADGE_PACKS[0], false, "Creepy Crawlies Badge Pack", "", 2, Some(SKU_SERVER_TAG), None),
    ];
    (levels, perks)
}

/// Discord's catalog answer → (levels, perks), each in SKU order.
pub fn parse_catalog(v: &Value) -> Option<(Vec<Powerup>, Vec<Powerup>)> {
    let mut all: Vec<Powerup> = v
        .as_array()?
        .iter()
        .filter_map(|e| {
            let kind = e["powerup_metadata"]["category_type"].as_str()?;
            let meta = e["sku"].get("powerup_metadata").filter(|m| m.is_object())?;
            let level = match kind {
                "level" => true,
                "perk" => false,
                _ => return None,
            };
            let image = e["powerup_metadata"]["static_image_url"].as_str().or_else(|| meta["static_image_url"].as_str());
            Some(Powerup {
                sku: e["sku"]["id"].as_str()?.to_string(),
                level,
                title: e["summary"].as_str().unwrap_or_default().to_string(),
                description: e["description"].as_str().unwrap_or_default().to_string(),
                cost: meta["boost_price"].as_u64().unwrap_or(0) as u32,
                dependency: e["sku"]["dependent_sku_id"].as_str().map(String::from),
                image: image.filter(|u| u.starts_with("https://")).map(String::from),
            })
        })
        .collect();
    // (Discord compares the ids as strings; they're all the same length.)
    all.sort_by(|a, b| a.sku.cmp(&b.sku));
    let (levels, perks): (Vec<_>, Vec<_>) = all.into_iter().partition(|p| p.level);
    (!levels.is_empty() || !perks.is_empty()).then_some((levels, perks))
}

/// The "Additional Perks" cards in Discord's order: perks by SKU with the
/// badge packs as one card, the server theme first, the badge packs right
/// after Server Tag.
pub fn arrange_perks(perks: Vec<Powerup>) -> Vec<Listing> {
    let mut packs: Vec<Powerup> = perks.iter().filter(|p| SKU_BADGE_PACKS.contains(&p.sku.as_str())).cloned().collect();
    packs.sort_by_key(|p| SKU_BADGE_PACKS.iter().position(|s| *s == p.sku));
    let mut out: Vec<Listing> = Vec::new();
    let mut packs = Some(packs).filter(|p| !p.is_empty());
    for p in perks {
        if SKU_BADGE_PACKS.contains(&p.sku.as_str()) {
            if let Some(group) = packs.take() {
                out.push(Listing::BadgePacks(group));
            }
        } else {
            out.push(Listing::Perk(p));
        }
    }
    let is = |l: &Listing, sku: &str| matches!(l, Listing::Perk(p) if p.sku == sku);
    if let Some(i) = out.iter().position(|l| is(l, SKU_GUILD_THEME)).filter(|i| *i > 0) {
        let theme = out.remove(i);
        out.insert(0, theme);
    }
    let tag = out.iter().position(|l| is(l, SKU_SERVER_TAG));
    let group = out.iter().position(|l| matches!(l, Listing::BadgePacks(_)));
    if let (Some(_), Some(g)) = (tag, group) {
        let packs = out.remove(g);
        let tag = out.iter().position(|l| is(l, SKU_SERVER_TAG)).unwrap_or(0);
        out.insert(tag + 1, packs);
    }
    out
}

/// A boost's phase and the time Discord files it under, at `now` (ms).
/// `started`: when it was given; `ends`: when it ends, once cancelled.
pub fn boost_phase(started: i64, ends: Option<i64>, ended: bool, now: i64) -> (Phase, i64) {
    const SOON: i64 = 3 * 86_400_000;
    match ends {
        _ if ended => (Phase::Expired, ends.unwrap_or(started)),
        Some(e) if e <= now => (Phase::Expired, e),
        Some(e) if e - now <= SOON => (Phase::Expiring(e), e - SOON),
        _ => (Phase::Gave, started),
    }
}

/// Every boost as a Recent Activity line, newest first; boosts that aren't
/// ended or ending; and whether `me` boosts.
fn parse_activity(v: &Value, store: &crate::store::Store, me: Option<Id>, now: i64) -> (Vec<Activity>, u32, bool) {
    let mut list = Vec::new();
    let (mut lasting, mut mine) = (0, false);
    for s in v.as_array().into_iter().flatten() {
        let Some(uid) = Id::from_value(&s["user_id"]).or_else(|| Id::from_value(&s["user"]["id"])) else { continue };
        let ended = s["ended"].as_bool().unwrap_or(false);
        let ends = s["ends_at"].as_str().and_then(|e| DateTime::parse_from_rfc3339(e).ok()).map(|d| d.timestamp_millis());
        let started = Id::from_value(&s["id"]).map(|i| i.timestamp_ms() as i64).unwrap_or(0);
        if !ended {
            mine |= Some(uid) == me;
            if ends.is_none() {
                lasting += 1;
            }
        }
        let user = <User as serde::Deserialize>::deserialize(&s["user"]).ok().filter(|u| u.id.0 != 0).or_else(|| store.users.get(&uid).cloned());
        let user = user.unwrap_or_else(|| User { id: uid, username: "Unknown User".into(), ..Default::default() });
        let (phase, at) = boost_phase(started, ends, ended, now);
        list.push(Activity { user, phase, at });
    }
    list.sort_by(|a, b| b.at.cmp(&a.at));
    (list, lasting, mine)
}

/// Everything Boosts can buy: Discord's Boost Goal. Level 3 (unless Discord
/// gave the server Level 3 for free) plus every standalone perk.
pub fn boost_goal(g: &Guild) -> u32 {
    let levels = if has_feature(g, "PREMIUM_TIER_3_OVERRIDE") { 0 } else { LEVEL_COST.iter().sum() };
    levels + FEATURE_COST.iter().map(|f| f.1).sum::<u32>()
}

impl BoostsData {
    fn powerup(&self, sku: &str) -> Option<&Powerup> {
        self.levels.iter().find(|p| p.sku == sku).or_else(|| {
            self.perks.iter().find_map(|l| match l {
                Listing::Perk(p) if p.sku == sku => Some(p),
                Listing::BadgePacks(v) => v.iter().find(|p| p.sku == sku),
                _ => None,
            })
        })
    }

    /// How `p` is on in a server of this `tier`, and when that runs out.
    pub fn status(&self, p: &Powerup, tier: u8, tier_override: bool) -> (Status, Option<i64>) {
        let ends = |sku: &str| self.unlocked.get(sku).copied().flatten();
        let level = SKU_LEVELS.iter().position(|s| *s == p.sku);
        if p.sku == SKU_INVITE_LINK && tier >= 3 {
            return (Status::Level, ends(SKU_LEVELS[2]));
        }
        let overridable = level.is_some() || p.sku == SKU_SERVER_TAG || p.sku == SKU_ROLE_STYLES || SKU_BADGE_PACKS.contains(&p.sku.as_str());
        if tier_override && overridable {
            return (Status::Override, None);
        }
        if self.unlocked.contains_key(&p.sku) {
            return (Status::Active, ends(&p.sku));
        }
        // Until Discord says what is switched on, the level is what RustCord knows.
        match level {
            Some(n) if !self.unlocked_known && tier as usize > n => (Status::Active, None),
            _ => (Status::Inactive, None),
        }
    }

    /// Boosts the server has put to use: its levels, and the perks it bought.
    pub fn spent(&self, g: &Guild, tier: u8) -> u32 {
        let tier_override = has_feature(g, "PREMIUM_TIER_3_OVERRIDE");
        let levels: u32 = if tier_override { 0 } else { LEVEL_COST.iter().take(tier.min(3) as usize).sum() };
        let perks: u32 = match &g.boost_features {
            Some(f) if !tier_override => FEATURE_COST.iter().filter(|(name, _)| f.iter().any(|x| x == name)).map(|f| f.1).sum(),
            Some(_) => 0,
            // Discord didn't list them: count the perks that are switched on.
            None => self
                .unlocked
                .keys()
                .filter_map(|sku| self.powerup(sku))
                .filter(|p| !p.level && self.status(p, tier, tier_override).0 == Status::Active)
                .map(|p| p.cost)
                .sum(),
        };
        levels + perks
    }
}

// ---- drawing helpers --------------------------------------------------------

/// Discord's --background-gradient-* overlay strengths under a client theme,
/// from the chat surface's (its "low"): lowest .54 / lower .51 / low .48,
/// each plus a share of the theme's mix.
#[derive(Clone, Copy)]
enum Depth {
    Lowest,
    Lower,
    Low,
}

fn depth(t: &Theme, d: Depth) -> f32 {
    let low = t.overlays.chat;
    let m = ((low - 0.48) / 0.32).clamp(0.0, 1.0);
    let a = match d {
        Depth::Lowest => low + 0.06 + m * 0.04,
        Depth::Lower => low + 0.03 + m * 0.02,
        Depth::Low => low,
    };
    a.min(0.97)
}

/// Fill a surface: `solid` on a plain theme; under a client theme its
/// gradient with the overlay at `strength`.
fn surface(ui: &Ui, t: &Theme, rect: Rect, rounding: f32, solid: Color32, strength: f32) {
    if !super::paint_theme_overlay(ui.ctx(), ui.painter(), rect, rounding, strength, t) {
        ui.painter().rect_filled(rect, rounding, solid);
    }
}

fn fade(c: Color32, a: f32) -> Color32 {
    if a >= 0.999 {
        c
    } else {
        c.gamma_multiply(a.clamp(0.0, 1.0))
    }
}

/// Discord's translucent "mod" grey at `a` (subtle .12, muted .08, strong .2).
fn modc(a: f32) -> Color32 {
    rgba(151, 151, 159, (a * 255.0).round() as u8)
}

/// One line of text in a `line` px tall box whose top-left is `at`.
fn line(p: &egui::Painter, at: Pos2, line: f32, text: &str, font: FontId, color: Color32) -> Rect {
    p.text(pos2(at.x, at.y + line / 2.0), Align2::LEFT_CENTER, text, font, color)
}

fn width(ui: &Ui, text: &str, font: FontId) -> f32 {
    ui.painter().layout_no_wrap(text.to_string(), font, Color32::WHITE).size().x
}

/// Text wrapped at `width` with `line` px rows.
fn wrapped(ui: &Ui, text: &str, font: FontId, color: Color32, width: f32, line: f32, center: bool) -> Arc<Galley> {
    let mut job = LayoutJob::default();
    job.append(text, 0.0, TextFormat { font_id: font, color, line_height: Some(line), ..Default::default() });
    job.wrap.max_width = width;
    if center {
        job.halign = egui::Align::Center;
    }
    ui.fonts(|f| f.layout_job(job))
}

/// A vertical black gradient (transparent → `bottom` alpha), Discord's shade
/// behind a perk's picture.
fn shade(p: &egui::Painter, rect: Rect, bottom: f32) {
    let mut mesh = egui::Mesh::default();
    let dark = Color32::from_rgba_premultiplied(0, 0, 0, (bottom * 255.0) as u8);
    mesh.colored_vertex(rect.left_top(), Color32::TRANSPARENT);
    mesh.colored_vertex(rect.right_top(), Color32::TRANSPARENT);
    mesh.colored_vertex(rect.left_bottom(), dark);
    mesh.colored_vertex(rect.right_bottom(), dark);
    mesh.add_triangle(0, 1, 2);
    mesh.add_triangle(1, 2, 3);
    p.add(egui::Shape::mesh(mesh));
}

/// A left → right gradient bar.
fn hgradient(p: &egui::Painter, rect: Rect, left: Color32, right: Color32) {
    let mut mesh = egui::Mesh::default();
    mesh.colored_vertex(rect.left_top(), left);
    mesh.colored_vertex(rect.right_top(), right);
    mesh.colored_vertex(rect.left_bottom(), left);
    mesh.colored_vertex(rect.right_bottom(), right);
    mesh.add_triangle(0, 1, 2);
    mesh.add_triangle(1, 2, 3);
    p.add(egui::Shape::mesh(mesh));
}

/// CSS `radial-gradient(circle, colour at `inner` alpha, … at `outer` alpha)`
/// over a rounded rect (the dark vignette on the video thumbnail).
fn vignette(p: &egui::Painter, rect: Rect, r: f32, rgb: [u8; 3], inner: f32, outer: f32) {
    let mut outline = Vec::new();
    egui::epaint::tessellator::path::rounded_rectangle(&mut outline, rect, Rounding::same(r));
    let c = rect.center();
    let far = (rect.right_bottom() - c).length().max(1.0);
    let at = |q: Pos2| {
        let k = ((q - c).length() / far).clamp(0.0, 1.0);
        rgba(rgb[0], rgb[1], rgb[2], ((inner + (outer - inner) * k) * 255.0).round() as u8)
    };
    let n = outline.len() as u32;
    let mut mesh = egui::Mesh::default();
    mesh.colored_vertex(c, at(c));
    // A ring half-way out keeps the fall-off round on a wide rectangle.
    for q in &outline {
        let mid = c + (*q - c) * 0.5;
        mesh.colored_vertex(mid, at(mid));
    }
    for q in &outline {
        mesh.colored_vertex(*q, at(*q));
    }
    for i in 0..n {
        let j = (i + 1) % n;
        mesh.add_triangle(0, 1 + i, 1 + j);
        mesh.add_triangle(1 + i, 1 + n + i, 1 + n + j);
        mesh.add_triangle(1 + i, 1 + n + j, 1 + j);
    }
    p.add(egui::Shape::mesh(mesh));
}

/// "{n} Boost(s)", with Discord's "+" for "from".
fn cost_text(cost: u32, plus: bool) -> String {
    format!("{cost}{} Boost{}", if plus { "+" } else { "" }, if cost == 1 { "" } else { "s" })
}

fn day_month(ms: i64) -> String {
    DateTime::from_timestamp_millis(ms).map(|d| d.with_timezone(&Local).format("%d/%m").to_string()).unwrap_or_default()
}

/// Recent Activity's date: Today, Yesterday or the date.
fn activity_date(ms: i64, today: chrono::NaiveDate) -> String {
    let Some(d) = DateTime::from_timestamp_millis(ms).map(|d| d.with_timezone(&Local)) else { return String::new() };
    match (today - d.date_naive()).num_days() {
        0 => "Today".into(),
        1 => "Yesterday".into(),
        _ => d.format("%d/%m/%Y").to_string(),
    }
}

/// A button's look.
#[derive(Clone, Copy, PartialEq)]
enum Look {
    /// Discord's brand-coloured primary button.
    Primary,
    /// The quiet grey button of the admin panel.
    Quiet,
    /// A destructive action.
    Danger,
}

/// Paint a button's background and return its response (`alpha` < 0.5: it's
/// fading in and can't be pressed yet).
fn button_bg(ui: &Ui, t: &Theme, rect: Rect, id: egui::Id, look: Look, alpha: f32, enabled: bool) -> egui::Response {
    let live = enabled && alpha > 0.5;
    let resp = ui.interact(rect, id, if live { Sense::click() } else { Sense::hover() });
    let alpha = if enabled { alpha } else { alpha * 0.5 };
    let (fill, border) = match look {
        Look::Primary => {
            let c = if !live {
                BRAND
            } else if resp.is_pointer_button_down_on() {
                BRAND_ACTIVE
            } else if resp.hovered() {
                BRAND_HOVER
            } else {
                BRAND
            };
            (c, rgba(255, 255, 255, 20))
        }
        Look::Quiet => (if live && resp.hovered() { modc(0.2) } else { modc(0.08) }, modc(0.04)),
        Look::Danger => (if live && resp.hovered() { Color32::from_rgb(161, 40, 44) } else { Color32::from_rgb(218, 55, 60) }, rgba(255, 255, 255, 20)),
    };
    let p = ui.painter();
    p.rect_filled(rect, 8.0, fade(fill, alpha));
    p.rect_stroke(rect.shrink(0.5), 8.0, Stroke::new(1.0_f32, fade(border, alpha)));
    let _ = t;
    if live {
        resp.on_hover_cursor(egui::CursorIcon::PointingHand)
    } else {
        resp
    }
}

/// What a click on the page asks for.
enum Act {
    /// "Boost This Server".
    Boost,
    Faq,
    Video,
    /// The "View Perks" pop-up of a level (0-2).
    LevelPerks(usize),
    /// A perk's pop-up, by SKU.
    Perk(String),
    /// The badge packs' pop-up.
    Packs,
    /// Switch a level or perk on, by SKU.
    Enable(String),
    /// Server Settings, for this perk.
    Configure(String),
    Profile(User, Pos2),
}

/// What the button that slides into a hovered card does.
#[derive(Clone)]
enum CardButton {
    /// "View Perks" / "View Perk" / "View Packs" / "Configure".
    Text(&'static str),
    /// "Enable • ◆ n": switch the perk on for `n` Boosts.
    Enable(u32, bool),
    None,
}

/// A card's state line: nothing, a green "Enabled", or a yellow "Expires …".
#[derive(Clone)]
enum Badge {
    None,
    On(String),
    Expires(String),
}

/// The frame shared by level and perk cards: lift and shadow on hover,
/// Discord's surfaces and state borders. Returns the lifted rect, the hover
/// amount (0-1) and whether the card itself was clicked.
fn card_frame(ui: &Ui, t: &Theme, base: Rect, id: egui::Id, active: bool, warning: bool) -> (Rect, f32, egui::Response) {
    let hit = Rect::from_min_max(base.min - vec2(0.0, 4.0), base.max);
    let resp = ui.interact(hit, id, Sense::click());
    let over = ui.rect_contains_pointer(hit);
    let h = ui.ctx().animate_bool_with_time(id.with("hover"), over, 0.2);
    let r = base.translate(vec2(0.0, -4.0 * h));
    if h > 0.0 {
        let shadow = Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha((0.24 * h * 255.0) as u8) };
        ui.painter().add(shadow.as_shape(r, Rounding::same(CARD_R)));
    }
    if active || warning {
        ui.painter().rect_filled(r, CARD_R, t.surface_high);
    } else {
        let solid = t.bg_primary.lerp_to_gamma(t.bg_secondary_alt, h);
        let strength = depth(t, Depth::Lower) + (depth(t, Depth::Low) - depth(t, Depth::Lower)) * h;
        surface(ui, t, r, CARD_R, solid, strength);
    }
    let border = if warning {
        rgba(WARNING.r(), WARNING.g(), WARNING.b(), 89)
    } else if active {
        rgba(POSITIVE.r(), POSITIVE.g(), POSITIVE.b(), 89)
    } else {
        t.border_subtle
    };
    ui.painter().rect_stroke(r.shrink(0.5), CARD_R, Stroke::new(1.0_f32, border));
    (r, h, resp.on_hover_cursor(egui::CursorIcon::PointingHand))
}

/// A card's footer ("◆ 2 Boosts" … "✓ Enabled") and the button that takes its
/// place on hover. Returns true when the button was pressed.
#[allow(clippy::too_many_arguments)]
fn card_footer(ui: &Ui, t: &Theme, r: Rect, id: egui::Id, h: f32, cost: Option<String>, badge: &Badge, button: &CardButton, tip: Option<&str>) -> bool {
    let p = ui.painter();
    let y = r.bottom() - 35.0;
    let a = 1.0 - h;
    if a > 0.0 {
        if let Some(cost) = &cost {
            paint_icon(ui, "gem", pos2(r.left() + 17.0, y), 18.0, fade(PINK, a));
            line(p, pos2(r.left() + 41.0, y), 18.0, cost, strong(14.0), fade(t.interactive_normal, a));
        }
        let (name, color, text_color, text) = match badge {
            Badge::None => ("", Color32::TRANSPARENT, Color32::TRANSPARENT, ""),
            Badge::On(s) => ("check", POSITIVE, t.tint_text(POSITIVE_TEXT), s.as_str()),
            Badge::Expires(s) => ("error", WARNING, t.tint_text(WARNING_TEXT), s.as_str()),
        };
        if !text.is_empty() {
            let w = width(ui, text, strong(14.0));
            let x = r.right() - 17.0 - w;
            line(p, pos2(x, y), 18.0, text, strong(14.0), fade(text_color, a));
            paint_icon(ui, name, pos2(x - 22.0, y + 1.0), 16.0, fade(color, a));
        }
    }
    if h <= 0.0 || matches!(button, CardButton::None) {
        return false;
    }
    let b = Rect::from_min_max(pos2(r.left() + 17.0, r.bottom() - 1.0 - 16.0 * h - 40.0), pos2(r.right() - 17.0, r.bottom() - 1.0 - 16.0 * h));
    let enabled = !matches!(button, CardButton::Enable(_, false));
    let resp = button_bg(ui, t, b, id.with("button"), Look::Primary, h, enabled);
    let fg = fade(Color32::WHITE, if enabled { h } else { h * 0.5 });
    match button {
        CardButton::Text(label) => {
            p.text(b.center(), Align2::CENTER_CENTER, *label, medium(16.0), fg);
        }
        CardButton::Enable(cost, _) => enable_label(ui, b, "Enable", "gem", *cost, fg),
        CardButton::None => {}
    }
    let resp = match tip {
        Some(tip) => resp.on_hover_text(tip),
        None => resp,
    };
    resp.clicked()
}

/// A button's "Enable \u{2022} \u{25c6} n" label: the word, a dot (6 px before, 4 after),
/// the gem, the price.
fn enable_label(ui: &Ui, b: Rect, word: &str, gem: &str, cost: u32, fg: Color32) {
    let p = ui.painter();
    let cost = cost.to_string();
    let (w1, w2, w3) = (width(ui, word, medium(16.0)), width(ui, "\u{2022}", medium(16.0)), width(ui, &cost, medium(16.0)));
    let total = w1 + 6.0 + w2 + 4.0 + 4.0 + 18.0 + 4.0 + w3;
    let mut x = b.center().x - total / 2.0;
    let cy = b.center().y;
    p.text(pos2(x, cy), Align2::LEFT_CENTER, word, medium(16.0), fg);
    x += w1 + 6.0;
    p.text(pos2(x, cy), Align2::LEFT_CENTER, "\u{2022}", medium(16.0), fg);
    x += w2 + 8.0;
    paint_icon(ui, gem, pos2(x, cy - 9.0), 18.0, fg);
    x += 22.0;
    p.text(pos2(x, cy), Align2::LEFT_CENTER, cost, medium(16.0), fg);
}

/// The perks listed on a level's card: (icon, text).
const CARD_PERKS: [[(&str, &str); 4]; 3] = [
    [("emoji", "100 Emoji Slots"), ("soundboard", "24 Soundboard Slots"), ("gif", "Animated Server Icon"), ("audio", "Better Quality Audio")],
    [("stream", "HD Streaming"), ("upload", "50MB File Uploads"), ("role-icon", "Custom Role Icons"), ("banner", "Server Banner")],
    [("star", "Custom Server Invite Link"), ("upload", "100MB File Uploads"), ("audio", "Highest Quality Audio"), ("gif", "Animated server banner")],
];

/// Everything a level brings, as its "View Perks" pop-up lists it.
const LEVEL_PERKS: [&[(&str, &str)]; 3] = [
    &[
        ("emoji", "100 Server Emoji Slots (+50)"),
        ("sticker", "15 Custom Sticker Slots (+10)"),
        ("soundboard", "24 Soundboard Slots (+16)"),
        ("gif", "Animated Server Icon"),
        ("audio", "128 kbps audio quality"),
        ("banner", "Custom Server Invite Banner"),
    ],
    &[
        ("emoji", "150 Server Emoji Slots (+50)"),
        ("sticker", "30 Custom Sticker Slots (+15)"),
        ("soundboard", "36 Soundboard Slots (+12)"),
        ("upload", "50MB File Uploads"),
        ("stream", "HD Streaming"),
        ("audio", "256 kbps audio quality"),
        ("role-icon", "Custom Role Icons"),
        ("banner", "Server Banner"),
    ],
    &[
        ("emoji", "250 Server Emoji Slots (+100)"),
        ("sticker", "60 Custom Sticker Slots (+30)"),
        ("soundboard", "48 Soundboard Slots (+12)"),
        ("audio", "384 kbps audio quality"),
        ("gif", "Animated server banner"),
        ("upload", "100MB File Uploads"),
        ("star", "Custom Invite Link"),
    ],
];

/// What the page needs to know about one level card.
struct LevelCard {
    title: String,
    cost: u32,
    active: bool,
    /// The next level is on too (None: this is the last one).
    next_active: Option<bool>,
    /// Discord gave the level: no price, no button.
    free: bool,
    badge: Badge,
    button: CardButton,
    tip: Option<String>,
}

/// What the page needs to know about one perk card.
struct PerkCard {
    key: String,
    title: String,
    description: String,
    image: Option<String>,
    /// Discord pads the role-styles picture.
    inset: bool,
    cost: Option<String>,
    active: bool,
    warning: bool,
    badge: Badge,
    button: CardButton,
    tip: Option<String>,
    beta: bool,
    /// The badge packs' shared card.
    packs: bool,
}

impl RustCord {
    /// Ask Discord for what the page shows (opening it).
    pub(super) fn boosts_open(&mut self, guild: Id) {
        let subs = subs_tag(guild);
        if !self.api_busy(&subs) {
            self.api(&subs, Method::GET, format!("/guilds/{guild}/premium/subscriptions?include_ended=true"), None);
        }
        let unlocked = unlocked_tag(guild);
        if !self.api_busy(&unlocked) {
            self.api(&unlocked, Method::GET, format!("/guilds/{guild}/powerups?include_ends_at=true"), None);
        }
        // The catalog rarely changes: once per server per run (Discord: once a day).
        self.api_get_once(&catalog_tag(guild), format!("/store/published-listings/skus?application_id={POWERUPS_APP}&guild_id={guild}"));
        let b = &mut self.guild_pages.boosts;
        b.data = None;
        b.levels_scroll = 0.0;
        b.modal = None;
        b.toggling = None;
    }

    /// Parse Discord's answers when one arrived, and ask for the members
    /// Recent Activity names (their nicknames and role colours).
    fn boosts_refresh(&mut self, gid: Id) {
        let stamp = [self.api_result(&catalog_tag(gid)).is_some(), self.api_result(&unlocked_tag(gid)).is_some(), self.api_result(&subs_tag(gid)).is_some()];
        if self.guild_pages.boosts.data.as_ref().is_some_and(|d| d.guild == gid && d.stamp == stamp) {
            return;
        }
        let (levels, perks) = match self.api_result(&catalog_tag(gid)) {
            Some(Ok(v)) => parse_catalog(v).unwrap_or_else(builtin_catalog),
            _ => builtin_catalog(),
        };
        let mut data = BoostsData { guild: gid, stamp, levels, perks: arrange_perks(perks), ..Default::default() };
        if let Some(Ok(v)) = self.api_result(&unlocked_tag(gid)) {
            data.unlocked_known = v.is_array();
            for e in v.as_array().into_iter().flatten() {
                let Some(sku) = e["sku_id"].as_str() else { continue };
                let ends = e["ends_at"].as_str().and_then(|s| DateTime::parse_from_rfc3339(s).ok()).map(|d| d.timestamp_millis());
                data.unlocked.insert(sku.to_string(), ends);
            }
        }
        if let Some(Ok(v)) = self.api_result(&subs_tag(gid)) {
            let (activity, lasting, mine) = parse_activity(v, &self.store, self.store.me_id(), chrono::Utc::now().timestamp_millis());
            data.activity = activity;
            data.lasting = lasting;
            data.boosting = mine;
        }
        // Nicknames and role colours of the people in Recent Activity.
        let mut unknown: Vec<Id> = Vec::new();
        for a in &data.activity {
            let key = (gid, a.user.id);
            if !self.store.members.contains_key(&key) && !self.store.members_requested.contains(&key) && !unknown.contains(&a.user.id) {
                unknown.push(a.user.id);
            }
        }
        for chunk in unknown.chunks(100) {
            for u in chunk {
                self.store.members_requested.insert((gid, *u));
            }
            self.backend.send(crate::backend::Command::RequestMembers { guild: gid, users: chunk.to_vec() });
        }
        self.guild_pages.boosts.data = Some(data);
    }

    /// The Server Boosts page, in place of the chat.
    pub(super) fn boosts_page_ui(&mut self, ui: &mut Ui, gid: Id) {
        let t = self.theme.clone();
        self.boosts_poll(gid);
        self.boosts_refresh(gid);
        let Some(gs) = self.store.guilds.get(&gid) else { return };
        let g = &gs.guild;
        let Some(data) = self.guild_pages.boosts.data.take() else { return };
        let (tier, total) = boost_level(g);
        let tier_override = has_feature(g, "PREMIUM_TIER_3_OVERRIDE");
        let admin = self.store.has_perm(gid, permissions::MANAGE_GUILD);
        let has_tags = has_feature(g, "GUILD_TAGS");
        let badge_of = |status: Status, ends: Option<i64>| match (ends, status) {
            (Some(e), _) => Badge::Expires(format!("Expires {}", day_month(e))),
            (None, Status::Level) => Badge::On("Included in Level 3".into()),
            (None, Status::Inactive) => Badge::None,
            (None, _) => Badge::On("Enabled".into()),
        };
        // The button that slides in on hover (Discord's rules for people who
        // manage the server, and for everyone else).
        let button_of = |p: &Powerup, status: Status| -> (CardButton, Option<String>) {
            if !admin {
                return (CardButton::Text(if p.level { "View Perks" } else { "View Perk" }), None);
            }
            let on = status != Status::Inactive;
            let configurable = !p.level && p.sku != SKU_UPLOADS_250;
            if on && configurable {
                (CardButton::Text("Configure"), None)
            } else if on {
                (CardButton::Text("View Perks"), None)
            } else if status == Status::Override {
                (CardButton::None, None)
            } else {
                let missing = p.dependency.as_deref().filter(|d| !data.unlocked.contains_key(*d)).and_then(|d| data.powerup(d));
                let tip = missing.map(|m| format!("You need to activate {} first.", m.title));
                (CardButton::Enable(p.cost, missing.is_none()), tip)
            }
        };

        let statuses: Vec<(Status, Option<i64>)> = data.levels.iter().map(|p| data.status(p, tier, tier_override)).collect();
        let levels: Vec<LevelCard> = data
            .levels
            .iter()
            .enumerate()
            .map(|(i, p)| {
                let (status, ends) = statuses[i];
                let (button, tip) = button_of(p, status);
                LevelCard {
                    title: p.title.clone(),
                    cost: p.cost,
                    active: status != Status::Inactive,
                    next_active: statuses.get(i + 1).map(|s| s.0 != Status::Inactive),
                    free: status == Status::Override,
                    badge: badge_of(status, ends),
                    button,
                    tip,
                }
            })
            .collect();
        let perks: Vec<PerkCard> = data
            .perks
            .iter()
            .map(|l| match l {
                Listing::Perk(p) => {
                    let (status, ends) = data.status(p, tier, tier_override);
                    let (button, tip) = button_of(p, status);
                    PerkCard {
                        key: p.sku.clone(),
                        title: p.title.clone(),
                        description: p.description.clone(),
                        image: p.image.clone(),
                        inset: p.sku == SKU_ROLE_STYLES,
                        cost: (status != Status::Level).then(|| cost_text(p.cost, false)),
                        active: status != Status::Inactive,
                        warning: ends.is_some(),
                        badge: badge_of(status, ends),
                        button,
                        tip,
                        beta: p.sku == SKU_UPLOADS_250 || p.sku == SKU_GUILD_THEME,
                        packs: false,
                    }
                }
                Listing::BadgePacks(packs) => {
                    let st: Vec<(Status, Option<i64>)> = packs.iter().map(|p| data.status(p, tier, tier_override)).collect();
                    let active = st.iter().any(|s| s.0 != Status::Inactive);
                    let ends = st.iter().filter_map(|s| s.1).min();
                    let bought: u32 = packs.iter().zip(&st).filter(|(_, s)| s.0 == Status::Active).map(|(p, _)| p.cost).sum();
                    let cheapest = packs.iter().map(|p| p.cost).min().unwrap_or(0);
                    let all: u32 = packs.iter().map(|p| p.cost).sum();
                    let cost = if active { bought } else { cheapest };
                    PerkCard {
                        key: "guildTagsBadgePacks".into(),
                        title: "Server Tag Badge Packs".into(),
                        description: "Stand out with special, themed badge packs for your Server Tag.".into(),
                        image: Some(BADGE_PACKS_IMAGE.into()),
                        inset: false,
                        cost: Some(cost_text(cost, !active && all > cost)),
                        active: ends.is_none() && active,
                        warning: ends.is_some(),
                        badge: match ends {
                            Some(e) => Badge::Expires(format!("Expires {}", day_month(e))),
                            None if active => Badge::On("Enabled".into()),
                            None => Badge::None,
                        },
                        button: CardButton::Text("View Packs"),
                        tip: (!has_tags).then(|| "You must activate the Server Tag perk first".to_string()),
                        beta: false,
                        packs: true,
                    }
                }
            })
            .collect();

        // The side panel's numbers and notices.
        let spent = data.spent(g, tier);
        let available = total.saturating_sub(spent);
        let expiring: Vec<String> = {
            let mut list: Vec<(i64, String)> = data.unlocked.iter().filter_map(|(sku, ends)| Some(((*ends)?, data.powerup(sku)?.title.clone()))).collect();
            list.sort();
            list.into_iter().map(|(_, title)| title).collect()
        };
        let needed = spent.saturating_sub(data.lasting);
        let losing = (!expiring.is_empty() && needed > 0).then(|| {
            let mut text = format!("This server needs {needed} more Boost{} to keep these perks: {}", if needed == 1 { "" } else { "s" }, expiring.join(", "));
            if data.unlocked.get(SKU_INVITE_LINK).is_some_and(|e| e.is_some()) {
                text.push_str("\nYour Custom Invite Link will stop working immediately, but the URL will be reserved for you for 30 more days before it's released.");
            }
            text
        });
        // The example message: you, in the booster role's colour.
        let booster_role = g.roles.iter().filter(|r| r.is_booster_role()).max_by_key(|r| r.position);
        let example = match (&self.store.me, booster_role) {
            (Some(me), Some(role)) if !data.boosting => {
                let nick = self.store.members.get(&(gid, me.id)).and_then(|m| m.nick.clone());
                let color = if role.color != 0 { rgb(super::custom_color(role.color)) } else { t.header_primary };
                Some((me.clone(), nick.unwrap_or_else(|| me.display_name().to_string()), color))
            }
            _ => None,
        };
        let boosting = data.boosting;
        let store = &self.store;
        let name_of = |u: &User| -> (String, Color32) {
            let m = store.members.get(&(gid, u.id));
            let name = m.and_then(|m| m.nick.clone()).unwrap_or_else(|| u.username.clone());
            let color = m.and_then(|m| store.role_color(Some(gid), &m.roles)).map(rgb).unwrap_or(t.text_normal);
            (name, color)
        };

        let mut acts: Vec<Act> = Vec::new();
        let mut scroll = self.guild_pages.boosts.levels_scroll;

        // Header: the gem and "Server Boosts".
        TopBottomPanel::top(egui::Id::new("gp_boosts_header")).exact_height(super::HEADER).frame(Frame::none()).show_inside(ui, |ui| {
            let r = ui.max_rect();
            surface(ui, &t, r, 0.0, t.bg_primary, depth(&t, Depth::Lower));
            ui.painter().hline(r.x_range(), r.bottom() - 0.5, Stroke::new(1.0_f32, t.border_subtle));
            ui.painter().text(pos2(r.left() + 25.0, r.center().y), Align2::CENTER_CENTER, icon::BOOST, icon_font(20.0), t.text_muted);
            ui.painter().text(pos2(r.left() + 44.0, r.center().y), Align2::LEFT_CENTER, "Server Boosts", medium(16.0), t.header_primary);
        });

        // Right: the Server Boosts counts or the booster card, then Recent Activity.
        SidePanel::right(egui::Id::new(("gp_boosts_side", gid.0))).exact_width(SIDEBAR_W).resizable(false).show_separator_line(false).frame(Frame::none()).show_inside(ui, |ui| {
            let side = ui.max_rect();
            surface(ui, &t, side, 0.0, t.bg_primary, depth(&t, Depth::Lower));
            ui.painter().vline(side.left() + 0.5, side.y_range(), Stroke::new(1.0_f32, t.border_subtle));
            let x0 = side.left() + 1.0;
            let inner_w = SIDEBAR_W - 1.0 - 32.0;
            let mut y = side.top();
            if admin {
                // "Server Boosts" — Learn More; Available / Spent / Total; the button.
                line(ui.painter(), pos2(x0 + 16.0, y + 16.0), 20.0, "Server Boosts", strong(16.0), t.header_primary);
                let lw = width(ui, "Learn More", medium(14.0));
                let link = Rect::from_min_size(pos2(x0 + 16.0 + inner_w - lw, y + 17.0), vec2(lw, 18.0));
                let lr = ui.interact(link, egui::Id::new("gp_boosts_learn"), Sense::click());
                line(ui.painter(), link.min, 18.0, "Learn More", medium(14.0), t.text_link);
                if lr.hovered() {
                    ui.painter().hline(link.x_range(), link.bottom() - 1.5, Stroke::new(1.0_f32, t.text_link));
                }
                if lr.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                    acts.push(Act::Faq);
                }
                let tile_w = (inner_w - 16.0) / 3.0;
                for (i, (n, label)) in [(available, "Available"), (spent, "Spent"), (total, "Total")].into_iter().enumerate() {
                    let r = Rect::from_min_size(pos2(x0 + 16.0 + i as f32 * (tile_w + 8.0), y + 44.0), vec2(tile_w, 76.0));
                    let p = ui.painter();
                    p.rect_filled(r, 8.0, modc(0.08));
                    p.rect_stroke(r.shrink(0.5), 8.0, Stroke::new(1.0_f32, modc(0.04)));
                    let (gem, num) = if i == 0 { (PINK, t.header_primary) } else { (t.text_muted, t.text_muted) };
                    let n = n.to_string();
                    let nw = width(ui, &n, strong(20.0));
                    let x = r.center().x - (18.0 + 4.0 + nw) / 2.0;
                    paint_icon(ui, "gem", pos2(x, r.top() + 20.0), 18.0, gem);
                    line(p, pos2(x + 22.0, r.top() + 17.0), 24.0, &n, strong(20.0), num);
                    p.text(pos2(r.center().x, r.top() + 50.0), Align2::CENTER_CENTER, label, FontId::proportional(14.0), t.text_muted);
                }
                let b = Rect::from_min_size(pos2(x0 + 16.0, y + 128.0), vec2(inner_w, 44.0));
                let br = button_bg(ui, &t, b, egui::Id::new("gp_boosts_boost"), Look::Quiet, 1.0, true);
                let tw = width(ui, "Boost This Server", medium(14.0));
                let x = b.center().x - (24.0 + tw) / 2.0;
                paint_icon(ui, "gem", pos2(x, b.center().y - 9.0), 18.0, PINK);
                ui.painter().text(pos2(x + 24.0, b.center().y), Align2::LEFT_CENTER, "Boost This Server", medium(14.0), t.text_normal);
                if br.clicked() {
                    acts.push(Act::Boost);
                }
                y += 188.0;
                // Notices: a free Level 3, perks about to lapse.
                if tier_override || losing.is_some() {
                    line(ui.painter(), pos2(x0 + 16.0, y), 20.0, "Notices", strong(16.0), t.header_primary);
                    y += 28.0;
                    if tier_override {
                        let g = wrapped(ui, "Your server has the perks of every level, plus some additional ones. Any other perks still need to be purchased with boosts", FontId::proportional(14.0), t.text_normal, inner_w - 26.0, 18.0, false);
                        let r = Rect::from_min_size(pos2(x0 + 16.0, y), vec2(inner_w, g.size().y + 26.0));
                        ui.painter().rect_filled(r, 8.0, modc(0.12));
                        ui.painter().rect_stroke(r.shrink(0.5), 8.0, Stroke::new(1.0_f32, t.border_subtle));
                        ui.painter().galley(r.min + vec2(13.0, 13.0), g, t.text_normal);
                        y = r.bottom() + 8.0;
                    }
                    if let Some(text) = &losing {
                        let warn = t.tint_text(WARNING_TEXT);
                        let g = wrapped(ui, text, FontId::proportional(14.0), t.text_normal, inner_w - 50.0, 18.0, true);
                        let r = Rect::from_min_size(pos2(x0 + 16.0, y), vec2(inner_w, 25.0 + 24.0 + 8.0 + 20.0 + 4.0 + g.size().y + 25.0));
                        ui.painter().rect_filled(r, 8.0, rgba(WARNING.r(), WARNING.g(), WARNING.b(), 26));
                        paint_icon(ui, "error", pos2(r.center().x - 12.0, r.top() + 25.0), 24.0, warn);
                        ui.painter().text(pos2(r.center().x, r.top() + 67.0), Align2::CENTER_CENTER, "You\u{2019}re about to lose perks!", strong(16.0), warn);
                        ui.painter().galley(pos2(r.center().x, r.top() + 81.0), g, t.text_normal);
                        y = r.bottom() + 8.0;
                    }
                    y += 8.0;
                }
            } else {
                // The video, and "Become a Server Booster".
                let v = Rect::from_min_size(pos2(x0 + 16.0, y + 16.0), vec2(inner_w, (inner_w - 2.0) * 9.0 / 16.0 + 2.0));
                let vr = ui.interact(v, egui::Id::new("gp_boosts_video"), Sense::click());
                egui::Image::new(video_thumbnail()).texture_options(super::SMOOTH).rounding(10.0).show_loading_spinner(false).paint_at(ui, v.shrink(1.0));
                vignette(ui.painter(), v.shrink(1.0), 9.0, [26, 26, 30], 0.2, 0.85);
                ui.painter().rect_stroke(v.shrink(0.5), 10.0, Stroke::new(1.0_f32, t.border_subtle));
                line(ui.painter(), v.min + vec2(13.0, 13.0), 18.0, "How do Boosts work?", strong(14.0), Color32::WHITE);
                ui.painter().circle_filled(v.center(), 24.0, rgba(0, 0, 0, 153));
                paint_icon(ui, "play", v.center() - vec2(11.0, 12.0), 24.0, rgba(255, 255, 255, 153));
                if vr.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                    acts.push(Act::Video);
                }
                y = v.bottom() + 16.0;

                let (title, body) = if boosting {
                    ("Unlock More Perks", "Continue Boosting this server to unlock new perks for everyone! ")
                } else {
                    ("Become a Server Booster", "Boosting will unlock new perks for you and everyone in this server! ")
                };
                let mut job = LayoutJob::default();
                let font = FontId::proportional(14.0);
                job.append(body, 0.0, TextFormat { font_id: font.clone(), color: t.text_normal, line_height: Some(18.0), ..Default::default() });
                job.append("Learn More", 0.0, TextFormat { font_id: font, color: t.text_link, line_height: Some(18.0), ..Default::default() });
                // (2 px of slack: at some zoom levels the first line is a hair wider
                // than Discord's and would wrap a word early.)
                job.wrap.max_width = inner_w - 32.0;
                job.halign = egui::Align::Center;
                let text = ui.fonts(|f| f.layout_job(job));
                let msg_h = if example.is_some() { 66.0 + 16.0 } else { 0.0 };
                let card = Rect::from_min_size(pos2(x0 + 16.0, y), vec2(inner_w, 17.0 + 20.0 + 4.0 + text.size().y + 16.0 + msg_h + 40.0 + 17.0));
                ui.painter().add(Shadow { offset: vec2(0.0, 1.0), blur: 4.0, spread: 0.0, color: Color32::from_black_alpha(36) }.as_shape(card, Rounding::same(CARD_R)));
                surface(ui, &t, card, CARD_R, t.bg_primary, depth(&t, Depth::Lower));
                ui.painter().rect_stroke(card.shrink(0.5), CARD_R, Stroke::new(1.0_f32, t.border_subtle));
                let cx = card.center().x;
                ui.painter().text(pos2(cx, card.top() + 27.0), Align2::CENTER_CENTER, title, strong(16.0), t.header_primary);
                // "Learn More": the link part of the wrapped text.
                let origin = pos2(cx, card.top() + 41.0);
                let mut link = Rect::NOTHING;
                for row in &text.rows {
                    for gl in row.glyphs.iter().filter(|gl| gl.section_index == 1) {
                        link = link.union(Rect::from_min_size(pos2(origin.x + gl.pos.x, origin.y + row.rect.top()), vec2(gl.advance_width, row.rect.height())));
                    }
                }
                ui.painter().galley(origin, text.clone(), t.text_normal);
                if link.is_positive() {
                    let lr = ui.interact(link, egui::Id::new("gp_boosts_learn"), Sense::click());
                    if lr.hovered() {
                        ui.painter().hline(link.x_range(), link.bottom() - 1.0, Stroke::new(1.0_f32, t.text_link));
                    }
                    if lr.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                        acts.push(Act::Faq);
                    }
                }
                let mut cy = card.top() + 41.0 + text.size().y + 16.0;
                if let Some((me, name, color)) = &example {
                    let message = "wow, this looks so cool";
                    let name_w = width(ui, name, strong(16.0));
                    let content = (name_w + 4.0 + 14.0).max(width(ui, message, medium(16.0)));
                    let m = Rect::from_min_size(pos2(cx - (content + 78.0) / 2.0, cy), vec2(content + 78.0, 66.0));
                    ui.painter().rect_stroke(m.shrink(0.5), 8.0, Stroke::new(1.0_f32, t.border_subtle));
                    let av = Rect::from_min_size(m.min + vec2(13.0, 13.0), vec2(40.0, 40.0));
                    super::paint_avatar(ui, av, Some(me.avatar_or_default(80)), name);
                    let tx = av.right() + 12.0;
                    line(ui.painter(), pos2(tx, m.top() + 13.0), 20.0, name, strong(16.0), *color);
                    paint_icon(ui, "gem", pos2(tx + name_w + 4.0, m.top() + 16.0), 14.0, PINK);
                    line(ui.painter(), pos2(tx, m.top() + 33.0), 20.0, message, medium(16.0), t.text_normal);
                    cy = m.bottom() + 16.0;
                }
                let b = Rect::from_min_size(pos2(card.left() + 17.0, cy), vec2(card.width() - 34.0, 40.0));
                let br = button_bg(ui, &t, b, egui::Id::new("gp_boosts_boost"), Look::Primary, 1.0, true);
                let tw = width(ui, "Boost This Server", medium(16.0));
                let x = b.center().x - (24.0 + tw) / 2.0;
                paint_icon(ui, "gem", pos2(x, b.center().y - 9.0), 18.0, Color32::WHITE);
                ui.painter().text(pos2(x + 24.0, b.center().y), Align2::LEFT_CENTER, "Boost This Server", medium(16.0), Color32::WHITE);
                if br.clicked() {
                    acts.push(Act::Boost);
                }
                y = card.bottom() + 16.0;
                ui.painter().hline((x0)..=side.right(), y + 0.5, Stroke::new(1.0_f32, t.border_subtle));
                y += 1.0;
            }

            // Recent Activity: every boost given, running out or expired.
            if data.activity.is_empty() {
                return;
            }
            line(ui.painter(), pos2(x0 + 16.0, y + 8.0), 20.0, "Recent Activity", strong(16.0), t.header_primary);
            y += 36.0;
            let list = Rect::from_min_max(pos2(x0, y), side.max);
            if list.height() <= 0.0 {
                return;
            }
            let mut lui = ui.new_child(egui::UiBuilder::new().max_rect(list));
            lui.set_clip_rect(list.intersect(ui.clip_rect()));
            ScrollArea::vertical().id_salt(("gp_boost_activity", gid.0)).auto_shrink([false, false]).show(&mut lui, |ui| {
                let n = data.activity.len();
                let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), n as f32 * 28.0 - 8.0 + 16.0), Sense::hover());
                let clip = ui.clip_rect();
                let first = (((clip.top() - rect.top()) / 28.0).floor().max(0.0) as usize).min(n);
                let last = (((clip.bottom() - rect.top()) / 28.0).ceil().max(0.0) as usize).min(n);
                let today = Local::now().date_naive();
                let right = x0 + SIDEBAR_W - 1.0 - 16.0 - 8.0;
                for (i, a) in data.activity.iter().enumerate().take(last).skip(first) {
                    let row = Rect::from_min_max(pos2(x0 + 16.0, rect.top() + i as f32 * 28.0), pos2(right, rect.top() + i as f32 * 28.0 + 20.0));
                    let p = ui.painter();
                    let (ic, color) = match a.phase {
                        Phase::Gave => ("gem", t.text_muted),
                        Phase::Expiring(_) => ("gem-slash", t.tint_text(WARNING_TEXT)),
                        Phase::Expired => ("gem-slash", t.tint_text(CRITICAL)),
                    };
                    paint_icon(ui, ic, row.min + vec2(0.0, 1.0), 18.0, color);
                    let what = match a.phase {
                        Phase::Gave => "gave 1 boost.".to_string(),
                        Phase::Expiring(e) => format!("boost expiring {}.", day_month(e)),
                        Phase::Expired => "1 boost expired.".to_string(),
                    };
                    let when = activity_date(a.at, today);
                    let when_w = width(ui, &when, medium(12.0));
                    let ts = Rect::from_min_max(pos2(row.right() - when_w, row.top()), row.max);
                    p.text(ts.left_center(), Align2::LEFT_CENTER, &when, medium(12.0), fade(t.interactive_normal, 0.5));
                    let what_w = width(ui, &what, FontId::proportional(16.0));
                    // The name gives way (ellipsis) so the rest always fits.
                    let (name, name_color) = name_of(&a.user);
                    let room = (ts.left() - 8.0 - what_w - 4.0 - (row.left() + 22.0)).max(24.0);
                    let mut job = LayoutJob::single_section(name, TextFormat { font_id: strong(16.0), color: name_color, ..Default::default() });
                    job.wrap = egui::text::TextWrapping { max_width: room, max_rows: 1, break_anywhere: true, overflow_character: Some('\u{2026}') };
                    let ng = ui.fonts(|f| f.layout_job(job));
                    let name_rect = Rect::from_min_size(pos2(row.left() + 22.0, row.center().y - ng.size().y / 2.0), ng.size());
                    p.galley(name_rect.min, ng, name_color);
                    p.text(pos2(name_rect.right() + 4.0, row.center().y), Align2::LEFT_CENTER, what, FontId::proportional(16.0), t.text_normal);
                    if ui.interact(name_rect, egui::Id::new(("gp_boost_who", i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                        acts.push(Act::Profile(a.user.clone(), row.left_top() - vec2(330.0, 0.0)));
                    }
                    let full = DateTime::from_timestamp_millis(a.at).map(|d| d.with_timezone(&Local).format(if super::hour24() { "%A, %-d %B %Y at %H:%M" } else { "%A, %-d %B %Y at %I:%M %P" }).to_string());
                    if let Some(full) = full {
                        ui.interact(ts, egui::Id::new(("gp_boost_when", i)), Sense::hover()).on_hover_text(full);
                    }
                }
            });
        });

        // Left: Levels and Additional Perks.
        CentralPanel::default().frame(Frame::none()).show_inside(ui, |ui| {
            let area = ui.max_rect();
            surface(ui, &t, area, 0.0, t.bg_primary, depth(&t, Depth::Lowest));
            ScrollArea::vertical().id_salt(("gp_boosts_scroll", gid.0)).auto_shrink([false, false]).show(ui, |ui| {
                ui.spacing_mut().item_spacing.y = 0.0;
                // Discord keeps an 8 px scrollbar gutter; sections are 1200 px at most.
                let full = (ui.available_width() - 8.0).max(0.0);
                let w = full.min(1200.0);
                let left = ui.max_rect().left() + (full - w) / 2.0;
                let inner = (w - 48.0).max(0.0);
                let heading = |ui: &mut Ui, title: &str, text: &str| {
                    let g = wrapped(ui, text, FontId::proportional(14.0), t.text_normal, inner, 18.0, false);
                    let (r, _) = ui.allocate_exact_size(vec2(full, 24.0 + g.size().y), Sense::hover());
                    line(ui.painter(), pos2(left + 24.0, r.top()), 24.0, title, strong(20.0), t.header_primary);
                    ui.painter().galley(pos2(left + 24.0, r.top() + 24.0), g, t.text_normal);
                };
                ui.add_space(24.0);

                // Levels: one row of three cards, scrolled sideways when narrow.
                heading(ui, "Levels", "Your server will automatically \u{201C}level up\u{201D} once it has enough available Boosts.");
                ui.add_space(16.0);
                let cw = ((inner - 32.0) / 3.0).max(224.0);
                let n = levels.len().max(1) as f32;
                let content = cw * n + 16.0 * (n - 1.0);
                let max_scroll = (content - inner).max(0.0);
                let overflow = max_scroll > 0.5;
                scroll = scroll.clamp(0.0, max_scroll);
                let (row, _) = ui.allocate_exact_size(vec2(full, LEVEL_H + 8.0 + if overflow { 8.0 } else { 0.0 }), Sense::hover());
                let strip = Rect::from_min_max(pos2(left, row.top() - 32.0), pos2(left + w, row.bottom() + 40.0));
                let over_row = ui.rect_contains_pointer(Rect::from_min_max(pos2(left, row.top()), pos2(left + w, row.bottom())));
                if overflow && over_row {
                    let dx = ui.input(|i| i.smooth_scroll_delta.x);
                    if dx != 0.0 {
                        scroll = (scroll - dx).clamp(0.0, max_scroll);
                    }
                }
                {
                    let mut cui = ui.new_child(egui::UiBuilder::new().max_rect(strip));
                    cui.set_clip_rect(strip.intersect(ui.clip_rect()));
                    let ui = &cui;
                    for (i, c) in levels.iter().enumerate() {
                        let base = Rect::from_min_size(pos2(left + 24.0 - scroll + i as f32 * (cw + 16.0), row.top()), vec2(cw, LEVEL_H));
                        if !base.intersects(strip) {
                            continue;
                        }
                        let id = egui::Id::new(("gp_boost_level", gid.0, i));
                        let warning = matches!(c.badge, Badge::Expires(_));
                        let (r, h, resp) = card_frame(ui, &t, base, id, c.active, warning);
                        let p = ui.painter();
                        // The progress line through the gem.
                        let (x0, x1) = (if i == 0 { r.left() + 17.0 } else { r.left() + 1.0 }, if c.next_active.is_none() { r.right() - 17.0 } else { r.right() - 1.0 });
                        let bar = Rect::from_min_max(pos2(x0, r.top() + 33.0), pos2(x1, r.top() + 39.0));
                        let ends_here = c.next_active.is_none();
                        let rounding = if ends_here { Rounding { ne: 3.0, se: 3.0, ..Rounding::ZERO } } else { Rounding::ZERO };
                        match (c.active, c.next_active) {
                            (true, Some(false)) => hgradient(p, bar, PINK, modc(0.12)),
                            (true, _) => {
                                p.rect_filled(bar, rounding, PINK);
                            }
                            (false, _) => {
                                p.rect_filled(bar, rounding, modc(0.12));
                            }
                        }
                        // The gem: a ring of the card's surface, then its disc.
                        let gem = Rect::from_center_size(pos2(r.left() + 33.0, r.top() + 37.0), vec2(40.0, 40.0));
                        if c.active || warning {
                            p.circle_filled(gem.center(), 20.0, t.surface_high);
                            // Pink on a plain theme. Under a client theme Discord's own
                            // gradient surface covers the pink (its CSS keeps the
                            // background image), so the disc is that surface.
                            if t.gradient.is_some() {
                                surface(ui, &t, gem.shrink(4.0), 16.0, PINK, depth(&t, Depth::Lower));
                            } else {
                                p.circle_filled(gem.center(), 16.0, PINK);
                            }
                        } else {
                            let solid = t.bg_primary.lerp_to_gamma(t.bg_secondary_alt, h);
                            let strength = depth(&t, Depth::Lower) + (depth(&t, Depth::Low) - depth(&t, Depth::Lower)) * h;
                            surface(ui, &t, gem, 20.0, solid, strength);
                        }
                        p.circle_filled(gem.center(), 16.0, modc(0.2));
                        egui::Image::new(level_gem(i)).show_loading_spinner(false).paint_at(ui, Rect::from_center_size(gem.center(), vec2(24.0, 24.0)));
                        // Title and perks.
                        let (fg, ic) = if c.active { (t.text_normal, t.text_normal) } else { (t.text_muted, t.text_muted) };
                        let tp = ui.painter_at(r.shrink2(vec2(17.0, 1.0)));
                        line(&tp, pos2(r.left() + 17.0, r.top() + 71.0), 20.0, &c.title, strong(16.0), fg);
                        let mut y = r.top() + 107.0;
                        for (name, text) in CARD_PERKS[i.min(2)] {
                            paint_icon(ui, name, pos2(r.left() + 17.0, y), 18.0, ic);
                            line(&tp, pos2(r.left() + 43.0, y), 18.0, text, FontId::proportional(14.0), fg);
                            y += 26.0;
                        }
                        line(&tp, pos2(r.left() + 17.0, y), 18.0, "...and more!", FontId::proportional(14.0), fg);
                        if !c.free && card_footer(ui, &t, r, id, h, Some(cost_text(c.cost, false)), &c.badge, &c.button, c.tip.as_deref()) {
                            match &c.button {
                                CardButton::Enable(..) => acts.push(Act::Enable(data.levels[i].sku.clone())),
                                _ => acts.push(Act::LevelPerks(i.min(2))),
                            }
                        } else if resp.clicked() {
                            acts.push(Act::LevelPerks(i.min(2)));
                        }
                    }
                    // Cards running off an edge fade into the page.
                    if overflow {
                        let page_bg = |rect: Rect, from_left: bool| {
                            let (a, b) = if from_left { (1.0, 0.0) } else { (0.0, 1.0) };
                            match &t.gradient {
                                Some(grad) => {
                                    // The page's own colour here: the gradient under Discord's overlay.
                                    let screen = ui.ctx().screen_rect();
                                    let k = depth(&t, Depth::Lowest);
                                    let at = |q: Pos2, alpha: f32| fade(grad.color_at(q, screen).lerp_to_gamma(t.overlays.color, k), alpha);
                                    let mut mesh = egui::Mesh::default();
                                    mesh.colored_vertex(rect.left_top(), at(rect.left_top(), a));
                                    mesh.colored_vertex(rect.right_top(), at(rect.right_top(), b));
                                    mesh.colored_vertex(rect.left_bottom(), at(rect.left_bottom(), a));
                                    mesh.colored_vertex(rect.right_bottom(), at(rect.right_bottom(), b));
                                    mesh.add_triangle(0, 1, 2);
                                    mesh.add_triangle(1, 2, 3);
                                    ui.painter().add(egui::Shape::mesh(mesh));
                                }
                                None => hgradient(ui.painter(), rect, fade(t.bg_primary, a), fade(t.bg_primary, b)),
                            }
                        };
                        if scroll > 1.0 {
                            page_bg(Rect::from_min_max(strip.min, pos2(left + 80.0, strip.bottom())), true);
                        }
                        if scroll < max_scroll - 1.0 {
                            page_bg(Rect::from_min_max(pos2(left + w - 48.0, strip.top()), strip.max), false);
                        }
                    }
                }
                if overflow {
                    // Discord's thin scrollbar under the cards (shown on hover).
                    let track = Rect::from_min_max(pos2(left + 24.0, row.bottom() - 8.0), pos2(left + w - 24.0, row.bottom()));
                    let tw = (track.width() * inner / content).max(24.0);
                    let thumb = Rect::from_min_size(pos2(track.left() + (track.width() - tw) * scroll / max_scroll, track.top() + 2.0), vec2(tw, 4.0));
                    let tr = ui.interact(track, egui::Id::new(("gp_boost_levels_bar", gid.0)), Sense::click_and_drag());
                    if tr.dragged() {
                        scroll = (scroll + tr.drag_delta().x * max_scroll / (track.width() - tw).max(1.0)).clamp(0.0, max_scroll);
                    }
                    if over_row || tr.dragged() {
                        ui.painter().rect_filled(thumb, 2.0, t.scrollbar_thumb());
                    }
                }
                ui.add_space(40.0);

                // Additional Perks: a grid of perk cards.
                heading(ui, "Additional Perks", "Individual perks that can be unlocked using available Boosts. No level required.");
                ui.add_space(16.0);
                let cols = if w >= 1152.0 {
                    4
                } else if w >= 752.0 {
                    3
                } else if w >= 520.0 {
                    2
                } else {
                    1
                };
                let pw = ((inner - 16.0 * (cols as f32 - 1.0)) / cols as f32).max(0.0);
                for (ri, chunk) in perks.chunks(cols).enumerate() {
                    let texts: Vec<Arc<Galley>> = chunk.iter().map(|c| wrapped(ui, &c.description, FontId::proportional(14.0), if c.active { t.text_normal } else { t.text_muted }, pw - 34.0, 18.0, false)).collect();
                    let tallest = texts.iter().map(|g| g.size().y).fold(0.0, f32::max);
                    let ch = 2.0 + 180.0 + 16.0 + 20.0 + 6.0 + tallest + 32.0 + 18.0 + 16.0;
                    if ri > 0 {
                        ui.add_space(16.0);
                    }
                    let (row, _) = ui.allocate_exact_size(vec2(full, ch), Sense::hover());
                    for (j, (c, text)) in chunk.iter().zip(texts).enumerate() {
                        let base = Rect::from_min_size(pos2(left + 24.0 + j as f32 * (pw + 16.0), row.top()), vec2(pw, ch));
                        let id = egui::Id::new(("gp_boost_perk", gid.0, &c.key));
                        let (r, h, resp) = card_frame(ui, &t, base, id, c.active, c.warning);
                        let p = ui.painter();
                        // The picture: Discord's 2:1 art, contained in a 180 px band.
                        let band = Rect::from_min_size(r.min + vec2(1.0, 1.0), vec2(pw - 2.0, 180.0));
                        shade(&p.with_clip_rect(band.intersect(ui.clip_rect())), band, if t.light { 0.1 } else { 0.4 });
                        if let Some(url) = &c.image {
                            let iw = (band.width() - if c.inset { 32.0 } else { 0.0 }).min(360.0);
                            let img = Rect::from_center_size(band.center(), vec2(iw, iw / 2.0));
                            let rounding = if img.top() <= band.top() + 0.5 { Rounding { nw: CARD_R - 1.0, ne: CARD_R - 1.0, ..Rounding::ZERO } } else { Rounding::ZERO };
                            egui::Image::new(url.as_str()).texture_options(super::SMOOTH).rounding(rounding).show_loading_spinner(false).paint_at(ui, img);
                        }
                        if c.beta {
                            let g = p.layout_no_wrap("BETA".into(), strong(12.0), Color32::WHITE);
                            let chip = Rect::from_min_size(pos2(r.right() - 13.0 - g.size().x - 12.0, r.top() + 13.0), vec2(g.size().x + 12.0, 16.0));
                            p.rect_filled(chip, 8.0, BRAND);
                            p.galley(pos2(chip.left() + 6.0, chip.center().y - g.size().y / 2.0), g, Color32::WHITE);
                        }
                        let fg = if c.active { t.text_normal } else { t.text_muted };
                        let tp = ui.painter_at(r.shrink2(vec2(17.0, 1.0)));
                        line(&tp, pos2(r.left() + 17.0, r.top() + 197.0), 20.0, &c.title, strong(16.0), fg);
                        tp.galley(pos2(r.left() + 17.0, r.top() + 223.0), text, fg);
                        if card_footer(ui, &t, r, id, h, c.cost.clone(), &c.badge, &c.button, c.tip.as_deref()) {
                            match &c.button {
                                CardButton::Text("Configure") => acts.push(Act::Configure(c.key.clone())),
                                CardButton::Enable(..) => acts.push(Act::Enable(c.key.clone())),
                                _ if c.packs => acts.push(Act::Packs),
                                _ => acts.push(Act::Perk(c.key.clone())),
                            }
                        } else if resp.clicked() {
                            acts.push(if c.packs { Act::Packs } else { Act::Perk(c.key.clone()) });
                        }
                    }
                }
                ui.add_space(40.0 + 24.0);
            });
        });

        self.guild_pages.boosts.levels_scroll = scroll;
        self.guild_pages.boosts.data = Some(data);
        for act in acts {
            match act {
                Act::Boost => self.boost_dialog_open(gid),
                Act::Faq => self.ctx.open_url(egui::OpenUrl::new_tab(FAQ_URL)),
                Act::Video => {
                    // Discord's explainer, in the app's own video pop-up.
                    let mut v = crate::quest_video::QuestVideo::start(&self.ctx, Id(0), "How Boosting Works".into(), VIDEO_URL.into(), 30.0, 0.0, (1920, 1080));
                    v.report = false;
                    v.plain = true;
                    self.quest_video = Some(v);
                }
                Act::LevelPerks(n) => self.guild_pages.boosts.modal = Some((gid, Modal::Level(n))),
                Act::Perk(sku) => self.guild_pages.boosts.modal = Some((gid, Modal::Perk(sku))),
                Act::Packs => self.guild_pages.boosts.modal = Some((gid, Modal::Packs)),
                Act::Enable(sku) => self.boost_enable(gid, &sku),
                Act::Configure(sku) => self.boost_configure(gid, &sku),
                Act::Profile(u, at) => self.open_profile(u, Some(gid), at),
            }
        }
        self.boost_modals_ui(&ui.ctx().clone(), gid);
    }

    /// What the pop-ups need to know about the server.
    fn boost_ctx(&self, gid: Id) -> Option<BoostCtx> {
        let g = &self.store.guilds.get(&gid)?.guild;
        let d = self.guild_pages.boosts.data.as_ref()?;
        let (tier, total) = boost_level(g);
        Some(BoostCtx {
            admin: self.store.has_perm(gid, permissions::MANAGE_GUILD),
            tier,
            tier_override: has_feature(g, "PREMIUM_TIER_3_OVERRIDE"),
            available: total.saturating_sub(d.spent(g, tier)),
            has_tags: has_feature(g, "GUILD_TAGS"),
            name: g.name.clone(),
        })
    }

    /// Switch a level or perk on. As in Discord there is no "are you sure":
    /// with enough available Boosts it is switched on at once; without, the
    /// pop-up says how many are missing.
    fn boost_enable(&mut self, gid: Id, sku: &str) {
        let (Some(c), Some(p)) = (self.boost_ctx(gid), self.guild_pages.boosts.data.as_ref().and_then(|d| d.powerup(sku)).cloned()) else { return };
        if !c.admin || self.guild_pages.boosts.toggling.is_some() {
            return;
        }
        if c.available < p.cost {
            self.guild_pages.boosts.modal = Some((gid, Modal::NeedBoosts(p.sku)));
            return;
        }
        self.api("gp:boost-toggle", Method::POST, format!("/guilds/{gid}/skus/{}", p.sku), None);
        self.guild_pages.boosts.toggling = Some((p.sku, true));
    }

    /// Switch a perk off (after "Disable {perk}?").
    fn boost_disable(&mut self, gid: Id, sku: &str) {
        if !self.store.has_perm(gid, permissions::MANAGE_GUILD) || self.guild_pages.boosts.toggling.is_some() {
            return;
        }
        self.api("gp:boost-toggle", Method::DELETE, format!("/guilds/{gid}/skus/{sku}"), None);
        self.guild_pages.boosts.toggling = Some((sku.to_string(), false));
    }

    /// "Configure": Server Settings, on the page that perk lives on (Roles
    /// for role styles; Server Tag for the tag and its badge packs).
    fn boost_configure(&mut self, gid: Id, sku: &str) {
        self.guild_pages.boosts.modal = None;
        if sku == SKU_ROLE_STYLES {
            self.open_server_roles(gid);
        } else if sku == SKU_SERVER_TAG || SKU_BADGE_PACKS.contains(&sku) {
            self.open_server_tag(gid);
        } else {
            self.open_server_settings(gid);
        }
    }

    /// The Server Boosts page with the Server Tag badge packs showing (from
    /// a locked badge in Server Settings → Server Tag).
    pub fn open_boost_badge_packs(&mut self, gid: Id) {
        self.open_guild_page(gid, super::guild_pages::GuildPage::Boosts);
        self.guild_pages.boosts.modal = Some((gid, Modal::Packs));
    }

    /// "Boost This Server": look up your Boosts, then ask.
    fn boost_dialog_open(&mut self, gid: Id) {
        if !self.api_busy("gp:boost-slots") {
            self.api("gp:boost-slots", Method::GET, "/users/@me/guilds/premium/subscription-slots", None);
        }
        self.guild_pages.boosts.modal = Some((gid, Modal::Boost));
    }

    /// Discord's answers to switching a perk on / off and to applying a Boost.
    fn boosts_poll(&mut self, gid: Id) {
        if let Some(result) = self.api_take("gp:boost-toggle") {
            if let Some((sku, on)) = self.guild_pages.boosts.toggling.take() {
                let title = self.guild_pages.boosts.data.as_ref().and_then(|d| d.powerup(&sku)).map(|p| p.title.clone()).unwrap_or_else(|| "The perk".into());
                match result {
                    Ok(_) => {
                        // What is switched on changed: ask Discord again.
                        self.api(&unlocked_tag(gid), Method::GET, format!("/guilds/{gid}/powerups?include_ends_at=true"), None);
                        if on {
                            self.guild_pages.boosts.modal = Some((gid, Modal::Enabled(sku)));
                        } else {
                            self.guild_pages.boosts.modal = None;
                            self.toast(format!("{title} is disabled. Its Boosts are available again."), false);
                        }
                    }
                    Err(e) => self.toast(format!("Discord didn't {} {title}: {e}", if on { "enable" } else { "disable" }), true),
                }
            }
        }
        if let Some(result) = self.api_take("gp:boost-apply") {
            match result {
                Ok(_) => {
                    self.guild_pages.boosts.modal = None;
                    self.api_take("gp:boost-slots");
                    self.api(&subs_tag(gid), Method::GET, format!("/guilds/{gid}/premium/subscriptions?include_ended=true"), None);
                    self.toast("Boosted! Thanks for supporting this server.", false);
                }
                Err(e) => self.toast(format!("Discord didn't apply the Boost: {e}"), true),
            }
        }
    }

    /// The pop-up over the page, if one is open.
    fn boost_modals_ui(&mut self, ctx: &egui::Context, gid: Id) {
        let Some((owner, modal)) = self.guild_pages.boosts.modal.clone() else { return };
        if owner != gid || !self.guild_page_active() {
            self.guild_pages.boosts.modal = None;
            return;
        }
        let Some(c) = self.boost_ctx(gid) else { return };
        let t = self.theme.clone();
        let busy = self.guild_pages.boosts.toggling.is_some();
        let me = self.store.me.clone();
        let my_name = me.as_ref().map(|u| self.store.members.get(&(gid, u.id)).and_then(|m| m.nick.clone()).unwrap_or_else(|| u.display_name().to_string())).unwrap_or_default();
        // Your Boosts that aren't on a server or cooling down.
        let free: Option<Result<Vec<String>, String>> = match self.api_result("gp:boost-slots") {
            None => None,
            Some(Err(e)) => Some(Err(e.clone())),
            Some(Ok(v)) => {
                let now = chrono::Utc::now();
                let ids = v
                    .as_array()
                    .into_iter()
                    .flatten()
                    .filter(|s| s["premium_guild_subscription"].is_null())
                    .filter(|s| s["cooldown_ends_at"].as_str().and_then(|c| DateTime::parse_from_rfc3339(c).ok()).is_none_or(|c| c <= now))
                    .filter_map(|s| s["id"].as_str().map(String::from))
                    .collect();
                Some(Ok(ids))
            }
        };
        let applying = self.api_busy("gp:boost-apply");
        let Some(data) = self.guild_pages.boosts.data.take() else { return };
        let title_of = |sku: &str| data.powerup(sku).map(|p| p.title.clone()).unwrap_or_else(|| "This perk".into());
        let (mut close, mut go) = (false, None);
        match &modal {
            Modal::Level(n) => (close, go) = level_modal(ctx, &t, &data, &c, *n, busy),
            Modal::Perk(sku) => (close, go) = perk_modal(ctx, &t, &data, &c, sku, me.as_ref(), &my_name, busy),
            Modal::Packs => (close, go) = packs_modal(ctx, &t, &data, &c),
            Modal::Disable(sku) => {
                let (title, cost) = (title_of(sku), data.powerup(sku).map_or(0, |p| p.cost));
                let mut body = vec![format!("Are you sure you want to disable {title}?")];
                if sku == SKU_SERVER_TAG {
                    body.push(format!("If you choose to disable this perk, {title} will be removed from all members."));
                } else if SKU_BADGE_PACKS.contains(&sku.as_str()) {
                    body.push("If this perk is disabled, your Server Tag will be reset to a default badge.".into());
                } else if sku == SKU_INVITE_LINK {
                    body.push("You will immediately lose access to your Custom Invite Link, but the URL will be reserved for you for 30 days.".into());
                }
                body.push(format!("Get {} back.", cost_text(cost, false)));
                let (pressed, dismissed) = dialog(ctx, &t, "boost_disable", &format!("Disable {title}?"), &body, &[("Cancel", Look::Quiet, true), ("Disable Perk", Look::Danger, !busy)]);
                match pressed {
                    Some(1) => go = Some(Go::Disable(sku.clone())),
                    Some(_) => go = Some(Go::Open(Modal::Perk(sku.clone()))),
                    None => close = dismissed,
                }
            }
            Modal::Enabled(sku) => {
                let title = title_of(sku);
                let level = data.powerup(sku).is_some_and(|p| p.level);
                let body = if level {
                    vec![format!("Congrats! Your server now has full access to all of the {title} perks.")]
                } else {
                    vec![format!("In your server, go to Server Settings to start customizing {title}")]
                };
                let buttons: &[(&str, Look, bool)] = if level { &[("Close", Look::Primary, true)] } else { &[("Close", Look::Quiet, true), ("Configure", Look::Primary, true)] };
                let heading = if level { format!("You've reached {title}") } else { format!("{title} enabled!") };
                let (pressed, dismissed) = dialog(ctx, &t, "boost_enabled", &heading, &body, buttons);
                match pressed {
                    Some(1) => go = Some(Go::Configure(sku.clone())),
                    Some(_) => close = true,
                    None => close = dismissed,
                }
            }
            Modal::NeedBoosts(sku) => {
                let (title, cost) = (title_of(sku), data.powerup(sku).map_or(0, |p| p.cost));
                let missing = cost.saturating_sub(c.available);
                let body = vec![format!(
                    "{title} costs {} and this server has {} available. It needs {missing} more Boost{} before {title} can be enabled.",
                    cost_text(cost, false),
                    c.available,
                    if missing == 1 { "" } else { "s" }
                )];
                let (pressed, dismissed) = dialog(ctx, &t, "boost_need", "Not enough Boosts", &body, &[("Cancel", Look::Quiet, true), ("Boost This Server", Look::Primary, true)]);
                match pressed {
                    Some(1) => go = Some(Go::BoostDialog),
                    Some(_) => close = true,
                    None => close = dismissed,
                }
            }
            Modal::Boost => match &free {
                None => {
                    let (pressed, dismissed) = dialog(ctx, &t, "boost_apply", "Boost This Server", &["Checking your Boosts\u{2026}".to_string()], &[("Cancel", Look::Quiet, true)]);
                    close = dismissed || pressed.is_some();
                }
                Some(Err(e)) => {
                    let (pressed, dismissed) = dialog(ctx, &t, "boost_apply", "Boost This Server", &[format!("Couldn't look up your Boosts: {e}")], &[("Close", Look::Quiet, true)]);
                    close = dismissed || pressed.is_some();
                }
                Some(Ok(ids)) if ids.is_empty() => {
                    let body = vec![
                        "You have no unused Boosts to give this server.".to_string(),
                        "Buying another Boost is a purchase, and Discord only takes payment on its own checkout.".to_string(),
                    ];
                    let (pressed, dismissed) = dialog(ctx, &t, "boost_apply", "No unused Boosts", &body, &[("Close", Look::Quiet, true), ("Open Discord's checkout", Look::Primary, true)]);
                    match pressed {
                        Some(1) => go = Some(Go::Checkout),
                        Some(_) => close = true,
                        None => close = dismissed,
                    }
                }
                Some(Ok(ids)) => {
                    let n = ids.len();
                    let body = vec![
                        format!("You have {n} unused Boost{}. Boosting {} uses one of them.", if n == 1 { "" } else { "s" }, c.name),
                        "A Boost can't be moved to another server for 7 days after it's applied.".to_string(),
                    ];
                    let (pressed, dismissed) = dialog(ctx, &t, "boost_apply", &format!("Boost {}?", c.name), &body, &[("Cancel", Look::Quiet, true), ("Boost", Look::Primary, !applying)]);
                    match pressed {
                        Some(1) => go = Some(Go::Apply(ids[0].clone())),
                        Some(_) => close = true,
                        None => close = dismissed,
                    }
                }
            },
        }
        self.guild_pages.boosts.data = Some(data);
        if close || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
            self.guild_pages.boosts.modal = None;
        }
        match go {
            Some(Go::Open(m)) => self.guild_pages.boosts.modal = Some((gid, m)),
            Some(Go::Enable(sku)) => self.boost_enable(gid, &sku),
            Some(Go::AskDisable(sku)) => self.guild_pages.boosts.modal = Some((gid, Modal::Disable(sku))),
            Some(Go::Disable(sku)) => self.boost_disable(gid, &sku),
            Some(Go::Configure(sku)) => self.boost_configure(gid, &sku),
            Some(Go::BoostDialog) => self.boost_dialog_open(gid),
            Some(Go::Apply(slot)) => {
                if !self.api_busy("gp:boost-apply") {
                    let body = serde_json::json!({ "user_premium_guild_subscription_slot_ids": [slot] });
                    self.api("gp:boost-apply", Method::PUT, format!("/guilds/{gid}/premium/subscriptions"), Some(body));
                }
            }
            Some(Go::Checkout) => {
                self.guild_pages.boosts.modal = None;
                self.ctx.open_url(egui::OpenUrl::new_tab(format!("https://discord.com/channels/{gid}/boosts")));
            }
            None => {}
        }
    }
}

/// Server facts the pop-ups need.
struct BoostCtx {
    /// You manage the server.
    admin: bool,
    tier: u8,
    tier_override: bool,
    /// Boosts the server hasn't put to use.
    available: u32,
    has_tags: bool,
    name: String,
}

/// What a pop-up asks for.
enum Go {
    Open(Modal),
    Enable(String),
    /// "Disable {perk}?"
    AskDisable(String),
    Disable(String),
    Configure(String),
    BoostDialog,
    /// Apply this Boost slot of yours.
    Apply(String),
    /// Buying Boosts: Discord's checkout.
    Checkout,
}

/// The close "X" of a pop-up, in `rect`.
fn close_x(ui: &Ui, t: &Theme, rect: Rect, id: egui::Id) -> bool {
    let r = ui.interact(rect, id, Sense::click());
    if r.hovered() {
        ui.painter().rect_filled(rect, 8.0, modc(0.12));
    }
    let size = (rect.width() - 12.0).clamp(16.0, 24.0);
    paint_icon(ui, "close", rect.center() - vec2(size / 2.0, size / 2.0), size, if r.hovered() { t.header_primary } else { t.interactive_normal });
    r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
}

/// Discord's purple glow behind a pop-up's artwork: strongest along the top,
/// gone toward the bottom centre (its radial mask).
fn purple_glow(p: &egui::Painter, head: Rect) {
    let mut mesh = egui::Mesh::default();
    let (start, end) = (Color32::from_rgb(164, 88, 240), Color32::from_rgb(77, 22, 137));
    let (cols, rows) = (12, 8);
    for iy in 0..=rows {
        for ix in 0..=cols {
            let (u, v) = (ix as f32 / cols as f32, iy as f32 / rows as f32);
            // CSS: radial-gradient(100% 100% at 50% 100%, transparent 60%, #000) as the mask.
            let d = ((u - 0.5).powi(2) + (1.0 - v).powi(2)).sqrt();
            let mask = ((d - 0.6) / 0.4).clamp(0.0, 1.0);
            mesh.colored_vertex(pos2(head.left() + head.width() * u, head.top() + head.height() * v), fade(start.lerp_to_gamma(end, u), 0.3 * mask));
        }
    }
    for iy in 0..rows {
        for ix in 0..cols {
            let a = (iy * (cols + 1) + ix) as u32;
            let b = a + cols as u32 + 1;
            mesh.add_triangle(a, a + 1, b);
            mesh.add_triangle(a + 1, b, b + 1);
        }
    }
    p.add(egui::Shape::mesh(mesh));
}

/// A button with a centred label.
fn text_button(ui: &Ui, t: &Theme, rect: Rect, id: egui::Id, look: Look, label: &str, enabled: bool) -> egui::Response {
    let resp = button_bg(ui, t, rect, id, look, 1.0, enabled);
    let fg = if look == Look::Quiet { t.text_normal } else { Color32::WHITE };
    ui.painter().text(rect.center(), Align2::CENTER_CENTER, label, medium(16.0), fade(fg, if enabled { 1.0 } else { 0.5 }));
    resp
}

/// A small pop-up: a title, paragraphs and right-aligned buttons. Returns the
/// button pressed, and whether it was dismissed (X or a click outside).
fn dialog(ctx: &egui::Context, t: &Theme, id: &str, title: &str, body: &[String], buttons: &[(&str, Look, bool)]) -> (Option<usize>, bool) {
    let (mut pressed, mut close) = (None, false);
    let w = 440.0 - 2.0;
    let dim = modal_frame(ctx, t, id, w, |ui| {
        let texts: Vec<Arc<Galley>> = body.iter().map(|s| wrapped(ui, s, FontId::proportional(16.0), t.text_normal, w - 48.0, 20.0, false)).collect();
        let body_h: f32 = texts.iter().map(|g| g.size().y).sum::<f32>() + 8.0 * texts.len().saturating_sub(1) as f32;
        let (r, _) = ui.allocate_exact_size(vec2(w, 24.0 + 24.0 + 12.0 + body_h + 24.0 + 40.0 + 24.0), Sense::hover());
        let tp = ui.painter_at(Rect::from_min_max(r.min, pos2(r.right() - 56.0, r.bottom())));
        line(&tp, pos2(r.left() + 24.0, r.top() + 24.0), 24.0, title, strong(20.0), t.header_primary);
        close |= close_x(ui, t, Rect::from_min_size(pos2(r.right() - 16.0 - 32.0, r.top() + 20.0), vec2(32.0, 32.0)), egui::Id::new((id, "x")));
        let mut y = r.top() + 60.0;
        for g in texts {
            let h = g.size().y;
            ui.painter().galley(pos2(r.left() + 24.0, y), g, t.text_normal);
            y += h + 8.0;
        }
        let mut x = r.right() - 24.0;
        for (i, (label, look, enabled)) in buttons.iter().enumerate().rev() {
            let bw = (width(ui, label, medium(16.0)) + 32.0).max(96.0);
            let b = Rect::from_min_size(pos2(x - bw, r.bottom() - 24.0 - 40.0), vec2(bw, 40.0));
            if text_button(ui, t, b, egui::Id::new((id, i)), *look, label, *enabled).clicked() {
                pressed = Some(i);
            }
            x -= bw + 8.0;
        }
    });
    (pressed, close || dim)
}

/// Discord's "View Perks" pop-up of a level: its gem, what it costs in all,
/// everything it brings and, for people who manage the server, "Enable".
fn level_modal(ctx: &egui::Context, t: &Theme, d: &BoostsData, c: &BoostCtx, n: usize, busy: bool) -> (bool, Option<Go>) {
    let (mut close, mut go) = (false, None);
    let level = d.levels.get(n);
    let title = level.map(|p| p.title.clone()).unwrap_or_else(|| format!("Level {}", n + 1));
    // A level costs its own Boosts and those of the levels under it.
    let cost: u32 = if d.levels.is_empty() { LEVEL_COST.iter().take(n + 1).sum() } else { d.levels.iter().take(n + 1).map(|p| p.cost).sum() };
    let status = level.map_or(Status::Inactive, |p| d.status(p, c.tier, c.tier_override).0);
    let enable = level.filter(|_| c.admin && status == Status::Inactive);
    let missing = enable.and_then(|p| p.dependency.as_deref()).filter(|dep| !d.unlocked.contains_key(*dep)).and_then(|dep| d.powerup(dep)).map(|m| m.title.clone());
    let perks = LEVEL_PERKS[n.min(2)];
    let width_px = 480.0;
    let dim = modal_frame(ctx, t, "boost_perks", width_px - 2.0, |ui| {
        // Rows of two: 201 px columns, 12 px apart; a long perk wraps.
        let col = 201.0;
        let rows: Vec<Vec<Arc<Galley>>> = perks.chunks(2).map(|pair| pair.iter().map(|(_, text)| wrapped(ui, text, FontId::proportional(14.0), t.text_normal, col - 24.0, 18.0, false)).collect()).collect();
        let body: f32 = rows.iter().map(|r| r.iter().map(|g| g.size().y).fold(20.0, f32::max)).sum::<f32>() + 12.0 * (rows.len().saturating_sub(1)) as f32;
        let foot = if enable.is_some() { 56.0 } else { 0.0 };
        let (r, _) = ui.allocate_exact_size(vec2(width_px - 2.0, 310.0 + 16.0 + body + 32.0 + foot), Sense::hover());
        purple_glow(ui.painter(), Rect::from_min_max(r.min, pos2(r.right(), r.top() + 310.0)));
        egui::Image::new(level_gem(n)).show_loading_spinner(false).paint_at(ui, Rect::from_center_size(pos2(r.center().x, r.top() + 123.0), vec2(128.0, 128.0)));
        close |= close_x(ui, t, Rect::from_min_size(pos2(r.right() - 9.0 - 38.0, r.top() + 8.0), vec2(38.0, 38.0)), egui::Id::new("boost_perks_close"));
        let p = ui.painter();
        p.text(pos2(r.center().x, r.top() + 250.0), Align2::CENTER_CENTER, &title, strong(24.0), t.header_primary);
        let cost = cost_text(cost, false);
        let cw = width(ui, &cost, FontId::proportional(16.0));
        let x0 = r.center().x - (22.0 + cw) / 2.0;
        paint_icon(ui, "gem", pos2(x0, r.top() + 275.0), 18.0, PINK);
        line(p, pos2(x0 + 22.0, r.top() + 274.0), 20.0, &cost, FontId::proportional(16.0), t.interactive_normal);
        let mut y = r.top() + 326.0;
        for (pair, texts) in perks.chunks(2).zip(rows) {
            let row_h = texts.iter().map(|g| g.size().y).fold(20.0, f32::max);
            for (j, ((name, _), g)) in pair.iter().zip(texts).enumerate() {
                let x = r.left() + 32.0 + j as f32 * (col + 12.0);
                paint_icon(ui, name, pos2(x, y + (row_h - 20.0) / 2.0), 20.0, t.text_normal);
                let gy = y + (row_h - g.size().y) / 2.0;
                ui.painter().galley(pos2(x + 24.0, gy), g, t.text_normal);
            }
            y += row_h + 12.0;
        }
        if let Some(p) = enable {
            let b = Rect::from_min_size(pos2(r.left() + 32.0, r.bottom() - 16.0 - 40.0), vec2(r.width() - 64.0, 40.0));
            let ok = missing.is_none() && !busy;
            let resp = button_bg(ui, t, b, egui::Id::new("boost_perks_enable"), Look::Primary, 1.0, ok);
            enable_label(ui, b, "Enable", "gem", p.cost, fade(Color32::WHITE, if ok { 1.0 } else { 0.5 }));
            let resp = match &missing {
                Some(m) => resp.on_hover_text(format!("You need to activate {m} first.")),
                None => resp,
            };
            if resp.clicked() {
                go = Some(Go::Enable(p.sku.clone()));
            }
        }
    });
    (close || dim, go)
}

/// A perk's pop-up: its artwork, name and description on the left with the
/// buttons of people who manage the server (Enable, or Disable and Configure),
/// and an example message on the right.
#[allow(clippy::too_many_arguments)]
fn perk_modal(ctx: &egui::Context, t: &Theme, d: &BoostsData, c: &BoostCtx, sku: &str, me: Option<&User>, my_name: &str, busy: bool) -> (bool, Option<Go>) {
    let Some(perk) = d.powerup(sku).cloned() else { return (true, None) };
    let (mut close, mut go) = (false, None);
    let (status, _) = d.status(&perk, c.tier, c.tier_override);
    let missing = perk.dependency.as_deref().filter(|dep| !d.unlocked.contains_key(*dep)).and_then(|dep| d.powerup(dep)).map(|m| m.title.clone());
    let manage = c.admin && status != Status::Override;
    let pack = SKU_BADGE_PACKS.contains(&sku);
    let configurable = sku != SKU_UPLOADS_250;
    let screen = ctx.screen_rect();
    let w = (screen.width() - 48.0).clamp(560.0, 852.0) - 2.0;
    let h = (screen.height() - 48.0).clamp(420.0, 602.0) - 2.0;
    let dim = modal_frame(ctx, t, "boost_perk", w, |ui| {
        let (r, _) = ui.allocate_exact_size(vec2(w, h), Sense::hover());
        let left = Rect::from_min_size(r.min, vec2(350.0, h));
        let right = Rect::from_min_max(pos2(left.right(), r.top()), r.max);
        ui.painter().rect_filled(right, Rounding { ne: 11.0, se: 11.0, ..Rounding::ZERO }, t.bg_primary);
        let desc = (!perk.description.is_empty() && perk.description != perk.title).then(|| wrapped(ui, &perk.description, FontId::proportional(16.0), t.text_normal, 286.0, 20.0, false));
        let name = wrapped(ui, &perk.title, strong(24.0), t.header_primary, 286.0, 32.0, false);
        let name_h = name.size().y.max(32.0);
        let content_h = 32.0 + name_h + desc.as_ref().map_or(0.0, |g| 4.0 + g.size().y) + if manage { 24.0 + 40.0 } else { 0.0 } + 32.0;
        let art = Rect::from_min_max(left.min, pos2(left.right(), left.bottom() - content_h));
        purple_glow(ui.painter(), art);
        if let Some(url) = &perk.image {
            let iw = if sku == SKU_ROLE_STYLES { 318.0 } else if pack { 240.0 } else { 350.0 };
            let ih = if pack { iw * 125.0 / 170.0 } else { iw / 2.0 };
            egui::Image::new(url.as_str()).texture_options(super::SMOOTH).show_loading_spinner(false).paint_at(ui, Rect::from_center_size(art.center(), vec2(iw, ih)));
        }
        let mut y = art.bottom() + 32.0;
        ui.painter().galley(pos2(left.left() + 32.0, y), name, t.header_primary);
        y += name_h + 4.0;
        if let Some(g) = desc {
            ui.painter().galley(pos2(left.left() + 32.0, y), g, t.text_normal);
        }
        if manage {
            let row = Rect::from_min_size(pos2(left.left() + 32.0, left.bottom() - 32.0 - 40.0), vec2(286.0, 40.0));
            if status == Status::Inactive {
                let ok = missing.is_none() && !busy;
                let resp = button_bg(ui, t, row, egui::Id::new("boost_perk_enable"), Look::Primary, 1.0, ok);
                enable_label(ui, row, "Enable", "gem", perk.cost, fade(Color32::WHITE, if ok { 1.0 } else { 0.5 }));
                let resp = match &missing {
                    Some(m) => resp.on_hover_text(format!("You need to activate {m} first.")),
                    None => resp,
                };
                if resp.clicked() {
                    go = Some(Go::Enable(perk.sku.clone()));
                }
            } else {
                // Disable (the slashed gem and what comes back), then Configure.
                let can_disable = status == Status::Active && !busy;
                let off = if configurable { Rect::from_min_size(row.min, vec2(65.0, 40.0)) } else { row };
                let resp = button_bg(ui, t, off, egui::Id::new("boost_perk_disable"), Look::Quiet, 1.0, can_disable);
                let fg = fade(t.text_normal, if can_disable { 1.0 } else { 0.5 });
                let cost = perk.cost.to_string();
                let cw = width(ui, &cost, medium(16.0));
                let x = off.center().x - (18.0 + 4.0 + cw) / 2.0;
                paint_icon(ui, "gem-slash", pos2(x, off.center().y - 9.0), 18.0, fg);
                ui.painter().text(pos2(x + 22.0, off.center().y), Align2::LEFT_CENTER, &cost, medium(16.0), fg);
                let tip = if status == Status::Level { "Can't Disable: Included in Level 3".to_string() } else { format!("Disable Perk. Get {} back.", cost_text(perk.cost, false)) };
                if resp.on_hover_text(tip).clicked() {
                    go = Some(Go::AskDisable(perk.sku.clone()));
                }
                if configurable {
                    let b = Rect::from_min_max(pos2(off.right() + 8.0, row.top()), row.max);
                    if text_button(ui, t, b, egui::Id::new("boost_perk_configure"), Look::Primary, "Configure", true).clicked() {
                        go = Some(Go::Configure(if pack { SKU_SERVER_TAG.to_string() } else { perk.sku.clone() }));
                    }
                }
            }
        }
        // The example: you, saying Discord's line, with the perk showing.
        let mw = (right.width() - 48.0).min(352.0);
        let m = Rect::from_center_size(right.center(), vec2(mw, 66.0));
        ui.painter().rect_filled(m, 8.0, modc(0.08));
        ui.painter().rect_stroke(m.shrink(0.5), 8.0, Stroke::new(1.0_f32, t.border_subtle));
        let av = Rect::from_min_size(m.min + vec2(13.0, 13.0), vec2(40.0, 40.0));
        if let Some(me) = me {
            super::paint_avatar(ui, av, Some(me.avatar_or_default(80)), my_name);
        }
        let tx = av.right() + 12.0;
        let mp = ui.painter_at(m.shrink(8.0));
        let name_color = if sku == SKU_ROLE_STYLES { Color32::from_rgb(158, 107, 255) } else { t.header_primary };
        let nr = line(&mp, pos2(tx, m.top() + 13.0), 20.0, my_name, strong(16.0), name_color);
        if sku == SKU_SERVER_TAG || pack {
            // The server's tag next to your name (its initials stand in for the badge).
            let tag: String = c.name.chars().filter(|ch| ch.is_alphanumeric()).take(4).collect::<String>().to_uppercase();
            let g = mp.layout_no_wrap(tag, strong(12.0), t.text_normal);
            let chip = Rect::from_min_size(pos2(nr.right() + 4.0, m.top() + 15.0), vec2(g.size().x + 8.0, 16.0));
            mp.rect_filled(chip, 4.0, modc(0.2));
            mp.galley(pos2(chip.left() + 4.0, chip.center().y - g.size().y / 2.0), g, t.text_normal);
        }
        line(&mp, pos2(tx, m.top() + 33.0), 20.0, "wow, this looks so cool", medium(16.0), t.text_normal);
        close |= close_x(ui, t, Rect::from_min_size(pos2(r.right() - 17.0 - 32.0, r.top() + 17.0), vec2(32.0, 32.0)), egui::Id::new("boost_perk_close"));
    });
    (close || dim, go)
}

/// The Server Tag badge packs: each pack's art, name and price (a click opens
/// the pack), and the way to the Server Tag itself.
fn packs_modal(ctx: &egui::Context, t: &Theme, d: &BoostsData, c: &BoostCtx) -> (bool, Option<Go>) {
    let (mut close, mut go) = (false, None);
    let packs: Vec<Powerup> = d.perks.iter().find_map(|l| if let Listing::BadgePacks(v) = l { Some(v.clone()) } else { None }).unwrap_or_default();
    let rows = packs.len().div_ceil(2).max(1) as f32;
    let foot = if c.admin { 72.0 } else { 0.0 };
    let w = 480.0 - 2.0;
    let dim = modal_frame(ctx, t, "boost_packs", w, |ui| {
        let (r, _) = ui.allocate_exact_size(vec2(w, 100.0 + rows * 206.0 - 4.0 + 16.0 + foot), Sense::hover());
        let p = ui.painter();
        line(p, pos2(r.left() + 24.0, r.top() + 24.0), 24.0, "Server Tag Badge Packs", strong(20.0), t.header_primary);
        line(p, pos2(r.left() + 24.0, r.top() + 56.0), 20.0, "Make your Server Tag stand out with exclusive icons.", FontId::proportional(16.0), t.interactive_normal);
        close |= close_x(ui, t, Rect::from_min_size(pos2(r.right() - 8.0 - 40.0, r.top() + 8.0), vec2(40.0, 40.0)), egui::Id::new("boost_packs_close"));
        for (i, pack) in packs.iter().enumerate() {
            let cell = Rect::from_min_size(pos2(r.left() + 16.0 + (i % 2) as f32 * 224.0, r.top() + 100.0 + (i / 2) as f32 * 206.0), vec2(220.0, 202.0));
            let resp = ui.interact(cell, egui::Id::new(("boost_pack", i)), Sense::click());
            let p = ui.painter();
            if resp.hovered() {
                p.rect_filled(cell, 12.0, modc(0.06));
            }
            let art = Rect::from_min_size(cell.min + vec2(8.0, 8.0), vec2(204.0, 140.0));
            p.rect_stroke(art.shrink(0.5), 12.0, Stroke::new(1.0_f32, t.border_subtle));
            if let Some(url) = &pack.image {
                egui::Image::new(url.as_str()).texture_options(super::SMOOTH).show_loading_spinner(false).paint_at(ui, Rect::from_center_size(art.center(), vec2(170.0, 125.0)));
            }
            let tp = ui.painter_at(cell.shrink2(vec2(8.0, 0.0)));
            line(&tp, pos2(cell.left() + 8.0, cell.top() + 156.0), 18.0, &pack.title, medium(14.0), t.interactive_normal);
            if d.status(pack, c.tier, c.tier_override).0 != Status::Inactive {
                paint_icon(ui, "check", pos2(cell.left() + 8.0, cell.top() + 177.0), 16.0, POSITIVE);
                line(&tp, pos2(cell.left() + 30.0, cell.top() + 176.0), 18.0, "Enabled", strong(14.0), t.tint_text(POSITIVE_TEXT));
            } else {
                paint_icon(ui, "gem", pos2(cell.left() + 8.0, cell.top() + 176.0), 18.0, PINK);
                line(&tp, pos2(cell.left() + 30.0, cell.top() + 176.0), 18.0, &cost_text(pack.cost, false), medium(14.0), t.interactive_normal);
            }
            if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                go = Some(Go::Open(Modal::Perk(pack.sku.clone())));
            }
        }
        if c.admin {
            let b = Rect::from_min_size(pos2(r.left() + 24.0, r.bottom() - 16.0 - 40.0), vec2(r.width() - 48.0, 40.0));
            if c.has_tags {
                if text_button(ui, t, b, egui::Id::new("boost_packs_tag"), Look::Quiet, "Edit Server Tag", true).clicked() {
                    go = Some(Go::Configure(SKU_SERVER_TAG.to_string()));
                }
            } else if text_button(ui, t, b, egui::Id::new("boost_packs_tag"), Look::Primary, "View Server Tag", true).on_hover_text("The Server Tag perk is required to unlock Badge Packs.").clicked() {
                go = Some(Go::Open(Modal::Perk(SKU_SERVER_TAG.to_string())));
            }
        }
    });
    (close || dim, go)
}

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

    fn perk(sku: &str, cost: u32) -> Powerup {
        Powerup { sku: sku.into(), level: false, title: sku.into(), description: String::new(), cost, dependency: None, image: None }
    }

    #[test]
    fn catalog_keeps_levels_and_perks_in_sku_order() {
        let v = json!([
            { "summary": "Server Tag", "description": "Tags!", "powerup_metadata": { "category_type": "perk", "static_image_url": "https://cdn.discordapp.com/x.png" },
              "sku": { "id": SKU_SERVER_TAG, "powerup_metadata": { "boost_price": 3 } } },
            { "summary": "Level 2", "powerup_metadata": { "category_type": "level" },
              "sku": { "id": SKU_LEVELS[1], "dependent_sku_id": SKU_LEVELS[0], "powerup_metadata": { "boost_price": 5 } } },
            { "summary": "Level 1", "powerup_metadata": { "category_type": "level" },
              "sku": { "id": SKU_LEVELS[0], "powerup_metadata": { "boost_price": 2 } } },
            { "summary": "Not a powerup", "sku": { "id": "1" } },
            { "summary": "Script", "powerup_metadata": { "category_type": "perk", "static_image_url": "javascript:alert(1)" },
              "sku": { "id": "9999999999999999999", "powerup_metadata": { "boost_price": 1 } } },
        ]);
        let (levels, perks) = parse_catalog(&v).expect("catalog");
        assert_eq!(levels.iter().map(|p| p.title.as_str()).collect::<Vec<_>>(), ["Level 1", "Level 2"]);
        assert_eq!(levels[1].dependency.as_deref(), Some(SKU_LEVELS[0]));
        assert_eq!(levels[1].cost, 5);
        assert_eq!(perks[0].title, "Server Tag");
        assert_eq!(perks[0].image.as_deref(), Some("https://cdn.discordapp.com/x.png"));
        // Only https pictures are ever fetched.
        assert_eq!(perks[1].image, None);
        assert!(parse_catalog(&json!({ "message": "401" })).is_none());
        assert!(parse_catalog(&json!([])).is_none());
    }

    #[test]
    fn badge_packs_are_one_card_after_server_tag() {
        let (_, perks) = builtin_catalog();
        let cards = arrange_perks(perks);
        assert_eq!(cards.len(), 3);
        assert!(matches!(&cards[0], Listing::Perk(p) if p.sku == SKU_SERVER_TAG));
        match &cards[1] {
            Listing::BadgePacks(v) => assert_eq!(v.iter().map(|p| p.sku.as_str()).collect::<Vec<_>>(), SKU_BADGE_PACKS),
            other => panic!("expected the badge packs, got {other:?}"),
        }
        assert!(matches!(&cards[2], Listing::Perk(p) if p.sku == SKU_ROLE_STYLES));
        // The server theme, when Discord sells it, goes first.
        let mut with_theme = builtin_catalog().1;
        with_theme.push(perk(SKU_GUILD_THEME, 3));
        assert!(matches!(&arrange_perks(with_theme)[0], Listing::Perk(p) if p.sku == SKU_GUILD_THEME));
    }

    #[test]
    fn boost_phases_follow_discord() {
        let day = 86_400_000;
        let now = 100 * day;
        // Running: filed when it was given.
        assert_eq!(boost_phase(10 * day, None, false, now), (Phase::Gave, 10 * day));
        // Cancelled but more than three days left: still "gave".
        assert_eq!(boost_phase(10 * day, Some(now + 4 * day), false, now), (Phase::Gave, 10 * day));
        // Ending within three days: "expiring", filed three days before the end.
        assert_eq!(boost_phase(10 * day, Some(now + 2 * day), false, now), (Phase::Expiring(now + 2 * day), now - day));
        // Past its end, or marked ended: "expired" at its end.
        assert_eq!(boost_phase(10 * day, Some(now - day), false, now), (Phase::Expired, now - day));
        assert_eq!(boost_phase(10 * day, Some(now + 2 * day), true, now), (Phase::Expired, now + 2 * day));
        assert_eq!(boost_phase(10 * day, None, true, now), (Phase::Expired, 10 * day));
    }

    #[test]
    fn spent_and_goal_match_discord() {
        let (levels, perks) = builtin_catalog();
        let mut d = BoostsData { levels, perks: arrange_perks(perks), unlocked_known: true, ..Default::default() };
        let mut g = Guild::default();
        // A server seen at Level 3 with a Server Tag: 17 spent of 33.
        g.boost_features = Some(vec!["GUILD_TAGS".into()]);
        assert_eq!(d.spent(&g, 3), 17);
        assert_eq!(boost_goal(&g), 33);
        // Without Discord's list, the perks switched on are counted.
        g.boost_features = None;
        d.unlocked.insert(SKU_SERVER_TAG.into(), None);
        d.unlocked.insert(SKU_LEVELS[0].into(), None);
        assert_eq!(d.spent(&g, 1), 5);
        // A free Level 3 costs nothing and only the perks count toward the goal.
        g.features = Some(vec!["PREMIUM_TIER_3_OVERRIDE".into()]);
        assert_eq!(d.spent(&g, 3), 0);
        assert_eq!(boost_goal(&g), 19);
    }

    #[test]
    fn powerup_status() {
        let (levels, perks) = builtin_catalog();
        let mut d = BoostsData { levels, perks: arrange_perks(perks), unlocked_known: true, ..Default::default() };
        let l1 = d.levels[0].clone();
        let l2 = d.levels[1].clone();
        assert_eq!(d.status(&l1, 0, false), (Status::Inactive, None));
        d.unlocked.insert(l1.sku.clone(), None);
        d.unlocked.insert(l2.sku.clone(), Some(42));
        assert_eq!(d.status(&l1, 2, false), (Status::Active, None));
        // A level that is running out keeps its end.
        assert_eq!(d.status(&l2, 2, false), (Status::Active, Some(42)));
        // Before Discord answers, the server's level decides.
        let unknown = BoostsData { levels: d.levels.clone(), ..Default::default() };
        assert_eq!(unknown.status(&l2, 2, false).0, Status::Active);
        assert_eq!(unknown.status(&d.levels[2], 2, false).0, Status::Inactive);
        // Level 3 includes the custom invite link.
        assert_eq!(d.status(&perk(SKU_INVITE_LINK, 5), 3, false).0, Status::Level);
        assert_eq!(d.status(&perk(SKU_INVITE_LINK, 5), 2, false).0, Status::Inactive);
        assert_eq!(d.status(&l1, 3, true).0, Status::Override);
    }
}