#' Neutrosophic Analysis of Variance for Completely Randomized Design
#'
#' Performs neutrosophic analysis of variance (NANOVA) for a
#' completely randomized design using interval-valued observations.
#'
#' @param Lower_y Matrix of lower bounds of the response variable.
#' @param Upper_y Matrix of upper bounds of the response variable.
#' @param design Matrix specifying treatment allocation.
#' @param alpha Significance level for LSD test.
#' @param verbose Logical. If TRUE, prints the analysis.
#'
#' @return A list containing the NANOVA table, treatment means,
#' pairwise comparisons, and LSD interval.
#'
#' @importFrom MASS ginv
#' @importFrom stats qf qt
#' @export
#' @examples
#' Lower_y <- matrix(c(
#'   9.5, 19.5, 29.5, 39.5,
#'   10.0, 20.0, 30.0, 40.0,
#'   10.5, 20.5, 30.5, 40.5,
#'   9.8, 19.8, 29.8, 39.8,
#'   10.2, 20.2, 30.2, 40.2
#' ), nrow = 5, byrow = TRUE)
#'
#' Upper_y <- matrix(c(
#'   10.5, 20.5, 30.5, 40.5,
#'   11.0, 21.0, 31.0, 41.0,
#'   11.5, 21.5, 31.5, 41.5,
#'   10.8, 20.8, 30.8, 40.8,
#'   11.2, 21.2, 31.2, 41.2
#' ), nrow = 5, byrow = TRUE)
#'
#' design <- matrix(c(
#'   1, 2, 3, 4,
#'   1, 2, 3, 4,
#'   1, 2, 3, 4,
#'   1, 2, 3, 4,
#'   1, 2, 3, 4
#' ), nrow = 5, byrow = TRUE)
#'
#' CRDnsANOVA(
#'   Lower_y = Lower_y,
#'   Upper_y = Upper_y,
#'   design = design,
#'   alpha = 0.05,
#'   verbose = TRUE
#' )


