#' Compute axis scale positions for brain atlas plots
#'
#' Returns axis breaks, labels, and lab strings based on atlas layout.
#' Used internally by [scale_continous_brain()] and related functions.
#'
#' @param geobrain A data.frame containing atlas information with columns
#'   `hemi`, `view`, `type`, `.lat`, and `.long`.
#' @inheritParams reposition_brain
#' @inheritParams scale_brain
#' @return A list with scale components (breaks, labels, or axis titles).
#' @keywords internal
#' @noRd
#' @importFrom dplyr group_by summarise
adapt_scales <- function(
  geobrain,
  position = "dispersed",
  aesthetics = "labs"
) {
  if (!is.data.frame(geobrain)) {
    geobrain <- sf2coords(as.data.frame(geobrain))
    geobrain <- tidyr::unnest(geobrain, ggseg)
  }

  atlas_type <- unique(geobrain$type)
  if (atlas_type == "cortical") {
    adapt_scales_cortical(geobrain, position, aesthetics)
  } else if (atlas_type %in% c("subcortical", "tract")) {
    adapt_scales_subcortical(geobrain, position, aesthetics)
  }
}


#' @keywords internal
#' @noRd
adapt_scales_cortical <- function(geobrain, position, aesthetics) {
  stk_y <- dplyr::summarise(dplyr::group_by(geobrain, hemi), val = gap(.lat))
  stk_x <- dplyr::summarise(dplyr::group_by(geobrain, view), val = gap(.long))
  disp <- dplyr::summarise_at(
    dplyr::group_by(geobrain, hemi),
    dplyr::vars(.long, .lat),
    list(gap)
  )

  ad_scale <- list(
    stacked = list(
      x = list(breaks = stk_x$val, labels = stk_x$view),
      y = list(breaks = stk_y$val, labels = stk_y$hemi),
      labs = list(y = "hemisphere", x = "view")
    ),
    dispersed = list(
      x = list(breaks = disp$.long, labels = disp$hemi),
      y = list(breaks = NULL, labels = NULL),
      labs = list(y = NULL, x = "hemisphere")
    )
  )

  ad_scale[[position]][[aesthetics]]
}


#' @keywords internal
#' @noRd
adapt_scales_subcortical <- function(geobrain, position, aesthetics) {
  stk_y <- dplyr::summarise(dplyr::group_by(geobrain, view), val = gap(.lat))
  disp <- dplyr::summarise_at(
    dplyr::group_by(geobrain, view),
    dplyr::vars(.long, .lat),
    list(gap)
  )

  ad_scale <- list(
    stacked = list(
      x = list(breaks = NULL, labels = NULL),
      y = list(breaks = stk_y$val, labels = stk_y$view),
      labs = list(y = "view", x = NULL)
    ),
    dispersed = list(
      x = list(breaks = disp$.long, labels = disp$view),
      y = list(breaks = NULL, labels = NULL),
      labs = list(y = NULL, x = "view")
    )
  )

  ad_scale[[position]][[aesthetics]]
}
