#' Efficiency Measures for p-Rep Test-Control Designs
#'
#' Computes efficiency measures for partially replicated
#' (p-rep) test-control designs. The function calculates
#' average variances for test-versus-test and
#' test-versus-control comparisons, together with the
#' canonical efficiency factor.
#'
#' @param design A design matrix containing test and
#' control treatments.
#' @param test Number of test treatments in the design.
#'
#' @return A data frame containing average variance
#' measures and the canonical efficiency factor.
#'
#' @importFrom MASS ginv
#' @examples
#' design <- matrix(c(
#'   1,6,11,"C1",
#'   2,5,12,"C1",
#'   3,8,9,"C1",
#'   4,7,10,"C1",
#'   1,7,12,"C1",
#'   2,8,11,"C1",
#'   1,8,10,"C1",
#'   2,7,9,"C1",
#'   3,6,12,"C1",
#'   4,5,11,"C1",
#'   3,5,10,"C1",
#'   4,6,9,"C1"
#' ), byrow = TRUE, ncol = 4)
#'
#' TCpRepEfficiency(design, test = 12)
#'
#' @export
TCpRepEfficiency <- function(design, test){

  if(!requireNamespace("MASS", quietly = TRUE))
    stop("Package 'MASS' is required")

  a <- as.matrix(design)

  labels <- sort(unique(as.vector(a)))
  v <- length(labels)
  b <- nrow(a)
  n <- sum(a > 0)

  # Incidence matrices
  labels <- unique(as.vector(a))

  trt <- matrix(0, n, length(labels))
  block <- matrix(0, n, b)

  k <- 1
  for(i in 1:b){
    for(j in 1:ncol(a)){

      lab <- as.character(a[i,j])

      trt[k, match(lab, labels)] <- 1
      block[k, i] <- 1

      k <- k + 1
    }
  }

  trt <- trt[1:(k-1), , drop = FALSE]
  block <- block[1:(k-1), , drop = FALSE]

  m <- matrix(1, nrow(trt), 1)

  X1 <- trt
  X2 <- cbind(m, block)

  C <- t(X1) %*% X1 -
    t(X1) %*% X2 %*%
    MASS::ginv(t(X2) %*% X2) %*%
    t(X2) %*% X1

  Cinv <- MASS::ginv(C)

  ## Test vs Test
  vt <- test
  nTT <- choose(vt, 2)

  CM_TT <- matrix(0, nTT, v)

  k <- 1
  for(i in 1:(vt-1)){
    for(j in (i+1):vt){
      CM_TT[k,i] <- 1
      CM_TT[k,j] <- -1
      k <- k + 1
    }
  }

  Var_TT <- diag(CM_TT %*% Cinv %*% t(CM_TT))
  AV_TT <- mean(Var_TT)

  ## Test vs Control
  vc <- v - vt
  nTC <- vt * vc

  CM_TC <- matrix(0, nTC, v)

  k <- 1
  for(i in 1:vt){
    for(j in (vt+1):v){
      CM_TC[k,i] <- 1
      CM_TC[k,j] <- -1
      k <- k + 1
    }
  }

  Var_TC <- diag(CM_TC %*% Cinv %*% t(CM_TC))
  AV_TC <- mean(Var_TC)

  ## Canonical Efficiency Factor
  eig <- Re(eigen(C)$values)
  eig <- eig[eig > 1e-7]

  rep1 <- diag(t(trt) %*% trt)[1]

  cefs <- eig / rep1

  CEF <- length(cefs) / sum(1/cefs)

  result <- data.frame(
    Measure = c(
      "Average Variance (Test vs Test)",
      "Average Variance (Test vs Control)",
      "Canonical Efficiency Factor"
    ),
    Value = round(c(AV_TT, AV_TC, CEF), 4)
  )

  return(result)
}

