{%- assign targetStr = date | Append:' ' | Append:time -%}
{%- assign target = targetStr | Date:'MM/dd/yyyy HH:mm' | AsDateTime -%}
{%- if target == null -%}
    <span>Invalid date/time format.</span>
{%- else -%}
    {%- assign now = 'Now' | Date | AsDateTime -%}
    {%- assign seconds = now | DateDiff:target,'s' -%}
    {%- if seconds < 0 -%}{%- assign seconds = 0 -%}{%- endif -%}
    {%- assign days = seconds | DividedBy:86400 | Floor -%}
    {%- assign hours = seconds | Modulo:86400 | DividedBy:3600 | Floor -%}
    {%- assign minutes = seconds | Modulo:3600 | DividedBy:60 | Floor -%}
    {%- assign seconds = seconds | Modulo:60 | Floor -%}
    {%- assign colorBackground = color-background | Default:'#149cd8' -%}
    {%- assign colorFont = color-font | Default:'black' -%}
    {%- assign colorNumber = color-number | Default:'white' -%}
    {%- assign animationType = animation-type | Default:'default' | Downcase -%}
    {%- assign uniqueId = 'Now' | Date:'yyyyMMddHHmmssffff' -%}

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/TextPlugin.min.js"></script>

<div class="countdown-timer countdown-{{ uniqueId }}" data-target="{{ target | Date:'yyyy-MM-ddTHH:mm:ss' }}" data-animation="{{ animationType }}" style="display: flex; justify-content: center; gap: 15px; font-family: Arial, sans-serif; max-width: 100%; flex-wrap: wrap;">
    <div class="countdown-unit days">
        <div class="digit-box" data-unit="days" style="background-color: {{ colorBackground }}; color: {{ colorNumber }}; padding: 15px; border-radius: 8px; text-align: center; min-width: 80px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); margin-bottom: 20px; position: relative; overflow: hidden;">
            <span class="value animated-value">{{ days | Format:'00' }}</span>
            <div class="particle-container" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;"></div>
        </div>
        <div class="label" style="color: {{ colorFont }}; text-align: center; font-size: 0.9em;">Days</div>
    </div>
    <div class="countdown-unit hours">
        <div class="digit-box" data-unit="hours" style="background-color: {{ colorBackground }}; color: {{ colorNumber }}; padding: 15px; border-radius: 8px; text-align: center; min-width: 80px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); margin-bottom: 20px; position: relative; overflow: hidden;">
            <span class="value animated-value">{{ hours | Format:'00' }}</span>
            <div class="particle-container" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;"></div>
        </div>
        <div class="label" style="color: {{ colorFont }}; text-align: center; font-size: 0.9em;">Hours</div>
    </div>
    <div class="countdown-unit minutes">
        <div class="digit-box" data-unit="minutes" style="background-color: {{ colorBackground }}; color: {{ colorNumber }}; padding: 15px; border-radius: 8px; text-align: center; min-width: 80px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); margin-bottom: 20px; position: relative; overflow: hidden;">
            <span class="value animated-value">{{ minutes | Format:'00' }}</span>
            <div class="particle-container" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;"></div>
        </div>
        <div class="label" style="color: {{ colorFont }}; text-align: center; font-size: 0.9em;">Minutes</div>
    </div>
    <div class="countdown-unit seconds">
        <div class="digit-box" data-unit="seconds" style="background-color: {{ colorBackground }}; color: {{ colorNumber }}; padding: 15px; border-radius: 8px; text-align: center; min-width: 80px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); margin-bottom: 20px; position: relative; overflow: hidden;">
            <span class="value animated-value">{{ seconds | Format:'00' }}</span>
            <div class="particle-container" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;"></div>
        </div>
        <div class="label" style="color: {{ colorFont }}; text-align: center; font-size: 0.9em;">Seconds</div>
    </div>
</div>

