//! Vue Demo 渲染逻辑完整示例
//! 
//! 这个文件将 Vue 源码（App.vue）转换为 GPU 渲染命令的完整流程
//! 包括：布局计算、文本渲染、渐变背景、圆角卡片等

use std::collections::HashMap;

// ============================================
// 1. 数据结构定义
// ============================================

/// 绘制命令枚举
#[derive(Debug, Clone)]
pub enum DrawCommand {
    /// 纯色矩形
    Rect {
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        color: [f32; 4],
        z_index: i32,
    },
    /// 线性渐变矩形
    GradientRect {
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        start_color: [f32; 4],
        end_color: [f32; 4],
        horizontal: bool,
        z_index: i32,
    },
    /// 边框
    Border {
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        border_width: (f32, f32, f32, f32),
        border_color: [f32; 4],
        z_index: i32,
    },
    /// 圆角矩形
    RoundedRect {
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        radius: f32,
        color: [f32; 4],
        z_index: i32,
    },
    /// 文本
    Text {
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        text: String,
        color: [f32; 4],
        font_size: f32,
        bold: bool,
        z_index: i32,
    },
}

/// CSS 样式映射
type Styles = HashMap<String, String>;

/// 组件节点
struct ComponentNode {
    tag: String,
    text: Option<String>,
    styles: Styles,
    children: Vec<ComponentNode>,
}

// ============================================
// 2. 文本测量（与实际项目 iris-layout 一致）
// ============================================

/// 测量文本宽度：区分ASCII和非ASCII字符
/// 
/// 与实际项目 `crates/iris-layout/src/layout.rs:measure_text()` 完全一致
/// - ASCII字符宽度约0.6倍字体大小
/// - CJK字符（中日韩）约1.0倍字体大小
/// - 其他Unicode字符约0.8倍字体大小
fn measure_text(text: &str, font_size: f32) -> f32 {
    text.chars()
        .map(|c| {
            if c.is_ascii() {
                font_size * 0.6
            } else {
                // 检测是否为CJK字符（中日韩）
                let cp = c as u32;
                if (cp >= 0x4E00 && cp <= 0x9FFF) ||  // CJK统一表意符号
                   (cp >= 0x3400 && cp <= 0x4DBF) ||  // CJK扩展A
                   (cp >= 0xF900 && cp <= 0xFAFF) ||  // CJK兼容表意符号
                   (cp >= 0x3040 && cp <= 0x309F) ||  // 平假名
                   (cp >= 0x30A0 && cp <= 0x30FF) ||  // 片假名
                   (cp >= 0xAC00 && cp <= 0xD7AF) ||  // 韩文音节
                   (cp >= 0xFF00 && cp <= 0xFFEF) {   // 全角形式
                    font_size  // 全角字符宽度约等于字体大小
                } else {
                    font_size * 0.8  // 其他Unicode字符中间值
                }
            }
        })
        .sum()
}

// ============================================
// 3. Vue 源码（App.vue）转换为组件树
// ============================================

