/**
 * Deterministic cover artwork.
 *
 * Until the cover-upload endpoint exists (prompt 6's wizard), every card gets a
 * generated gradient instead of an image. It's derived from the slug, so a
 * given dashboard always looks the same — the grid becomes scannable by colour
 * rather than a wall of identical grey placeholders.
 *
 * Hues are spread around the wheel and kept at a mid lightness that reads
 * correctly against both the light and dark shells, so no theme-specific
 * variants are needed.
 */

const hashString = (value: string): number => {
  let hash = 0;
  for (let i = 0; i < value.length; i++) {
    hash = (hash << 5) - hash + value.charCodeAt(i);
    hash |= 0; // force int32
  }
  return Math.abs(hash);
};

export type CoverArt = {
  background: string;
  /** Up to two letters, for the placeholder monogram. */
  initials: string;
};

export const coverArtFor = (seed: string, name: string): CoverArt => {
  const hash = hashString(seed || name || "dashboard");

  // 137.5° steps (golden angle) keep consecutive hues far apart.
  const baseHue = (hash * 137.5) % 360;
  const secondHue = (baseHue + 48) % 360;
  const thirdHue = (baseHue + 312) % 360;
  const tilt = 115 + (hash % 60);

  /*
   * Muted on purpose. An earlier pass used 70-80% saturation at mid lightness;
   * eight of those side by side read as a novelty colour swatch, not a set of
   * business dashboards, and the saturation left badge text unreadable. These
   * are deep, desaturated jewel tones — still distinct per dashboard, but they
   * sit behind the content instead of shouting over it.
   */
  const background = [
    `radial-gradient(130% 120% at 15% 0%, hsl(${secondHue} 42% 46% / 0.55), transparent 62%)`,
    `radial-gradient(120% 130% at 88% 100%, hsl(${thirdHue} 38% 30% / 0.5), transparent 66%)`,
    `linear-gradient(${tilt}deg, hsl(${baseHue} 34% 30%), hsl(${secondHue} 30% 21%))`,
  ].join(", ");

  const initials = (name || "?")
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((word) => word[0]?.toUpperCase() ?? "")
    .join("");

  return { background, initials: initials || "?" };
};
