export type WidgetVisualInput = {
  title?: string
  color?: string
  icon?: string
  images?: string[]
}

export type WidgetVisuals = {
  color: string
  icon: string
  images: string[]
}

const getHashValue = (value: string) =>
  value.split("").reduce((acc, char) => acc * 31 + char.charCodeAt(0), 7)

export const generateColorFromName = (name: string): string => {
  // Same input name -> same output color (stable across reloads/environments).
  const normalizedName = name.trim().toLowerCase() || "widget"
  const hash = Math.abs(getHashValue(normalizedName))
  // Spread widgets over the full color wheel.
  const hue = hash % 360
  // Keep saturation/lightness in a readable mid-range to avoid too grey or too neon colors.
  const saturation = 55 + (hash % 18) // 55..72
  const lightness = 42 + (hash % 16) // 42..57
  return `hsl(${hue} ${saturation}% ${lightness}%)`
}

export const getWidgetInitials = (name: string): string => {
  const parts = name
    .trim()
    .split(/\s+/)
    .filter(Boolean)

  if (parts.length === 0) {
    return "W"
  }

  if (parts.length === 1) {
    return parts[0].slice(0, 2).toUpperCase()
  }

  return `${parts[0][0]}${parts[1][0]}`.toUpperCase()
}

export const normalizeWidgetVisuals = (
  details: WidgetVisualInput,
  widgetName: string,
): WidgetVisuals => {
  // Prefer plugin-provided values; only fallback when field is missing/empty.
  const normalizedColor =
    typeof details.color === "string" && details.color.trim().length > 0
      ? details.color
      : generateColorFromName(details.title || widgetName)

  const normalizedIcon =
    typeof details.icon === "string" && details.icon.trim().length > 0
      ? details.icon
      : ""

  const normalizedImages = Array.isArray(details.images)
    // Ignore invalid/empty entries to keep consumers simple.
    ? details.images.filter((image) => typeof image === "string" && image.trim())
    : []

  return {
    color: normalizedColor,
    icon: normalizedIcon,
    images: normalizedImages,
  }
}
