import { useRef } from 'react'

import isNumber from 'lodash/isNumber'

import { useLocalStore } from 'hooks'

const defaultVolume = 1

export const useVolume = () => {
  const prevVolumeRef = useRef(defaultVolume)
  const [volume, setVolume] = useLocalStore({
    defaultValue: defaultVolume,
    key: 'player_volume',
    validator: isNumber,
  })

  const onVolumeChange = (value: number) => {
    setVolume(value)
  }

  const onVolumeClick = () => {
    setVolume(volume === 0 ? prevVolumeRef.current : 0)
    prevVolumeRef.current = volume || defaultVolume
  }

  return {
    muted: volume === 0,
    onVolumeChange,
    onVolumeClick,
    volume,
    volumeInPercent: volume * 100,
  }
}
