import { useEffect, useReducer, useRef } from 'react';
import { usePlayer } from '../providers/PlayerProvider';
import styles from '../styles/Background.module.css';

const onCooldown = (lastRaidedAt: bigint) => (
  ((new Date()).getTime()
    - (parseInt(lastRaidedAt.toString()) * 1000 /* convert block time to seconds */))
  / 1000 /* convert milliseconds back to seconds*/
) <= 15

const emptyFn = () => { }

const Tower = () => {
  const { raid, player } = usePlayer();
  const isOnCooldown = useRef(false);
  const [, render] = useReducer(p => !p, false);

  useEffect(() => {
    const checkCooldownInterval = setInterval(() => {
      isOnCooldown.current = onCooldown(player?.last_raided_at ?? BigInt(0))
      render()
    }, 1000);
    return () => clearInterval(checkCooldownInterval)
  }, [player?.last_raided_at])

  return <div onClick={isOnCooldown.current ? emptyFn : raid} className={`
    ${styles.tower} 
    ${styles.background_asset}
    ${isOnCooldown.current ? styles.cooldown : ""}
  `} />
}

export default Tower