CRDnsANOVA <- function(Lower_y, Upper_y, design,
                       alpha = 0.05,
                       verbose = FALSE){

  #-------------------------------------------------------
  # Input Validation and Initialization
  #-------------------------------------------------------

  Lower_y <- as.matrix(Lower_y)
  Upper_y <- as.matrix(Upper_y)
  design  <- as.matrix(design)

  v <- max(design)
  b <- nrow(design)
  k <- ncol(design)

  rep_counts <- table(design)
  r <- unique(rep_counts)

  interval <- function(L, U){
    list(
      d = (L + U)/2,
      i = abs(U - L)/2
    )
  }

  n <- b * k

  #-------------------------------------------------------
  # Construction of Experimental Design and Model Matrices
  #-------------------------------------------------------

  trt_vec <- as.vector(t(design))

  Tmat <- matrix(0, n, v)

  for(i in 1:n){
    Tmat[i, trt_vec[i]] <- 1
  }

  mu <- matrix(1, n, 1)

  X <- cbind(Tmat, mu)

  #-------------------------------------------------------
  # Interval Decomposition of Responses
  #-------------------------------------------------------

  d_y <- (Lower_y + Upper_y)/2
  i_y <- abs(Upper_y - Lower_y)/2

  dy <- as.vector(t(d_y))
  iy <- as.vector(t(i_y))

  #-------------------------------------------------------
  # Computation of Overall Interval Means and
  # Centered Interval Responses
  #-------------------------------------------------------

  ybar_l <- mean(Lower_y)
  ybar_u <- mean(Upper_y)
  ybar_d <- mean(d_y)
  ybar_i <- mean(i_y)

  yminusbar_l <- d_y - ybar_d
  yminusbar_u <- yminusbar_l + i_y - ybar_i

  yminusbar_d <- (yminusbar_l + yminusbar_u)/2
  yminusbar_i <- abs(yminusbar_u - yminusbar_l)/2

  yminusbar_sq_l <- yminusbar_d * yminusbar_d

  yminusbar_sq_u <- yminusbar_sq_l +
    2 * yminusbar_d * yminusbar_i +
    yminusbar_i * yminusbar_i

  yminusbar_sq_d <- (yminusbar_sq_l + yminusbar_sq_u)/2
  yminusbar_sq_i <- abs(yminusbar_sq_u - yminusbar_sq_l)/2

  #-------------------------------------------------------
  # Estimation of Adjusted Treatment Effects
  #-------------------------------------------------------

  Z <- cbind(mu)

  M <- diag(nrow(X)) - Z %*% MASS::ginv(t(Z) %*% Z) %*% t(Z)

  Ct_adj <- t(Tmat) %*% M %*% Tmat

  bcdy_t_ad_d <- t(Tmat) %*% cbind(mu) %*%
    MASS::ginv(t(cbind(mu)) %*% cbind(mu)) %*%
    t(cbind(mu)) %*% dy

  bcdy_t_ad_i <- t(Tmat) %*% cbind(mu) %*%
    MASS::ginv(t(cbind(mu)) %*% cbind(mu)) %*%
    t(cbind(mu)) %*% iy

  Qy_ad_l <- t(Tmat) %*% dy - bcdy_t_ad_d

  Qy_ad_u <- Qy_ad_l[(1:v), ] +
    t(Tmat) %*% iy - bcdy_t_ad_i

  Qy_t_ad_d <- (Qy_ad_l + Qy_ad_u)/2
  Qy_t_ad_i <- abs(Qy_ad_l - Qy_ad_u)/2

  ay_t_ad_l <- MASS::ginv(Ct_adj) %*% Qy_t_ad_d

  ay_t_ad_u <- ay_t_ad_l + Qy_t_ad_i/b

  ay_t_ad_d <- (ay_t_ad_l + ay_t_ad_u)/2
  ay_t_ad_i <- abs(ay_t_ad_l - ay_t_ad_u)/2

  #-------------------------------------------------------
  # Computation of Interval Sums of Squares
  #-------------------------------------------------------

  toss_l <- sum(yminusbar_sq_l)
  toss_u <- sum(yminusbar_sq_u)
  toss_d <- sum(yminusbar_sq_d)
  toss_i <- abs(toss_l - toss_u)/2

  ss_t_ad_l <- sum(Qy_t_ad_d * ay_t_ad_d)

  ss_t_ad_u <- ss_t_ad_l +
    sum(Qy_t_ad_d * ay_t_ad_i +
          Qy_t_ad_i * ay_t_ad_d +
          Qy_t_ad_i * ay_t_ad_i)

  ss_t_ad_d <- (ss_t_ad_l + ss_t_ad_u)/2
  ss_t_ad_i <- abs(ss_t_ad_u - ss_t_ad_l)/2

  mdss_all_ad_l <- ss_t_ad_l
  mdss_all_ad_u <- ss_t_ad_u

  mdss_all_ad_d <- (mdss_all_ad_u + mdss_all_ad_l)/2
  mdss_all_ad_i <- abs(mdss_all_ad_u - mdss_all_ad_l)/2

  ess_all_ad_l <- toss_d - mdss_all_ad_d

  ess_all_ad_u <- ess_all_ad_l +
    toss_i - mdss_all_ad_i

  ess_all_ad_d <- (ess_all_ad_l + ess_all_ad_u)/2
  ess_all_ad_i <- abs(ess_all_ad_u - ess_all_ad_l)/2

  #-------------------------------------------------------
  # Computation of Interval Mean Squares and F-Statistics
  #-------------------------------------------------------

  SV <- c("Treatment","Error","Total")

  DF <- c(v - 1, n - v, n - 1)

  SSN <- list(
    c(ss_t_ad_l, ss_t_ad_u),
    c(ess_all_ad_l, ess_all_ad_u),
    c(toss_l, toss_u)
  )

  MSSN <- list(
    c(ss_t_ad_l/(v - 1), ss_t_ad_u/(v - 1)),
    c(ess_all_ad_l/(n - v), ess_all_ad_u/(n - v)),
    c(NA, NA)
  )

  F_t_ad_L <- (ss_t_ad_d/(v - 1)) / (ess_all_ad_d/(n - v))

  F_t_ad_U <- F_t_ad_L +
    (((ss_t_ad_d/(v - 1)) * (ess_all_ad_i/(n - v))) +
       ((ss_t_ad_i/(v - 1)) * (ess_all_ad_d/(n - v))) +
       ((ss_t_ad_i/(v - 1)) * (ess_all_ad_i/(n - v)))) /
    ((ess_all_ad_d/(n - v)) * (ess_all_ad_d/(n - v)))

  FN <- list(
    c(F_t_ad_L, F_t_ad_U),
    c(NA, NA),
    c(NA, NA)
  )

  format_interval <- function(x){
    if(any(is.na(x))) return("")
    paste0("[", round(x[1], 2), ", ", round(x[2], 2), "]")
  }

  SSN_fmt  <- sapply(SSN, format_interval)
  MSSN_fmt <- sapply(MSSN, format_interval)
  FN_fmt   <- sapply(FN, format_interval)

  nanova_table <- data.frame(
    SV = SV,
    DF = DF,
    SSN = SSN_fmt,
    MSSN = MSSN_fmt,
    FN = FN_fmt,
    stringsAsFactors = FALSE
  )
  #-------------------------------------------------------
  # Determination of Significance
  #-------------------------------------------------------

  Ftab_5   <- qf(0.95,  v - 1, n - v)
  Ftab_1   <- qf(0.99,  v - 1, n - v)
  Ftab_001 <- qf(0.999, v - 1, n - v)

  significance <- ifelse(
    F_t_ad_L > Ftab_001, "***",
    ifelse(
      F_t_ad_L > Ftab_1, "**",
      ifelse(
        F_t_ad_L > Ftab_5, "*", "NS"
      )
    )
  )

  nanova_table$Significance <- c(significance, "", "")


  #-------------------------------------------------------
  # Interval-Based LSD Analysis
  #-------------------------------------------------------

  dfe <- n - v

  MSE_d <- ess_all_ad_d / dfe
  MSE_i <- ess_all_ad_i / dfe

  SEd_d <- sqrt((2 * MSE_d) / r)
  SEd_i <- sqrt((2 * MSE_i) / r)

  tval <- qt(1 - alpha/2, dfe)

  LSD_l <- tval * SEd_d
  LSD_u <- LSD_l + tval * SEd_i

  #-------------------------------------------------------
  # Adjusted Treatment Means
  #-------------------------------------------------------

  trtmeans_d <- as.vector(ay_t_ad_d)
  trtmeans_i <- as.vector(ay_t_ad_i)

  grand_mean <- mean(dy)

  adjmeans_d <- grand_mean + trtmeans_d
  adjmeans_i <- trtmeans_i

  #-------------------------------------------------------
  # Pairwise Treatment Comparisons
  #-------------------------------------------------------

  comparison <- data.frame()

  for(i in 1:(v - 1)){

    for(j in (i + 1):v){

      Diff_l <- abs(adjmeans_d[i] - adjmeans_d[j])

      Diff_u <- Diff_l + adjmeans_i[i] + adjmeans_i[j]

      Lower <- min(Diff_l, Diff_u)
      Upper <- max(Diff_l, Diff_u)

      diff_interval <- paste0(
        "[",
        round(Lower, 2),
        ", ",
        round(Upper, 2),
        "]"
      )

      if(Upper < LSD_l){

        result <- "NS"

      }else if(Lower > LSD_u){

        result <- "S"

      }else{

        result <- "I"

      }

      rowdata <- data.frame(
        Treatment1 = i,
        Treatment2 = j,
        Difference = diff_interval,
        LSD = paste0(
          "[",
          round(LSD_l, 2),
          ", ",
          round(LSD_u, 2),
          "]"
        ),
        Result = result,
        stringsAsFactors = FALSE
      )

      comparison <- rbind(comparison, rowdata)

    }

  }

  #-------------------------------------------------------
  # Display Results
  #-------------------------------------------------------

  if(verbose){

    message("\nNeutrosophic Analysis of Variance Table")
    print(nanova_table, row.names = FALSE)

    if(significance != "NS"){

      message(
        "\nLSD Interval : [",
        round(LSD_l,4),
        ", ",
        round(LSD_u,4),
        "]"
      )

      message("\nTreatment Comparisons Using LSD")

      print(comparison, row.names = FALSE)

    }else{

      message("\nTreatment effect is non-significant.")
      message("Multiple comparison is not performed.")

    }

    message("\nSignificance Codes:")
    message("*** : Significant at p < 0.001")
    message("**  : Significant at p < 0.01")
    message("*   : Significant at p < 0.05")
    message("NS  : Non Significant")
    message("I   : Indeterminate")

  }

  #-------------------------------------------------------
  # Return Results
  #-------------------------------------------------------

  invisible(list(
    nanova_table = nanova_table,
    comparison = if(significance != "NS") comparison else NULL,
    LSD = if(significance != "NS")
      c(Lower = LSD_l, Upper = LSD_u)
    else NULL
  ))

}