/// 构建 App.vue 的组件树
fn build_app_component_tree() -> ComponentNode {
    ComponentNode {
        tag: "div".to_string(),
        text: None,
        styles: vec![
            ("class".to_string(), "app".to_string()),
        ].into_iter().collect(),
        children: vec![
            // Header 区域
            ComponentNode {
                tag: "header".to_string(),
                text: None,
                styles: vec![
                    ("class".to_string(), "header".to_string()),
                    ("text-align".to_string(), "center".to_string()),
                    ("margin-bottom".to_string(), "48px".to_string()),
                ].into_iter().collect(),
                children: vec![
                    // h1 标题
                    ComponentNode {
                        tag: "h1".to_string(),
                        text: Some("Iris Runtime".to_string()),
                        styles: vec![
                            ("font-size".to_string(), "52px".to_string()),
                            ("font-weight".to_string(), "700".to_string()),
                            ("margin".to_string(), "0 0 8px 0".to_string()),
                        ].into_iter().collect(),
                        children: vec![],
                    },
                    // 副标题
                    ComponentNode {
                        tag: "p".to_string(),
                        text: Some("GPU Accelerated Vue 3 Rendering Engine".to_string()),
                        styles: vec![
                            ("class".to_string(), "subtitle".to_string()),
                            ("font-size".to_string(), "18px".to_string()),
                            ("opacity".to_string(), "0.7".to_string()),
                            ("margin".to_string(), "0".to_string()),
                        ].into_iter().collect(),
                        children: vec![],
                    },
                ],
            },
            // 主内容区域
            ComponentNode {
                tag: "main".to_string(),
                text: None,
                styles: vec![
                    ("class".to_string(), "content".to_string()),
                ].into_iter().collect(),
                children: vec![
                    // 统计卡片行
                    ComponentNode {
                        tag: "section".to_string(),
                        text: None,
                        styles: vec![
                            ("class".to_string(), "stats-row".to_string()),
                            ("display".to_string(), "flex".to_string()),
                            ("gap".to_string(), "16px".to_string()),
                            ("justify-content".to_string(), "center".to_string()),
                        ].into_iter().collect(),
                        children: vec![
                            // FPS 卡片
                            ComponentNode {
                                tag: "div".to_string(),
                                text: None,
                                styles: vec![
                                    ("class".to_string(), "stat-card".to_string()),
                                    ("background".to_string(), "rgba(255, 255, 255, 0.08)".to_string()),
                                    ("border-radius".to_string(), "16px".to_string()),
                                    ("padding".to_string(), "24px 28px".to_string()),
                                    ("text-align".to_string(), "center".to_string()),
                                ].into_iter().collect(),
                                children: vec![
                                    ComponentNode {
                                        tag: "span".to_string(),
                                        text: Some("⚡".to_string()),
                                        styles: vec![
                                            ("class".to_string(), "stat-icon".to_string()),
                                            ("font-size".to_string(), "28px".to_string()),
                                        ].into_iter().collect(),
                                        children: vec![],
                                    },
                                    ComponentNode {
                                        tag: "span".to_string(),
                                        text: Some("60".to_string()),
                                        styles: vec![
                                            ("class".to_string(), "stat-value".to_string()),
                                            ("font-size".to_string(), "20px".to_string()),
                                            ("font-weight".to_string(), "700".to_string()),
                                            ("color".to_string(), "#fff".to_string()),
                                        ].into_iter().collect(),
                                        children: vec![],
                                    },
                                    ComponentNode {
                                        tag: "span".to_string(),
                                        text: Some("FPS".to_string()),
                                        styles: vec![
                                            ("class".to_string(), "stat-label".to_string()),
                                            ("font-size".to_string(), "13px".to_string()),
                                            ("opacity".to_string(), "0.6".to_string()),
                                        ].into_iter().collect(),
                                        children: vec![],
                                    },
                                ],
                            },
                            // 其他统计卡片类似...
                        ],
                    },
                    // 功能卡片区域
                    ComponentNode {
                        tag: "section".to_string(),
                        text: None,
                        styles: vec![
                            ("class".to_string(), "features".to_string()),
                        ].into_iter().collect(),
                        children: vec![
                            // Native Rendering 卡片
                            ComponentNode {
                                tag: "div".to_string(),
                                text: None,
                                styles: vec![
                                    ("class".to_string(), "feature-card".to_string()),
                                    ("background".to_string(), "rgba(255, 255, 255, 0.06)".to_string()),
                                    ("border-radius".to_string(), "12px".to_string()),
                                    ("padding".to_string(), "24px".to_string()),
                                    ("border".to_string(), "1px solid rgba(255, 255, 255, 0.08)".to_string()),
                                ].into_iter().collect(),
                                children: vec![
                                    ComponentNode {
                                        tag: "h2".to_string(),
                                        text: Some("Native Rendering".to_string()),
                                        styles: vec![
                                            ("font-size".to_string(), "20px".to_string()),
                                            ("color".to_string(), "#a5b4fc".to_string()),
                                            ("margin".to_string(), "0 0 12px 0".to_string()),
                                        ].into_iter().collect(),
                                        children: vec![],
                                    },
                                    ComponentNode {
                                        tag: "p".to_string(),
                                        text: Some("Direct GPU acceleration via wgpu + Vulkan on AMD Radeon 890M. Full hardware-accelerated rendering pipeline with batch optimization.".to_string()),
                                        styles: vec![
                                            ("font-size".to_string(), "15px".to_string()),
                                            ("line-height".to_string(), "1.6".to_string()),
                                            ("opacity".to_string(), "0.8".to_string()),
                                            ("margin".to_string(), "0".to_string()),
                                        ].into_iter().collect(),
                                        children: vec![],
                                    },
                                ],
                            },
                            // Font System 卡片
                            ComponentNode {
                                tag: "div".to_string(),
                                text: None,
                                styles: vec![
                                    ("class".to_string(), "feature-card".to_string()),
                                    ("background".to_string(), "rgba(255, 255, 255, 0.06)".to_string()),
                                    ("border-radius".to_string(), "12px".to_string()),
                                    ("padding".to_string(), "24px".to_string()),
                                    ("border".to_string(), "1px solid rgba(255, 255, 255, 0.08)".to_string()),
                                ].into_iter().collect(),
                                children: vec![
                                    ComponentNode {
                                        tag: "h2".to_string(),
                                        text: Some("Font System".to_string()),
                                        styles: vec![
                                            ("font-size".to_string(), "20px".to_string()),
                                            ("color".to_string(), "#a5b4fc".to_string()),
                                            ("margin".to_string(), "0 0 12px 0".to_string()),
                                        ].into_iter().collect(),
                                        children: vec![],
                                    },
                                    ComponentNode {
                                        tag: "p".to_string(),
                                        text: Some("CPU rasterized font atlas with GPU sampling. Baseline-aligned text rendering with ascent/descent metrics for accurate typography.".to_string()),
                                        styles: vec![
                                            ("font-size".to_string(), "15px".to_string()),
                                            ("line-height".to_string(), "1.6".to_string()),
                                            ("opacity".to_string(), "0.8".to_string()),
                                            ("margin".to_string(), "0".to_string()),
                                        ].into_iter().collect(),
                                        children: vec![],
                                    },
                                ],
                            },
                        ],
                    },
                ],
            },
            // Footer
            ComponentNode {
                tag: "footer".to_string(),
                text: None,
                styles: vec![
                    ("class".to_string(), "footer".to_string()),
                    ("text-align".to_string(), "center".to_string()),
                    ("margin-top".to_string(), "48px".to_string()),
                    ("padding-top".to_string(), "24px".to_string()),
                    ("border-top".to_string(), "1px solid rgba(255, 255, 255, 0.08)".to_string()),
                ].into_iter().collect(),
                children: vec![
                    ComponentNode {
                        tag: "p".to_string(),
                        text: Some("Built with Rust + WebGPU + Vue 3 | Iris Runtime".to_string()),
                        styles: vec![
                            ("font-size".to_string(), "13px".to_string()),
                            ("opacity".to_string(), "0.5".to_string()),
                        ].into_iter().collect(),
                        children: vec![],
                    },
                ],
            },
        ],
    }
}

