#' Plot Method for gpcifit_censor Objects
#'
#' Visualizes interval-censored observations, fitted distribution density curve, and specification limits.
#'
#' @param x An object of class \code{gpcifit_censor}.
#' @param main Title of the plot.
#' @param ... Additional graphical parameters.
#' @export
plot.gpcifit_censor <- function(x, main = "Process Capability Analysis (Interval-Censored)", ...) {
  oldpar <- graphics::par(no.readonly = TRUE)
  on.exit(graphics::par(oldpar))
  
  graphics::par(mfrow = c(1, 2), mar = c(4, 4, 3, 1))
  
  # Plot 1: Interval observations
  n <- length(x$data_left)
  if (n > 0) {
    y_vals <- 1:n
    xlim_range <- range(c(x$data_left, x$data_right, x$LSL, x$USL), na.rm = TRUE)
    graphics::plot(x$data_left, y_vals, xlim = xlim_range, ylim = c(0, n + 1),
                   xlab = "Process Measurement", ylab = "Observation Index",
                   main = "Interval-Censored Data", pch = 16, col = "blue", ...)
    graphics::points(x$data_right, y_vals, pch = 17, col = "red")
    for (i in 1:n) {
      graphics::segments(x$data_left[i], i, x$data_right[i], i, col = "gray50", lty = 1)
    }
    graphics::abline(v = x$LSL, col = "red", lty = 2, lwd = 2)
    graphics::abline(v = x$USL, col = "red", lty = 2, lwd = 2)
    graphics::abline(v = x$target, col = "darkgreen", lty = 3, lwd = 2)
    graphics::legend("topleft", legend = c("Left Bound", "Right Bound", "Spec Limits", "Target"),
                     col = c("blue", "red", "red", "darkgreen"), pch = c(16, 17, NA, NA),
                     lty = c(NA, NA, 2, 3), cex = 0.8)
  } else {
    graphics::plot(1, 1, type = "n", main = "No Raw Data")
  }
  
  # Plot 2: Fitted PDF and Spec Limits
  grid_x <- seq(x$LSL - 0.5 * (x$USL - x$LSL), x$USL + 0.5 * (x$USL - x$LSL), length.out = 300)
  pdf_vals <- sapply(grid_x, function(v) {
    val <- tryCatch(do.call(x$distribution$pdf, c(list(v), x$distribution$params)), error = function(e) 0)
    if (is.na(val) || !is.finite(val)) 0 else val
  })
  
  graphics::plot(grid_x, pdf_vals, type = "l", col = "darkblue", lwd = 2,
                 xlab = "x", ylab = "Density", main = main, ...)
  graphics::abline(v = x$LSL, col = "red", lty = 2, lwd = 2)
  graphics::abline(v = x$USL, col = "red", lty = 2, lwd = 2)
  graphics::abline(v = x$target, col = "darkgreen", lty = 3, lwd = 2)
  
  invisible(x)
}

#' Plot Method for gpci_ci_censor Objects
#'
#' Visualizes bootstrap confidence intervals across different significance levels.
#'
#' @param x An object of class \code{gpci_ci_censor}.
#' @param ... Additional graphical parameters.
#' @export
plot.gpci_ci_censor <- function(x, ...) {
  tbl <- x$ci_table
  indices <- unique(tbl$index)
  n_idx <- length(indices)
  
  oldpar <- graphics::par(no.readonly = TRUE)
  on.exit(graphics::par(oldpar))
  
  graphics::par(mfrow = c(ceiling(n_idx / 2), min(2, n_idx)), mar = c(4, 4, 3, 1))
  
  for (idx in indices) {
    sub_tbl <- tbl[tbl$index == idx, ]
    xlim_val <- range(c(sub_tbl$lower, sub_tbl$upper, sub_tbl$estimate), na.rm = TRUE)
    if (diff(xlim_val) == 0) xlim_val <- xlim_val + c(-0.1, 0.1)
    
    y_pos <- seq_len(nrow(sub_tbl))
    graphics::plot(sub_tbl$estimate, y_pos, xlim = xlim_val, ylim = c(0, nrow(sub_tbl) + 1),
                   yaxt = "n", xlab = "Estimate & CI", ylab = "",
                   main = paste("Bootstrap CI:", idx), pch = 19, col = "blue", ...)
    graphics::axis(2, at = y_pos, labels = sub_tbl$conf_level, las = 1)
    
    for (i in seq_len(nrow(sub_tbl))) {
      graphics::segments(sub_tbl$lower[i], y_pos[i], sub_tbl$upper[i], y_pos[i], col = "darkblue", lwd = 2)
    }
  }
  
  invisible(x)
}

#' Plot Method for gpci_diagnostics_censor Objects
#'
#' Visualizes standard errors for parameters and capability indices.
#'
#' @param x An object of class \code{gpci_diagnostics_censor}.
#' @param ... Additional graphical parameters.
#' @export
plot.gpci_diagnostics_censor <- function(x, ...) {
  oldpar <- graphics::par(no.readonly = TRUE)
  on.exit(graphics::par(oldpar))
  
  graphics::par(mfrow = c(1, 2), mar = c(4, 5, 3, 1))
  
  # Parameter SEs
  se_p <- x$se_params
  graphics::barplot(se_p, main = "SE: Parameters", col = "skyblue", las = 2, ylab = "Standard Error", ...)
  
  # Index SEs
  se_i <- x$se_indices
  graphics::barplot(se_i, main = "SE: Capability Indices", col = "salmon", las = 2, ylab = "Standard Error", ...)
  
  invisible(x)
}

#' Autoplot Generic and Methods for Compatibility
#'
#' @param object Object to plot.
#' @param ... Additional arguments.
#' @export
autoplot <- function(object, ...) {
  UseMethod("autoplot")
}

#' @rdname autoplot
#' @export
autoplot.gpcifit_censor <- function(object, ...) {
  plot.gpcifit_censor(object, ...)
}

#' @rdname autoplot
#' @export
autoplot.gpci_ci_censor <- function(object, ...) {
  plot.gpci_ci_censor(object, ...)
}

#' @rdname autoplot
#' @export
autoplot.gpci_diagnostics_censor <- function(object, ...) {
  plot.gpci_diagnostics_censor(object, ...)
}
