#' Neutrosophic MANOVA for a Completely Randomized Design
#'
#' Performs neutrosophic multivariate analysis of variance (MANOVA) for
#' interval-valued multivariate observations under a completely randomized
#' design using Wilks' Lambda as the multivariate test criterion.
#'
#' @param Lower_y A numeric matrix containing the lower bounds of the response
#'   variables. Rows represent observations and columns represent response
#'   variables.
#' @param Upper_y A numeric matrix containing the upper bounds of the response
#'   variables. Must have the same dimensions as `Lower_y`.
#' @param group A vector or factor identifying the treatment group for each
#'   observation. Its length must equal `nrow(Lower_y)`.
#' @param alpha Significance level used to obtain the critical F value.
#'   Defaults to `0.05`.
#' @param verbose Logical; if `TRUE`, prints the neutrosophic MANOVA table.
#'   Defaults to `TRUE`.
#'
#' @return
#' A list containing the results of the neutrosophic MANOVA with the following
#' components:
#' \describe{
#'   \item{MANOVA.table}{A data frame containing the neutrosophic MANOVA table,
#'   including the source of variation, degrees of freedom, Wilks' Lambda
#'   interval, approximate F-statistic interval, and decision.}
#'   \item{Wilks.Lambda}{A named numeric vector containing the lower and upper
#'   bounds of Wilks' Lambda.}
#'   \item{Approx.F}{A named numeric vector containing the lower and upper
#'   bounds of the approximate F-statistic.}
#'   \item{F.critical}{The critical F value at the specified significance
#'   level.}
#'   \item{Decision}{The hypothesis testing decision ("Significant",
#'   "Not Significant", or "Indeterminate").}
#'   \item{treatment_ss}{A list containing the lower, upper, determinate, and
#'   indeterminate treatment sum of squares matrices.}
#'   \item{total_ss}{A list containing the lower, upper, determinate, and
#'   indeterminate total sum of squares matrices.}
#'   \item{residual_ss}{A list containing the lower, upper, determinate, and
#'   indeterminate residual sum of squares matrices.}
#' }
#'
#' @importFrom MASS ginv
#' @importFrom stats model.matrix qf
#'
#' @examples
#' YL <- matrix(c(8.27, 2.50, 5.30, 1.41,
#'                8.40, 6.27, 0.00, 3.42),
#'              ncol = 2, byrow = TRUE)
#'
#' YU <- matrix(c(9.73, 3.50, 6.70, 2.59,
#'                9.60, 7.73, 0.00, 4.58),
#'              ncol = 2, byrow = TRUE)
#'
#' g <- c(1, 1, 2, 2)
#'
#' fit <- CRDnsMANOVA(
#'   Lower_y = YL,
#'   Upper_y = YU,
#'   group = g
#' )
#'
#' fit$MANOVA.table
#' fit$Decision
#' @export

