import React, {useEffect, useState} from 'react';
import {useInterval} from './use_interval';

export function CounterCharacter(props) {
  const {character, leadingZero, state} = props;
  const [flash, setFlash] = useState(false);

  const renderCover = () => {
    if (state == 'resolved' && !leadingZero) {
      return null;
    } else {
      return (
        <div className="cover"></div>
      );
    }
  };

  let delay = null;
  if (state == 'flashing' || state == 'resolving') {
    delay = 100;
  }

  useInterval(() => {
    if (Math.random() <= 0.5) {
      setFlash(true);
    } else {
      setFlash(false);
    }
  }, delay);

  let characterClasses = ['character'];
  let displayCharacter = '0';
  if (state == 'resolved') {
    displayCharacter = character;
    if (!leadingZero) {
      characterClasses.push('resolved');
    }
  } else {
    if (flash) {
      characterClasses.push('covered');
    }
  }

  return (
    <div className={characterClasses.join(" ")}>
      {renderCover()}
      {displayCharacter}
    </div>
  );
}
