import { useState, useEffect, useRef } from "react";
import styles from "../styles/Army.module.css"

const tavernerQuotes = [
  "There is always Moloch to be slain here...",
  "We prioritize Shipping at All Costs!",
  "Get out there RAIDER, Moloch won't Slay Himself!",
];

function PixelatedQuote() {
  const [isShown, setIsShown] = useState(true);
  const [currentQuote, setCurrentQuote] = useState(
    "Welcome to the Dark Forest!"
  );
  const intervalIdRef = useRef<NodeJS.Timeout | null>(null); // Define the type for Node environment compatibility

  useEffect(() => {
    if (intervalIdRef.current !== null) {
      clearInterval(intervalIdRef.current);
    } // Clear interval if it exists

    // Set up an interval to show the toast every 10 seconds
    intervalIdRef.current = setInterval(() => {
      setCurrentQuote(
        tavernerQuotes[Math.floor(Math.random() * tavernerQuotes.length)]
      );
      setIsShown(true);

      // Hide the toast after 4 seconds
      setTimeout(() => {
        setIsShown(false);
      }, 4000);
    }, 6000);

    // Clean up the interval on component unmount
    return () => {
      if (intervalIdRef.current !== null) {
        clearInterval(intervalIdRef.current); // Clear interval using correct reference
        intervalIdRef.current = null;
      }
    };
  }, []);

  return (
    <div>
      <div
        className={`pixel-borders pixel-borders--2 pixelFont ${styles.pixelQuote}`}
        style={{ opacity: isShown ? 1 : 0 /* Control visibility with opacity */ }}
      >
        {currentQuote}
      </div>
    </div>
  );
}

export default PixelatedQuote;
