//! 长方形布局定位测试（不依赖 Vue SFC）
//!
//! 在窗口中绘制 5 个彩色长方形，除了居中白色矩形外，
//! 其余 4 个各有一个顶点与窗口四角重叠：
//!   左上(红) — 顶点重叠 (0,0)
//!   右上(蓝) — 顶点重叠 (800,0)
//!   居中(白) — 不与任何角重叠
//!   左下(绿) — 顶点重叠 (0,600)
//!   右下(紫) — 顶点重叠 (800,600)
//!
//! 测试：flex row/column 组合布局 + justify-content space-between 将元素推到四角
//!
//! ```bash
//! cargo run --example rect_layout_test -p iris-engine
//! ```

use iris_engine::orchestrator::RuntimeOrchestrator;
use iris_gpu::Renderer;
use iris_layout::vdom::{VElement, VNode, VTree};
use tracing::info;
use winit::{
    application::ApplicationHandler,
    event::{ElementState, KeyEvent, WindowEvent},
    event_loop::{ActiveEventLoop, EventLoop},
    keyboard::{Key, NamedKey},
    window::{Window, WindowId},
};

macro_rules! attrs {
    ($($k:expr => $v:expr),*) => {{
        let mut m = std::collections::HashMap::new();
        $(m.insert($k.to_string(), $v.to_string());)*
        m
    }};
}

fn create_rect_layout_vtree() -> VTree {
    // 窗口 800x600，分为上中下三行
    // 上行 150px：红(200x150)靠左，蓝(200x150)靠右 — 顶点分别重叠左右上角
    // 中行 250px：白(180x150)居中 — 不与角重叠
    // 下行 200px：绿(150x200)靠左，紫(150x200)靠右 — 顶点分别重叠左右下角
    VTree {
        root: VNode::Element(VElement {
            tag: "div".to_string(),
            attrs: attrs![
                "style" => "background: #1a1a2e; width: 800px; height: 600px; display: flex; flex-direction: column;"
            ],
            children: vec![
                // ── 上行：红(左上角) + 蓝(右上角) ──
                VNode::Element(VElement {
                    tag: "div".to_string(),
                    attrs: attrs![
                        "style" => "height: 150px; display: flex; flex-direction: row; justify-content: space-between;"
                    ],
                    children: vec![
                        // 红色横长方形 — 左上角，顶点重叠 (0,0)
                        VNode::Element(VElement {
                            tag: "div".to_string(),
                            attrs: attrs![
                                "style" => "width: 200px; height: 150px; background: #E06C75;"
                            ],
                            children: vec![],
                            key: None,
                        }),
                        // 蓝色横长方形 — 右上角，顶点重叠 (800,0)
                        VNode::Element(VElement {
                            tag: "div".to_string(),
                            attrs: attrs![
                                "style" => "width: 200px; height: 150px; background: #61AFEF;"
                            ],
                            children: vec![],
                            key: None,
                        }),
                    ],
                    key: None,
                }),
                // ── 中行：白(居中) ──
                VNode::Element(VElement {
                    tag: "div".to_string(),
                    attrs: attrs![
                        "style" => "height: 250px; display: flex; flex-direction: row; justify-content: center; align-items: center;"
                    ],
                    children: vec![
                        // 白色横长方形 — 居中
                        VNode::Element(VElement {
                            tag: "div".to_string(),
                            attrs: attrs![
                                "style" => "width: 180px; height: 150px; background: #E5E9F0;"
                            ],
                            children: vec![],
                            key: None,
                        }),
                    ],
                    key: None,
                }),
                // ── 下行：绿(左下角) + 紫(右下角) ──
                VNode::Element(VElement {
                    tag: "div".to_string(),
                    attrs: attrs![
                        "style" => "height: 200px; display: flex; flex-direction: row; justify-content: space-between;"
                    ],
                    children: vec![
                        // 绿色竖长方形 — 左下角，顶点重叠 (0,600)
                        VNode::Element(VElement {
                            tag: "div".to_string(),
                            attrs: attrs![
                                "style" => "width: 150px; height: 200px; background: #98C379;"
                            ],
                            children: vec![],
                            key: None,
                        }),
                        // 紫色竖长方形 — 右下角，顶点重叠 (800,600)
                        VNode::Element(VElement {
                            tag: "div".to_string(),
                            attrs: attrs![
                                "style" => "width: 150px; height: 200px; background: #C678DD;"
                            ],
                            children: vec![],
                            key: None,
                        }),
                    ],
                    key: None,
                }),
            ],
            key: None,
        }),
    }
}

struct App {
    window: Option<Window>,
    orchestrator: RuntimeOrchestrator,
    size: winit::dpi::PhysicalSize<u32>,
    suspended: bool,
    renderer_initialized: bool,
}