// ============================================
// 3. 样式解析工具函数
// ============================================

/// 解析 CSS 颜色值为 RGBA [0.0-1.0]
fn parse_color(color_str: &str) -> [f32; 4] {
    let color_str = color_str.trim();
    
    // 处理十六进制颜色
    if color_str.starts_with('#') {
        let hex = &color_str[1..];
        match hex.len() {
            6 => {
                let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0) as f32 / 255.0;
                let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0) as f32 / 255.0;
                let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0) as f32 / 255.0;
                [r, g, b, 1.0]
            }
            3 => {
                let r = u8::from_str_radix(&format!("{}{}", &hex[0..1], &hex[0..1]), 16).unwrap_or(0) as f32 / 255.0;
                let g = u8::from_str_radix(&format!("{}{}", &hex[1..2], &hex[1..2]), 16).unwrap_or(0) as f32 / 255.0;
                let b = u8::from_str_radix(&format!("{}{}", &hex[2..3], &hex[2..3]), 16).unwrap_or(0) as f32 / 255.0;
                [r, g, b, 1.0]
            }
            _ => [0.0, 0.0, 0.0, 1.0],
        }
    } else if color_str.starts_with("rgba") {
        // 修复：正确解析 rgba(r, g, b, a)
        // 示例：rgba(255, 255, 255, 0.08)
        let inner = color_str.trim_start_matches("rgba(").trim_end_matches(")");
        let parts: Vec<&str> = inner.split(',').map(|s| s.trim()).collect();
        
        if parts.len() == 4 {
            let r = parts[0].parse::<f32>().unwrap_or(0.0) / 255.0;
            let g = parts[1].parse::<f32>().unwrap_or(0.0) / 255.0;
            let b = parts[2].parse::<f32>().unwrap_or(0.0) / 255.0;
            let a = parts[3].parse::<f32>().unwrap_or(1.0);
            [r, g, b, a]
        } else {
            [0.0, 0.0, 0.0, 1.0]
        }
    } else if color_str.starts_with("rgb") {
        // 修复：正确解析 rgb(r, g, b)
        let inner = color_str.trim_start_matches("rgb(").trim_end_matches(")");
        let parts: Vec<&str> = inner.split(',').map(|s| s.trim()).collect();
        
        if parts.len() == 3 {
            let r = parts[0].parse::<f32>().unwrap_or(0.0) / 255.0;
            let g = parts[1].parse::<f32>().unwrap_or(0.0) / 255.0;
            let b = parts[2].parse::<f32>().unwrap_or(0.0) / 255.0;
            [r, g, b, 1.0]
        } else {
            [0.0, 0.0, 0.0, 1.0]
        }
    } else {
        // 默认白色
        [1.0, 1.0, 1.0, 1.0]
    }
}

