use cvkg_render_gpu::{
    SurtrRenderer, ShieldWallAdapter,
    ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler,
    Node, NodeId, Role, Tree, TreeId, TreeUpdate,
};
use cvkg_core::Rect;
use std::sync::Arc;
use winit::{
    application::ApplicationHandler,
    event::WindowEvent,
    event_loop::{ActiveEventLoop, EventLoop},
    window::{Window, WindowId},
};

struct NiflheimApp {
    window:     Option<Arc<Window>>,
    renderer:   Option<SurtrRenderer>,
    /// ShieldWall — OS accessibility adapter (AccessKit backend)
    shieldwall: Option<ShieldWallAdapter>,
}

struct ShieldWallActivation(NodeId);
impl ActivationHandler for ShieldWallActivation {
    fn request_initial_tree(&mut self) -> Option<TreeUpdate> {
        let root_id = self.0;
        Some(TreeUpdate {
            nodes: vec![(root_id, {
                let mut n = Node::new(Role::Window);
                n.set_label("Niflheim Mist Demo");
                n
            })],
            tree: Some(Tree::new(root_id)),
            tree_id: TreeId::ROOT,
            focus: root_id,
        })
    }
}

struct ShieldWallAction;
impl ActionHandler for ShieldWallAction {
    fn do_action(&mut self, _request: ActionRequest) {}
}

struct ShieldWallDeactivation;
impl DeactivationHandler for ShieldWallDeactivation {
    fn deactivate_accessibility(&mut self) {}
}

impl ApplicationHandler for NiflheimApp {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        // Window must be initially invisible so ShieldWall can be created
        // before first show (AccessKit requirement).
        let window = Arc::new(
            event_loop
                .create_window(
                    Window::default_attributes()
                        .with_title("Niflheim Mist Demo — CVKG Phase 6")
                        .with_inner_size(winit::dpi::LogicalSize::new(800u32, 600u32))
                        .with_visible(false),
                )
                .unwrap(),
        );

        // Build the ShieldWall adapter with a root Window node.
        let root_id = NodeId(1);
        let shieldwall = ShieldWallAdapter::with_direct_handlers(
            event_loop,
            &window,
            ShieldWallActivation(root_id),
            ShieldWallAction,
            ShieldWallDeactivation,
        );

        // Now safe to show the window.
        window.set_visible(true);

        let renderer = pollster::block_on(SurtrRenderer::forge(window.clone()));
        self.window     = Some(window);
        self.renderer   = Some(renderer);
        self.shieldwall = Some(shieldwall);
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
        let renderer = match self.renderer.as_mut() { Some(r) => r, None => return };
        match event {
            WindowEvent::CloseRequested => {
                event_loop.exit();
            }
            WindowEvent::RedrawRequested => {
                let encoder = renderer.begin_frame();


                // ── Background void ──────────────────────────────────────────
                renderer.fill_rect(
                    Rect { x: 0.0, y: 0.0, width: 800.0, height: 600.0 },
                    [0.0, 0.0, 0.0, 1.0], // Ginnungagap — the primordial void, true black
                    0,
                );

                // ── Card body (dark, transparent — mode 0) ───────────────────
                renderer.fill_rect(
                    Rect { x: 80.0, y: 60.0, width: 640.0, height: 480.0 },
                    [0.05, 0.03, 0.12, 1.0], // Dark card background
                    0,
                );

                // ── NEON BORDER — top edge (Mode 1 = Gungnir Glow) ──────────
                renderer.fill_rect(
                    Rect { x: 80.0, y: 60.0, width: 640.0, height: 3.0 },
                    [0.0, 0.9, 1.0, 1.0], // Hot NiflCyan
                    1,
                );
                // Bottom edge
                renderer.fill_rect(
                    Rect { x: 80.0, y: 537.0, width: 640.0, height: 3.0 },
                    [0.0, 0.9, 1.0, 1.0],
                    1,
                );
                // Left edge
                renderer.fill_rect(
                    Rect { x: 80.0, y: 60.0, width: 3.0, height: 480.0 },
                    [0.0, 0.9, 1.0, 1.0],
                    1,
                );
                // Right edge
                renderer.fill_rect(
                    Rect { x: 717.0, y: 60.0, width: 3.0, height: 480.0 },
                    [0.0, 0.9, 1.0, 1.0],
                    1,
                );

                // ── Header accent line ───────────────────────────────────────
                renderer.fill_rect(
                    Rect { x: 80.0, y: 110.0, width: 640.0, height: 2.0 },
                    [0.8, 0.0, 1.0, 1.0], // Seiðr Magenta
                    1,
                );

                // ── Corner accent dots ───────────────────────────────────────
                for (cx, cy) in [(80.0f32, 60.0f32), (714.0, 60.0), (80.0, 534.0), (714.0, 534.0)] {
                    renderer.fill_rect(
                        Rect { x: cx, y: cy, width: 6.0, height: 6.0 },
                        [1.0, 0.6, 0.0, 1.0], // Surtr Orange
                        1,
                    );
                }

                // ── Horizontal divider lines (inner cards) ───────────────────
                renderer.fill_rect(
                    Rect { x: 100.0, y: 160.0, width: 280.0, height: 2.0 },
                    [0.0, 0.7, 0.9, 0.8],
                    1,
                );
                renderer.fill_rect(
                    Rect { x: 420.0, y: 160.0, width: 280.0, height: 2.0 },
                    [0.8, 0.0, 1.0, 0.8],
                    1,
                );

                // ── Progress/status bars ─────────────────────────────────────
                // Bar background
                renderer.fill_rect(
                    Rect { x: 100.0, y: 400.0, width: 600.0, height: 16.0 },
                    [0.08, 0.05, 0.18, 1.0],
                    0,
                );
                // Bar fill (glow)
                renderer.fill_rect(
                    Rect { x: 100.0, y: 400.0, width: 420.0, height: 16.0 },
                    [0.0, 0.85, 1.0, 1.0],
                    1,
                );

                // Second bar
                renderer.fill_rect(
                    Rect { x: 100.0, y: 430.0, width: 600.0, height: 12.0 },
                    [0.08, 0.05, 0.18, 1.0],
                    0,
                );
                renderer.fill_rect(
                    Rect { x: 100.0, y: 430.0, width: 180.0, height: 12.0 },
                    [1.0, 0.2, 0.5, 1.0], // Valkyrie Pink
                    1,
                );

                // Third bar
                renderer.fill_rect(
                    Rect { x: 100.0, y: 455.0, width: 600.0, height: 12.0 },
                    [0.08, 0.05, 0.18, 1.0],
                    0,
                );
                renderer.fill_rect(
                    Rect { x: 100.0, y: 455.0, width: 310.0, height: 12.0 },
                    [1.0, 0.5, 0.0, 1.0], // Surtr Orange
                    1,
                );

                // ── Quench the blade ─────────────────────────────────────────
                renderer.end_frame(encoder);
            }
            _ => {}
        }
    }
}

fn main() {
    let event_loop = EventLoop::new().unwrap();
    let mut app = NiflheimApp { window: None, renderer: None, shieldwall: None };
    event_loop.run_app(&mut app).unwrap();
}
