//! 工具函数
//!
//! 通用辅助函数

// ============================================
// 类型定义
// ============================================

/// 渐变停止点
#[derive(Debug, Clone)]
pub struct GradientStop {
    pub position: f32,
    pub color: [f32; 4],
}

/// 渐变类型
#[derive(Debug, Clone)]
pub enum GradientType {
    Linear {
        horizontal: bool,
        reverse: bool,
    },
    Radial {
        center_x: f32,
        center_y: f32,
        radius: f32,
    },
}

/// 背景类型
#[derive(Debug, Clone)]
pub enum Background {
    Solid([f32; 4]),
    Gradient {
        gradient_type: GradientType,
        stops: Vec<GradientStop>,
    },
}

/// 边框信息
#[derive(Debug, Clone)]
pub struct BorderInfo {
    pub width: (f32, f32, f32, f32), // top, right, bottom, left
    pub color: [f32; 4],
}

/// 文本信息
#[derive(Debug, Clone)]
pub struct TextInfo {
    pub content: String,
    pub font_size: f32,
    pub color: [f32; 4],
    pub x: f32,
    pub y: f32,
}

pub fn parse_css_color(color: &str) -> Option<[f32; 4]> {
    let color = color.trim();

    // 支持 rgba(r, g, b, a) 格式
    if color.starts_with("rgba(") {
        let inner = &color[5..color.len() - 1];
        let parts: Vec<&str> = inner.split(',').collect();
        if parts.len() == 4 {
            let r: f32 = ((parts[0].trim().parse::<f32>().unwrap_or(0.0) / 255.0)).clamp(0.0, 1.0);
            let g: f32 = ((parts[1].trim().parse::<f32>().unwrap_or(0.0) / 255.0)).clamp(0.0, 1.0);
            let b: f32 = ((parts[2].trim().parse::<f32>().unwrap_or(0.0) / 255.0)).clamp(0.0, 1.0);
            let a: f32 = parts[3].trim().parse::<f32>().unwrap_or(1.0).clamp(0.0, 1.0);
            return Some([r, g, b, a]);
        }
    }

    // 支持 rgb(r, g, b) 格式
    if color.starts_with("rgb(") {
        let inner = &color[4..color.len() - 1];
        let parts: Vec<&str> = inner.split(',').collect();
        if parts.len() == 3 {
            let r: f32 = ((parts[0].trim().parse::<f32>().unwrap_or(0.0) / 255.0)).clamp(0.0, 1.0);
            let g: f32 = ((parts[1].trim().parse::<f32>().unwrap_or(0.0) / 255.0)).clamp(0.0, 1.0);
            let b: f32 = ((parts[2].trim().parse::<f32>().unwrap_or(0.0) / 255.0)).clamp(0.0, 1.0);
            return Some([r, g, b, 1.0]);
        }
    }

    // 支持 hsl(h, s%, l%) / hsla(h, s%, l%, a) 格式
    if color.starts_with("hsla(") {
        let inner = &color[5..color.len() - 1];
        let parts: Vec<&str> = inner.split(',').collect();
        if parts.len() == 4 {
            let h: f32 = parts[0].trim().parse().unwrap_or(0.0);
            let s: f32 = parts[1].trim().trim_end_matches('%').parse().unwrap_or(0.0);
            let l: f32 = parts[2].trim().trim_end_matches('%').parse().unwrap_or(0.0);
            let a: f32 = parts[3].trim().parse::<f32>().unwrap_or(1.0).clamp(0.0, 1.0);
            let mut c = hsl_to_rgb(h, s, l);
            c[3] = a;
            return Some(c);
        }
    }
    if color.starts_with("hsl(") {
        let inner = &color[4..color.len() - 1];
        let parts: Vec<&str> = inner.split(',').collect();
        if parts.len() == 3 {
            let h: f32 = parts[0].trim().parse().unwrap_or(0.0);
            let s: f32 = parts[1].trim().trim_end_matches('%').parse().unwrap_or(0.0);
            let l: f32 = parts[2].trim().trim_end_matches('%').parse().unwrap_or(0.0);
            return Some(hsl_to_rgb(h, s, l));
        }
    }

    // 支持 hex 颜色（必须以 # 开头）
    if color.starts_with('#') {
        return parse_hex_color(color);
    }

    // 支持颜色名
    parse_css_color_name(color)
}

fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 4] {
    let h = h / 360.0;
    let s = s / 100.0;
    let l = l / 100.0;
    let a = s * l.min(1.0 - l);
    let f = |n: f32| -> f32 {
        let k = (n + h * 12.0) % 12.0;
        l - a * (k - 3.0).min(9.0 - k).max(-1.0).clamp(-1.0, 1.0)
    };
    [f(0.0), f(8.0), f(4.0), 1.0]
}

pub fn parse_hex_color(hex: &str) -> Option<[f32; 4]> {
    let hex = hex.trim();

    if let Some(hex) = hex.strip_prefix('#') {
        match hex.len() {
            8 => {
                // #RRGGBBAA
                if let (Ok(r), Ok(g), Ok(b), Ok(a)) = (
                    u8::from_str_radix(&hex[0..2], 16),
                    u8::from_str_radix(&hex[2..4], 16),
                    u8::from_str_radix(&hex[4..6], 16),
                    u8::from_str_radix(&hex[6..8], 16),
                ) {
                    return Some([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, a as f32 / 255.0]);
                }
            }
            6 => {
                // #RRGGBB
                if let (Ok(r), Ok(g), Ok(b)) = (
                    u8::from_str_radix(&hex[0..2], 16),
                    u8::from_str_radix(&hex[2..4], 16),
                    u8::from_str_radix(&hex[4..6], 16),
                ) {
                    return Some([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0]);
                }
            }
            4 => {
                // #RGBA
                if let (Ok(r), Ok(g), Ok(b), Ok(a)) = (
                    u8::from_str_radix(&hex[0..1], 16),
                    u8::from_str_radix(&hex[1..2], 16),
                    u8::from_str_radix(&hex[2..3], 16),
                    u8::from_str_radix(&hex[3..4], 16),
                ) {
                    return Some([(r * 17) as f32 / 255.0, (g * 17) as f32 / 255.0, (b * 17) as f32 / 255.0, (a * 17) as f32 / 255.0]);
                }
            }
            3 => {
                // #RGB
                if let (Ok(r), Ok(g), Ok(b)) = (
                    u8::from_str_radix(&hex[0..1], 16),
                    u8::from_str_radix(&hex[1..2], 16),
                    u8::from_str_radix(&hex[2..3], 16),
                ) {
                    return Some([(r * 17) as f32 / 255.0, (g * 17) as f32 / 255.0, (b * 17) as f32 / 255.0, 1.0]);
                }
            }
            _ => {}
        }
    }

    None
}

