import { Colors } from '@blueprintjs/core'

let state = 0 as number

const strokeOffset = (value: number) =>
  280 - 280 * Math.min(Math.max(value, 0), 1)
let el = document.getElementById('counterElement') as HTMLDivElement | null
let path = el?.querySelector('.bp5-spinner-head') as SVGPathElement | null

export const netvar = (chg: number) => {
  state = state + chg
  const value = Math.sqrt(Math.sqrt(1 / (state + 1)))
  if (!el || !path) {
    el = document.getElementById('counterElement') as HTMLDivElement | null
    path = el?.querySelector('.bp5-spinner-head') as SVGPathElement | null
  }
  if (el && path) {
    el.ariaValueNow = String(value * 100)
    if (state === 0) {
      el.title = `Backend status: working`
      path.style.removeProperty('stroke')
    } else {
      el.title = `Backend status: pending queries (${state})`
      path.style.setProperty('stroke', Colors.BLUE3, 'important')
    }
    path.setAttribute('stroke-dashoffset', strokeOffset(value).toString())
  }
}
