import type { CSSProperties } from "react";

export type RgbTuple = readonly [number, number, number];

const DARK_TEXT_RGB: RgbTuple = [11, 17, 23];
const LIGHT_TEXT_RGB: RgbTuple = [245, 247, 251];

function clampRgbChannel(value: number): number {
  return Math.min(Math.max(Math.round(value), 0), 255);
}

export function formatRgbTuple(rgb: readonly number[]): string {
  return rgb.map(clampRgbChannel).join(" ");
}

export function getNodedcRelativeLuminance(rgb: readonly number[]): number {
  const [r, g, b] = rgb.map((channel) => {
    const normalized = channel / 255;
    return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
  });

  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

export function getReadableNodedcTextRgb(rgb: readonly number[]): RgbTuple {
  return getNodedcRelativeLuminance(rgb) > 0.52 ? DARK_TEXT_RGB : LIGHT_TEXT_RGB;
}

export function createNodedcAccentStyleVars(
  accentRgb: RgbTuple,
  accentVarName = "--nodedc-component-accent-rgb",
  onAccentVarName = "--nodedc-component-on-accent-rgb"
): CSSProperties {
  return {
    [accentVarName]: formatRgbTuple(accentRgb),
    [onAccentVarName]: formatRgbTuple(getReadableNodedcTextRgb(accentRgb)),
  } as CSSProperties;
}