pub fn parse_css_color_name(name: &str) -> Option<[f32; 4]> {
    match name.to_lowercase().as_str() {
        // 基本颜色
        "red" => Some([1.0, 0.0, 0.0, 1.0]),
        "blue" => Some([0.0, 0.0, 1.0, 1.0]),
        "green" => Some([0.0, 0.502, 0.0, 1.0]),
        "yellow" => Some([1.0, 1.0, 0.0, 1.0]),
        "white" => Some([1.0, 1.0, 1.0, 1.0]),
        "black" => Some([0.0, 0.0, 0.0, 1.0]),
        "transparent" => Some([0.0, 0.0, 0.0, 0.0]),
        // 扩展颜色
        "orange" => Some([1.0, 0.65, 0.0, 1.0]),
        "purple" => Some([0.5, 0.0, 0.5, 1.0]),
        "pink" => Some([1.0, 0.75, 0.8, 1.0]),
        "cyan" => Some([0.0, 1.0, 1.0, 1.0]),
        "magenta" => Some([1.0, 0.0, 1.0, 1.0]),
        "gray" | "grey" => Some([0.5, 0.5, 0.5, 1.0]),
        "silver" => Some([0.75, 0.75, 0.75, 1.0]),
        "maroon" => Some([0.5, 0.0, 0.0, 1.0]),
        "olive" => Some([0.5, 0.5, 0.0, 1.0]),
        "lime" => Some([0.0, 1.0, 0.0, 1.0]),
        "teal" => Some([0.0, 0.5, 0.5, 1.0]),
        "navy" => Some([0.0, 0.0, 0.5, 1.0]),
        "fuchsia" => Some([1.0, 0.0, 1.0, 1.0]),
        "aqua" => Some([0.0, 1.0, 1.0, 1.0]),
        "coral" => Some([1.0, 0.5, 0.31, 1.0]),
        "tomato" => Some([1.0, 0.39, 0.28, 1.0]),
        "salmon" => Some([0.98, 0.5, 0.45, 1.0]),
        "gold" => Some([1.0, 0.84, 0.0, 1.0]),
        "khaki" => Some([0.94, 0.9, 0.55, 1.0]),
        "ivory" => Some([1.0, 1.0, 0.94, 1.0]),
        "beige" => Some([0.96, 0.96, 0.86, 1.0]),
        "lavender" => Some([0.9, 0.9, 0.98, 1.0]),
        "plum" => Some([0.87, 0.63, 0.87, 1.0]),
        "violet" => Some([0.93, 0.51, 0.93, 1.0]),
        "indigo" => Some([0.29, 0.0, 0.51, 1.0]),
        "crimson" => Some([0.86, 0.08, 0.24, 1.0]),
        "skyblue" => Some([0.53, 0.81, 0.92, 1.0]),
        "deepskyblue" => Some([0.0, 0.75, 1.0, 1.0]),
        "steelblue" => Some([0.27, 0.51, 0.71, 1.0]),
        "royalblue" => Some([0.25, 0.41, 0.88, 1.0]),
        "midnightblue" => Some([0.1, 0.1, 0.44, 1.0]),
        "slategray" => Some([0.44, 0.5, 0.56, 1.0]),
        "darkgray" => Some([0.66, 0.66, 0.66, 1.0]),
        "darkgreen" => Some([0.0, 0.39, 0.0, 1.0]),
        "darkblue" => Some([0.0, 0.0, 0.55, 1.0]),
        "darkred" => Some([0.55, 0.0, 0.0, 1.0]),
        _ => None,
    }
}

pub fn parse_css_unit(css: &str) -> f32 {
    // 移除 "px" 后缀并解析为 f32
    let num_str = css.trim_end_matches("px").trim();
    num_str.parse::<f32>().unwrap_or(0.0)
}

pub fn parse_css_unit_with_viewport(css: &str, viewport_width: f32, viewport_height: f32) -> f32 {
    let css = css.trim();
    if css.ends_with("vh") {
        let num_str = css.strip_suffix("vh").unwrap_or("0").trim();
        num_str.parse::<f32>().unwrap_or(0.0) * viewport_height / 100.0
    } else if css.ends_with("vw") {
        let num_str = css.strip_suffix("vw").unwrap_or("0").trim();
        num_str.parse::<f32>().unwrap_or(0.0) * viewport_width / 100.0
    } else {
        parse_css_unit(css)
    }
}

