"use client"; import { ChangeEvent, SyntheticEvent, useEffect, useRef, useState } from "react"; import styles from "../../css/WelcomeScreen.module.css"; import ChargedButton from "../ChargedButton"; import { useLocalStorage } from "@/hooks/useLocalStorage"; import { PREF } from "@/utils/const"; const CODE_LENGTH = 9; const COOLDOWN_MS = 3000; export default function WelcomeScreen() { const [tourCode, setTourCode] = useState(""); const [lastSubmitTs, setLastSubmitTs] = useState(0); const [isCooldown, setIsCooldown] = useState(false); const tourCodeRef = useRef(""); const cooldownRef = useRef(-1); const [, setCode ] = useLocalStorage(PREF.code, ""); const [, setStep ] = useLocalStorage(PREF.step, "0"); const checkCooldown = () => { if (cooldownRef.current === -1) return false; return Date.now() - cooldownRef.current <= COOLDOWN_MS }; const isTourCodeValid = () => { return tourCode.length === CODE_LENGTH; }; const cleanTourCode = (dirtyTourCode: string): string => { return dirtyTourCode.toUpperCase().replaceAll(/\W/g, "").substring(0, 9); }; useEffect(() => { if (checkCooldown()) { setIsCooldown(true); const inputTimeout = setTimeout(() => { console.log("Cooldown over"); setIsCooldown(false); }, 3000); return () => clearTimeout(inputTimeout); } else { setIsCooldown(false); } }, [lastSubmitTs]); const submit = () => { const value = cleanTourCode(tourCodeRef.current); if (!isTourCodeValid() && checkCooldown()) { return; } cooldownRef.current = Date.now(); setLastSubmitTs(cooldownRef.current); console.log("submitted", value); setCode(value); setStep("1"); }; const handleChange = (event: ChangeEvent): boolean => { const value = event.target.value; if (value.length > CODE_LENGTH) { event.preventDefault(); return false; } tourCodeRef.current = value; setTourCode(cleanTourCode(value)); return true; }; const buttonDisabled = isCooldown || !isTourCodeValid(); return (


{(!buttonDisabled) ? "Halten zum Spielen!" : "Halten zum Spielen."}
); }