import type { NetworkNode } from "@/api/client";

export type RGBA = [number, number, number, number];

export function cssVarToRGBA(varName: string): RGBA {
  const raw = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
  if (!raw) return [0.5, 0.5, 0.5, 1];
  const ctx = document.createElement("canvas").getContext("2d")!;
  ctx.fillStyle = raw;
  // ctx.fillStyle normalizes to #rrggbb
  const hex = ctx.fillStyle;
  const r = parseInt(hex.slice(1, 3), 16) / 255;
  const g = parseInt(hex.slice(3, 5), 16) / 255;
  const b = parseInt(hex.slice(5, 7), 16) / 255;
  return [r, g, b, 1];
}

export function lerpRGBA(a: RGBA, b: RGBA, t: number): RGBA {
  return [
    a[0] + (b[0] - a[0]) * t,
    a[1] + (b[1] - a[1]) * t,
    a[2] + (b[2] - a[2]) * t,
    a[3] + (b[3] - a[3]) * t,
  ];
}

export function brighten(c: RGBA, amount: number): RGBA {
  return [
    Math.min(1, c[0] + amount),
    Math.min(1, c[1] + amount),
    Math.min(1, c[2] + amount),
    c[3],
  ];
}

export interface StatusColors {
  online: RGBA;
  stale: RGBA;
  offline: RGBA;
}

export function getThemeStatusColors(): StatusColors {
  const primary = brighten(cssVarToRGBA("--primary"), 0.15);
  const muted = cssVarToRGBA("--muted-foreground");
  return {
    online: primary,
    stale: lerpRGBA(primary, muted, 0.4),
    offline: muted,
  };
}

export function statusRGBA(entry: NetworkNode, theme: StatusColors): RGBA {
  const age = Date.now() / 1000 - (entry.last_seen ?? 0);
  if (age < 300) return theme.online;
  if (age < 3600) return theme.stale;
  return theme.offline;
}

export function rgbaToHex(c: RGBA): string {
  const r = Math.round(c[0] * 255);
  const g = Math.round(c[1] * 255);
  const b = Math.round(c[2] * 255);
  return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
}