pub fn parse_border_width(css: &str) -> (f32, f32, f32, f32) {
    let parts: Vec<&str> = css.split_whitespace().collect();

    match parts.len() {
        1 => {
            // 1 个值: 所有边相同
            let val = parse_css_unit(parts[0]);
            (val, val, val, val)
        }
        2 => {
            // 2 个值: 上下, 左右
            let top_bottom = parse_css_unit(parts[0]);
            let left_right = parse_css_unit(parts[1]);
            (top_bottom, left_right, top_bottom, left_right)
        }
        3 => {
            // 3 个值: 上, 左右, 下
            let top = parse_css_unit(parts[0]);
            let left_right = parse_css_unit(parts[1]);
            let bottom = parse_css_unit(parts[2]);
            (top, left_right, bottom, left_right)
        }
        4 => {
            // 4 个值: 上, 右, 下, 左
            let top = parse_css_unit(parts[0]);
            let right = parse_css_unit(parts[1]);
            let bottom = parse_css_unit(parts[2]);
            let left = parse_css_unit(parts[3]);
            (top, right, bottom, left)
        }
        _ => (0.0, 0.0, 0.0, 0.0),
    }
}

pub fn parse_linear_gradient(css: &str) -> Option<Background> {
    // 提取括号内容: linear-gradient(to right, red, blue)
    let start = css.find('(')? + 1;
    let end = css.rfind(')')?;
    let content = &css[start..end];

    // 分割参数
    let parts: Vec<&str> = content.split(',').map(|s| s.trim()).collect();
    if parts.len() < 2 {
        return None;
    }

    // 解析方向（第一个参数）
    let (horizontal, reverse, color_start) = parse_gradient_direction(parts[0]);

    // 解析颜色
    let mut stops = Vec::new();
    let color_parts = &parts[color_start..];

    for (i, color_css) in color_parts.iter().enumerate() {
        // 剥离位置后缀（如 " 0%", " 100%", " 50%", " 200px" 等）
        let clean_color = color_css.trim();
        let clean_color = if clean_color.ends_with('%') || clean_color.ends_with("px") {
            // 尝试从空格处分割颜色和位置
            let space_at = clean_color.rfind(' ');
            space_at.map(|sp| clean_color[..sp].trim()).unwrap_or(clean_color)
        } else {
            clean_color
        };

        if let Some(color) = parse_css_color(clean_color) {
            let position = if color_parts.len() <= 1 {
                0.0
            } else {
                i as f32 / (color_parts.len() - 1) as f32
            };
            stops.push(GradientStop { position, color });
        }
    }

    if stops.len() < 2 {
        return None;
    }

    Some(Background::Gradient {
        gradient_type: GradientType::Linear { horizontal, reverse },
        stops,
    })
}

pub fn parse_gradient_direction(dir: &str) -> (bool, bool, usize) {
    let dir = dir.trim();
    // 检测角度格式，如 "135deg"、"45deg" 等
    if dir.ends_with("deg") {
        let angle_str = &dir[..dir.len()-3];
        if let Ok(angle) = angle_str.trim().parse::<f32>() {
            // CSS角度规范: 0deg=to top, 90deg=to right, 180deg=to bottom, 270deg=to left
            let normalized = angle % 360.0;
            // 根据角度判断主要方向
            // 45-135deg: 向右
            // 135-225deg: 向下
            // 225-315deg: 向左
            // 315-360deg/0-45deg: 向上
            if normalized >= 45.0 && normalized < 135.0 {
                return (true, false, 1); // 向右
            } else if normalized >= 135.0 && normalized < 225.0 {
                return (false, false, 1); // 向下
            } else if normalized >= 225.0 && normalized < 315.0 {
                return (true, true, 1); // 向左
            } else {
                return (false, true, 1); // 向上
            }
        }
        // 解析失败，默认水平
        return (true, false, 1);
    }
    match dir {
        "to right" => (true, false, 1),
        "to left" => (true, true, 1),
        "to bottom" => (false, false, 1),
        "to top" => (false, true, 1),
        "to bottom right" => (true, false, 1),
        "to right bottom" => (true, false, 1),
        "to bottom left" => (true, true, 1),
        "to left bottom" => (true, true, 1),
        "to top right" => (true, false, 1),
        "to right top" => (true, false, 1),
        "to top left" => (true, true, 1),
        "to left top" => (true, true, 1),
        _ => (false, false, 0), // 默认垂直，第一个参数是颜色
    }
}