{%- stylesheet id:'countdown-timer-style' -%}
    .countdown-timer { font-size: 1.2em; padding: 10px; }
    .countdown-unit { text-align: center; min-width: 100px; }
    .digit-box { 
        font-size: 2em; 
        font-weight: bold; 
        position: relative; 
        overflow: hidden; 
        perspective: 1000px;
        transform-style: preserve-3d;
    }
    .animated-value { 
        display: inline-block; 
        position: relative;
        z-index: 2;
    }
    .liquid-fill {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        background: linear-gradient(180deg, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0.1) 100%);
        z-index: 1;
        transition: height 1s ease-out;
    }
    .particle {
        position: absolute;
        width: 4px;
        height: 4px;
        background: rgba(255,255,255,0.8);
        border-radius: 50%;
        pointer-events: none;
    }
    .slot-container {
        position: relative;
        height: 1.2em;
        overflow: hidden;
    }
    .slot-reel {
        position: absolute;
        width: 100%;
    }
    .cube-container {
        width: 100%;
        height: 100%;
        position: relative;
        transform-style: preserve-3d;
        transition: transform 0.6s;
    }
    .cube-face {
        position: absolute;
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        backface-visibility: hidden;
    }
    .cube-face.front { transform: translateZ(40px); }
    .cube-face.back { transform: rotateY(180deg) translateZ(40px); }
    .cube-face.top { transform: rotateX(90deg) translateZ(40px); }
    .cube-face.bottom { transform: rotateX(-90deg) translateZ(40px); }
    @media (max-width: 768px) {
        .digit-box { font-size: 1.5em; padding: 10px; min-width: 60px; }
        .countdown-unit { min-width: 80px; }
    }
{%- endstylesheet -%}

