/**
 * Coupon Countdown Timer with Cloud Animation
 * Real-time countdown for coupon expiry
 */

class CouponCountdown {
    constructor(element) {
        this.element = element;
        this.expiryDate = new Date(element.dataset.expiry);
        this.init();
    }
    
    init() {
        if (isNaN(this.expiryDate.getTime())) {
            this.element.innerHTML = '<span class="countdown-label">⚠️ Invalid expiry date</span>';
            return;
        }
        
        this.update();
        this.interval = setInterval(() => this.update(), 1000);
    }
    
    update() {
        const now = new Date();
        const diff = this.expiryDate - now;
        
        if (diff <= 0) {
            this.showExpired();
            clearInterval(this.interval);
            return;
        }
        
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((diff % (1000 * 60)) / 1000);
        
        this.render(days, hours, minutes, seconds, diff);
    }
    
    render(days, hours, minutes, seconds, totalDiff) {
        const isUrgent = totalDiff < (24 * 60 * 60 * 1000); // Less than 24 hours
        
        this.element.className = 'coupon-countdown' + (isUrgent ? ' urgent' : '');
        
        let timeString = '';
        if (days > 0) {
            timeString = `${days}d ${hours}h ${minutes}m`;
        } else if (hours > 0) {
            timeString = `${hours}h ${minutes}m ${seconds}s`;
        } else {
            timeString = `${minutes}m ${seconds}s`;
        }
        
        this.element.innerHTML = `
            <span class="countdown-icon">⚡</span>
            <span class="countdown-label">Ends in:</span>
            <span class="countdown-time">${timeString}</span>
            <div class="countdown-cloud"></div>
        `;
    }
    
    showExpired() {
        this.element.className = 'coupon-countdown expired';
        this.element.innerHTML = `
            <span class="countdown-icon">🕐</span>
            <span class="countdown-label">Expired</span>
        `;
    }
    
    destroy() {
        if (this.interval) {
            clearInterval(this.interval);
        }
    }
}

// Initialize all countdown timers
function initCouponCountdowns() {
    const countdowns = document.querySelectorAll('[data-countdown]');
    const instances = [];
    
    countdowns.forEach(element => {
        instances.push(new CouponCountdown(element));
    });
    
    return instances;
}

// Auto-initialize on DOM ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initCouponCountdowns);
} else {
    initCouponCountdowns();
}

// Export for manual initialization
window.CouponCountdown = CouponCountdown;
window.initCouponCountdowns = initCouponCountdowns;