/// 解析渐变（返回颜色数组和是否水平）
pub fn parse_gradient(css: &str) -> Option<(Vec<[f32; 4]>, bool)> {
    if css.contains("linear-gradient") {
        if let Some(Background::Gradient { gradient_type, stops }) = parse_linear_gradient(css) {
            let horizontal = match gradient_type {
                GradientType::Linear { horizontal, .. } => horizontal,
                _ => false,
            };
            let colors: Vec<[f32; 4]> = stops.iter().map(|s| s.color).collect();
            return Some((colors, horizontal));
        }
    }
    None
}

/// 解析径向渐变
pub fn parse_radial_gradient(css: &str) -> Option<(f32, f32, f32, [f32; 4], [f32; 4])> {
    if !css.contains("radial-gradient") {
        return None;
    }

    let start = css.find('(')? + 1;
    let end = css.rfind(')')?;
    let content = &css[start..end];

    let parts: Vec<&str> = content.split(',').map(|s| s.trim()).collect();
    if parts.len() < 2 {
        return None;
    }

    // 默认值
let center_x = 0.5;
    let center_y = 0.5;
    let radius = 0.5;

    // 解析颜色
    let start_color = parse_css_color(parts[parts.len() - 2])?;
    let end_color = parse_css_color(parts[parts.len() - 1])?;

    Some((center_x, center_y, radius, start_color, end_color))
}

/// 解析 padding（返回 top/bottom, left/right）
pub fn parse_css_padding(padding: &str) -> (f32, f32) {
    let padding = padding.trim();
    let parts: Vec<&str> = padding.split_whitespace().collect();

    match parts.len() {
        1 => {
            let val = parse_css_unit(parts[0]).max(0.0);
            (val, val)
        }
        2 => {
            let vertical = parse_css_unit(parts[0]).max(0.0);
            let horizontal = parse_css_unit(parts[1]).max(0.0);
            (vertical, horizontal)
        }
        4 => {
            let top = parse_css_unit(parts[0]).max(0.0);
            let right = parse_css_unit(parts[1]).max(0.0);
            let bottom = parse_css_unit(parts[2]).max(0.0);
            let left = parse_css_unit(parts[3]).max(0.0);
            ((top + bottom) / 2.0, (left + right) / 2.0)
        }
        _ => (0.0, 0.0),
    }
}

#[cfg(test)]
mod test_utils {
    // TODO: 这些模块当前不存在，测试需要时再启用
    // use crate::dom::DOMNode;
    // use crate::style::ComputedStyles;
    // use super::layout_types::*;
    use super::*;

    fn test_parse_css_color_rgba() {
        let color = parse_css_color("rgba(255, 128, 64, 0.5)");
        assert!(color.is_some());
        let color = color.unwrap();
        assert!((color[0] - 1.0).abs() < 0.01);
        assert!((color[1] - 0.502).abs() < 0.01);
        assert!((color[2] - 0.251).abs() < 0.01);
        assert!((color[3] - 0.5).abs() < 0.01);
    }

    fn test_parse_css_color_invalid() {
        let color = parse_css_color("invalid");
        assert!(color.is_none());
    }

    fn test_parse_css_color_hex() {
        let color = parse_css_color("#667eea");
        assert!(color.is_some());
        let c = color.unwrap();
        assert!((c[0] - 102.0 / 255.0).abs() < 0.01);
        assert!((c[1] - 126.0 / 255.0).abs() < 0.01);
        assert!((c[2] - 234.0 / 255.0).abs() < 0.01);
    }

    fn test_parse_css_color_named() {
        let red = parse_css_color("red");
        assert!(red.is_some());
        assert!((red.unwrap()[0] - 1.0).abs() < 0.01);

        let blue = parse_css_color("blue");
        assert!(blue.is_some());
        assert!((blue.unwrap()[2] - 1.0).abs() < 0.01);
    }

