#' Multivariate DSC (MDSC) Input: X and Y are matrices where columns are components
#'
#' @param x Numeric vector, first component.
#' @param y Numeric vector, second component.
#' @param n_s Integer, number of states.
#' @param lag Integer, lag order.
#'
#' @return Matrix of dimension n_s x n_s.
#' @export
#'
cross_transition_matrix <- function(x, y, n_s = 15, lag = 1) {
  states_x <- discretize_quantile(x, n_s)
  states_y <- discretize_quantile(y, n_s)
  n <- length(states_x)
  if (n <= lag) stop("Time series too short for specified lag")

  from <- states_x[1:(n - lag)]
  to   <- states_y[(1 + lag):n]

  counts <- table(from, to)
  P <- matrix(0, n_s, n_s)
  row_idx <- as.integer(rownames(counts))
  col_idx <- as.integer(colnames(counts))
  for (i in seq_along(row_idx)) {
    P[row_idx[i], col_idx] <- counts[i, ]
  }
  row_sums <- rowSums(P)
  P[row_sums > 0, ] <- P[row_sums > 0, ] / row_sums[row_sums > 0]
  return(P)
}
