#' Plot Method for gpciImpSam Objects
#'
#' Visualizes GPCI posterior density distributions, trace plots, and HPD intervals.
#'
#' @param x An object of class \code{"gpciImpSam"}.
#' @param type Type of plot: \code{"density"} (default) or \code{"trace"}.
#' @param index Character string naming the specific GPCI to plot. Default plots the first index.
#' @param ... Additional graphical parameters.
#' @return Invisible \code{NULL}.
#' @export
#' @examples
#' data_x <- rnorm(40, mean = 10, sd = 1)
#' fit <- impsam_gpci(data = data_x, distribution = dist_normal(), USL = 13, LSL = 7)
#' plot(fit, type = "density", index = "Cpy")
plot.gpciImpSam <- function(x, type = c("density", "trace"), index = NULL, ...) {
  type <- match.arg(type)
  gpci_chain <- x$gpci_chain
  
  if (is.null(index)) {
    index <- colnames(gpci_chain)[1]
  }
  
  if (!index %in% colnames(gpci_chain)) {
    stop("Specified index not found in GPCI chain.")
  }
  
  chain <- gpci_chain[[index]]
  chain <- chain[is.finite(chain)]
  
  op <- graphics::par(no.readonly = TRUE)
  on.exit(graphics::par(op))
  
  if (type == "density") {
    hpd95 <- hpd_interval(chain, prob = 0.95)
    
    graphics::hist(chain, prob = TRUE, main = paste("Posterior Density of", index),
                   xlab = index, col = grDevices::adjustcolor("skyblue", alpha.f = 0.6),
                   border = "white")
    graphics::lines(stats::density(chain), col = "darkblue", lwd = 2)
    graphics::abline(v = hpd95, col = "red", lty = 2, lwd = 2)
    graphics::legend("topright", legend = c("Density", "95% HPD Limits"),
                     col = c("darkblue", "red"), lty = c(1, 2), lwd = 2)
  } else if (type == "trace") {
    graphics::plot(chain, type = "l", col = "darkgreen",
                   main = paste("MCMC Trace Plot for", index),
                   xlab = "Iteration", ylab = index)
    graphics::abline(h = mean(chain), col = "orange", lwd = 2, lty = 2)
  }
  
  invisible(NULL)
}
