#' Kaplan-Meier plot by group
#'
#' @param data A data frame.
#' @param time Name of duration/time variable.
#' @param event Name of event variable: 1 = event occurred, 0 = censored.
#' @param group Name of grouping variable.
#'
#' @return A survminer ggsurvplot object.
#' @export
plot_km_by_delay <- function(data, time, event, group) {

  if (!requireNamespace("survival", quietly = TRUE)) {
    stop("Package 'survival' is required.")
  }

  if (!requireNamespace("survminer", quietly = TRUE)) {
    stop("Package 'survminer' is required.")
  }

  plot_data <- data.frame(
    time_var  = data[[time]],
    event_var = data[[event]],
    group_var = as.factor(data[[group]])
  )

  fit <- survival::survfit(
    survival::Surv(time_var, event_var) ~ group_var,
    data = plot_data
  )

  survminer::ggsurvplot(
    fit,
    data = plot_data,
    risk.table = TRUE,
    conf.int = TRUE,
    pval = TRUE,
    legend.title = "Group",
    legend.labs = levels(plot_data$group_var),
    xlab = "Days until threshold breach",
    ylab = "Probability of remaining below threshold"
  )
}
