///|
let timer : @app.Timer = @app.Timer::new()

///|
let tracker : @app.HabitTracker = @app.HabitTracker::new()

///|
let global_buffer : @tui.Buffer = @tui.Buffer::new(80, 24)

///|
pub fn init_web() -> Unit {
  tracker.add("Read 30 mins")
  tracker.add("Exercise")
  tracker.add("Write code")
}

///|
pub fn timer_tick() -> Unit {
  timer.tick()
}

///|
pub fn timer_start() -> Unit {
  timer.start()
}

///|
pub fn timer_pause() -> Unit {
  timer.pause()
}

///|
pub fn timer_reset() -> Unit {
  timer.reset()
}

///|
pub fn timer_get_seconds() -> Int {
  timer.remaining_seconds
}

///|
pub fn timer_get_state() -> Int {
  match timer.state {
    Focus => 0
    ShortBreak => 1
    LongBreak => 2
  }
}

///|
pub fn timer_set_state(state_val : Int) -> Unit {
  let state = match state_val {
    0 => @app.TimerState::Focus
    1 => @app.TimerState::ShortBreak
    _ => @app.TimerState::LongBreak
  }
  timer.set_state(state)
  timer.reset()
}

///|
pub fn timer_is_running() -> Bool {
  timer.is_running
}

///|
pub fn tracker_get_count() -> Int {
  tracker.habits.length()
}

///|
pub fn tracker_get_selected() -> Int {
  tracker.selected_index
}

///|
pub fn tracker_toggle_index(idx : Int) -> Unit {
  if idx >= 0 && idx < tracker.habits.length() {
    tracker.habits[idx].toggle()
  }
}

///|
pub fn tracker_select_next() -> Unit {
  tracker.select_next()
}

///|
pub fn tracker_select_prev() -> Unit {
  tracker.select_prev()
}

///|
pub fn tracker_toggle_current() -> Unit {
  tracker.toggle_current()
}

///|
pub fn tracker_get_completed(idx : Int) -> Bool {
  if idx >= 0 && idx < tracker.habits.length() {
    tracker.habits[idx].completed
  } else {
    false
  }
}

///|
pub fn tracker_add_habit_placeholder() -> Unit {
  tracker.add("")
}

///|
pub fn render_tui_to_buffer() -> Unit {
  @app.render_app(timer, tracker, global_buffer, 80, 24)
}

///|
pub fn get_tui_char(x : Int, y : Int) -> Int {
  if x >= 0 && x < 80 && y >= 0 && y < 24 {
    global_buffer.cells[y * 80 + x].ch.to_int()
  } else {
    32
  }
}

///|
pub fn get_tui_fg_color(x : Int, y : Int) -> Int {
  if x >= 0 && x < 80 && y >= 0 && y < 24 {
    let cell = global_buffer.cells[y * 80 + x]
    (cell.fg_r << 16) | (cell.fg_g << 8) | cell.fg_b
  } else {
    0xffffff
  }
}

///|
pub fn get_tui_bg_color(x : Int, y : Int) -> Int {
  if x >= 0 && x < 80 && y >= 0 && y < 24 {
    let cell = global_buffer.cells[y * 80 + x]
    (cell.bg_r << 16) | (cell.bg_g << 8) | cell.bg_b
  } else {
    0
  }
}

///|
fn main {
  ()
}