    fn test_parse_border_width_single() {
        assert_eq!(parse_border_width("2px"), (2.0, 2.0, 2.0, 2.0));
    }

    fn test_parse_border_width_two_values() {
        assert_eq!(parse_border_width("5px 10px"), (5.0, 10.0, 5.0, 10.0));
    }

    fn test_parse_border_width_four_values() {
        assert_eq!(parse_border_width("1px 2px 3px 4px"), (1.0, 2.0, 3.0, 4.0));
    }

    fn test_parse_border_width_three_values() {
        assert_eq!(parse_border_width("1px 2px 3px"), (1.0, 2.0, 3.0, 2.0));
    }

    fn test_parse_css_unit_px() {
        assert!((parse_css_unit("16px") - 16.0).abs() < 0.01);
        assert!((parse_css_unit("0px") - 0.0).abs() < 0.01);
    }

    fn test_parse_hex_color_3digit() {
        // #RGB -> #RRGGBB 展开
        let color = parse_css_color("#f0a");
        assert!(color.is_some());
        let c = color.unwrap();
        // #ff00aa
        assert!((c[0] - 1.0).abs() < 0.01);
        assert!((c[1] - 0.0).abs() < 0.01);
        assert!((c[2] - 0.667).abs() < 0.01); // 0xaa = 170, 170/255 ≈ 0.667
    }

    fn test_parse_linear_gradient_horizontal() {
        let bg = parse_linear_gradient("linear-gradient(to right, red, blue)");
        assert!(bg.is_some());
        match bg.unwrap() {
            Background::Gradient { gradient_type, stops } => {
                match gradient_type {
                    GradientType::Linear { horizontal, .. } => {
                        assert!(horizontal);
                    }
                }
                assert_eq!(stops.len(), 2);
            }
            _ => panic!("Expected gradient"),
        }
    }

    fn test_parse_linear_gradient_vertical() {
        let bg = parse_linear_gradient("linear-gradient(to bottom, red, blue)");
        assert!(bg.is_some());
        match bg.unwrap() {
            Background::Gradient { gradient_type, .. } => {
                match gradient_type {
                    GradientType::Linear { horizontal, .. } => {
                        assert!(!horizontal); // to bottom = 垂直
                    }
                }
            }
            _ => panic!("Expected gradient"),
        }
    }

    fn test_parse_linear_gradient_direction_reverse() {
        // to left 应有 reverse = true
        let bg = parse_linear_gradient("linear-gradient(to left, red, blue)");
        assert!(bg.is_some());
        match bg.unwrap() {
            Background::Gradient { gradient_type, .. } => {
                match gradient_type {
                    GradientType::Linear { horizontal, reverse } => {
                        assert!(horizontal);
                        assert!(reverse);
                    }
                }
            }
            _ => panic!("Expected gradient"),
        }

        // to top 应有 reverse = true
        let bg = parse_linear_gradient("linear-gradient(to top, red, blue)");
        assert!(bg.is_some());
        match bg.unwrap() {
            Background::Gradient { gradient_type, .. } => {
                match gradient_type {
                    GradientType::Linear { horizontal, reverse } => {
                        assert!(!horizontal);
                        assert!(reverse);
                    }
                }
            }
            _ => panic!("Expected gradient"),
        }

        // to right 不应有 reverse
        let bg = parse_linear_gradient("linear-gradient(to right, red, blue)");
        assert!(bg.is_some());
        match bg.unwrap() {
            Background::Gradient { gradient_type, .. } => {
                match gradient_type {
                    GradientType::Linear { reverse, .. } => {
                        assert!(!reverse);
                    }
                }
            }
            _ => panic!("Expected gradient"),
        }
    }

