import type { BeamColorName } from "./types";

const MASK_BY_NAME: Record<BeamColorName, number> = {
  red: 0b001,
  green: 0b010,
  blue: 0b100,
  yellow: 0b011,
  magenta: 0b101,
  cyan: 0b110,
  white: 0b111
};

const NAME_BY_MASK: Record<number, BeamColorName> = {
  0b001: "red",
  0b010: "green",
  0b011: "yellow",
  0b100: "blue",
  0b101: "magenta",
  0b110: "cyan",
  0b111: "white"
};

const HEX_BY_NAME: Record<BeamColorName, string> = {
  red: "#ff5f6d",
  green: "#7dff8a",
  blue: "#6da6ff",
  yellow: "#ffe76e",
  magenta: "#ff8dfb",
  cyan: "#74f8ff",
  white: "#f5fcff"
};

const PRISM_PALETTE: BeamColorName[] = ["red", "green", "blue", "yellow", "magenta", "cyan", "white"];

export function colorNameToMask(name: BeamColorName): number {
  return MASK_BY_NAME[name];
}

export function colorMaskToName(mask: number): BeamColorName {
  const normalized = mask & 0b111;
  return NAME_BY_MASK[normalized] ?? "white";
}

export function colorMaskToNameOrNone(mask: number): BeamColorName | "none" {
  const normalized = mask & 0b111;
  if (normalized === 0) {
    return "none";
  }
  return colorMaskToName(normalized);
}

export function colorNameToHex(name: BeamColorName): string {
  return HEX_BY_NAME[name];
}

export function colorMaskToHex(mask: number): string {
  const normalized = mask & 0b111;
  if (normalized === 0) {
    return "#1d2b36";
  }
  return colorNameToHex(colorMaskToName(normalized));
}

export function cyclePrismColor(current: BeamColorName, delta: number): BeamColorName {
  const index = PRISM_PALETTE.indexOf(current);
  const normalized = index >= 0 ? index : 0;
  const offset = ((normalized + delta) % PRISM_PALETTE.length + PRISM_PALETTE.length) % PRISM_PALETTE.length;
  return PRISM_PALETTE[offset];
}