impl App {
    fn new() -> Self {
        let mut orchestrator = RuntimeOrchestrator::new();
        orchestrator.initialize().expect("Failed to initialize orchestrator");

        let vtree = create_rect_layout_vtree();
        orchestrator.set_vtree(vtree);
        orchestrator.add_css_stylesheet("main", "");

        orchestrator.set_viewport_size(800.0, 600.0);
        match orchestrator.compute_layout() {
            Ok(dom) => {
                info!("✅ Layout computed");
                // 调试：打印 DOM 树中的布局数据
                fn dump_layout(node: &iris_layout::dom::DOMNode, depth: usize) {
                    let indent = "  ".repeat(depth);
                    let tag = match &node.node_type {
                        iris_layout::dom::NodeType::Element(t) => t.clone(),
                        iris_layout::dom::NodeType::Text(t) => format!("text: '{}'", &t[..t.len().min(20)].to_string()),
                        _ => "?".to_string(),
                    };
                    let x = node.get_attribute("__layout_x").cloned().unwrap_or_default();
                    let y = node.get_attribute("__layout_y").cloned().unwrap_or_default();
                    let w = node.get_attribute("__layout_width").cloned().unwrap_or_default();
                    let h = node.get_attribute("__layout_height").cloned().unwrap_or_default();
                    let bg = node.computed_styles().and_then(|s| s.get("background").map(|v| v.clone())).unwrap_or_default();
                    info!("{}{} pos=({},{}) size=({}x{}) bg={:?}", indent, tag, x, y, w, h, bg);
                    for child in &node.children {
                        dump_layout(child, depth + 1);
                    }
                }
                dump_layout(dom, 0);
            },
            Err(e) => info!("⚠️  Layout error: {}", e),
        }

        // 生成并打印渲染命令
        let commands = orchestrator.generate_render_commands();
        for cmd in &commands {
            match cmd {
                iris_gpu::DrawCommand::Rect { x, y, width, height, color, .. } => {
                    info!("  DrawCommand::Rect x={} y={} w={} h={}", x, y, width, height);
                }
                _ => {}
            }
        }
        info!("Total render commands: {}", commands.len());

        Self {
            window: None,
            orchestrator,
            size: winit::dpi::PhysicalSize::new(800, 600),
            suspended: false,
            renderer_initialized: false,
        }
    }

    fn init_renderer_sync(&mut self) {
        if self.renderer_initialized { return; }
        if let Some(window) = self.window.take() {
            match pollster::block_on(Renderer::new(window)) {
                Ok(renderer) => {
                    self.orchestrator.set_gpu_renderer(renderer);
                    self.renderer_initialized = true;
                    info!("✅ GPU renderer initialized");
                    self.orchestrator.mark_dirty();
                }
                Err(e) => {
                    info!("❌ Failed to init GPU renderer: {}", e);
                    self.renderer_initialized = true;
                }
            }
        }
    }

    fn render(&mut self) {
        if self.suspended { return; }
        let rendered = self.orchestrator.render_frame_gpu();
        if rendered {
            info!("Frame rendered");
        }
    }
}

impl ApplicationHandler for App {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        self.suspended = false;
        if self.window.is_none() {
            let window = event_loop
                .create_window(
                    Window::default_attributes()
                        .with_title("Rect Layout Test")
                        .with_inner_size(winit::dpi::PhysicalSize::new(800, 600)),
                )
                .expect("Failed to create window");
            self.window = Some(window);
            self.size = winit::dpi::PhysicalSize::new(800, 600);
            self.init_renderer_sync();
        }
    }

    fn suspended(&mut self, _el: &ActiveEventLoop) {
        self.suspended = true;
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        _window_id: WindowId,
        event: WindowEvent,
    ) {
        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::KeyboardInput {
                event: KeyEvent { state: ElementState::Pressed, logical_key: Key::Named(NamedKey::Escape), .. },
                ..
            } => event_loop.exit(),
            WindowEvent::Resized(new_size) => {
                self.size = new_size;
                self.orchestrator.set_viewport_size(new_size.width as f32, new_size.height as f32);
                if let Err(e) = self.orchestrator.compute_layout() {
                    info!("Layout error: {}", e);
                }
                if let Some(renderer) = self.orchestrator.gpu_renderer_mut() {
                    renderer.resize(new_size);
                }
            }
            WindowEvent::RedrawRequested => {
                self.render();
                if self.orchestrator.is_dirty() {
                    if let Some(ref window) = self.window {
                        window.request_redraw();
                    }
                }
            }
            _ => {}
        }
    }
}

fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .init();

    info!("🎯 Rect Layout Test");
    info!("===================");

    let event_loop = EventLoop::new().expect("Failed to create event loop");
    let mut app = App::new();
    event_loop.run_app(&mut app).expect("Failed to run event loop");
}
