const { h, register, matter } = globalThis.ami
const { Box } = matter

// Default values for medium and low gauges
const DEFAULT_MEDIUM = 89
const DEFAULT_LOW = 50
// Single percent of the circle is 360 / 100
const SINGLE_PERCENT = 3.6
// Default circle radius
const DEFAULT_RADIUS = 30
// We need to double Pi to calculate the circumference
const DEFAULT_DOUBLE_PI = 2
// Ensure the circle fill starts from the top of the circle
const DEFAULT_TOPSTART = 4
// Set the default circle perimeter
const DEFAULT_CIRCLEPERIMETER = 360
// Default circumference
const DEFAULT_CIRCUMFERENCE = DEFAULT_DOUBLE_PI * Math.PI * DEFAULT_RADIUS
// Default stroke dash offset
const DEFAULT_STROKE_DASH_OFFSET = (1 / DEFAULT_TOPSTART) * DEFAULT_CIRCUMFERENCE

function GaugeValue ({ score, label, medium, low }) {
  // If medium or low are set, use those values
  const mediumScore = medium ?? DEFAULT_MEDIUM
  const lowScore = low ?? DEFAULT_LOW

  // Set colours based on score, default is green
  let stroke, fill, textFill

  if (score <= lowScore) {
    stroke = '#DD1D21'; fill = '#FFF2F0'; textFill = '#DD1D21'
  } else if (score <= mediumScore) {
    stroke = '#ED8A00'; fill = '#FFF3E5'; textFill = '#D54410'
  } else {
    stroke = '#008557'; fill = '#EFF7F2'; textFill = '#008557'
  }

  // Circle calculations to display the right gauge
  const number = (score * SINGLE_PERCENT)
  const angle = Number.parseFloat(number) || 0
  const strokeDashArray = (angle / DEFAULT_CIRCLEPERIMETER) * DEFAULT_CIRCUMFERENCE

  return h(Box, { className: 'bg-bga text-txa h-full rounded-2xl overflow-hidden' },
    h('div', { className: 'items-center justify-center' },
      h('div', { className: 'flex items-center h-full justify-center' },
        h('svg', {
          height: '64',
          width: '64',
          xmlns: 'http://www.w3.org/2000/svg',
          _style: id => `
            svg${id} { stroke-width: 4px; stroke: ${stroke}; fill: ${fill}; }
            svg${id} text { font-family: var(--font-headers); font-size: 22px; stroke: none; fill: ${textFill}; }
          `
        },
        h('circle', { cx: '32', cy: '32', r: '30', 'stroke-dasharray': [strokeDashArray, DEFAULT_CIRCUMFERENCE - strokeDashArray], 'stroke-dashoffset': DEFAULT_STROKE_DASH_OFFSET }),
        h('text', { x: '50%', y: '52%', 'dominant-baseline': 'middle', 'text-anchor': 'middle' }, score)
        )
      ),
      h('div', { className: 'flex items-center h-full justify-center' },
        h('h4', { className: 'pt-2' }, label)
      )
    )
  )
}
register(GaugeValue, 'gauge-value')
