function splitRGBA(rgbValue: string) {
  // Extract the numerical values from the string
  let [r, g, b, a] = rgbValue
    .replace(/^(rgba?|\(|\)|,|%)+/g, "") // remove extraneous characters
    .split(",")
    .map(x => parseFloat(x))

  if (isNaN(a)) {
    a = 1.0 // default to fully opaque if no alpha value is provided
  }

  return { r, g, b, a }
}

const padRound = (n: number) => Math.round(n).toString(16).padStart(2, "0")

export function parseColor(rgbValue: string) {
  const { r, g, b, a } = splitRGBA(rgbValue)

  let hex = `#${padRound(r)}${padRound(g)}${padRound(b)}`

  if (rgbValue.startsWith("rgba")) {
    hex += padRound(a * 255)
  }

  return {
    hex,
    flip: r * 0.299 + g * 0.587 + b * 0.114 < 146,
  }
}
