import { useEffect } from "react";
import { useParams } from "react-router-dom";

import { debounce } from "./utils";
import { socket } from "./socket";
import { useAppSelector } from "./hooks";
import { selectCanBuzz, selectSignature } from "./store/contestantSlice";

const Contestant = () => {
  const { room } = useParams();

  const signature = useAppSelector(selectSignature);
  const canBuzz = useAppSelector(selectCanBuzz);

  useEffect(() => {
    socket.emit("contestant-join", { room, signature });
  }, []);

  const handleBuzz = debounce(() => {
    if (canBuzz) {
      socket.emit("buzz");
    }
  });

  return (
    <div>
      <svg viewBox={`0 0 100 100`}>
        <circle
          cx={50}
          cy={50}
          r={30}
          fill={canBuzz ? "red" : "grey"}
          stroke="black"
          onClick={handleBuzz}
        />
        <text x={50} y={50} textAnchor="middle">
          Buzz
        </text>
      </svg>
    </div>
  );
};

export default Contestant;
