//! SVG → `data:image/svg+xml;base64,…` helper.
//!
//! Hydrogen's tab strip accepts either `mdi:<name>` icon names or a
//! `data:image/svg+xml;base64,…` URL. MDI strings are shorter but
//! limited to whatever MDI subset Hydrogen ships, and the rendering
//! is sometimes inconsistent across panel types. Embedded SVG data
//! URLs always render and let us ship distinctive, brand-colored
//! icons per subcommand.
//!
//! This module has a small hand-rolled base64 encoder so we don't
//! pull in a dependency just for 15 lines of code.

const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

fn base64_encode(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b0 = chunk[0];
        let b1 = *chunk.get(1).unwrap_or(&0);
        let b2 = *chunk.get(2).unwrap_or(&0);
        let n = ((b0 as u32) << 16) | ((b1 as u32) << 8) | (b2 as u32);
        out.push(ALPHABET[((n >> 18) & 0x3f) as usize] as char);
        out.push(ALPHABET[((n >> 12) & 0x3f) as usize] as char);
        out.push(if chunk.len() > 1 {
            ALPHABET[((n >> 6) & 0x3f) as usize] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            ALPHABET[(n & 0x3f) as usize] as char
        } else {
            '='
        });
    }
    out
}

/// Wrap an SVG string as a `data:image/svg+xml;base64,...` URL.
/// Kept around for any future caller (inline CSS background,
/// placeholder `--display-icon` values, etc.) even though the
/// canonical tab-icon path is now the served `/favicon.svg`
/// per the hydrogen-tab-icons skill.
#[allow(dead_code)]
pub fn svg_data_url(svg: &str) -> String {
    format!("data:image/svg+xml;base64,{}", base64_encode(svg.as_bytes()))
}