use egui::Theme;
use tracing::debug;
use wxbox_client::ui::tokens::DESIGN_TOKENS;

#[cfg(not(target_arch = "wasm32"))]
fn main() -> eframe::Result {
    tracing_subscriber::fmt::init();

    let native_options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default(),
        multisampling: 8,
        ..Default::default()
    };

    debug!("{:?}", DESIGN_TOKENS.get_color("colors.bg", Theme::Dark));

    eframe::run_native(
        "wxbox",
        native_options,
        Box::new(|cc| Ok(Box::new(wxbox_client::app::App::new(cc)))),
    )
}

#[cfg(target_arch = "wasm32")]
fn main() {
    use tracing::Level;
    use tracing_subscriber::fmt::format::Pretty;
    use tracing_subscriber::prelude::*;
    use tracing_web::{performance_layer, MakeWebConsoleWriter};

    console_error_panic_hook::set_once();

    let fmt_layer = tracing_subscriber::fmt::layer()
        .with_ansi(false) // not supported in browsers
        .without_time() // std::time doesn't exist in wasm
        .with_writer(MakeWebConsoleWriter::new().with_max_level(Level::DEBUG)); // wgpu spams the console, and this is slow as hell

    let perf_layer = performance_layer() // enable performance tracing
        .with_details_from_fields(Pretty::default()); // ... with pretty fields

    tracing_subscriber::registry()
        .with(fmt_layer)
        .with(perf_layer)
        .init(); // register the logger

    use eframe::wasm_bindgen::JsCast as _;

    let web_options = eframe::WebOptions::default();

    wasm_bindgen_futures::spawn_local(async {
        let document = web_sys::window()
            .expect("No window")
            .document()
            .expect("No document");

        let canvas = document
            .get_element_by_id("the_canvas_id")
            .expect("Failed to find the_canvas_id")
            .dyn_into::<web_sys::HtmlCanvasElement>()
            .expect("the_canvas_id was not a HtmlCanvasElement");

        let start_result = eframe::WebRunner::new()
            .start(
                canvas,
                web_options,
                Box::new(|cc| Ok(Box::new(wxbox_client::app::App::new(cc)))),
            )
            .await;

        // Remove the loading text and spinner:
        if let Some(loading_text) = document.get_element_by_id("loading_text") {
            match start_result {
                Ok(_) => {
                    loading_text.remove();
                }
                Err(e) => {
                    loading_text.set_inner_html(
                        "<p> The app has crashed. See the developer console for details. </p>",
                    );
                    panic!("Failed to start eframe: {e:?}");
                }
            }
        }
    });
}
