
use std::f64;
use leptos::html::Canvas;
use leptos::*;
use wasm_bindgen::JsCast;

#[component]
pub fn Background(cx: Scope) -> impl IntoView {
    let canvas = create_node_ref::<Canvas>(cx);

    canvas.on_load(cx, move |_| {
        log!("in canvas");
        let context = canvas
            .get()
            .expect("canvas is mounted")
            .get_context("2d")
            .ok()
            .flatten()
            .expect("canvas to have context")
            .unchecked_into::<web_sys::CanvasRenderingContext2d>();
        log!("context = {:#?}", context);
        context.begin_path();

        // Draw the outer circle.
        context
            .arc(75.0, 75.0, 50.0, 0.0, f64::consts::PI * 2.0)
            .unwrap();

        // Draw the mouth.
        context.move_to(110.0, 75.0);
        context.arc(75.0, 75.0, 35.0, 0.0, f64::consts::PI).unwrap();

        // Draw the left eye.
        context.move_to(65.0, 65.0);
        context
            .arc(60.0, 65.0, 5.0, 0.0, f64::consts::PI * 2.0)
            .unwrap();

        // Draw the right eye.
        context.move_to(95.0, 65.0);
        context
            .arc(90.0, 65.0, 5.0, 0.0, f64::consts::PI * 2.0)
            .unwrap();

        context.stroke();
    });
    view! { cx,
        <div class="canvas border-solid border-white border-2 fixed h-screen w-screen">
            <canvas node_ref=canvas></canvas>
        </div>
    }
}

// #[component]
// fn ComponentA(cx: Scope) -> impl IntoView {
//     let canvas = NodeRef::<HtmlElement<Canvas>>::new(cx);
//     let on_click = move |_| {
//         // checks to see if node has been rendered
//         let context = canvas.get()
//             // if you're able to click the button, canvas should already be there
//             .expect("canvas to have been mounted")
//             // here's the getContext() call
//             .get_context("2d")
//             // it returns Result<Option<Object>, ...>
//             // so we massage the types a little
//             .ok()
//             .flatten()
//             .expect("canvas to have context")
//             .unchecked_into::<web_sys::CanvasRenderingContext2d>();
//         leptos::log!("context = {:#?}", context);
//     };
//     view! { cx,
//         <button on:click=on_click>"Click me"</button>
//         <canvas node_ref=canvas></canvas>
//     }
// }
