#' Clustering with Minkowski distance, p > 1 (internal)
#'
#' Intercept-only design: `B` represents cluster centres. Uses
#' [stats::uniroot()] to solve first-order conditions for each centre
#' coordinate.
#'
#' @noRd
PDVWithMinkowskiMoreThanOne <- function(Y, K, a, b, pow, threshold, max.iter) {

  X <- matrix(1, nrow(Y), 1)
  Y <- as.matrix(Y)

  const <- b / (a - 1)

  dx <- ncol(X)
  dy <- ncol(Y)
  n  <- nrow(X)

  B    <- array(t(stats::kmeans(Y, K)$centers), dim = c(dy, dx, K))
  newB <- B

  d <- data.frame(matrix(ncol = K, nrow = n))
  p <- data.frame(matrix(0, ncol = K, nrow = n))

  for (x in 1:K) {
    names(d)[x] <- paste("Cluster", x)
    names(p)[x] <- paste("Cluster", x)
  }

  JDF     <- c()
  newNorm <- threshold + 1
  iter    <- 0

  f_i_1 <- function(i, j, s, x) {
    term <- p[i, j]^a / d[i, j]^(pow - b)
    u    <- (Y[i, s] - x)
    return(term * abs(u)^(pow - 2) * u)
  }

  f_1 <- function(j, s, x) {
    total_sum <- 0
    for (i in 1:n) {
      total_sum <- total_sum + f_i_1(i, j, s, x)
    }
    return(total_sum)
  }

  while (newNorm >= threshold & iter < max.iter) {
    iter <- iter + 1

    for (j in 1:K) {
      for (i in 1:n) {
        resids  <- cbind(matrix(unlist(Y[i, ])),
                         B[, , j] %*% matrix(unlist(X[i, ])))
        d[i, j] <- sum(abs(resids[, 1] - resids[, 2])^pow)^(1 / pow)
      }
    }

    JDF_value <- 0
    for (x in 1:n) {
      JDF_numerator   <- prod(d[x, ])^const
      JDF_denominator <- 0
      for (y in 1:K) {
        JDF_denominator <- JDF_denominator + prod(d[x, -y])^const
      }
      JDF_value <- JDF_value + (JDF_numerator / JDF_denominator)^(a - 1)
    }
    JDF <- c(JDF, JDF_value)

    for (x in 1:n) {
      sum1 <- 0
      for (y in 1:K) {
        sum1 <- sum1 + prod(d[x, -y])^const
      }
      for (z in 1:K) {
        product1 <- prod(d[x, -z])^const
        p[x, z]  <- product1 / sum1
      }
    }
    p[sapply(p, is.nan)] <- 1

    for (j in 1:K) {
      for (s in 1:dy) {
        newB[s, 1, j] <- stats::uniroot(function(x) f_1(j, s, x),
                                        c(-1e18, 1e18), tol = 0.0001)$root
      }
    }

    B <- newB
  }

  l <- apply(p, 1, which.max)
  return(list(C = B, d = d, p = p, JDF = JDF, l = l))
}
