if (getRversion() >= "2.15.1") {
  utils::globalVariables(c(
    "Cpc", "alpha_factor", "avg_width", "cdf", "density", "empirical",
    "empirical_coverage", "estimate", "hpd_95_lower", "hpd_95_upper", "index",
    "iter", "lower", "nominal_coverage", "p0", "pdf", "posterior_mean",
    "ppoints", "replicate", "runif", "stack", "theoretical", "upper", "value", "x",
    "data_left", "data_right", "left", "right"
  ))
}

#' Safe Numerical Integration for Interval-Censored Analysis
#'
#' A robust wrapper around \code{stats::integrate} that handles vectorization,
#' infinite bounds, and numerical exceptions gracefully.
#'
#' @param f A function to integrate.
#' @param lower Lower limit of integration.
#' @param upper Upper limit of integration.
#' @param ... Additional arguments passed to \code{f}.
#' @return A numeric value representing the integral.
#' @keywords internal
safe_integrate_censor <- function(f, lower, upper, ...) {
  vf <- Vectorize(function(x) {
    val <- tryCatch(f(x, ...), error = function(e) 0)
    if (is.na(val) || !is.finite(val)) 0 else val
  })
  
  res <- tryCatch({
    stats::integrate(vf, lower = lower, upper = upper, rel.tol = 1e-8, stop.on.error = FALSE)
  }, error = function(e) {
    NULL
  })
  
  if (is.null(res) || inherits(res, "error") || (res$message != "OK" && res$message != "subdivisions limit exceeded")) {
    if (is.finite(lower) && is.finite(upper)) {
      grid <- seq(lower, upper, length.out = 1000)
      y <- vf(grid)
      w <- (upper - lower) / 999
      val <- sum(y[-1] + y[-length(y)]) * w / 2
      return(if (is.na(val) || !is.finite(val)) 0 else val)
    } else {
      return(0)
    }
  }
  val <- res$value
  if (is.na(val) || !is.finite(val)) 0 else val
}

#' Safe Root Finding for Quantile Inversion
#'
#' A robust wrapper around \code{stats::uniroot} that finds roots for CDF or quantile inversion.
#'
#' @param f A function whose root is to be found.
#' @param interval A vector containing the end-points of the interval to be searched.
#' @param ... Additional arguments passed to \code{f}.
#' @return A numeric value of the root.
#' @keywords internal
safe_uniroot_censor <- function(f, interval, ...) {
  if (any(is.na(interval)) || any(!is.finite(interval)) || interval[1] >= interval[2]) {
    interval <- c(-1e3, 1e3)
  }
  res <- tryCatch({
    stats::uniroot(f, interval = interval, tol = 1e-8, extendInt = "yes")$root
  }, error = function(e) {
    x_grid <- seq(interval[1], interval[2], length.out = 100)
    y_grid <- sapply(x_grid, function(val) {
      v <- tryCatch(f(val, ...), error = function(err) NA)
      if (is.na(v) || !is.finite(v)) 1e10 else v
    })
    signs <- sign(y_grid)
    zero_crossings <- which(signs[-1] != signs[-length(signs)])
    if (length(zero_crossings) > 0) {
      idx <- zero_crossings[1]
      tryCatch({
        stats::uniroot(f, interval = c(x_grid[idx], x_grid[idx+1]), tol = 1e-8)$root
      }, error = function(err) {
        x_grid[which.min(abs(y_grid))]
      })
    } else {
      x_grid[which.min(abs(y_grid))]
    }
  })
  if (is.na(res) || !is.finite(res)) mean(interval) else res
}

#' Safe Numerical Differentiation
#'
#' A wrapper around \code{numDeriv::grad} with fallback to finite differences.
#'
#' @param f A function to differentiate.
#' @param x The point(s) at which to differentiate.
#' @param ... Additional arguments passed to \code{f}.
#' @return The numerical derivative at \code{x}.
#' @keywords internal
safe_deriv_censor <- function(f, x, ...) {
  res <- tryCatch({
    numDeriv::grad(f, x, ...)
  }, error = function(e) {
    h <- 1e-5
    (f(x + h, ...) - f(x - h, ...)) / (2 * h)
  })
  if (is.na(res) || !is.finite(res)) 0 else res
}

#' Helper to Round Numeric Columns of a Data Frame
#'
#' @param x A data frame.
#' @param digits Integer specifying digits.
#' @return Data frame with rounded numeric columns.
#' @keywords internal
round_df_censor <- function(x, digits) {
  numeric_cols <- sapply(x, is.numeric)
  x[numeric_cols] <- lapply(x[numeric_cols], round, digits = digits)
  x
}
