#' Calculate mean TRUE
#'
#' @param ... SpatRasters/SpatRaster list - logical - with time attribute
#' @returns SpatRaster - logical - with time attribute
#' @family Calculation
#' @keywords internal
#' @description Takes multiple logical SpatRasters with time attribute and
#' returns SpatRaster with the mean time serial number of first and last TRUE
#' value.

calc_mean <- function(...) {

  li <- list(...)

  if (methods::is(li[[1]], "list")) {

    if (length(li) == 1) li <- li[[1]] else stop("Cant calc_first of multiple lists!")

  }

  if (!methods::is(li[[1]], "SpatRaster")) stop("Input needs to be SpatRaster!")

  # take shared common time
  time <- lapply(li, terra::time)

  common <- Reduce(
    function(x, y) x[x %in% y],
    time
  )

  # subset all SpatRaster to common time
  sr <- lapply(li,
               function(x) terra::subset(x, which(terra::time(x) %in% common))
  )

  ishatch <- Reduce(function(x, y) sum(x, y), sr)

  # reduce to one SpatRaster
  meanhatch <- lapply(sr, terra::which.lyr)
  meanhatch <- terra::rast(meanhatch)
  meanhatch <- terra::mean(meanhatch, na.rm = TRUE)

  out <- sr[[1]]
  time <- terra::time(out)

  for (i in 1:terra::nlyr(out)) {

    out[[i]] <- terra::ifel(ishatch[[i]] > 1, i >= meanhatch, ishatch[[i]])

  }

  terra::time(out) <- time

  return(out)

}
