//! 纯底层渲染测试（不依赖 Vue SFC）
//!
//! 直接创建 VTree → DOM 树 → 布局 → GPU 渲染
//! 测试：文本渲染、图形渲染、布局系统
//!
//! ```bash
//! cargo run --example font_render_test -p iris-engine
//! ```
//!
//! ## 测试记录
//!
//! - [2026-05-05] 居中正方形测试 ✅ 通过
//!   用例：800x600 根容器 + 200x200 蓝色方块，
//!   flex row + justify-content:center + align-items:center
//!   结果：水平垂直均居中
//!   修复：flex row cross_size 从子元素 height 中正确取值

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},
};

// 辅助宏：创建单 key-value 对的 HashMap
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_test_vtree() -> VTree {
    // 在屏幕中心绘制一个 200x200 的蓝色正方形
    VTree {
        root: VNode::Element(VElement {
            tag: "div".to_string(),
            attrs: attrs![
                "style" => "background: #11111B; width: 800px; height: 600px; display: flex; flex-direction: row; justify-content: center; align-items: center;"
            ],
            children: vec![
                VNode::Element(VElement {
                    tag: "div".to_string(),
                    attrs: attrs![
                        "style" => "background: #89B4FA; width: 200px; height: 200px;"
                    ],
                    children: vec![],
                    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");

        // 直接创建 VTree（完全脱离 Vue SFC）
        let vtree = create_test_vtree();
        orchestrator.set_vtree(vtree);
        info!("✅ VTree set directly (no Vue SFC)");

        // 初始化 CSSOM 以确保样式计算正常
        orchestrator.add_css_stylesheet("main", "");

        orchestrator.set_viewport_size(800.0, 600.0);
        match orchestrator.compute_layout() {
            Ok(_) => info!("✅ Layout computed"),
            Err(e) => info!("⚠️  Layout error: {}", e),
        }

        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("Pure Render Test - No Vue")
                        .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!("🎯 Pure Render Test - No Vue SFC");
    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");
}
