// Deterministic fallback color for a space when it has no explicit brand_color.
//
// The cross-space calendar paints one dot per space, so every space needs a
// stable color even when the owner never set a brand color. We derive it from
// the space id via a small FNV-1a hash into a fixed palette. The UI mirrors
// this EXACTLY (ui/src/lib/spaceColor.ts) so a space's dot color matches
// whether the color came from the API payload or was computed client-side.
//
// Keep the palette and hash in lockstep with the UI copy. The palette is a set
// of mid-saturation hues that read well as small dots on both light and dark
// surfaces.

const SPACE_COLOR_PALETTE = [
  '#6366f1', // indigo
  '#0ea5e9', // sky
  '#10b981', // emerald
  '#f59e0b', // amber
  '#ef4444', // red
  '#ec4899', // pink
  '#8b5cf6', // violet
  '#14b8a6', // teal
  '#f97316', // orange
  '#84cc16', // lime
] as const;

/** FNV-1a 32-bit hash of a string → unsigned int. Mirrored in the UI copy. */
function fnv1a(str: string): number {
  let h = 0x811c9dc5;
  for (let i = 0; i < str.length; i++) {
    h ^= str.charCodeAt(i);
    // h *= 16777619, kept in 32-bit unsigned range.
    h = Math.imul(h, 0x01000193) >>> 0;
  }
  return h >>> 0;
}

/** Stable hex color for a space id (deterministic palette pick). */
export function spaceColor(id: string): string {
  const idx = fnv1a(id) % SPACE_COLOR_PALETTE.length;
  return SPACE_COLOR_PALETTE[idx]!;
}