CRDnsMANOVA <- function(Lower_y, Upper_y, group,
                        alpha = 0.05, verbose = TRUE) {

  stopifnot(is.matrix(Lower_y), is.matrix(Upper_y),
            all(dim(Lower_y) == dim(Upper_y)),
            length(group) == nrow(Lower_y),
            alpha > 0, alpha < 1)

  N <- nrow(Lower_y)
  p <- ncol(Lower_y)
  group <- factor(group)
  g <- nlevels(group)
  n <- as.numeric(table(group))

  if (N <= g + 1) {
    stop("Wilks F approximation requires N > number of groups + 1.")
  }

  # Design matrices
  X1 <- model.matrix(~ group - 1)
  Ones <- rep(1, N)
  xt <- cbind(X1, Ones)

  C <- t(X1) %*% X1 -
    t(X1) %*% Ones %*%
    ginv(t(Ones) %*% Ones) %*%
    t(Ones) %*% X1
  C_inv <- ginv(C)

  # Determinate and indeterminate response matrices
  Yd <- (Lower_y + Upper_y) / 2
  Yi <- abs(Upper_y - Lower_y) / 2

  # Treatment Sum of Squares
  xdashyd <- t(xt) %*% Yd
  xdashyi <- t(xt) %*% Yi

  det_bcd <- t(X1) %*% Ones %*%
    ginv(t(Ones) %*% Ones) %*%
    xdashyd[nrow(xdashyd), , drop = FALSE]

  i_bcd <- t(X1) %*% Ones %*%
    ginv(t(Ones) %*% Ones) %*%
    xdashyi[nrow(xdashyi), , drop = FALSE]

  L_q <- xdashyd[seq_len(g), , drop = FALSE] - det_bcd
  U_q <- L_q + xdashyi[seq_len(g), , drop = FALSE] - i_bcd

  det_q <- (L_q + U_q) / 2
  i_q <- abs((U_q - L_q) / 2)

  L_tuo <- C_inv %*% det_q
  U_tuo <- L_tuo + C_inv %*% i_q

  det_tuo <- (L_tuo + U_tuo) / 2
  i_tuo <- abs((U_tuo - L_tuo) / 2)

  L_trtss <- t(det_q) %*% det_tuo
  U_trtss <- L_trtss +
    t(det_q) %*% i_tuo +
    t(i_q) %*% det_tuo +
    t(i_q) %*% i_tuo

  det_trtss <- (L_trtss + U_trtss) / 2
  i_trtss <- abs((U_trtss - L_trtss) / 2)

  # Total Sum of Squares
  L_ydashy <- t(Yd) %*% Yd
  U_ydashy <- L_ydashy + 2 * t(Yd) %*% Yi + t(Yi) %*% Yi

  det_ydashy <- (L_ydashy + U_ydashy) / 2
  i_ydashy <- abs((U_ydashy - L_ydashy) / 2)

  J <- matrix(1, N, N)

  L_ydashj <- t(Yd) %*% J
  U_ydashj <- t(Yi) %*% J + L_ydashj

  det_ydashj <- (L_ydashj + U_ydashj) / 2
  i_ydashj <- abs((U_ydashj - L_ydashj) / 2)

  L_ydashjy <- det_ydashj %*% Yd
  U_ydashjy <- L_ydashjy +
    det_ydashj %*% Yi +
    i_ydashj %*% Yd +
    i_ydashj %*% Yi

  det_ydashjy <- (L_ydashjy + U_ydashjy) / 2
  i_ydashjy <- abs((U_ydashjy - L_ydashjy) / 2)

  L_TSS <- det_ydashy - det_ydashjy / N
  U_TSS <- L_TSS + i_ydashy - i_ydashjy / N

  det_TSS <- (L_TSS + U_TSS) / 2
  i_TSS <- abs((U_TSS - L_TSS) / 2)

  # Residual Sum of Squares
  L_RSS <- det_TSS - det_trtss
  U_RSS <- L_RSS + i_TSS - i_trtss

  det_RSS <- (L_RSS + U_RSS) / 2
  i_RSS <- abs((U_RSS - L_RSS) / 2)

  # Wilks lambda interval
  L_w <- det(det_RSS) / det(det_TSS)

  U_w <- L_w +
    det(det_RSS %*% i_TSS +
          i_RSS %*% det_TSS +
          i_RSS %*% i_TSS) /
    det(det_TSS %*% det_TSS)

  # F-statistic interval
  L_F <- ((1 - sqrt(L_w)) / sqrt(L_w)) * ((N - g - 1) / (g - 1))
  U_F <- ((1 - sqrt(U_w)) / sqrt(U_w)) * ((N - g - 1) / (g - 1))

  #-------------------------------------------------------
  # Decision
  #-------------------------------------------------------
  F_critical <- stats::qf(
    1 - alpha,
    df1 = g - 1,
    df2 = N - g
  )

  if (L_F > F_critical) {
    Decision <- "Significant"
  } else if (U_F < F_critical) {
    Decision <- "Not Significant"
  } else {
    Decision <- "Indeterminate"
  }

  #-------------------------------------------------------
  # MANOVA Table
  #-------------------------------------------------------
  MANOVA.table <- data.frame(
    Source = c("Treatments", "Error", "Total"),
    DF = c(g - 1, N - g, N - 1),
    `Wilks' Lambda` = c(
      sprintf("[%.4f, %.4f]", L_w, U_w),
      "-", "-"
    ),
    `Approx. F` = c(
      sprintf("[%.4f, %.4f]", L_F, U_F),
      "-", "-"
    ),
    Decision = c(Decision, "-", "-"),
    check.names = FALSE
  )

  #-------------------------------------------------------
  # Printing
  #-------------------------------------------------------
  if (verbose) {
    cat("\n")
    cat("============================================================\n")
    cat("      NEUTROSOPHIC MULTIVARIATE ANALYSIS OF VARIANCE\n")
    cat("                 (Wilks' Lambda Criterion)\n")
    cat("============================================================\n\n")

    print(MANOVA.table, row.names = FALSE, right = FALSE)
    cat("\nF critical value:", round(F_critical, 4), "\n")
  }

  result = list(
    MANOVA.table = MANOVA.table,
    Wilks.Lambda = c(Lower = L_w, Upper = U_w),
    Approx.F = c(Lower = L_F, Upper = U_F),
    F.critical = F_critical,
    Decision = Decision,
    treatment_ss = list(
      lower = L_trtss, upper = U_trtss,
      determinate = det_trtss, indeterminate = i_trtss
    ),
    total_ss = list(
      lower = L_TSS, upper = U_TSS,
      determinate = det_TSS, indeterminate = i_TSS
    ),
    residual_ss = list(
      lower = L_RSS, upper = U_RSS,
      determinate = det_RSS, indeterminate = i_RSS
    )
  )

  if (verbose) {
    cat("Neutrosophic CRD MANOVA\n")
    cat("Groups:", g, "| Observations:", N, "| Responses:", p, "\n")
    cat("Wilks' Lambda interval:", L_w, "to", U_w, "\n")
    cat("F-statistic interval:", L_F, "to", U_F, "\n")
  }

  return(result)
}


