
(function () {
    'use strict';

    var SVGNS = 'http://www.w3.org/2000/svg';
    var UID = 0;

    function pad(n) { return (n < 10 ? '0' : '') + n; }

    function remain(target) {
        var d = Math.max(0, target - Date.now());
        var s = Math.floor(d / 1000);
        return {
            total: s,
            d: Math.floor(s / 86400),
            h: Math.floor((s % 86400) / 3600),
            m: Math.floor((s % 3600) / 60),
            s: s % 60
        };
    }

    var CDFONTS = {
        system: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
        serif: 'Georgia, "Times New Roman", serif',
        geometric: '"Futura", "Century Gothic", "Avant Garde", "Trebuchet MS", sans-serif',
        mono: 'ui-monospace, "SF Mono", Menlo, Consolas, monospace'
    };

    function cfg(el) {
        var units = (el.getAttribute('data-cd-units') || 'd,h,m,s').split(',')
            .map(function (u) { return u.trim(); })
            .filter(function (u) { return ['d', 'h', 'm', 's'].indexOf(u) !== -1; });
        if (!units.length) units = ['d', 'h', 'm', 's'];
        var labels = {};
        try { labels = JSON.parse(decodeURIComponent(el.getAttribute('data-cd-labels') || '')) || {}; } catch (e) {}
        return {
            target: parseFloat(el.getAttribute('data-cd-target')) || (Date.now() + 7 * 86400000),
            
            rings: el.getAttribute('data-cd-rings') !== '0',
            
            labels_on: el.getAttribute('data-cd-labels-on') !== '0',
            units: units,
            labels: {
                d: labels.d || 'Days', h: labels.h || 'Hours',
                m: labels.m || 'Minutes', s: labels.s || 'Seconds'
            },
            size: Math.max(20, Math.min(220, parseInt(el.getAttribute('data-cd-size') || '64', 10) || 64)),
            accent: el.getAttribute('data-cd-accent') || '#999999',
            ring: decodeURIComponent(el.getAttribute('data-cd-ring') || '') || 'limited offer',
            font: CDFONTS[el.getAttribute('data-cd-font')] || '',
            
            digit: el.getAttribute('data-cd-digit') || '#1d2327',
            gap: (function () {
                var v = parseFloat(el.getAttribute('data-cd-gap'));
                return (!isFinite(v) || v < 0 || v > 80) ? -1 : v;
            })(),
            align: (function () {
                var a = (el.getAttribute('data-cd-align') || 'center').toLowerCase();
                return ['left', 'center', 'right'].indexOf(a) !== -1 ? a : 'center';
            })(),
            ringSize: (function () {
                var v = parseFloat(el.getAttribute('data-cd-ring-size'));
                return (!isFinite(v) || v < 30 || v > 100) ? 100 : v;
            })(),
            ringColor: el.getAttribute('data-cd-ring-color') || '',
            parallax: el.getAttribute('data-cd-parallax') === '1',
            zero: (el.getAttribute('data-cd-zero') || 'keep').toLowerCase(),
            message: decodeURIComponent(el.getAttribute('data-cd-message') || '') || 'We are live'
        };
    }

    function unitVal(r, u) {
        if (u === 'd') return String(r.d);
        return pad(r[u]);
    }

    
    function buildReadout(c, inst, fs) {
        var H = Math.round(fs * 1.25);
        
        var gap = (c.gap > 0) ? c.gap : Math.round(fs * 0.3);
        var row = document.createElement('div');
        row.style.cssText = 'display:flex;align-items:flex-start;flex-wrap:nowrap;'
            + 'gap:' + gap + 'px;justify-content:'
            + (c.align === 'left' ? 'flex-start' : c.align === 'right' ? 'flex-end' : 'center') + ';';
        inst.cells = {};
        c.units.forEach(function (u, i) {
            if (i) {
                
                var sep = document.createElement('div');
                sep.textContent = ':';
                sep.style.cssText = 'height:' + H + 'px;display:flex;align-items:center;'
                    + 'font-size:' + fs + 'px;font-weight:800;line-height:1;opacity:0.35;'
                    + 'color:' + c.digit + ';';
                row.appendChild(sep);
            }
            var col = document.createElement('div');
            col.style.cssText = 'display:flex;flex-direction:column;align-items:center;';
            var group = document.createElement('div');
            group.style.cssText = 'display:flex;';
            col.appendChild(group);
            if (c.labels_on) {
                var lab = document.createElement('div');
                lab.textContent = c.labels[u];
                lab.style.cssText = 'margin-top:' + Math.round(fs * 0.26) + 'px;white-space:nowrap;'
                    + 'font-size:' + Math.max(9, Math.round(fs * 0.2)) + 'px;font-weight:700;'
                    + 'letter-spacing:0.18em;text-transform:uppercase;color:' + c.accent + ';';
                col.appendChild(lab);
            }
            row.appendChild(col);
            inst.cells[u] = { digits: [], group: group };
        });
        inst.mkDigit = function () {
            var win = document.createElement('div');
            
            win.style.cssText = 'height:' + H + 'px;overflow:hidden;position:relative;contain:paint;';
            var strip = document.createElement('div');
            strip.style.cssText = 'display:flex;flex-direction:column;will-change:transform;'
                + 'transition:transform 620ms ease-in-out;';
            
            for (var i = 0; i <= 19; i++) {
                var dg = document.createElement('div');
                dg.textContent = String(i % 10);
                dg.style.cssText = 'height:' + H + 'px;display:flex;align-items:center;'
                    + 'justify-content:center;font-size:' + fs + 'px;font-weight:900;line-height:1;'
                    + 'color:' + c.digit + ';font-variant-numeric:tabular-nums;';
                strip.appendChild(dg);
            }
            win.appendChild(strip);
            win._strip = strip;
            win._h = H;
            return win;
        };
        return row;
    }

    function setReadout(inst, c, r) {
        var resized = false;
        c.units.forEach(function (u) {
            var val = unitVal(r, u);
            var cell = inst.cells[u];
            
            while (cell.digits.length < val.length) {
                var add = inst.mkDigit();
                cell.group.insertBefore(add, cell.group.firstChild);
                cell.digits.unshift(add);
                resized = true;
            }
            while (cell.digits.length > val.length) {
                var rm = cell.digits.shift();
                if (rm.parentNode) rm.parentNode.removeChild(rm);
                resized = true;
            }
            for (var i = 0; i < val.length; i++) {
                var want = parseInt(val.charAt(i), 10) || 0;
                var win = cell.digits[i], st = win._strip, h = win._h;
                if (win._d === undefined) {          
                    win._d = want; win._i = want;
                    st.style.transition = 'none';
                    st.style.transform = 'translateY(' + (-want * h) + 'px)';
                    void st.offsetHeight;
                    st.style.transition = 'transform 620ms ease-in-out';
                    continue;
                }
                
                var step = ((win._d - want) + 10) % 10;
                if (!step) continue;
                if (win._i - step < 0) {
                    
                    st.style.transition = 'none';
                    win._i += 10;
                    st.style.transform = 'translateY(' + (-win._i * h) + 'px)';
                    void st.offsetHeight;
                    st.style.transition = 'transform 620ms ease-in-out';
                }
                win._i -= step; win._d = want;
                st.style.transform = 'translateY(' + (-win._i * h) + 'px)';
            }
        });
        return resized;
    }

    function fitReadout(inst) {
        if (!inst.readout || !inst.innerW) return;
        inst.readout.style.transform = 'scale(1)';
        var w = inst.readout.scrollWidth || inst.readout.getBoundingClientRect().width;
        if (!w) return;
        inst.readout.style.transform = 'scale(' + Math.min(1, inst.innerW / w).toFixed(3) + ')';
    }

    function buildRings(el, c, inst) {
        
        var _availW = el.clientWidth || el.offsetWidth || 900;
        var D = Math.round(Math.max(240, Math.min(_availW, 1400)) * (c.ringSize / 100));
        var box = document.createElement('div');
        box.style.cssText = 'position:relative;width:' + D + 'px;height:' + D + 'px;margin:0 auto;';
        var svg = document.createElementNS(SVGNS, 'svg');
        svg.setAttribute('viewBox', '0 0 ' + D + ' ' + D);
        svg.setAttribute('width', String(D));
        svg.setAttribute('height', String(D));
        svg.style.cssText = 'position:absolute;inset:0;overflow:visible;';
        var id = 'cdr' + (++UID);
        var just = [];   
        [{ r: D * 0.46, fs: c.size * 0.42, dir: 1, dur: 36000 },
         { r: D * 0.33, fs: c.size * 0.30, dir: -1, dur: 28000 }].forEach(function (ring, ri) {
            var gp = document.createElementNS(SVGNS, 'g');   
            inst.ringCarriers = inst.ringCarriers || [];
            inst.ringCarriers.push(gp);
            var g = document.createElementNS(SVGNS, 'g');
            g.style.transformOrigin = (D / 2) + 'px ' + (D / 2) + 'px';
            var pid = id + '_' + ri;
            var path = document.createElementNS(SVGNS, 'path');
            path.setAttribute('d', 'M ' + (D / 2 - ring.r) + ' ' + (D / 2)
                + ' a ' + ring.r + ' ' + ring.r + ' 0 1 1 ' + (2 * ring.r) + ' 0'
                + ' a ' + ring.r + ' ' + ring.r + ' 0 1 1 ' + (-2 * ring.r) + ' 0');
            path.setAttribute('id', pid);
            path.setAttribute('fill', 'none');
            var t = document.createElementNS(SVGNS, 'text');
            
            t.setAttribute('fill', c.ringColor || c.digit);
            if (ri) t.setAttribute('fill-opacity', '0.4');
            t.style.cssText = 'font-size:' + Math.round(ring.fs) + 'px;font-weight:800;letter-spacing:0.14em;text-transform:uppercase;';
            var tp = document.createElementNS(SVGNS, 'textPath');
            tp.setAttribute('href', '#' + pid);
            tp.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#' + pid);
            
            var unit = c.ring + '   ';
            var circ = 2 * Math.PI * ring.r;
            
            var estUnit = unit.length * ring.fs * 0.62;
            var reps = Math.max(1, Math.round(circ / estUnit));
            var fitK = Math.max(0.88, Math.min(1.12, circ / (reps * estUnit)));
            t.style.fontSize = Math.round(ring.fs * fitK) + 'px';
            var s = '';
            for (var k = 0; k < reps; k++) s += unit;
            tp.textContent = s;
            just.push({ t: t, circ: circ });
            t.appendChild(tp);
            g.appendChild(path); g.appendChild(t);
            gp.appendChild(g);
            svg.appendChild(gp);
            try {
                inst.anims.push(g.animate(
                    [{ transform: 'rotate(0deg)' }, { transform: 'rotate(' + (ring.dir * 360) + 'deg)' }],
                    { duration: ring.dur, iterations: Infinity, easing: 'linear' }));
            } catch (e) {}
        });
        box.appendChild(svg);
        var center = document.createElement('div');
        center.style.cssText = 'position:absolute;inset:0;display:flex;'
            + 'align-items:center;justify-content:center;';
        
        var readout = buildReadout(c, inst, Math.min(c.size, Math.max(14, Math.round(D * 0.16))));
        readout.style.transformOrigin = 'center center';
        center.appendChild(readout);
        box.appendChild(center);
        el.appendChild(box);
        inst.readout = readout;
        inst.innerW = D * 0.66 * 0.9;

        just.forEach(function (o) {
            try {
                var chars = (o.t.textContent || '').length;
                if (chars < 2) return;
                
                for (var pass = 0; pass < 3; pass++) {
                    var natural = o.t.getComputedTextLength();
                    if (!(natural > 0)) return;
                    var delta = o.circ - natural;
                    if (Math.abs(delta) < 1) break;
                    var base = parseFloat(getComputedStyle(o.t).letterSpacing) || 0;
                    o.t.style.letterSpacing = (base + delta / (chars - 1)).toFixed(3) + 'px';
                }
            } catch (e) {}
        });
        
        if (c.parallax) {
            var units = [];
            for (var gi = 0; gi < inst.ringCarriers.length; gi++) {
                units.push({ el: inst.ringCarriers[gi], depth: gi === 0 ? 1.0 : 0.55 });
            }
            units.push({ el: center, depth: 0.25 });
            var tx = 0, ty = 0, cx2 = 0, cy2 = 0, raf = null;
            function apply() {
                raf = null;
                cx2 += (tx - cx2) * 0.12;
                cy2 += (ty - cy2) * 0.12;
                for (var i = 0; i < units.length; i++) {
                    units[i].el.setAttribute
                        ? units[i].el.setAttribute('transform', 'translate(' + (cx2 * units[i].depth).toFixed(1) + ',' + (cy2 * units[i].depth).toFixed(1) + ')')
                        : (units[i].el.style.transform = 'translate(' + (cx2 * units[i].depth).toFixed(1) + 'px,' + (cy2 * units[i].depth).toFixed(1) + 'px)');
                }
                if (Math.abs(tx - cx2) > 0.3 || Math.abs(ty - cy2) > 0.3) raf = requestAnimationFrame(apply);
            }
            var onMove = function (e) {
                var r = box.getBoundingClientRect();
                if (!r.width) return;
                var amp = Math.min(26, D * 0.05);
                tx = ((e.clientX - (r.left + r.width / 2)) / (r.width / 2)) * amp;
                ty = ((e.clientY - (r.top + r.height / 2)) / (r.height / 2)) * amp;
                if (!raf) raf = requestAnimationFrame(apply);
            };
            window.addEventListener('mousemove', onMove, { passive: true });
            inst.offs = inst.offs || [];
            inst.offs.push(function () { window.removeEventListener('mousemove', onMove); if (raf) cancelAnimationFrame(raf); });
        }
    }

    function build(el) {
        if (el._cdInst) destroy(el);
        var c = cfg(el);
        var inst = { alive: true, anims: [], cells: {}, cfg: c };
        el._cdInst = inst;
        el.textContent = '';
        el.style.textAlign = c.align;
        el.style.fontFamily = c.font || '';

        if (c.rings) buildRings(el, c, inst);
        else         el.appendChild(buildReadout(c, inst, c.size));

        var lastSec = -1, done = false;
        function tick() {
            if (!inst.alive) return;
            var r = remain(c.target);
            if (r.total !== lastSec) {
                lastSec = r.total;
                
                if (setReadout(inst, c, r)) fitReadout(inst);
                if (r.total <= 0 && !done) {
                    done = true;
                    if (c.zero === 'hide') {
                        el.style.display = 'none';
                    } else if (c.zero === 'message') {
                        el.textContent = '';
                        var msg = document.createElement('div');
                        msg.textContent = c.message;
                        msg.style.cssText = 'font-size:' + Math.round(c.size * 0.6) + 'px;font-weight:800;'
                            + 'color:' + c.digit + ';text-align:center;letter-spacing:0.04em;';
                        el.appendChild(msg);
                        inst.alive = false;
                    }
                    
                }
            }
            if (inst.alive && !done) inst.timer = setTimeout(tick, 250);
        }
        tick();
    }

    function destroy(el) {
        var inst = el._cdInst;
        if (!inst) return;
        inst.alive = false;
        clearTimeout(inst.timer);
        (inst.offs || []).forEach(function (f) { try { f(); } catch (e) {} });
        (inst.anims || []).forEach(function (a) { try { a.cancel(); } catch (e) {} });
        delete el._cdInst;
    }

    function initAll(root) {
        var scope = root && root.querySelectorAll ? root : document;
        scope.querySelectorAll('.impulse-countdown').forEach(function (el) {
            if (el._cdInit) return;
            el._cdInit = true;
            build(el);
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () { initAll(document); });
    } else {
        initAll(document);
    }

    window.ImpulseCountdown = { init: initAll, build: build };

    if (window._impulseEditorPreview && window.MutationObserver) {
        var mo = new MutationObserver(function (muts) {
            for (var i = 0; i < muts.length; i++) {
                if (muts[i].addedNodes && muts[i].addedNodes.length) {
                    clearTimeout(window._cdReinitT);
                    window._cdReinitT = setTimeout(function () { initAll(document); }, 80);
                    return;
                }
            }
        });
        try { mo.observe(document.body, { childList: true, subtree: true }); } catch (e) {}
    }
})();
