import React, { useEffect, useState } from "react"; import { Swiper, SwiperSlide } from "swiper/react"; import { Navigation } from "swiper/modules"; import "swiper/css"; import "swiper/css/navigation"; import { Zap } from "lucide-react"; import { Flex } from "antd"; import { useGetFlashSalesQuery } from "../../app/api/flashSalesApi"; import ProductCard from "../ProductCard"; import styles from "./FlashSales.module.scss"; import { useTranslation } from "react-i18next"; const parseTime = (timeStr) => { if (!timeStr) return { hours: "00", minutes: "00", seconds: "00" }; const parts = timeStr.split(":"); return { hours: parts[0] || "00", minutes: parts[1] || "00", seconds: parts[2] || "00", }; }; const FlashSales = () => { const { t } = useTranslation(); const { data, isLoading, isError } = useGetFlashSalesQuery(); const [timers, setTimers] = useState([]); const getTimeLeft = (end) => { const endTime = new Date(end).getTime(); const now = new Date().getTime(); let diff = endTime - now; if (diff <= 0) return "00:00:00"; const days = Math.floor(diff / (1000 * 60 * 60 * 24)); diff = diff % (1000 * 60 * 60 * 24); const hours = String(Math.floor(diff / (1000 * 60 * 60))).padStart(2, "0"); const minutes = String(Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))).padStart(2, "0"); const seconds = String(Math.floor((diff % (1000 * 60)) / 1000)).padStart(2, "0"); if (days > 0) { return `${days}g ${hours}:${minutes}:${seconds}`; } return `${hours}:${minutes}:${seconds}`; }; useEffect(() => { if (!data?.data) return; const updateTimers = () => { setTimers(data.data.map((flashSale) => getTimeLeft(flashSale.ends_at))); }; updateTimers(); const interval = setInterval(updateTimers, 1000); return () => clearInterval(interval); }, [data]); if (isLoading || isError || !data?.data?.length) return null; return (
{data.data.map((flashSale, idx) => { // Timer parse let days = 0, hours = "00", minutes = "00", seconds = "00"; if (timers[idx]) { const match = timers[idx].match(/(?:(\d+)g )?(\d{2}):(\d{2}):(\d{2})/); if (match) { days = match[1] ? Number(match[1]) : 0; hours = match[2]; minutes = match[3]; seconds = match[4]; } } return (
{/* ── Header ── */} {/* Left: icon + title */} {t("flashSales.flash_sale")} {flashSale.title && ( {flashSale.title} )} {/* Right: countdown timer */} {t("flashSales.ends_in")} {days > 0 && (
{days} {t("flashSales.day")}
)}
{hours} {t("flashSales.hour")}
:
{minutes} {t("flashSales.minute")}
:
{seconds} {t("flashSales.second")}
{/* ── Products Carousel ── */}
{flashSale.products.map((product) => ( ))}
); })}
); }; export default FlashSales;