    fn test_parse_linear_gradient_no_direction() {
        // 无方向参数，默认垂直
        let bg = parse_linear_gradient("linear-gradient(red, blue)");
        assert!(bg.is_some());
        match bg.unwrap() {
            Background::Gradient { gradient_type, stops } => {
                match gradient_type {
                    GradientType::Linear { horizontal, .. } => {
                        assert!(!horizontal);
                    }
                }
                assert_eq!(stops.len(), 2);
            }
            _ => panic!("Expected gradient"),
        }
    }

    fn test_parse_gradient_linear() {
        // 测试 linear-gradient 解析（135度对角线）
        let style = "background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);";
        let result = parse_gradient(style);
        
        assert!(result.is_some());
        let (colors, horizontal) = result.unwrap();
        
        // 应该解析出 2 个颜色
        assert_eq!(colors.len(), 2);
        
        // 135度属于水平方向范围（135-225度）
        assert!(horizontal, "135deg 应该是水平方向");
        
        // #667eea = rgb(102, 126, 234)
        assert!((colors[0][0] - 102.0 / 255.0).abs() < 0.01);
        assert!((colors[0][1] - 126.0 / 255.0).abs() < 0.01);
        assert!((colors[0][2] - 234.0 / 255.0).abs() < 0.01);
        
        // #764ba2 = rgb(118, 75, 162)
        assert!((colors[1][0] - 118.0 / 255.0).abs() < 0.01);
        assert!((colors[1][1] - 75.0 / 255.0).abs() < 0.01);
        assert!((colors[1][2] - 162.0 / 255.0).abs() < 0.01);
    }

    fn test_parse_gradient_horizontal() {
        // 测试水平渐变 (to right)
        let style = "background: linear-gradient(to right, #ff0000, #00ff00);";
        let result = parse_gradient(style);
        
        assert!(result.is_some(), "应该能解析水平渐变");
        let (_, horizontal) = result.unwrap();
        assert!(horizontal, "to right 应该是水平渐变");
    }

    fn test_parse_gradient_vertical() {
        // 测试垂直渐变 (to bottom)
        let style = "background: linear-gradient(to bottom, #0000ff, #ffff00);";
        let result = parse_gradient(style);
        
        assert!(result.is_some());
        let (_, horizontal) = result.unwrap();
        assert!(!horizontal, "to bottom 应该是垂直渐变");
    }

    fn test_parse_gradient_rgb() {
        // 测试 rgb() 颜色格式
        let style = "background: linear-gradient(to right, rgb(255, 0, 0), rgb(0, 255, 0));";
        let result = parse_gradient(style);
        
        assert!(result.is_some());
        let (colors, horizontal) = result.unwrap();
        
        assert_eq!(colors.len(), 2);
        assert!(horizontal);
        assert!((colors[0][0] - 1.0).abs() < 0.01); // red
        assert!((colors[0][1] - 0.0).abs() < 0.01);
        assert!((colors[0][2] - 0.0).abs() < 0.01);
        
        assert!((colors[1][0] - 0.0).abs() < 0.01);
        assert!((colors[1][1] - 1.0).abs() < 0.01); // green
        assert!((colors[1][2] - 0.0).abs() < 0.01);
    }

    fn test_parse_gradient_rgba() {
        // 测试 rgba() 颜色格式（带透明度）
        let style = "background: linear-gradient(to bottom, rgba(255, 0, 0, 0.5), rgba(0, 0, 255, 0.8));";
        let result = parse_gradient(style);
        
        assert!(result.is_some());
        let (colors, horizontal) = result.unwrap();
        
        assert_eq!(colors.len(), 2);
        assert!(!horizontal, "to bottom 应该是垂直渐变");
        assert!((colors[0][0] - 1.0).abs() < 0.01);
        assert!((colors[0][3] - 0.5).abs() < 0.01); // alpha = 0.5
        
        assert!((colors[1][2] - 1.0).abs() < 0.01);
        assert!((colors[1][3] - 0.8).abs() < 0.01); // alpha = 0.8
    }