/// 解析像素值（支持复合值如 "24px 28px"）
/// 
/// 返回 (top, right, bottom, left) 四个方向的值
/// 如果输入是单一值，四个方向都返回该值
fn parse_px(value: &str) -> (f32, f32, f32, f32) {
    let value = value.trim();
    
    // 移除所有 "px" 后缀
    let cleaned = value.replace("px", "");
    let parts: Vec<&str> = cleaned.split_whitespace().collect();
    
    match parts.len() {
        1 => {
            // 单一值：四边相同
            let val = parts[0].trim().parse::<f32>().unwrap_or(0.0);
            (val, val, val, val)
        }
        2 => {
            // 两个值：上下、左右
            let top = parts[0].trim().parse::<f32>().unwrap_or(0.0);
            let right = parts[1].trim().parse::<f32>().unwrap_or(0.0);
            (top, right, top, right)
        }
        3 => {
            // 三个值：上、左右、下
            let top = parts[0].trim().parse::<f32>().unwrap_or(0.0);
            let right = parts[1].trim().parse::<f32>().unwrap_or(0.0);
            let bottom = parts[2].trim().parse::<f32>().unwrap_or(0.0);
            (top, right, bottom, right)
        }
        4 => {
            // 四个值：上、右、下、左
            let top = parts[0].trim().parse::<f32>().unwrap_or(0.0);
            let right = parts[1].trim().parse::<f32>().unwrap_or(0.0);
            let bottom = parts[2].trim().parse::<f32>().unwrap_or(0.0);
            let left = parts[3].trim().parse::<f32>().unwrap_or(0.0);
            (top, right, bottom, left)
        }
        _ => (0.0, 0.0, 0.0, 0.0),
    }
}

/// 解析单一像素值（向后兼容）
fn parse_px_single(value: &str) -> f32 {
    let (top, _, _, _) = parse_px(value);
    top
}

/// 获取样式值
fn get_style<'a>(styles: &'a Styles, key: &str) -> Option<&'a str> {
    styles.get(key).map(|s| s.as_str())
}

// ============================================
// 4. 布局计算（简化版 Flexbox）
// ============================================

/// 布局上下文
struct LayoutContext {
    parent_x: f32,
    parent_y: f32,
    parent_width: f32,
    parent_height: f32,
}

