# Avoid R CMD check note
if (getRversion() >= "2.15.1") utils::globalVariables(c(".data"))

#' Plot a Process Capability Sensitivity Grid
#'
#' Produces a \pkg{ggplot2} line-and-ribbon plot showing the PCI estimate
#' and confidence bands as a function of the chosen sweep variable, faceted
#' by significance level.
#'
#' @param x A \code{\link{pci_grid}} object.
#' @param x_axis Character: which sweep variable to place on the x-axis.
#'   One of \code{"sigma"}, \code{"s"}, or \code{"p0"}.
#' @param facet_by Character: column name to facet by. Default \code{"alpha"}.
#' @param ... Additional arguments (currently ignored).
#'
#' @return Invisibly returns a \code{\link[ggplot2]{ggplot}} object representing
#'   the sensitivity plot. Called primarily for its side effect of rendering a
#'   line-and-ribbon plot to the active graphic device.
#'
#' @examples
#' \donttest{
#' if (requireNamespace("ggplot2", quietly = TRUE)) {
#'   grid <- pci_grid("Cp", LSL = 57, USL = 63,
#'                    sigma_vals = seq(0.5, 2, 0.1), mu = 60,
#'                    alpha_vals = c(0.05, 0.01),
#'                    n = 30, B = 200,
#'                    dist = pci_dist_normal(60, 1))
#'   plot(grid, x_axis = "sigma")
#' }
#' }
#'
#' @seealso \code{\link{pci_grid}}
#' @export
plot.pci_grid <- function(x, x_axis = c("sigma", "s", "p0"),
                          facet_by = "alpha", ...) {

  if (!requireNamespace("ggplot2", quietly = TRUE)) {
    stop("Package 'ggplot2' is required for plotting. ",
         "Install it with install.packages(\"ggplot2\").",
         call. = FALSE)
  }

  x_axis <- match.arg(x_axis)

  # Filter to rows where the x-axis variable is not NA
  plot_data <- x[!is.na(x[[x_axis]]), , drop = FALSE]

  if (nrow(plot_data) == 0) {
    stop("No rows with non-NA values for '", x_axis, "'.")
  }

  # Convert facet variable to factor for nice labelling
  if (facet_by %in% names(plot_data)) {
    plot_data[[facet_by]] <- factor(
      plot_data[[facet_by]],
      labels = paste0((1 - sort(unique(plot_data[[facet_by]]))) * 100, "% CI")
    )
  }

  idx_name <- plot_data$index[1]

  # Axis labels
  x_label <- switch(x_axis,
    sigma = expression(sigma ~ "(short-term SD)"),
    s     = expression(s ~ "(long-term SD)"),
    p0    = expression(p[0] ~ "(desired yield)")
  )
  y_label <- idx_name

  # Build plot
  p <- ggplot2::ggplot(plot_data,
                       ggplot2::aes(x = .data[[x_axis]], y = .data[["estimate"]])) +
    ggplot2::geom_line(color = "#2563EB", linewidth = 1) +
    ggplot2::geom_point(color = "#2563EB", size = 2)

  # Add ribbon if CI bounds exist
  has_ci <- any(!is.na(plot_data$lower) & !is.na(plot_data$upper))
  if (has_ci) {
    p <- p + ggplot2::geom_ribbon(
      ggplot2::aes(ymin = .data[["lower"]], ymax = .data[["upper"]]),
      fill = "#93C5FD", alpha = 0.3
    )
  }

  # Reference line at 1
  p <- p + ggplot2::geom_hline(yintercept = 1, linetype = "dashed",
                                color = "#DC2626", alpha = 0.6)

  # Facet
  if (facet_by %in% names(plot_data) &&
      length(unique(plot_data[[facet_by]])) > 1) {
    p <- p + ggplot2::facet_wrap(stats::as.formula(paste("~", facet_by)))
  }

  # Theme
  p <- p +
    ggplot2::labs(
      title = paste("Sensitivity of", idx_name),
      x     = x_label,
      y     = y_label
    ) +
    ggplot2::theme_minimal(base_size = 13) +
    ggplot2::theme(
      plot.title       = ggplot2::element_text(face = "bold", hjust = 0.5),
      panel.grid.minor = ggplot2::element_blank()
    )

  if (interactive() || grDevices::dev.cur() > 1) {
    print(p)
  }
  invisible(p)
}