    fn test_parse_gradient_color_names() {
        // 测试颜色名称
        let style = "background: linear-gradient(to right, red, blue);";
        let result = parse_gradient(style);
        
        assert!(result.is_some(), "应该能解析颜色名称");
        let (colors, horizontal) = result.unwrap();
        
        assert_eq!(colors.len(), 2);
        assert!(horizontal);
        
        // red = rgb(255, 0, 0)
        assert!((colors[0][0] - 1.0).abs() < 0.01);
        assert!((colors[0][1] - 0.0).abs() < 0.01);
        assert!((colors[0][2] - 0.0).abs() < 0.01);
        
        // blue = rgb(0, 0, 255)
        assert!((colors[1][0] - 0.0).abs() < 0.01);
        assert!((colors[1][1] - 0.0).abs() < 0.01);
        assert!((colors[1][2] - 1.0).abs() < 0.01);
    }

    fn test_parse_gradient_multi_colors() {
        // 测试多色标渐变（3个颜色）
        let style = "background: linear-gradient(to right, red, yellow, blue);";
        let result = parse_gradient(style);
        
        if let Some((colors, _)) = &result {
            println!("解析出的颜色数量: {}", colors.len());
            for (i, color) in colors.iter().enumerate() {
                println!("  颜色{}: {:?}", i, color);
            }
        }
        
        assert!(result.is_some(), "应该能解析多色标渐变");
        let (colors, horizontal) = result.unwrap();
        
        assert_eq!(colors.len(), 3, "应该有 3 个颜色");
        assert!(horizontal);
        
        // red
        assert!((colors[0][0] - 1.0).abs() < 0.01);
        // yellow
        assert!((colors[1][0] - 1.0).abs() < 0.01);
        assert!((colors[1][1] - 1.0).abs() < 0.01);
        // blue
        assert!((colors[2][2] - 1.0).abs() < 0.01);
    }

    fn test_parse_gradient_mixed_formats() {
        // 测试混合格式（hex + rgb + 颜色名称）
        let style = "background: linear-gradient(to bottom, #ff0000, rgb(0, 255, 0), blue);";
        let result = parse_gradient(style);
        
        assert!(result.is_some(), "应该能解析混合格式");
        let (colors, horizontal) = result.unwrap();
        
        assert_eq!(colors.len(), 3, "应该有 3 个颜色");
        assert!(!horizontal);
        
        // #ff0000 = red
        assert!((colors[0][0] - 1.0).abs() < 0.01);
        // rgb(0, 255, 0) = green
        assert!((colors[1][1] - 1.0).abs() < 0.01);
        // blue
        assert!((colors[2][2] - 1.0).abs() < 0.01);
    }

    fn test_parse_gradient_no_gradient() {
        // 测试没有渐变的情况
        let style = "background: #ff0000;";
        let result = parse_gradient(style);
        assert!(result.is_none());
    }

    fn test_parse_radial_gradient() {
        // 测试径向渐变解析
        let style = "background: radial-gradient(circle, red, blue);";
        let result = parse_radial_gradient(style);
        
        assert!(result.is_some(), "应该能解析径向渐变");
        let (center_x, center_y, radius, start_color, end_color) = result.unwrap();
        
        // 验证相对位置
        assert!((center_x - 0.5).abs() < 0.01);
        assert!((center_y - 0.5).abs() < 0.01);
        assert!((radius - 0.5).abs() < 0.01);
        
        // 验证颜色
        assert!((start_color[0] - 1.0).abs() < 0.01); // red
        assert!((end_color[2] - 1.0).abs() < 0.01);   // blue
    }

    fn test_parse_css_padding() {
        let result = parse_css_padding("10px 20px");
        assert!((result.0 - 10.0).abs() < 0.01);
        assert!((result.1 - 20.0).abs() < 0.01);
    }

}