#' @name calculate_errors
#' @title Calculate Errors for Factor Analysis Estimates
#' @description This function calculates the Mean Squared Error (MSE) and 
#'   relative error for factor loadings and uniqueness estimates.
#'
#' @param data Matrix of BFM data.
#' @param A Matrix of true factor loadings.
#' @param D Matrix of true uniquenesses (diagonal matrix).
#' @param estimation_results A list containing \code{A_hat} (estimated loadings)
#'   and \code{D_hat} (estimated uniquenesses).
#'
#' @return A named vector containing:
#' \item{MSEA}{Mean Squared Error for factor loadings.}
#' \item{MSED}{Mean Squared Error for uniqueness estimates.}
#' \item{LSA}{Relative error for factor loadings.}
#' \item{LSD}{Relative error for uniqueness estimates.}
#'
#' @export
#' @examples
#' set.seed(123)
#' n <- 10
#' p <- 5
#' A <- matrix(runif(p * p, -1, 1), nrow = p)
#' D <- diag(runif(p, 1, 2))
#' data <- matrix(runif(n * p), nrow = n)
#' estimation_results <- list(A_hat = A, D_hat = D)
#' errors <- calculate_errors(data, A, D, estimation_results)
#' print(errors)
calculate_errors <- function(data, A, D, estimation_results) {
  
  A_hat <- estimation_results$A_hat
  D_hat <- estimation_results$D_hat
  
  frobenius_norm <- function(mat) {
    sqrt(sum(mat^2))
  }
  
  diff_A <- A_hat - A
  diff_D <- D_hat - D
  
  MSEA <- frobenius_norm(diff_A)^2 / (ncol(A)^2)
  MSED <- frobenius_norm(diff_D)^2 / (ncol(D)^2)
  LSA <- frobenius_norm(diff_A)^2 / frobenius_norm(A)^2
  LSD <- frobenius_norm(diff_D)^2 / frobenius_norm(D)^2
  
  return(c(MSEA = MSEA, MSED = MSED, LSA = LSA, LSD = LSD))
}