/// 计算节点布局并生成绘制命令
fn layout_node(
    node: &ComponentNode,
    ctx: &LayoutContext,
    commands: &mut Vec<DrawCommand>,
    z_index: i32,
    inherited_opacity: f32, // 新增：继承的 opacity
) {
    let mut node_x = ctx.parent_x;
    let mut node_y = ctx.parent_y;
    
    // 修复：解析完整的 margin（支持复合值）
    if let Some(margin) = get_style(&node.styles, "margin") {
        let (margin_top, margin_right, margin_bottom, margin_left) = parse_px(margin);
        node_x += margin_left;
        node_y += margin_top;
        // margin_right 和 margin_bottom 在后续布局中使用
    } else {
        // 兼容旧版独立属性
        if let Some(margin_top_str) = get_style(&node.styles, "margin-top") {
            node_y += parse_px_single(margin_top_str);
        }
        if let Some(margin_left_str) = get_style(&node.styles, "margin-left") {
            node_x += parse_px_single(margin_left_str);
        }
    }
    
    // 修复：解析完整的 padding（支持复合值）
    let (padding_top, padding_right, padding_bottom, padding_left) = if let Some(padding) = get_style(&node.styles, "padding") {
        parse_px(padding)
    } else {
        // 兼容旧版独立属性
        let top = get_style(&node.styles, "padding-top")
            .map(|p| parse_px_single(p))
            .unwrap_or(0.0);
        let left = get_style(&node.styles, "padding-left")
            .map(|p| parse_px_single(p))
            .unwrap_or(0.0);
        let right = get_style(&node.styles, "padding-right")
            .map(|p| parse_px_single(p))
            .unwrap_or(0.0);
        let bottom = get_style(&node.styles, "padding-bottom")
            .map(|p| parse_px_single(p))
            .unwrap_or(0.0);
        (top, right, bottom, left)
    };
    
    // 解析 background
    if let Some(bg) = get_style(&node.styles, "background") {
        // 渐变背景
        if bg.contains("gradient") {
            commands.push(DrawCommand::GradientRect {
                x: node_x,
                y: node_y,
                width: ctx.parent_width,
                height: ctx.parent_height,
                start_color: [0.059, 0.047, 0.161, 1.0], // #0f0c29
                end_color: [0.141, 0.141, 0.243, 1.0],   // #24243e
                horizontal: false,
                z_index,
            });
        } else {
            // 纯色背景
            let color = parse_color(bg);
            if color[3] > 0.0 {
                commands.push(DrawCommand::Rect {
                    x: node_x,
                    y: node_y,
                    width: ctx.parent_width,
                    height: ctx.parent_height,
                    color,
                    z_index,
                });
            }
        }
    }
    
    // 解析 border-radius 和 background 的组合（圆角卡片）
    if let Some(radius_str) = get_style(&node.styles, "border-radius") {
        if get_style(&node.styles, "background").is_some() {
            let radius = parse_px(radius_str);
            let bg_color = if let Some(bg) = get_style(&node.styles, "background") {
                parse_color(bg)
            } else {
                [1.0, 1.0, 1.0, 0.0]
            };
            
            // 圆角矩形（用纯色矩形模拟，实际应该用圆角路径）
            let (_, _, _, radius_top_left) = parse_px(radius_str);
            commands.push(DrawCommand::RoundedRect {
                x: node_x + padding_left,
                y: node_y + padding_top,
                width: ctx.parent_width - padding_left * 2.0,
                height: ctx.parent_height - padding_top * 2.0,
                radius: radius_top_left, // 使用左上角 radius
                color: bg_color,
                z_index: z_index + 1,
            });
        }
    }
    
    // 解析 border
    if let Some(border_str) = get_style(&node.styles, "border") {
        let border_color = [0.157, 0.157, 0.157, 0.08]; // rgba(255, 255, 255, 0.08)
        commands.push(DrawCommand::Border {
            x: node_x,
            y: node_y,
            width: ctx.parent_width,
            height: ctx.parent_height,
            border_width: (1.0, 1.0, 1.0, 1.0),
            border_color,
            z_index: z_index + 1,
        });
    }
    
    // 渲染文本
    if let Some(text) = &node.text {
        let font_size = get_style(&node.styles, "font-size")
            .map(|s| parse_px_single(s))
            .unwrap_or(16.0);
        
        let text_color = if let Some(color_str) = get_style(&node.styles, "color") {
            parse_color(color_str)
        } else {
            [0.878, 0.878, 0.878, 1.0] // #e0e0e0
        };
        
        // 处理 opacity（修复：支持继承）
        let mut final_color = text_color;
        let node_opacity = if let Some(opacity_str) = get_style(&node.styles, "opacity") {
            opacity_str.parse::<f32>().unwrap_or(1.0)
        } else {
            1.0
        };
        // 应用继承的 opacity 和当前节点的 opacity
        let effective_opacity = inherited_opacity * node_opacity;
        if effective_opacity < 1.0 {
            final_color[3] *= effective_opacity;
        }
        
        let bold = get_style(&node.styles, "font-weight")
            .map(|w| w == "700" || w == "bold")
            .unwrap_or(false);
        
        // 文本对齐
        let text_align = get_style(&node.styles, "text-align")
            .unwrap_or("left");
        
        // 修复：使用 measure_text 精确测量文本宽度（与实际项目一致）
        let estimated_width = measure_text(text, font_size);
        
        let text_x = match text_align {
            "center" => node_x + (ctx.parent_width - estimated_width) / 2.0,
            "right" => node_x + ctx.parent_width - estimated_width,
            _ => node_x + padding_left,
        };
        
        commands.push(DrawCommand::Text {
            x: text_x,
            y: node_y + padding_top + font_size * 0.8, // 基线对齐
            width: estimated_width,
            height: font_size,
            text: text.clone(),
            color: final_color,
            font_size,
            bold,
            z_index: z_index + 2,
        });
    }
    
    // 递归处理子节点
    // 计算 effective_opacity（如果节点有 opacity 样式）
    let node_opacity = if let Some(opacity_str) = get_style(&node.styles, "opacity") {
        opacity_str.parse::<f32>().unwrap_or(1.0)
    } else {
        1.0
    };
    let effective_opacity = inherited_opacity * node_opacity;
    
    let mut child_y = node_y + padding_top;
    if let Some(gap_str) = get_style(&node.styles, "gap") {
        let gap = parse_px_single(gap_str);
        for (i, child) in node.children.iter().enumerate() {
            if i > 0 {
                child_y += gap;
            }
            
            let child_height = estimate_child_height(child);
            layout_node(
                child,
                &LayoutContext {
                    parent_x: node_x + padding_left,
                    parent_y: child_y,
                    parent_width: ctx.parent_width - padding_left * 2.0,
                    parent_height: child_height,
                },
                commands,
                z_index + 1,
                effective_opacity, // 传递继承的 opacity
            );
            child_y += child_height;
        }
    } else {
        for child in &node.children {
            let child_height = estimate_child_height(child);
            layout_node(
                child,
                &LayoutContext {
                    parent_x: node_x + padding_left,
                    parent_y: child_y,
                    parent_width: ctx.parent_width - padding_left * 2.0,
                    parent_height: child_height,
                },
                commands,
                z_index + 1,
                effective_opacity, // 传递继承的 opacity
            );
            child_y += child_height;
        }
    }
}

