use rune::{Color, TextStyle};
use rune_kit::{Kit, MarkdownStyle, PaletteSeed, Type};
use std::sync::OnceLock;

pub struct Pal {
    pub bg: Color,
    pub surface: Color,
    pub raised: Color,
    pub line: Color,
    pub fg: Color,
    pub strong: Color,
    pub muted: Color,
    pub faint: Color,
    pub accent: Color,
    pub accent_fg: Color,
    pub soft: Color,
    pub selection: Color,
    pub ok: Color,
    pub danger: Color,
    pub hover: Color,
    pub shadow: Color,
}

fn c(h: &str) -> Color {
    rune::color::hex(h).unwrap_or(Color::WHITE)
}

pub fn pal() -> &'static Pal {
    static P: OnceLock<Pal> = OnceLock::new();
    P.get_or_init(|| Pal {
        bg: c("#0a0b0d"),
        surface: c("#0e1013"),
        raised: c("#16191e"),
        line: c("#22262d"),
        fg: c("#cfd3da"),
        strong: c("#f2f3f5"),
        muted: c("#7b8290"),
        faint: c("#5d6470"),
        accent: c("#ff8a3d"),
        accent_fg: c("#0a0b0d"),
        soft: c("#1d1710"),
        selection: c("#3a2814"),
        ok: c("#3ddc97"),
        danger: c("#ff5d5d"),
        hover: c("#cfd3da").alpha(0.06),
        shadow: Color::BLACK.alpha(0.6),
    })
}

pub const SMALL: TextStyle = TextStyle::new(14.0, 400.0).mono().lh(20.0);
pub const BODY: TextStyle = TextStyle::new(16.0, 400.0).lh(24.0);
pub const STRONG: TextStyle = TextStyle::new(16.0, 500.0).lh(24.0);
pub const MONO: TextStyle = BODY.mono();
pub const TITLE: TextStyle = TextStyle::new(20.0, 500.0).lh(28.0);
pub const DISPLAY: TextStyle = TextStyle::new(30.0, 500.0).mono().lh(36.0);
pub const CONTROL: f32 = 28.0;

pub fn kit() -> Kit {
    let p = pal();
    let mut k = Kit::from_palette(PaletteSeed {
        bg: p.bg,
        fg: p.fg,
        accent: p.accent,
    });
    k.radius.sm = 4.0;
    k.radius.md = 4.0;
    k.ty = Type {
        ui: BODY,
        ui_medium: STRONG,
        ui_compact: BODY.lh(20.0),
        small: SMALL,
        small_medium: SMALL,
        body: BODY,
        body_medium: STRONG,
        text_small: BODY,
        text_small_medium: STRONG,
        text_xsmall: BODY,
        text_xsmall_medium: STRONG,
        mono: MONO,
    };
    k
}

pub fn markdown(k: &Kit) -> MarkdownStyle {
    MarkdownStyle::from_kit(k)
        .body_font(BODY)
        .heading_font(1, TITLE)
        .heading_font(2, STRONG)
        .heading_font(3, STRONG)
        .heading_font(4, STRONG)
        .code_block_font(MONO)
        .diagram_font(BODY)
}
