import { normalizedGroupCode } from './groups'

const PRESET = {
  A: { accent: '#2f4d9a', soft: 'rgba(47, 77, 154, 0.10)', border: 'rgba(47, 77, 154, 0.34)' },
  B: { accent: '#0d8fa5', soft: 'rgba(13, 143, 165, 0.10)', border: 'rgba(13, 143, 165, 0.34)' },
  C: { accent: '#d54a3f', soft: 'rgba(213, 74, 63, 0.10)', border: 'rgba(213, 74, 63, 0.34)' },
  D: { accent: '#c2891f', soft: 'rgba(194, 137, 31, 0.12)', border: 'rgba(194, 137, 31, 0.36)' },
  F1: { accent: '#5b4fc9', soft: 'rgba(91, 79, 201, 0.11)', border: 'rgba(91, 79, 201, 0.36)' },
  F2: { accent: '#0f9f63', soft: 'rgba(15, 159, 99, 0.11)', border: 'rgba(15, 159, 99, 0.36)' },
  U: { accent: '#7f8ca8', soft: 'rgba(127, 140, 168, 0.11)', border: 'rgba(127, 140, 168, 0.34)' },
}

export function scoreGroupToken(row) {
  const finalGroup = Number(row?.finalGroup || 0)
  if (finalGroup === 1) return 'F1'
  if (finalGroup === 2) return 'F2'
  const code = normalizedGroupCode(row?.groupCode || '')
  if (code) return code
  return 'U'
}

export function scoreGroupStyle(row) {
  const token = scoreGroupToken(row)
  const preset = PRESET[token]
  if (preset) {
    return {
      '--score-group-accent': preset.accent,
      '--score-group-soft': preset.soft,
      '--score-group-border': preset.border,
    }
  }

  const hue = hashToHue(token)
  return {
    '--score-group-accent': `hsl(${hue} 70% 38%)`,
    '--score-group-soft': `hsla(${hue}, 72%, 46%, 0.10)`,
    '--score-group-border': `hsla(${hue}, 70%, 38%, 0.34)`,
  }
}

export function scoreValueStyle(scoreValue) {
  const score = Number(scoreValue || 0)
  const normalized = Number.isFinite(score) ? score : 0
  const hue = hashToHue(`score:${normalized}`)
  return {
    '--score-group-accent': `hsl(${hue} 70% 38%)`,
    '--score-group-soft': `hsla(${hue}, 72%, 46%, 0.10)`,
    '--score-group-border': `hsla(${hue}, 70%, 38%, 0.34)`,
  }
}

function hashToHue(value) {
  const input = String(value || 'U')
  let hash = 0
  for (let i = 0; i < input.length; i += 1) {
    hash = (hash * 31 + input.charCodeAt(i)) % 360
  }
  return (hash + 360) % 360
}