/// 估算子节点高度（修复：考虑 border 和完整 margin）
fn estimate_child_height(node: &ComponentNode) -> f32 {
    let mut height = 0.0;
    
    // 解析 margin（使用新的 parse_px）
    if let Some(margin_str) = get_style(&node.styles, "margin") {
        let (margin_top, _, margin_bottom, _) = parse_px(margin_str);
        height += margin_top + margin_bottom;
    } else {
        // 兼容独立属性
        if let Some(margin_top_str) = get_style(&node.styles, "margin-top") {
            height += parse_px_single(margin_top_str);
        }
        if let Some(margin_bottom_str) = get_style(&node.styles, "margin-bottom") {
            height += parse_px_single(margin_bottom_str);
        }
    }
    
    // 解析 border（影响高度）
    if let Some(border_str) = get_style(&node.styles, "border") {
        // 简化处理：假设边框宽度为 1px，上下各 1px
        height += 2.0;
    }
    
    // 文本节点高度
    if let Some(font_size_str) = get_style(&node.styles, "font-size") {
        let font_size = parse_px_single(font_size_str);
        if node.text.is_some() {
            // 文本高度 = font_size * line_height (约 1.2-1.4)
            let line_height = get_style(&node.styles, "line-height")
                .map(|h| parse_px_single(h))
                .unwrap_or(font_size * 1.4);
            height += line_height;
            return height;
        }
    }
    
    // 解析 padding
    if let Some(padding_str) = get_style(&node.styles, "padding") {
        let (padding_top, _, padding_bottom, _) = parse_px(padding_str);
        height += padding_top + padding_bottom;
        
        // 如果有内容，加上内容高度估算
        if !node.children.is_empty() {
            // 子元素总高度
            for child in &node.children {
                height += estimate_child_height(child);
            }
        } else if node.text.is_none() {
            // 没有文本和子元素，给一个默认内容高度
            height += 50.0;
        }
        
        return height;
    }
    
    // 默认高度
    if height == 0.0 {
        height = 100.0;
    }
    
    height
}

// ============================================
// 5. 主渲染流程
// ============================================

/// 渲染 Vue 应用
fn render_vue_app() -> Vec<DrawCommand> {
    let mut commands = Vec::new();
    
    // 构建组件树
    let app_tree = build_app_component_tree();
    
    // 视口尺寸
    let viewport_width = 1024.0;
    let viewport_height = 768.0;
    
    // 执行布局计算
    layout_node(
        &app_tree,
        &LayoutContext {
            parent_x: 0.0,
            parent_y: 0.0,
            parent_width: viewport_width,
            parent_height: viewport_height,
        },
        &mut commands,
        0,
        1.0, // 初始 opacity 为 1.0
    );
    
    commands
}

