# {{APP_NAME}} - message handlers (Async Mode)

init_handlers <- function(app) {

  # -- Ready -----------------------------------------------------------------
  app$on_ready(function() {
    app$set_menu(list(
      File = list(
        "Refresh"   = function() app$send("refresh", list()),
        "---",
        "Exit"      = app$quit
      ),
      Help = list(
        "About"     = function() {
          app$toast("{{APP_TITLE}} v1.0.0 - built with RDesk", type = "info")
        }
      )
    ))
    # Send initial data to UI
    df <- init_data()
    if (!is.null(df)) {
      res <- RDesk::rdesk_df_to_list(df)
      res$kpis <- get_app_kpis(df)
      app$send("data_ready", res)
    }
  })

  # -- Main data handler -----------------------------------------------------
  app$on_message("get_data", async(function(payload) {
    df <- init_data()
    # If viz_type is mixed or charts, include chart
    chart_b64 <- if ("{{VIZ_TYPE}}" %in% c("mixed", "charts")) make_chart(df) else NULL
    res <- RDesk::rdesk_df_to_list(df)
    res$chart <- chart_b64
    res$kpis  <- get_app_kpis(df)
    res
  }, app = app, loading_message = "Loading data..."))

  # -- Filter handler --------------------------------------------------------
  app$on_message("filter", async(function(payload) {
    df  <- init_data()
    val <- payload$value
    if (!is.null(val) && nzchar(val) && val != "all") {
      df <- df[as.character(df[[payload$column]]) == as.character(val), ]
    }
    list(
      data  = RDesk::rdesk_df_to_list(df),
      chart = if ("{{VIZ_TYPE}}" %in% c("mixed", "charts")) make_chart(df) else NULL,
      count = nrow(df),
      kpis  = get_app_kpis(df)
    )
  }, app = app, loading_message = "Filtering..."))
}
