(function () {
    'use strict';
    var runtime = window.SwairishXRuntime || {};

    var track = function (campaignId, eventName) {
        if (!runtime.ajaxUrl) { return; }
        var body = new URLSearchParams({ action: runtime.action, token: runtime.token, campaignId: campaignId, event: eventName });
        window.fetch(runtime.ajaxUrl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString(), keepalive: true }).catch(function () {});
    };

    var readStorage = function (storage, key) {
        try { return storage.getItem(key); } catch (error) { return null; }
    };

    var writeStorage = function (storage, key, value) {
        try { storage.setItem(key, value); } catch (error) {}
    };

    var formatCountdown = function (milliseconds) {
        var total = Math.max(0, Math.floor(milliseconds / 1000));
        var days = Math.floor(total / 86400);
        var hours = Math.floor((total % 86400) / 3600);
        var minutes = Math.floor((total % 3600) / 60);
        var seconds = total % 60;
        var parts = [hours, minutes, seconds].map(function (number) { return String(number).padStart(2, '0'); });
        return days > 0 ? days + 'd ' + parts.join(':') : parts.join(':');
    };

    document.querySelectorAll('[data-swairishx-deadline]').forEach(function (clock) {
        var end = Number(clock.dataset.swairishxDeadline || 0);
        if (!end) { return; }
        var update = function () { clock.textContent = formatCountdown(end - Date.now()); };
        update();
        window.setInterval(update, 1000);
    });

    document.querySelectorAll('[data-swairishx-id]').forEach(function (notice) {
        var id = notice.dataset.swairishxId;
        var key = 'swairishx-dismissed-' + id;
        var behavior = notice.dataset.reappearance || 'after_hours';
        var localValue = readStorage(window.localStorage, key);
        var sessionValue = readStorage(window.sessionStorage, key);
        if ('never' === localValue || ('after_hours' === behavior && Number(localValue || 0) > Date.now()) || ('session' === behavior && '1' === sessionValue)) { return; }

        var show = function () {
            notice.hidden = false;
            window.requestAnimationFrame(function () { notice.classList.add('is-visible'); });
            if (notice.dataset.tracking === '1') { track(id, 'impression'); }
        };

        if (notice.dataset.notificationType === 'exit_intent_popup') {
            notice.addEventListener('swairishx:show', show, { once: true });
        } else {
            window.setTimeout(show, Number(notice.dataset.delay || 0));
        }

        var close = notice.querySelector('[data-swairishx-dismiss]');
        if (close) {
            close.addEventListener('click', function () {
                notice.classList.remove('is-visible');
                if ('session' === behavior) {
                    writeStorage(window.sessionStorage, key, '1');
                } else if ('after_hours' === behavior) {
                    var hours = Number(notice.dataset.dismissHours || 24);
                    writeStorage(window.localStorage, key, String(Date.now() + hours * 3600000));
                } else if ('never' === behavior) {
                    writeStorage(window.localStorage, key, 'never');
                }
                if (notice.dataset.tracking === '1') { track(id, 'dismiss'); }
                window.setTimeout(function () { notice.hidden = true; }, 280);
            });
        }

        var link = notice.querySelector('[data-swairishx-click]');
        if (link) { link.addEventListener('click', function () { if (notice.dataset.tracking === '1') { track(id, 'click'); } }); }

        var coupon = notice.querySelector('[data-swairishx-coupon]');
        if (coupon) {
            coupon.addEventListener('click', function () {
                var code = coupon.dataset.couponCode || '';
                var status = coupon.querySelector('[data-coupon-status]');
                var copied = function () {
                    if (status) { status.textContent = coupon.dataset.copiedText || 'Copied'; }
                    window.setTimeout(function () { if (status) { status.textContent = ''; } }, 1800);
                    if (notice.dataset.tracking === '1') { track(id, 'click'); }
                };
                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard.writeText(code).then(copied).catch(function () {});
                    return;
                }
                var field = document.createElement('textarea');
                field.value = code;
                field.setAttribute('readonly', '');
                field.style.position = 'fixed';
                field.style.opacity = '0';
                document.body.appendChild(field);
                field.select();
                try { document.execCommand('copy'); copied(); } catch (error) {}
                field.remove();
            });
        }

        var autoHide = Number(notice.dataset.autoHide || 0);
        if (autoHide > 0) { window.setTimeout(function () { if (close) { close.click(); } }, autoHide); }
    });
}());