// ============================================
// 6. 实际项目关键实现说明
// ============================================

/// 实际项目中的 Text Measurer 注册
/// 
/// 在 iris-engine 初始化时，会注册精确的文字测量函数：
/// 
/// ```rust
/// // crates/iris-engine/src/orchestrator/core.rs:2674-2685
/// iris_layout::layout::set_text_measurer(Box::new(move |text: &str, font_size_param: f32| {
///     // 按比例缩放字符宽度：ASCII 0.6em，非ASCII 1.0em
///     text.chars()
///         .map(|c| {
///             let base_width = if c.is_ascii() { 0.6 } else { 1.0 };
///             font_size_param * base_width
///         })
///         .sum::<f32>()
/// }));
/// ```
/// 
/// 本示例使用更精确的 measure_text() 函数（包含 CJK 检测），
/// 但核心逻辑与实际项目一致：区分 ASCII 和非 ASCII 字符。

/// Emoji Fallback 字体加载
/// 
/// 实际项目会在初始化时加载 Emoji 字体：
/// 
/// ```rust
/// // crates/iris-engine/src/orchestrator/core.rs:2689-2711
/// let emoji_font_paths = if cfg!(target_os = "windows") {
///     vec![
///         "C:/Windows/Fonts/seguiemj.ttf",    // Segoe UI Emoji
///         "C:/Windows/Fonts/seguisym.ttf",    // Segoe UI Symbol
///     ]
/// } else if cfg!(target_os = "macos") {
///     vec![
///         "/System/Library/Fonts/Apple Color Emoji.ttc",
///     ]
/// } else {
///     vec![
///         "/usr/share/fonts/truetype/noto/NotoEmoji-Regular.ttf",
///     ]
/// };
/// 
/// for emoji_path in emoji_font_paths {
///     if let Ok(emoji_data) = std::fs::read(emoji_path) {
///         if let Some(emoji_font) = iris_gpu::SwashFont::from_bytes(&emoji_data) {
///             renderer.set_emoji_font(emoji_font);
///             info!(emoji_path, "Loaded emoji fallback font");
///             return;
///         }
///     }
/// }
/// ```
/// 
/// 这确保 Emoji 和特殊符号能正确渲染（如 ⚡ 🎨 🔤 🦀 等）。

/// Flex 布局引擎
/// 
/// 实际项目有完整的 Flex 布局引擎：
/// - 位置：`crates/iris-layout/src/layout.rs:778-920`（3425 行）
/// - 支持：flex-direction, justify-content, align-items, flex-wrap, gap
/// - 包含：compute_flex_row, compute_flex_column 等函数
/// 
/// 本示例简化了布局逻辑，仅用于演示流程。

// ============================================
// 7. 文本渲染核心逻辑（Font Atlas + Swash）
// ============================================

/// 字形数据（用于批渲染）
struct GlyphData {
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    uv: [f32; 4],
    is_color: bool,
}

/// 渲染文本到字形列表（模拟 Font Atlas 流程）
/// 
/// 这是 batch_renderer.rs 中 submit_text 函数的核心逻辑
fn render_text_to_glyphs(
    text: &str,
    x: f32,
    y: f32,
    font_size: f32,
    atlas_font_size: f32,
    font_ascent: f32,
) -> Vec<GlyphData> {
    let mut glyphs = Vec::new();
    
    // 计算字体大小缩放比例（关键修复！）
    let scale = font_size / atlas_font_size;
    
    // 基线 Y = 容器顶部 Y + 字体 ascent * scale
    let baseline_y = y + font_ascent * scale;
    
    let mut cursor_x = x;
    let mut cursor_y = baseline_y;
    
    // 遍历每个字符
    for ch in text.chars() {
        if ch == '\n' {
            cursor_x = x;
            cursor_y += atlas_font_size * 1.2; // line_height
            continue;
        }
        
        // 模拟字形光栅化（实际调用 font_atlas.get_or_rasterize_glyph）
        // 这里简化为假想的字形数据
        let glyph_width = 10.0 * scale;
        let glyph_height = 15.0 * scale;
        let glyph_ymin = -12.0 * scale; // 负值表示在基线上方
        
        if glyph_width > 0.0 && glyph_height > 0.0 {
            // 字形 Y 坐标 = 基线 Y + ymin * scale
            // ymin 为负，所以实际上是 baseline_y - |ymin| * scale
            let gy = cursor_y + glyph_ymin;
            
            glyphs.push(GlyphData {
                x: cursor_x,
                y: gy,
                width: glyph_width,
                height: glyph_height,
                uv: [0.0, 0.0, 1.0, 1.0], // 简化 UV
                is_color: false,
            });
            
            // 移动光标
            cursor_x += glyph_width * 1.2; // advance_width
        }
    }
    
    glyphs
}

