const PromotionDisplay = (props) => {
    const { divPromoId, promotion, item_code, config } = props;
    const lang = commonFunc.getCookies('user_lang') || 'vi';

    // Khởi tạo state với giá trị null để tránh nhảy số khi mới render
    const [remainingTime, setRemainingTime] = useState(null); 
    const [saleActive, setSaleActive] = useState(true);
    const [durationFlashSale, setDurationFlashSale] = useState(0);
    const [itemsLeft, setItemsLeft] = useState(1);
    const [isFlashSale, setIsFlashSale] = useState(false);
    const [loading, setLoading] = useState(true);

    // Hàm cập nhật thời gian còn lại chính xác
    const calculateTimeLeft = useCallback(() => {
        if (!promotion?.end_date) return 0;
        
        const now = new Date().getTime();
        const endTime = new Date(promotion.end_date).getTime();
        const difference = Math.floor((endTime - now) / 1000);
        
        return difference > 0 ? difference : 0;
    }, [promotion?.end_date]);

    useEffect(() => {
        if (!divPromoId || !promotion) return;

        // 1. Khởi tạo thông số ban đầu
        const initialTime = calculateTimeLeft();
        setRemainingTime(initialTime);
        
        if (initialTime <= 0) {
            setSaleActive(false);
            setLoading(false);
            return;
        }

        // Tính toán thời gian tổng của promo để làm progress bar
        const start = new Date().getTime();
        const end = new Date(promotion.end_date).getTime();
        setDurationFlashSale(Math.floor((end - start) / 1000));
        
        // Kiểm tra loại hình Flash Sale
        const durationInDays = (end - start) / (1000 * 60 * 60 * 24);
        if (promotion.is_flash_sale || durationInDays < 4) {
            setIsFlashSale(true);
        }

        // Giả lập lấy tồn kho (anh có thể thay bằng gọi API thực tế tại đây)
        setItemsLeft(1); 

        // 2. Thiết lập bộ đếm chạy mỗi giây
        const timer = setInterval(() => {
            const timeLeft = calculateTimeLeft();
            setRemainingTime(timeLeft);

            if (timeLeft <= 0) {
                setSaleActive(false);
                clearInterval(timer);
            }
        }, 1000);

        setLoading(false);
        return () => clearInterval(timer);
    }, [promotion, calculateTimeLeft, divPromoId]);

    const formatTime = (totalSeconds) => {
        if (!totalSeconds || totalSeconds <= 0) return { days: 0, hours: '00', minutes: '00', secs: '00' };
        
        const days = Math.floor(totalSeconds / (3600 * 24));
        const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const secs = totalSeconds % 60;
        
        const pad = (num) => num.toString().padStart(2, '0');
        return { days, hours: pad(hours), minutes: pad(minutes), secs: pad(secs) };
    };

    // Điều kiện dừng render
    if (!promotion || (remainingTime > 86400 && !isFlashSale)) return null;

    const { days, hours, minutes, secs } = formatTime(remainingTime);

    return (
        <>
            <style>{`
                .promo-display-card {
                    background: linear-gradient(135deg, #fdf4f9, #fbe9f5);
                    border-radius: 12px;
                    padding: 12px;
                    color: #581c87;
                    font-family: system-ui, -apple-system, sans-serif;
                    border: 1px solid #fbcfe8;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
                    margin: 10px 0;
                }
                .promo-header {
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    margin-bottom: 8px;
                }
                .promo-title {
                    font-size: 0.95rem;
                    font-weight: 700;
                    line-height: 1.3;
                    color: #e7339a;
                }
                .promo-timer-wrapper {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    font-size: 0.85rem;
                    margin-bottom: 10px;
                    font-weight: 500;
                }
                .timer-box {
                    background: #e7339a;
                    color: white;
                    padding: 2px 6px;
                    border-radius: 4px;
                    font-weight: 700;
                    min-width: 30px;
                    text-align: center;
                }
                .progress-section {
                    display: flex;
                    align-items: center;
                    gap: 10px;
                }
                .progress-bar-outer {
                    flex-grow: 1;
                    height: 10px;
                    background-color: rgba(255, 255, 255, 0.8);
                    border-radius: 6px;
                    overflow: hidden;
                    border: 1px solid #fce7f3;
                }
                .progress-bar-inner {
                    height: 100%;
                    background: linear-gradient(90deg, #e7339a, #f472b6);
                    transition: width 1s linear;
                }
                .items-left-text {
                    font-size: 0.75rem;
                    font-weight: 700;
                    color: #9d174d;
                    white-space: nowrap;
                }
            `}</style>

            <div className="promo-display-card">
                {saleActive && remainingTime > 0 ? (
                    <div>
                        <div className="promo-header">
                            {promotion.is_flash_sale && (
                                <img 
                                    style={{ height: 24, objectFit: 'contain' }} 
                                    src={`${host_name}/static/libs/images/flash_sale_logo.png`} 
                                    alt="Flash Sale"
                                />
                            )}
                            <div className="promo-title">
                                {lang === 'en' ? promotion?.name_en : promotion?.name_vi}
                                {promotion?.condition_value == 45 && " (Member)"}
                            </div>
                        </div>

                        <div className="promo-timer-wrapper">
                            <span>{lang === 'en' ? 'Ends in:' : 'Kết thúc trong:'}</span>
                            {days > 0 && (
                                <>
                                    <span className="timer-box">{days}</span>
                                    <span>{lang === 'en' ? 'd' : 'ngày'}</span>
                                </>
                            )}
                            <span className="timer-box">{hours}</span>:
                            <span className="timer-box">{minutes}</span>:
                            <span className="timer-box">{secs}</span>
                        </div>

                        <div className="progress-section">
                            <div className="progress-bar-outer">
                                <div 
                                    className="progress-bar-inner"
                                    style={{ 
                                        width: `${durationFlashSale > 0 ? (remainingTime / durationFlashSale) * 100 : 0}%` 
                                    }}
                                ></div>
                            </div>
                            {itemsLeft > 0 && (
                                <div className="items-left-text">
                                    {lang === 'en' ? `${itemsLeft} left` : `Còn ${itemsLeft} SP`}
                                </div>
                            )}
                        </div>
                    </div>
                ) : (
                    <div className="text-center py-2 fw-bold color-muted">
                        {lang === 'en' ? "PROMOTION HAS ENDED" : "CHƯƠNG TRÌNH ĐÃ KẾT THÚC"}
                    </div>
                )}
            </div>
        </>
    );
};