import React, { useState, useEffect } from 'react'

import constants from '../constants'

const soundCount = 7
function GetRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

export default function BB() {
  const [audios, setAudios] = useState(null)
  const [range, setRange] = useState([0, 3])
  const [clicks, setClicks] = useState(0)
  const [shouldRender, setShouldRender] = useState(false)

  useEffect(() => {
    setShouldRender(GetRandom(0, 200) === 4)
  }, [])

  useEffect(() => {
    if (shouldRender) {
      const res = []
      for (let i = 1; i < soundCount + 2; i++) {
        res.push(new Audio(`${constants.siteUrl}sound/deer${i}.mp3`))
      }
      setAudios(res)
    }
  }, [shouldRender])

  useEffect(() => {
    if (clicks > 3) {
      setRange([4, 5])
    }
    if (clicks > 6) {
      setRange([6, 7])
    }
  }, [clicks])

  if (!shouldRender) {
    return null
  }

  return (
    <div
      style={{ position: 'fixed', right: 0, bottom: 0, margin: 0, padding: 0 }}
      onClick={() => {
        const rnd = GetRandom(range[0], range[1])
        audios[rnd].play()
        setClicks(clicks + 1)
      }}
    >
      <img
        src={`${constants.siteUrl}img/tiszai.png`}
        alt="img"
        style={{ cursor: 'pointer', width: '200px' }}
      />
    </div>
  )
}