{%- javascript id:'countdown-timer-script-{{ uniqueId }}' disableanonymousfunction:'true' -%}
(function() {
    function initCountdown{{ uniqueId }}() {
        if (typeof gsap === 'undefined') {
            setTimeout(initCountdown{{ uniqueId }}, 100);
            return;
        }
        
        if (typeof gsap !== 'undefined' && gsap.registerPlugin) {
            if (typeof TextPlugin !== 'undefined') {
                gsap.registerPlugin(TextPlugin);
            }
        }
        
        var CountdownUtils = {
            getTimeDiff: function(targetDate) {
                var now = new Date();
                var diff = (new Date(targetDate) - now) / 1000;
                if (diff < 0) diff = 0;
                var days = Math.floor(diff / 86400);
                var hours = Math.floor((diff % 86400) / 3600);
                var minutes = Math.floor((diff % 3600) / 60);
                var seconds = Math.floor(diff % 60);
                return { days: days, hours: hours, minutes: minutes, seconds: seconds };
            },
            padNumber: function(num) {
                return num.toString().padStart(2, '0');
            }
        };

        function GSAPCountdownTimer(element) {
            var self = this;
            self.element = element;
            self.target = element.dataset.target;
            self.animationType = element.dataset.animation || 'default';
            self.units = {
                days: element.querySelector('.days .digit-box'),
                hours: element.querySelector('.hours .digit-box'),
                minutes: element.querySelector('.minutes .digit-box'),
                seconds: element.querySelector('.seconds .digit-box')
            };
            self.values = {
                days: self.units.days.querySelector('.value'),
                hours: self.units.hours.querySelector('.value'),
                minutes: self.units.minutes.querySelector('.value'),
                seconds: self.units.seconds.querySelector('.value')
            };
            self.previousValues = {};
            self.isFirstRun = true;
            self.originalBackgroundColor = self.units.days.style.backgroundColor || '{{ colorBackground }}';
            
            if (self.animationType === 'liquid') {
                self.initLiquidFill();
            }
            
            self.update();
            self.interval = setInterval(function() { self.update(); }, 1000);
        }
        
        GSAPCountdownTimer.prototype.initLiquidFill = function() {
            var self = this;
            Object.keys(self.units).forEach(function(key) {
                var fill = document.createElement('div');
                fill.className = 'liquid-fill';
                fill.style.height = '0%';
                self.units[key].appendChild(fill);
            });
        };
        
        GSAPCountdownTimer.prototype.update = function() {
            var self = this;
            var timeData = CountdownUtils.getTimeDiff(self.target);
            var totalSeconds = timeData.days * 86400 + timeData.hours * 3600 + timeData.minutes * 60 + timeData.seconds;
            var maxSeconds = 86400 * 365;
            
            var newValues = {
                days: CountdownUtils.padNumber(timeData.days),
                hours: CountdownUtils.padNumber(timeData.hours),
                minutes: CountdownUtils.padNumber(timeData.minutes),
                seconds: CountdownUtils.padNumber(timeData.seconds)
            };
            
            Object.keys(newValues).forEach(function(key) {
                if (self.isFirstRun || self.values[key].textContent !== newValues[key]) {
                    self.animateChange(key, newValues[key], timeData, totalSeconds, maxSeconds);
                    self.previousValues[key] = newValues[key];
                }
            });
            
            self.isFirstRun = false;
        };
        
        GSAPCountdownTimer.prototype.animateChange = function(unit, newValue, timeValues, totalSeconds, maxSeconds) {
            var self = this;
            var box = self.units[unit];
            var valueElement = self.values[unit];
            var oldValue = valueElement.textContent;
            var animType = self.animationType;
            
            if (animType === 'elastic') {
                self.elasticBounce(box, valueElement, newValue);
            } else if (animType === 'particle') {
                self.particleExplosion(box, valueElement, newValue);
            } else if (animType === 'wave') {
                self.waveAnimation(unit, valueElement, newValue);
            } else if (animType === 'cube') {
                self.cubeRotation(box, valueElement, newValue);
            } else if (animType === 'gradient') {
                self.gradientShift(box, valueElement, newValue, totalSeconds, maxSeconds);
            } else if (animType === 'scramble') {
                self.scrambleEffect(valueElement, newValue);
            } else if (animType === 'pulse') {
                self.pulseGlow(box, valueElement, newValue, timeValues);
            } else if (animType === 'slot') {
                self.slotMachine(box, valueElement, newValue);
            } else if (animType === 'liquid') {
                self.liquidFill(box, unit, timeValues, valueElement, newValue);
            } else if (animType === 'morph') {
                self.morphTransition(valueElement, oldValue, newValue);
            } else if (animType === 'matrix') {
                self.matrixRain(box, valueElement, newValue);
            } else {
                gsap.to(valueElement, {
                    opacity: 0,
                    duration: 0.2,
                    onComplete: function() {
                        valueElement.textContent = newValue;
                        gsap.to(valueElement, { opacity: 1, duration: 0.2 });
                    }
                });
            }
        };
        
        GSAPCountdownTimer.prototype.elasticBounce = function(box, valueElement, newValue) {
            gsap.timeline()
                .to(box, {
                    scale: 0.8,
                    duration: 0.1,
                    ease: "power2.in"
                })
                .call(function() { valueElement.textContent = newValue; })
                .to(box, {
                    scale: 1.2,
                    duration: 0.3,
                    ease: "elastic.out(1, 0.3)"
                })
                .to(box, {
                    scale: 1,
                    duration: 0.2,
                    ease: "power2.out"
                });
        };
        
        GSAPCountdownTimer.prototype.particleExplosion = function(box, valueElement, newValue) {
            var container = box.querySelector('.particle-container');
            
            for (var i = 0; i < 10; i++) {
                var particle = document.createElement('div');
                particle.className = 'particle';
                particle.style.left = '50%';
                particle.style.top = '50%';
                container.appendChild(particle);
                
                var angle = (Math.PI * 2 * i) / 10;
                var distance = 50 + Math.random() * 50;
                
                gsap.fromTo(particle, 
                    {
                        x: 0,
                        y: 0,
                        scale: 1,
                        opacity: 1
                    },
                    {
                        x: Math.cos(angle) * distance,
                        y: Math.sin(angle) * distance,
                        opacity: 0,
                        scale: 0,
                        duration: 0.8,
                        ease: "power2.out",
                        onComplete: function() { particle.remove(); }
                    }
                );
            }
            
            gsap.timeline()
                .to(valueElement, {
                    scale: 1.3,
                    duration: 0.2,
                    onComplete: function() { valueElement.textContent = newValue; }
                })
                .to(valueElement, {
                    scale: 1,
                    duration: 0.3,
                    ease: "back.out(1.7)"
                });
        };
        
        GSAPCountdownTimer.prototype.waveAnimation = function(unit, valueElement, newValue) {
            var allBoxes = document.querySelectorAll('.countdown-{{ uniqueId }} .digit-box');
            var index = Array.from(allBoxes).indexOf(this.units[unit]);
            
            gsap.timeline()
                .to(valueElement, {
                    y: -20,
                    opacity: 0,
                    duration: 0.3,
                    delay: index * 0.05,
                    onComplete: function() { valueElement.textContent = newValue; }
                })
                .to(valueElement, {
                    y: 0,
                    opacity: 1,
                    duration: 0.5,
                    ease: "back.out(1.7)"
                });
        };
        
        GSAPCountdownTimer.prototype.cubeRotation = function(box, valueElement, newValue) {
            gsap.timeline()
                .to(box, {
                    rotationX: 90,
                    duration: 0.3,
                    ease: "power2.in",
                    transformPerspective: 1000,
                    onComplete: function() { valueElement.textContent = newValue; }
                })
                .set(box, { rotationX: -90 })
                .to(box, {
                    rotationX: 0,
                    duration: 0.3,
                    ease: "power2.out",
                    transformPerspective: 1000
                });
        };
        
        GSAPCountdownTimer.prototype.gradientShift = function(box, valueElement, newValue, totalSeconds, maxSeconds) {
            var percentage = totalSeconds / maxSeconds;
            var baseColor = this.originalBackgroundColor || '#149cd8';
            
            var brightness;
            if (percentage > 0.5) {
                brightness = 1.2;
            } else if (percentage > 0.25) {
                brightness = 1.0;
            } else if (percentage > 0.1) {
                brightness = 0.7;
            } else if (percentage > 0.01) {
                brightness = 0.5;
            } else {
                brightness = 0.3;
            }
            
            var adjustedColor = this.adjustColorBrightness(baseColor, brightness);
            
            gsap.to(box, {
                backgroundColor: adjustedColor,
                duration: 0.3,
                ease: "power2.inOut"
            });
            
            gsap.to(valueElement, {
                scale: 0.9,
                duration: 0.2,
                onComplete: function() {
                    valueElement.textContent = newValue;
                    gsap.to(valueElement, { scale: 1, duration: 0.2 });
                }
            });
        };
        
        GSAPCountdownTimer.prototype.adjustColorBrightness = function(color, factor) {
            var hex = color.replace('#', '');
            var r = parseInt(hex.substr(0, 2), 16);
            var g = parseInt(hex.substr(2, 2), 16);
            var b = parseInt(hex.substr(4, 2), 16);
            
            var newR = Math.min(255, Math.floor(r * factor));
            var newG = Math.min(255, Math.floor(g * factor));
            var newB = Math.min(255, Math.floor(b * factor));
            
            return '#' + 
                ((1 << 24) + (newR << 16) + (newG << 8) + newB)
                .toString(16).slice(1);
        };
        
        GSAPCountdownTimer.prototype.scrambleEffect = function(valueElement, newValue) {
            var chars = "0123456789";
            var originalText = valueElement.textContent;
            var frame = 0;
            var totalFrames = 15;
            
            var scrambleInterval = setInterval(function() {
                if (frame >= totalFrames) {
                    clearInterval(scrambleInterval);
                    valueElement.textContent = newValue;
                    return;
                }
                
                var scrambled = '';
                for (var i = 0; i < newValue.length; i++) {
                    if (frame > i * 5) {
                        scrambled += newValue[i];
                    } else {
                        scrambled += chars[Math.floor(Math.random() * chars.length)];
                    }
                }
                valueElement.textContent = scrambled;
                frame++;
            }, 30);
        };
        
        GSAPCountdownTimer.prototype.pulseGlow = function(box, valueElement, newValue, timeValues) {
            var isUrgent = timeValues.days === 0 && timeValues.hours === 0 && timeValues.minutes < 1;
            
            if (isUrgent) {
                gsap.timeline({ repeat: 1 })
                    .to(box, {
                        boxShadow: "0 0 30px rgba(255,0,0,0.8)",
                        scale: 1.1,
                        duration: 0.3,
                        onStart: function() { valueElement.textContent = newValue; }
                    })
                    .to(box, {
                        boxShadow: "0 4px 8px rgba(0,0,0,0.2)",
                        scale: 1,
                        duration: 0.3
                    });
            } else {
                gsap.timeline()
                    .to(box, {
                        scale: 1.05,
                        duration: 0.2,
                        onComplete: function() { valueElement.textContent = newValue; }
                    })
                    .to(box, {
                        scale: 1,
                        duration: 0.3,
                        ease: "elastic.out(1, 0.5)"
                    });
            }
        };
        
        GSAPCountdownTimer.prototype.slotMachine = function(box, valueElement, newValue) {
            var duration = 0.5;
            var currentFrame = 0;
            var totalFrames = 20;
            
            gsap.to({}, {
                duration: duration,
                ease: "power2.inOut",
                onUpdate: function() {
                    currentFrame++;
                    if (currentFrame < totalFrames - 2) {
                        var randomNum = Math.floor(Math.random() * 100);
                        valueElement.textContent = CountdownUtils.padNumber(randomNum);
                    }
                },
                onComplete: function() {
                    valueElement.textContent = newValue;
                }
            });
            
            gsap.fromTo(valueElement, 
                { y: 0 },
                {
                    y: -20,
                    yoyo: true,
                    repeat: 1,
                    duration: duration,
                    ease: "power2.inOut"
                }
            );
        };
        
        GSAPCountdownTimer.prototype.liquidFill = function(box, unit, timeValues, valueElement, newValue) {
            var fill = box.querySelector('.liquid-fill');
            if (!fill) return;
            
            var percentage;
            if (unit === 'days') {
                percentage = (365 - timeValues.days) / 365 * 100;
            } else if (unit === 'hours') {
                percentage = (24 - timeValues.hours) / 24 * 100;
            } else if (unit === 'minutes') {
                percentage = (60 - timeValues.minutes) / 60 * 100;
            } else if (unit === 'seconds') {
                percentage = (60 - timeValues.seconds) / 60 * 100;
            }
            
            gsap.to(fill, {
                height: percentage + '%',
                duration: 0.8,
                ease: "power2.inOut"
            });
            
            gsap.to(valueElement, {
                y: -5,
                duration: 0.2,
                onComplete: function() {
                    valueElement.textContent = newValue;
                    gsap.to(valueElement, { y: 0, duration: 0.2 });
                }
            });
        };
        
        GSAPCountdownTimer.prototype.morphTransition = function(valueElement, oldValue, newValue) {
            if (oldValue !== newValue) {
                gsap.timeline()
                    .to(valueElement, {
                        scaleY: 0.1,
                        scaleX: 1.2,
                        opacity: 0.3,
                        duration: 0.2,
                        ease: "power2.in"
                    })
                    .call(function() {
                        valueElement.textContent = newValue;
                    })
                    .to(valueElement, {
                        scaleY: 1,
                        scaleX: 1,
                        opacity: 1,
                        duration: 0.3,
                        ease: "back.out(1.5)"
                    });
            }
        };
        
        GSAPCountdownTimer.prototype.matrixRain = function(box, valueElement, newValue) {
            var container = box.querySelector('.particle-container');
            var chars = "0123456789";
            var streams = 6;
            
            for (var i = 0; i < streams; i++) {
                (function(index) {
                    var stream = document.createElement('div');
                    stream.style.cssText = 'position:absolute;left:' + (15 + (index * 15)) + '%;top:-30px;font-size:10px;font-family:monospace;color:#00ff00;text-shadow:0 0 5px #00ff00;opacity:0;z-index:10;line-height:1;';
                    
                    var streamText = '';
                    for (var j = 0; j < 8; j++) {
                        streamText += chars[Math.floor(Math.random() * chars.length)] + '<br>';
                    }
                    stream.innerHTML = streamText;
                    container.appendChild(stream);
                    
                    gsap.to(stream, {
                        y: 100,
                        opacity: 0.7,
                        duration: 0.4,
                        delay: index * 0.05,
                        ease: "none",
                        onComplete: function() { 
                            gsap.to(stream, {
                                opacity: 0,
                                duration: 0.2,
                                onComplete: function() { stream.remove(); }
                            });
                        }
                    });
                })(i);
            }
            
            var tl = gsap.timeline();
            
            tl.to(valueElement, {
                x: -2,
                duration: 0.02
            })
            .to(valueElement, {
                x: 2,
                duration: 0.02
            })
            .to(valueElement, {
                x: 0,
                duration: 0.02
            })
            .to(valueElement, {
                opacity: 0,
                scale: 0.8,
                rotationY: 90,
                duration: 0.2,
                ease: "power2.in",
                onComplete: function() {
                    valueElement.textContent = newValue;
                }
            })
            .to(valueElement, {
                opacity: 1,
                scale: 1,
                rotationY: 0,
                duration: 0.2,
                ease: "power2.out"
            });
            
            gsap.to(box, {
                boxShadow: '0 0 15px #00ff00',
                duration: 0.2,
                yoyo: true,
                repeat: 1,
                onComplete: function() {
                    box.style.boxShadow = '0 4px 8px rgba(0,0,0,0.2)';
                }
            });
        };
        
        var timer = document.querySelector('.countdown-{{ uniqueId }}');
        if (timer && !timer.hasAttribute('data-initialized')) {
            new GSAPCountdownTimer(timer);
            timer.setAttribute('data-initialized', 'true');
        }
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initCountdown{{ uniqueId }});
    } else {
        initCountdown{{ uniqueId }}();
    }
})();
{%- endjavascript -%}
{%- endif -%}