// ============================================
// 7. 示例：渲染完整页面
// ============================================

fn main() {
    println!("=== Vue Demo 渲染流程示例 ===\n");
    
    // 1. 生成绘制命令
    let commands = render_vue_app();
    
    println!("生成 {} 个绘制命令\n", commands.len());
    
    // 2. 打印前 20 个命令
    for (i, cmd) in commands.iter().take(20).enumerate() {
        match cmd {
            DrawCommand::Rect { x, y, width, height, color, z_index } => {
                println!("[{}] Rect: pos=({:.1}, {:.1}), size={:.1}x{:.1}, color=RGB({:.2},{:.2},{:.2}), z={}",
                    i, x, y, width, height, color[0], color[1], color[2], z_index);
            }
            DrawCommand::GradientRect { x, y, width, height, start_color, end_color, horizontal, z_index } => {
                println!("[{}] GradientRect: pos=({:.1}, {:.1}), size={:.1}x{:.1}, {} gradient, z={}",
                    i, x, y, width, height, if *horizontal { "horizontal" } else { "vertical" }, z_index);
            }
            DrawCommand::Text { x, y, text, font_size, color, bold, z_index, .. } => {
                println!("[{}] Text: pos=({:.1}, {:.1}), \"{}\", font_size={:.1}, color=RGB({:.2},{:.2},{:.2}), bold={}, z={}",
                    i, x, y, text, font_size, color[0], color[1], color[2], bold, z_index);
            }
            DrawCommand::RoundedRect { x, y, width, height, radius, color, z_index } => {
                println!("[{}] RoundedRect: pos=({:.1}, {:.1}), size={:.1}x{:.1}, radius={:.1}, z={}",
                    i, x, y, width, height, radius, z_index);
            }
            DrawCommand::Border { x, y, width, height, border_width, border_color, z_index } => {
                println!("[{}] Border: pos=({:.1}, {:.1}), size={:.1}x{:.1}, width=({:.1},{:.1},{:.1},{:.1}), z={}",
                    i, x, y, width, height, border_width.0, border_width.1, border_width.2, border_width.3, z_index);
            }
        }
    }
    
    if commands.len() > 20 {
        println!("\n... 还有 {} 个命令", commands.len() - 20);
    }
    
    // 3. 演示文本渲染流程
    println!("\n=== 文本渲染示例 ===");
    let sample_text = "Iris Runtime";
    let font_size = 52.0;
    let atlas_font_size = 48.0;
    let font_ascent = 38.4; // font_size * 0.8
    
    let glyphs = render_text_to_glyphs(
        sample_text,
        100.0,  // x
        50.0,   // y
        font_size,
        atlas_font_size,
        font_ascent,
    );
    
    println!("\n文本: \"{}\" (font_size={})", sample_text, font_size);
    println!("图集字体大小: {}", atlas_font_size);
    println!("缩放比例: {:.3}", font_size / atlas_font_size);
    println!("基线 Y: {:.1}", 50.0 + font_ascent * (font_size / atlas_font_size));
    println!("\n生成 {} 个字形:", glyphs.len());
    for (i, g) in glyphs.iter().take(5).enumerate() {
        println!("  [{}] char='{}', pos=({:.1}, {:.1}), size={:.1}x{:.1}",
            i, sample_text.chars().nth(i).unwrap_or('?'),
            g.x, g.y, g.width, g.height);
    }
    
    println!("\n=== 关键修复说明 ===");
    println!("1. submit_text 函数添加了 font_size 参数");
    println!("2. 缩放比例计算: scale = font_size / atlas_font_size");
    println!("3. 基线对齐: baseline_y = y + font_ascent * scale");
    println!("4. 字形坐标: gy = baseline_y + ymin * scale (ymin 为负)");
    println!("\n这修复了文字重叠和截断问题！");
}
