/** Palette inspirée de Google Calendar. */
export const AGENDA_COLOR_PALETTE: { value: string; label: string }[] = [
  { value: "#039be5", label: "Paon" },
  { value: "#7986cb", label: "Lavande" },
  { value: "#33b679", label: "Sauge" },
  { value: "#8e24aa", label: "Raisin" },
  { value: "#e67c73", label: "Flamant rose" },
  { value: "#f6bf26", label: "Banane" },
  { value: "#f4511e", label: "Mandarine" },
  { value: "#616161", label: "Graphite" },
  { value: "#3f51b5", label: "Myrtille" },
  { value: "#0b8043", label: "Basilic" },
  { value: "#d50000", label: "Tomate" },
]

export const AGENDA_DEFAULT_COLOR = AGENDA_COLOR_PALETTE[0].value

/** Normalise une couleur DAV (`#RRGGBBAA` Nextcloud → `#RRGGBB`). */
export function normalizeAgendaColor(color: string | undefined | null): string {
  const c = (color ?? "").trim()
  if (/^#[0-9a-fA-F]{8}$/.test(c)) return c.slice(0, 7).toLowerCase()
  if (/^#[0-9a-fA-F]{6}$/.test(c)) return c.toLowerCase()
  if (/^#[0-9a-fA-F]{3}$/.test(c)) {
    return `#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}`.toLowerCase()
  }
  return ""
}

/** Couleur par défaut stable pour un agenda sans couleur. */
export function fallbackCalendarColor(calendarId: string): string {
  let hash = 0
  for (let i = 0; i < calendarId.length; i++) {
    hash = (hash * 31 + calendarId.charCodeAt(i)) | 0
  }
  return AGENDA_COLOR_PALETTE[Math.abs(hash) % AGENDA_COLOR_PALETTE.length].value
}

/** Couleur de texte lisible (blanc/noir) sur un fond hex. */
export function readableTextColor(hex: string): string {
  const c = normalizeAgendaColor(hex)
  if (!c) return "#fff"
  const r = parseInt(c.slice(1, 3), 16)
  const g = parseInt(c.slice(3, 5), 16)
  const b = parseInt(c.slice(5, 7), 16)
  return (r * 299 + g * 587 + b * 114) / 1000 > 150 ? "#1f1f1f" : "#fff"
}
