import ms from "pretty-ms";
import { useEffect, useState } from "react";
import { dispatch, useRoundSeconds } from "../../../../domain/gameStore";
import styles from "./GuessPane.module.css";

const RoundTimer = ({ onTimeout }) => {
  const remaining = useRoundSeconds();
  // eslint-disable-next-line consistent-return
  useEffect(() => {
    if (remaining > 0) {
      const timeout = setTimeout(() => {
        dispatch.updateRoundSeconds(r => r - 1);
      }, 1000);
      return () => clearTimeout(timeout);
    }
  }, [remaining]);
  const [called, setCalled] = useState(false);
  useEffect(() => {
    if (!called && remaining <= 0) {
      onTimeout();
      setCalled(true);
    }
  }, [onTimeout, remaining, called]);

  return remaining > 0 ? (
    <span className={styles.timer}>Time: {ms(remaining * 1000)}</span>
  ) : (
    <span className={`${styles.timer} ${styles["timer--timeout"]}`}>
      Time&apos;s up!
    </span>
  );
};

export default RoundTimer;
