use std::{cell::RefCell, rc::Rc};

use ratzilla::{
    backend::canvas::CanvasBackendOptions,
    event::KeyCode,
    ratatui::{
        widgets::{Block, Borders},
        Terminal,
    },
    web_sys, CanvasBackend, WebRenderer,
};
use wasm_bindgen::prelude::*;

mod utils;

use crate::app::App;

#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);
}

#[wasm_bindgen]
pub fn run(grid_id: &str) {
    console_error_panic_hook::set_once();

    let backend = CanvasBackend::new_with_options(
        CanvasBackendOptions::new()
            .grid_id(grid_id)
            .font(String::from("16px Fira Code")),
    )
    .unwrap();
    let terminal = Terminal::new(backend).unwrap();

    let app = Rc::new(RefCell::new(App::new()));

    terminal.on_key_event({
        let app = Rc::clone(&app);
        move |event| match event.code {
            KeyCode::Left => app.borrow_mut().prev_tab(),
            KeyCode::Right => app.borrow_mut().next_tab(),
            KeyCode::Char(c) => app.borrow_mut().add_char_to_number_guess(c),
            _ => {}
        }
    });

    terminal.draw_web({
        let app = Rc::clone(&app);
        move |frame| app.borrow_mut().draw(frame)
    })
}
