turkmentv_front/components/lottery/LotteryWinnersSection.tsx

250 lines
9.0 KiB
TypeScript
Raw Normal View History

2025-01-19 13:02:34 +00:00
import { useState, useEffect } from "react";
import { useLotteryAuth } from "@/store/useLotteryAuth";
import { LotteryWinnerDataSimplified } from "@/typings/lottery/lottery.types";
import LotteryWinnersList from "./winners/LotteryWinnersList";
import LotterySlotCounter from "./slotCounter/LotterySlotCounter";
import AnimatedText from "@/components/common/AnimatedText";
import { useWebsocketLottery } from "@/hooks/useWebSocketLottery";
import Confetti from "../common/Confetti";
import { AnimatePresence, motion } from "framer-motion";
2025-01-24 13:20:46 +00:00
const WEBSOCKET_URL = "wss://sms.turkmentv.gov.tm/ws/lottery?dst=";
2025-01-09 14:53:20 +00:00
const SLOT_COUNTER_DURATION = 30000;
2024-12-27 12:52:55 +00:00
2025-01-19 13:02:34 +00:00
const LotteryWinnersSection = ({
lotteryStatus,
}: {
lotteryStatus: string;
}) => {
2024-12-27 12:52:55 +00:00
const [winners, setWinners] = useState<LotteryWinnerDataSimplified[]>([]);
2025-01-19 13:02:34 +00:00
const [currentNumber, setCurrentNumber] = useState<string>("00-00-00-00-00");
2024-12-25 13:46:20 +00:00
const [isConfettiActive, setIsConfettiActive] = useState(false);
2024-12-29 18:02:23 +00:00
2024-12-23 19:32:28 +00:00
const { lotteryData } = useLotteryAuth();
2025-01-03 12:45:58 +00:00
const [winnerSelectingStatus, setWinnerSelectingStatus] = useState<
2025-01-19 13:02:34 +00:00
"not-selected" | "is-selecting" | "selected"
>("not-selected");
const [pendingWinner, setPendingWinner] =
useState<LotteryWinnerDataSimplified | null>(null);
const [topText, setTopText] = useState<string>("Bije az wagtdan başlaýar");
const [bottomText, setBottomText] = useState<string>("");
const [messageQueue, setMessageQueue] = useState<
LotteryWinnerDataSimplified[]
>([]); // Queue for incoming WebSocket messages
const [isProcessing, setIsProcessing] = useState<boolean>(false); // Track if a message is being processed
2025-01-05 18:32:06 +00:00
2025-01-24 13:20:46 +00:00
const { wsStatus, subscribeToMessages } = useWebsocketLottery(
`${WEBSOCKET_URL}${lotteryData?.data.sms_number}`
);
2025-01-03 13:13:06 +00:00
2025-01-25 13:40:18 +00:00
// Simulate WebSocket message for testing
2025-01-19 13:02:34 +00:00
const simulateMessage = () => {
const dummyWinner: LotteryWinnerDataSimplified = {
2025-01-25 13:40:18 +00:00
phone: `9936${Math.floor(10000000 + Math.random() * 90000000)}`, // Generate random client number
winner_no: winners.length + 1, // Increment winner number
2025-01-19 13:02:34 +00:00
ticket: `${Math.floor(Math.random() * 99)
.toString()
.padStart(2, "0")}-${Math.floor(Math.random() * 99)
.toString()
.padStart(2, "0")}-${Math.floor(Math.random() * 99)
.toString()
.padStart(2, "0")}-${Math.floor(Math.random() * 99)
.toString()
.padStart(2, "0")}-${Math.floor(Math.random() * 99)
.toString()
2025-01-25 13:40:18 +00:00
.padStart(2, "0")}`, // Generate random ticket
2025-01-19 13:02:34 +00:00
};
2025-01-25 13:40:18 +00:00
console.log("📩 Simulated Message:", dummyWinner); // Log the simulated message
2025-01-19 13:02:34 +00:00
setMessageQueue((prevQueue) => [...prevQueue, dummyWinner]);
};
2025-01-25 13:40:18 +00:00
// useEffect(() => {
// const interval = setInterval(() => {
// simulateMessage();
// }, 20000); // Trigger every 10 seconds
// return () => clearInterval(interval); // Clean up interval on unmount
// }, []);
2025-01-19 13:02:34 +00:00
// Initialize winners from lottery data
2025-01-15 18:44:28 +00:00
useEffect(() => {
2025-01-25 13:40:18 +00:00
console.log("🎟️ Lottery Data:", lotteryData);
2025-01-19 13:02:34 +00:00
if (lotteryData && lotteryData.data.winners.length > 0) {
const simplifiedWinners = lotteryData.data.winners.map((winner) => ({
2025-01-25 13:40:18 +00:00
phone: winner.client,
2025-01-19 13:02:34 +00:00
winner_no: winner.winner_no,
ticket: winner.ticket,
}));
setWinners(simplifiedWinners);
const lastWinner = simplifiedWinners[simplifiedWinners.length - 1];
setWinnerSelectingStatus("selected");
setTopText(`${lastWinner.winner_no}-nji ýeňiji`);
2025-01-25 13:40:18 +00:00
setBottomText(lastWinner.phone);
2025-01-19 13:02:34 +00:00
setIsConfettiActive(true);
2025-01-15 18:44:28 +00:00
}
}, [lotteryData]);
2024-12-23 19:32:28 +00:00
2025-01-19 13:02:34 +00:00
// Subscribe to WebSocket messages
2024-12-27 12:52:55 +00:00
useEffect(() => {
2025-01-05 19:17:39 +00:00
const unsubscribe = subscribeToMessages((event) => {
2025-01-19 13:02:34 +00:00
try {
const newWinner: LotteryWinnerDataSimplified = JSON.parse(event.data);
2025-01-25 13:40:18 +00:00
console.log("📩 WebSocket Message Received:", newWinner); // Log the parsed message
2025-01-03 13:13:06 +00:00
2025-01-19 13:02:34 +00:00
// Add new message to the queue
2025-01-25 13:40:18 +00:00
setMessageQueue((prevQueue) => {
console.log("📥 Adding to Queue:", newWinner);
return [...prevQueue, newWinner];
});
2025-01-19 13:02:34 +00:00
} catch (error) {
console.error("Error parsing WebSocket message:", error);
}
2025-01-05 19:17:39 +00:00
});
2025-01-05 18:32:06 +00:00
2025-01-19 13:02:34 +00:00
return () => unsubscribe();
2025-01-05 19:17:39 +00:00
}, [subscribeToMessages]);
2025-01-03 13:13:06 +00:00
2025-01-19 13:02:34 +00:00
// Process queue when a new message is added
useEffect(() => {
2025-01-25 13:40:18 +00:00
console.log("📋 Current Message Queue:", messageQueue);
2025-01-19 13:02:34 +00:00
if (!isProcessing && messageQueue.length > 0) {
processQueue();
}
}, [messageQueue, isProcessing]);
// Process a single message from the queue
const processQueue = async () => {
if (isProcessing || messageQueue.length === 0) return;
setIsProcessing(true); // Lock processing
const message = messageQueue[0]; // Get the first message in the queue
2025-01-25 13:40:18 +00:00
console.log("⚙️ Processing Message:", message); // Debug Log 4: Log the message being processed
2025-01-19 13:02:34 +00:00
try {
await handleMessage(message); // Process the message
} catch (error) {
console.error("Error processing message:", error);
}
setMessageQueue((prevQueue) => prevQueue.slice(1)); // Remove the processed message from the queue
setIsProcessing(false); // Unlock processing
};
// Handle the logic for processing a single WebSocket message
const handleMessage = async (winner: LotteryWinnerDataSimplified) => {
2025-01-25 13:40:18 +00:00
console.log("⬇️ Updating Top and Bottom Text:", winner); // Debug Log 5: Log winner data before setting states
2025-01-19 13:02:34 +00:00
setIsConfettiActive(false);
setTopText(`${winner.winner_no}-nji ýeňiji saýlanýar`);
setBottomText("...");
setWinnerSelectingStatus("is-selecting");
setPendingWinner(winner);
setCurrentNumber(winner.ticket);
// Wait for the animation duration
await new Promise((resolve) => setTimeout(resolve, SLOT_COUNTER_DURATION));
// Finalize winner selection
setTopText(`${winner.winner_no}-nji ýeňiji`);
2025-01-25 13:40:18 +00:00
setBottomText(winner.phone);
console.log("⬇️ Finalized Bottom Text:", winner.phone); // Debug Log 6: Log the final bottomText update
2025-01-19 13:02:34 +00:00
setWinnerSelectingStatus("selected");
setIsConfettiActive(true);
// Add the winner to the list
setWinners((prevWinners) => [...prevWinners, winner]);
// Wait for the animation duration
await new Promise((resolve) => setTimeout(resolve, 5000));
};
2025-01-09 14:53:20 +00:00
2024-11-25 14:33:01 +00:00
return (
<section>
2025-01-19 13:02:34 +00:00
{wsStatus === "error" && (
<div className="text-red-500 text-center mb-2">
Websocket connection error.
</div>
2024-12-25 13:46:20 +00:00
)}
2025-01-19 13:02:34 +00:00
<Confetti showConfetti={isConfettiActive} numberOfPieces={300} />
{/* Simmulation Button */}
{/* <div className="w-full flex justify-center py-4">
<button
onClick={simulateMessage}
className="px-4 py-2 bg-blue-500 text-white rounded"
>
Simulate Message
</button>
</div> */}
2024-11-25 14:33:01 +00:00
<div className="container">
2025-01-02 12:47:39 +00:00
<div
2025-01-03 12:52:05 +00:00
className="flex flex-col items-center rounded-[32px] gap-[40px]"
2025-01-05 18:32:06 +00:00
style={{
2025-01-19 13:02:34 +00:00
background: "linear-gradient(180deg, #F0ECF4 0%, #E1E0FF 43.5%)",
}}
>
2025-01-09 14:53:20 +00:00
<AnimatePresence>
<div className="flex items-center justify-center w-full sm:min-h-[240px] pt-6">
2025-01-19 13:02:34 +00:00
{winnerSelectingStatus === "not-selected" ? (
2025-01-09 14:53:20 +00:00
<AnimatedText
key={topText}
text={topText}
2025-01-16 12:59:03 +00:00
className="text-center flex items-center justify-center md:text-[80px] sm:text-[56px] text-[24px] leading-[120%] text-[#E65E19]"
duration={0.4}
2025-01-09 14:53:20 +00:00
/>
) : (
<motion.div
variants={{
enter: {
transition: { staggerChildren: 1, delayChildren: 0.5 },
},
exit: {
transition: {
staggerChildren: 0.05,
staggerDirection: -1,
},
2025-01-09 14:53:20 +00:00
},
}}
2025-01-19 13:02:34 +00:00
className="flex flex-col items-center justify-center"
>
2025-01-03 12:52:05 +00:00
<AnimatedText
2025-01-09 14:53:20 +00:00
key={topText}
text={topText}
className="text-center sm:text-[56px] text-[24px] w-full leading-[120%] text-[#E65E19]"
duration={0.4}
2025-01-03 12:52:05 +00:00
/>
2025-01-09 14:53:20 +00:00
{bottomText && (
<AnimatedText
key={bottomText}
text={bottomText}
className="text-center sm:text-[80px] text-[32px] leading-[120%] text-[#E65E19]"
duration={0.4}
/>
)}
</motion.div>
)}
</div>
</AnimatePresence>
2025-01-03 12:45:58 +00:00
<div className="z-10">
2025-01-19 13:02:34 +00:00
{currentNumber && (
<LotterySlotCounter numberString={currentNumber} />
)}
2024-12-25 13:46:20 +00:00
</div>
2025-01-03 12:52:05 +00:00
<div className="flex gap-6 rounded-[12px] flex-1 w-full items-center justify-center sm:pb-[62px] pb-[32px] px-4">
2025-01-16 12:59:03 +00:00
{winners.length > 0 && <LotteryWinnersList winners={winners} />}
2024-11-25 14:33:01 +00:00
</div>
</div>
</div>
</section>
);
};
export default LotteryWinnersSection;