(function (window, document) {
    'use strict';

    function getQrOption(element, name, fallback) {
        var value = element.getAttribute('data-noesia-cs-qr-' + name);
        if (value === null || value === '') {
            return fallback;
        }
        return value;
    }

    function renderQrCodes(context) {
        context = context || document;
        if (!window.noesiaCommerceSuiteQr) {
            return;
        }
        var config = (window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.qr) || {};
        context.querySelectorAll('[data-noesia-cs-qr]').forEach(function (element) {
            var url = element.getAttribute('data-noesia-cs-qr');
            var defaultSize = element.classList.contains('noesia-cs-mini-qr') ? 54 : (parseInt(config.size, 10) || 160);
            var size = parseInt(getQrOption(element, 'size', defaultSize), 10);
            if (!size || size < 40) {
                size = defaultSize;
            }
            window.noesiaCommerceSuiteQr.render(element, url, {
                size: size,
                color: getQrOption(element, 'foreground', config.foreground || '#111827'),
                background: getQrOption(element, 'background', config.background || '#ffffff')
            });
        });
    }

    function bindCopyButtons(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-copy]:not([data-noesia-cs-copy-bound])').forEach(function (button) {
            button.setAttribute('data-noesia-cs-copy-bound', '1');
            button.addEventListener('click', function () {
                var value = button.getAttribute('data-noesia-cs-copy') || '';
                if (!value) {
                    return;
                }
                navigator.clipboard.writeText(value).then(function () {
                    var old = button.textContent;
                    button.textContent = (window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.copyLabel) || 'Copied';
                    setTimeout(function () { button.textContent = old; }, 1200);
                }).catch(function () {
                    var source = document.createElement('input');
                    source.value = value;
                    document.body.appendChild(source);
                    source.select();
                    document.execCommand('copy');
                    document.body.removeChild(source);
                });
            });
        });
    }

    function applyBarWidths(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-width]').forEach(function (element) {
            var width = parseFloat(element.getAttribute('data-noesia-cs-width') || '0');
            if (!isFinite(width)) {
                width = 0;
            }
            element.style.setProperty('--noesia-cs-bar-width', Math.max(0, Math.min(100, width)) + '%');
        });
    }

    function bindAdminShell(context) {
        context = context || document;
        var app = document.querySelector('.noesia-cs-app');
        var toggle = context.querySelector('.noesia-cs-menu-button');
        if (!app || !toggle || toggle.getAttribute('data-noesia-cs-menu-bound')) {
            return;
        }
        toggle.setAttribute('data-noesia-cs-menu-bound', '1');
        toggle.addEventListener('click', function () {
            if (window.matchMedia && window.matchMedia('(max-width: 1100px)').matches) {
                app.classList.toggle('is-sidebar-open');
                toggle.setAttribute('aria-expanded', app.classList.contains('is-sidebar-open') ? 'true' : 'false');
                return;
            }
            app.classList.toggle('is-sidebar-collapsed');
            toggle.setAttribute('aria-expanded', app.classList.contains('is-sidebar-collapsed') ? 'false' : 'true');
        });
        if (!app.getAttribute('data-noesia-cs-overlay-bound')) {
            app.setAttribute('data-noesia-cs-overlay-bound', '1');
            app.addEventListener('click', function (event) {
                if (event.target === app && app.classList.contains('is-sidebar-open')) {
                    app.classList.remove('is-sidebar-open');
                    toggle.setAttribute('aria-expanded', 'false');
                }
            });
        }
    }

    function getStoredDateRange() {
        var key = window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.dateStorageKey;
        if (!key || !window.localStorage) {
            return null;
        }
        try {
            var stored = window.localStorage.getItem(key);
            return stored ? JSON.parse(stored) : null;
        } catch (e) {
            return null;
        }
    }

    function saveDateRange(form) {
        var key = window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.dateStorageKey;
        if (!key || !window.localStorage || !form) {
            return;
        }
        var mode = form.querySelector('[name="noesia_cs_date_mode"]');
        var from = form.querySelector('[name="noesia_cs_date_from"]');
        var to = form.querySelector('[name="noesia_cs_date_to"]');
        try {
            window.localStorage.setItem(key, JSON.stringify({
                mode: mode ? mode.value : 'preset',
                from: from ? from.value : '',
                to: to ? to.value : ''
            }));
        } catch (e) {}
    }

    function getDashboardDateNonce() {
        return window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.dashboardDateNonce ? window.noesiaCommerceSuiteAdmin.dashboardDateNonce : '';
    }

    function appendDashboardDateNonce(url) {
        var nonce = getDashboardDateNonce();
        if (!nonce) {
            return url;
        }
        url.searchParams.set('noesia_cs_dashboard_nonce', nonce);
        return url;
    }

    function appendDateParams(url) {
        var stored = getStoredDateRange();
        if (!stored) {
            return url;
        }
        var next = new URL(url, window.location.href);
        if (!next.searchParams.has('noesia_cs_date_mode')) {
            next.searchParams.set('noesia_cs_date_mode', stored.mode || 'preset');
            if (stored.from) {
                next.searchParams.set('noesia_cs_date_from', stored.from);
            }
            if (stored.to) {
                next.searchParams.set('noesia_cs_date_to', stored.to);
            }
        }
        appendDashboardDateNonce(next);
        return next.toString();
    }

    function bindDateFilters(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-date-filter]:not([data-noesia-cs-date-bound])').forEach(function (form) {
            form.setAttribute('data-noesia-cs-date-bound', '1');
            var stored = getStoredDateRange();
            var url = new URL(window.location.href);
            if (stored && !url.searchParams.has('noesia_cs_date_mode')) {
                var mode = form.querySelector('[name="noesia_cs_date_mode"]');
                var from = form.querySelector('[name="noesia_cs_date_from"]');
                var to = form.querySelector('[name="noesia_cs_date_to"]');
                if (mode) { mode.value = stored.mode || 'preset'; }
                if (from && stored.from) { from.value = stored.from; }
                if (to && stored.to) { to.value = stored.to; }
            }
            form.addEventListener('submit', function () {
                saveDateRange(form);
            });
        });
    }

    function updateTabLinks() {
        document.querySelectorAll('[data-noesia-cs-tab-link]').forEach(function (link) {
            if (link.tagName && link.tagName.toLowerCase() === 'a') {
                link.href = appendDateParams(link.href);
            }
        });
    }

    function setActiveNavFromUrl(url) {
        var next = new URL(url, window.location.href);
        var view = next.searchParams.get('view') || '';
        var tab = view ? '' : (next.searchParams.get('tab') || 'dashboard');
        document.querySelectorAll('[data-noesia-cs-tab-link]').forEach(function (link) {
            link.classList.toggle('is-active', !view && link.getAttribute('data-noesia-cs-tab-link') === tab);
        });
        document.querySelectorAll('[data-noesia-cs-commerce-view-link]').forEach(function (link) {
            link.classList.toggle('is-active', view && link.getAttribute('data-noesia-cs-commerce-view-link') === view);
        });
    }

    function loadTab(url, pushState) {
        var app = document.querySelector('.noesia-cs-app');
        var main = document.querySelector('.noesia-cs-main');
        if (!app || !main || !window.fetch || !window.DOMParser) {
            window.location.href = url;
            return;
        }
        app.classList.add('is-loading');
        fetch(url, { credentials: 'same-origin' })
            .then(function (response) { return response.text(); })
            .then(function (html) {
                var doc = new DOMParser().parseFromString(html, 'text/html');
                var nextMain = doc.querySelector('.noesia-cs-main');
                if (!nextMain) {
                    window.location.href = url;
                    return;
                }
                main.innerHTML = nextMain.innerHTML;
                if (pushState) {
                    window.history.pushState({ noesiaCommerceSuiteTab: true }, '', url);
                }
                setActiveNavFromUrl(url);
                init(main);
                updateTabLinks();
                document.dispatchEvent(new CustomEvent('noesiaCommerceSuiteTabLoaded', { detail: { url: url } }));
            })
            .catch(function () {
                window.location.href = url;
            })
            .finally(function () {
                app.classList.remove('is-loading');
            });
    }


    function bindAjaxTabs() {
        if (document.body.getAttribute('data-noesia-cs-ajax-tabs-bound')) {
            return;
        }
        document.body.setAttribute('data-noesia-cs-ajax-tabs-bound', '1');
        document.addEventListener('click', function (event) {
            var settingsTrigger = event.target && event.target.closest ? event.target.closest('[data-noesia-cs-settings-anchor], .noesia-cs-settings-anchor-nav a') : null;
            if (settingsTrigger) {
                return;
            }
            var clickedLink = event.target && event.target.closest ? event.target.closest('a') : null;
            if (!clickedLink) {
                return;
            }
            if (clickedLink.getAttribute('data-noesia-cs-no-ajax') === '1' || clickedLink.hasAttribute('data-noesia-cs-settings-anchor') || clickedLink.hasAttribute('data-noesia-cs-settings-jump') || clickedLink.closest('.noesia-cs-settings-anchor-nav')) {
                return;
            }
            var rawHref = clickedLink.getAttribute('href') || '';
            if (!rawHref || rawHref.charAt(0) === '#') {
                return;
            }
            var link = clickedLink.matches('a[data-noesia-cs-tab-link], a[data-noesia-cs-commerce-view-link]') ? clickedLink : null;
            if (!link || link.target || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
                return;
            }
            var next = new URL(appendDateParams(link.href), window.location.href);
            if (next.origin !== window.location.origin || next.searchParams.get('page') !== 'noesia-commerce-suite') {
                return;
            }
            event.preventDefault();
            loadTab(next.toString(), true);
        });
        window.addEventListener('popstate', function () {
            loadTab(window.location.href, false);
        });
    }

    function restoreStoredDateRangeIfNeeded() {
        var stored = getStoredDateRange();
        if (!stored || !stored.mode) {
            return;
        }
        var url = new URL(window.location.href);
        if (url.searchParams.get('page') !== 'noesia-commerce-suite' || url.searchParams.has('noesia_cs_date_mode')) {
            return;
        }
        if ((url.searchParams.get('tab') || 'dashboard') !== 'dashboard') {
            return;
        }
        url.searchParams.set('noesia_cs_date_mode', stored.mode || 'preset');
        if (stored.from) {
            url.searchParams.set('noesia_cs_date_from', stored.from);
        }
        if (stored.to) {
            url.searchParams.set('noesia_cs_date_to', stored.to);
        }
        appendDashboardDateNonce(url);
        loadTab(url.toString(), false);
        window.history.replaceState({ noesiaCommerceSuiteTab: true }, '', url.toString());
    }


    function bindModals(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-open-modal]:not([data-noesia-cs-modal-bound])').forEach(function (button) {
            button.setAttribute('data-noesia-cs-modal-bound', '1');
            button.addEventListener('click', function () {
                var selector = button.getAttribute('data-noesia-cs-open-modal');
                var modal = selector ? document.querySelector(selector) : null;
                if (!modal) {
                    return;
                }
                modal.hidden = false;
                modal.classList.add('is-open');
                var close = modal.querySelector('[data-noesia-cs-close-modal]');
                if (close) {
                    close.focus({ preventScroll: true });
                }
            });
        });
        context.querySelectorAll('[data-noesia-cs-close-modal]:not([data-noesia-cs-close-bound])').forEach(function (button) {
            button.setAttribute('data-noesia-cs-close-bound', '1');
            button.addEventListener('click', function () {
                var modal = button.closest('.noesia-cs-modal');
                if (!modal) {
                    return;
                }
                modal.classList.remove('is-open');
                modal.hidden = true;
            });
        });
    }

    function bindWooNavigator(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-woo-navigator]:not([data-noesia-cs-woo-bound])').forEach(function (nav) {
            nav.setAttribute('data-noesia-cs-woo-bound', '1');
            var collapseKey = 'noesia_cs_woo_navigator_collapsed';
            var targetKey = 'noesia_cs_woo_navigator_new_tab';
            var toggle = nav.querySelector('[data-noesia-cs-woo-nav-toggle]');
            var targetToggle = nav.querySelector('[data-noesia-cs-woo-target-toggle]');
            var links = nav.querySelectorAll('[data-noesia-cs-woo-link]');

            function applyTarget() {
                var newTab = false;
                try { newTab = window.localStorage && window.localStorage.getItem(targetKey) === '1'; } catch (e) {}
                if (targetToggle) {
                    targetToggle.checked = newTab;
                }
                links.forEach(function (link) {
                    if (newTab) {
                        link.setAttribute('target', '_blank');
                        link.setAttribute('rel', 'noopener noreferrer');
                    } else {
                        link.removeAttribute('target');
                        link.removeAttribute('rel');
                    }
                });
            }

            try {
                if (window.localStorage && window.localStorage.getItem(collapseKey) === '1') {
                    nav.classList.add('is-collapsed');
                    if (toggle) { toggle.setAttribute('aria-expanded', 'false'); }
                }
            } catch (e) {}

            applyTarget();

            if (toggle) {
                toggle.addEventListener('click', function () {
                    nav.classList.toggle('is-collapsed');
                    var collapsed = nav.classList.contains('is-collapsed');
                    toggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
                    try { if (window.localStorage) { window.localStorage.setItem(collapseKey, collapsed ? '1' : '0'); } } catch (e) {}
                });
            }

            if (targetToggle) {
                targetToggle.addEventListener('change', function () {
                    try { if (window.localStorage) { window.localStorage.setItem(targetKey, targetToggle.checked ? '1' : '0'); } } catch (e) {}
                    applyTarget();
                });
            }
        });
    }

    function bindWpChromeFocus(context) {
        context = context || document;
        var button = context.querySelector('[data-noesia-cs-wp-chrome-toggle]');
        if (!button || button.getAttribute('data-noesia-cs-chrome-bound')) {
            return;
        }
        button.setAttribute('data-noesia-cs-chrome-bound', '1');
        var restore = document.querySelector('[data-noesia-cs-wp-chrome-restore]');
        if (!restore) {
            restore = document.createElement('button');
            restore.type = 'button';
            restore.className = 'noesia-cs-wp-chrome-restore';
            restore.setAttribute('data-noesia-cs-wp-chrome-restore', '1');
            restore.textContent = 'Restore WordPress menu';
            restore.hidden = true;
            document.body.appendChild(restore);
        }
        function setState(active) {
            document.body.classList.toggle('noesia-cs-wp-chrome-hidden', active);
            button.setAttribute('aria-pressed', active ? 'true' : 'false');
            restore.hidden = !active;
        }
        button.addEventListener('click', function () {
            setState(!document.body.classList.contains('noesia-cs-wp-chrome-hidden'));
        });
        restore.addEventListener('click', function () {
            setState(false);
        });
    }

    function getProLightbox() {
        var modal = document.querySelector('[data-noesia-cs-pro-lightbox-modal]');
        if (modal) {
            return modal;
        }
        modal = document.createElement('div');
        modal.className = 'noesia-cs-pro-lightbox';
        modal.setAttribute('data-noesia-cs-pro-lightbox-modal', '1');
        modal.setAttribute('role', 'dialog');
        modal.setAttribute('aria-modal', 'true');
        modal.hidden = true;
        modal.innerHTML = '<button type="button" class="noesia-cs-pro-lightbox__close" data-noesia-cs-pro-lightbox-close aria-label="Close image preview">×</button><div class="noesia-cs-pro-lightbox__frame"><img src="" alt=""></div>';
        document.body.appendChild(modal);
        modal.addEventListener('click', function (event) {
            if (event.target === modal || event.target.getAttribute('data-noesia-cs-pro-lightbox-close') !== null) {
                closeProLightbox();
            }
        });
        return modal;
    }

    function openProLightbox(src, alt) {
        var modal = getProLightbox();
        var image = modal.querySelector('img');
        if (!image || !src) {
            return;
        }
        image.src = src;
        image.alt = alt || '';
        modal.hidden = false;
        modal.classList.add('is-open');
        var close = modal.querySelector('[data-noesia-cs-pro-lightbox-close]');
        if (close) {
            close.focus({ preventScroll: true });
        }
    }

    function closeProLightbox() {
        var modal = document.querySelector('[data-noesia-cs-pro-lightbox-modal]');
        if (!modal) {
            return;
        }
        modal.classList.remove('is-open');
        modal.hidden = true;
        var image = modal.querySelector('img');
        if (image) {
            image.removeAttribute('src');
        }
    }

    function bindProPageLightbox(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-pro-lightbox]:not([data-noesia-cs-pro-lightbox-bound])').forEach(function (link) {
            link.setAttribute('data-noesia-cs-pro-lightbox-bound', '1');
            link.addEventListener('click', function (event) {
                var image = link.querySelector('img');
                var href = link.getAttribute('href') || '';
                if (!href) {
                    return;
                }
                event.preventDefault();
                openProLightbox(href, image ? image.getAttribute('alt') : '');
            });
        });
    }

    function bindDoctorScanLoader(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-doctor-scan-form]:not([data-noesia-cs-doctor-bound])').forEach(function (form) {
            form.setAttribute('data-noesia-cs-doctor-bound', '1');
            form.addEventListener('submit', function () {
                form.classList.add('is-running');
                var loader = form.querySelector('[data-noesia-cs-doctor-loader]');
                var button = form.querySelector('button[type="submit"]');
                if (loader) { loader.hidden = false; }
                if (button) {
                    button.disabled = true;
                    button.textContent = (window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.doctorScanLoadingLabel) || 'Please wait';
                }
            });
        });
    }

    function bindImpactRangeStorage(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-impact-refresh]:not([data-noesia-cs-impact-range-bound])').forEach(function (form) {
            form.setAttribute('data-noesia-cs-impact-range-bound', '1');
            var key = window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.impactDateStorageKey;
            var mode = form.querySelector('[name="noesia_cs_impact_date_mode"]');
            var from = form.querySelector('[name="noesia_cs_impact_date_from"]');
            var to = form.querySelector('[name="noesia_cs_impact_date_to"]');
            try {
                if (key && window.localStorage) {
                    var stored = window.localStorage.getItem(key);
                    if (stored) {
                        stored = JSON.parse(stored);
                        if (mode && stored.mode) { mode.value = stored.mode; }
                        if (from && stored.from) { from.value = stored.from; }
                        if (to && stored.to) { to.value = stored.to; }
                    }
                }
            } catch (e) {}
            form.addEventListener('submit', function () {
                try {
                    if (key && window.localStorage) {
                        window.localStorage.setItem(key, JSON.stringify({
                            mode: mode ? mode.value : 'all',
                            from: from ? from.value : '',
                            to: to ? to.value : ''
                        }));
                    }
                } catch (e) {}
            });
        });
    }

    function bindImpactRefresh(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-impact-refresh]:not([data-noesia-cs-impact-bound])').forEach(function (form) {
            form.setAttribute('data-noesia-cs-impact-bound', '1');
            form.addEventListener('submit', function (event) {
                if (!window.fetch || !window.FormData || !window.noesiaCommerceSuiteAdmin || !window.noesiaCommerceSuiteAdmin.ajaxUrl) {
                    return;
                }
                event.preventDefault();
                var target = form.closest('.noesia-cs-panel, .noesia-cs-feature-hero, section') ? document.querySelector('[data-noesia-cs-impact-target]') : null;
                if (!target) {
                    target = document.querySelector('[data-noesia-cs-impact-target]');
                }
                var button = form.querySelector('button[type="submit"]');
                var oldText = button ? button.textContent : '';
                var data = new FormData(form);
                data.set('action', 'noesia_cs_refresh_impact_map_ajax');
                if (button) {
                    button.disabled = true;
                    button.textContent = window.noesiaCommerceSuiteAdmin.impactRefreshingLabel || 'Refreshing';
                }
                if (target) {
                    target.classList.add('is-refreshing');
                }
                fetch(window.noesiaCommerceSuiteAdmin.ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: data
                }).then(function (response) {
                    return response.json();
                }).then(function (payload) {
                    if (!payload || !payload.success || !payload.data || !payload.data.html) {
                        form.submit();
                        return;
                    }
                    if (target) {
                        target.innerHTML = payload.data.html;
                        init(target);
                    }
                }).catch(function () {
                    form.submit();
                }).finally(function () {
                    if (button) {
                        button.disabled = false;
                        button.textContent = oldText;
                    }
                    if (target) {
                        target.classList.remove('is-refreshing');
                    }
                });
            });
        });
    }

    function bindDashboardProductFilters(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-dashboard-products]:not([data-noesia-cs-dashboard-products-bound])').forEach(function (widget) {
            widget.setAttribute('data-noesia-cs-dashboard-products-bound', '1');
            widget.addEventListener('click', function (event) {
                var link = event.target && event.target.closest ? event.target.closest('[data-noesia-cs-dashboard-product-range]') : null;
                if (!link) {
                    return;
                }
                if (!window.fetch || !window.FormData || !window.noesiaCommerceSuiteAdmin || !window.noesiaCommerceSuiteAdmin.ajaxUrl) {
                    return;
                }
                event.preventDefault();
                var range = link.getAttribute('data-noesia-cs-dashboard-product-range') || 'all';
                var widgetTab = widget.getAttribute('data-noesia-cs-dashboard-products-tab') || 'dashboard';
                var data = new FormData();
                data.set('action', 'noesia_cs_dashboard_top_products_ajax');
                data.set('nonce', window.noesiaCommerceSuiteAdmin.dashboardProductsNonce || '');
                data.set('range', range);
                data.set('tab', widgetTab);
                var oldLabel = link.textContent;
                widget.classList.add('is-refreshing');
                link.textContent = window.noesiaCommerceSuiteAdmin.dashboardProductsLoadingLabel || oldLabel;
                fetch(window.noesiaCommerceSuiteAdmin.ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: data
                }).then(function (response) {
                    return response.json();
                }).then(function (payload) {
                    if (!payload || !payload.success || !payload.data || !payload.data.html) {
                        window.location.href = link.href;
                        return;
                    }
                    var holder = document.createElement('div');
                    holder.innerHTML = payload.data.html;
                    var replacement = holder.querySelector('[data-noesia-cs-dashboard-products]');
                    if (!replacement) {
                        window.location.href = link.href;
                        return;
                    }
                    widget.replaceWith(replacement);
                    init(replacement.parentNode || document);
                    try {
                        var nextUrl = new URL(window.location.href);
                        nextUrl.searchParams.set('noesia_cs_product_range', payload.data.range || range);
                        appendDashboardDateNonce(nextUrl);
                        window.history.replaceState({ noesiaCommerceSuiteDashboardProducts: true }, '', nextUrl.toString());
                    } catch (e) {}
                }).catch(function () {
                    window.location.href = link.href;
                }).finally(function () {
                    widget.classList.remove('is-refreshing');
                    link.textContent = oldLabel;
                });
            });
        });
    }



    function bindMediaUploadButtons(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-media-upload]:not([data-noesia-cs-media-bound])').forEach(function (button) {
            button.setAttribute('data-noesia-cs-media-bound', '1');
            button.addEventListener('click', function (event) {
                event.preventDefault();
                if (!window.wp || !window.wp.media) {
                    return;
                }
                var wrap = button.closest('.noesia-cs-media-url-field') || button.parentNode;
                var input = wrap ? wrap.querySelector('[data-noesia-cs-media-url]') : null;
                var frame = window.wp.media({
                    title: 'Choose logo or image',
                    button: { text: 'Use this file' },
                    multiple: false
                });
                frame.on('select', function () {
                    var attachment = frame.state().get('selection').first();
                    if (!attachment || !input) {
                        return;
                    }
                    attachment = attachment.toJSON();
                    if (attachment && attachment.url) {
                        input.value = attachment.url;
                        input.dispatchEvent(new Event('change', { bubbles: true }));
                    }
                });
                frame.open();
            });
        });
    }

    function bindHubSubtabs(context) {
        context = context || document;
        context.querySelectorAll('.noesia-cs-hub-subtabs a:not([data-noesia-cs-hub-subtab-bound])').forEach(function (link) {
            link.setAttribute('data-noesia-cs-hub-subtab-bound', '1');
            link.addEventListener('click', function (event) {
                if (!window.fetch || !window.DOMParser || link.target || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
                    return;
                }
                var url = new URL(link.href, window.location.href);
                if (url.origin !== window.location.origin || url.searchParams.get('page') !== 'noesia-commerce-suite' || url.searchParams.get('tab') !== 'order-care-hub') {
                    return;
                }
                event.preventDefault();
                loadTab(url.toString(), true);
            });
        });
    }

    function bindHubAjaxSave(context) {
        context = context || document;
        context.querySelectorAll('.noesia-cs-hub-form:not([data-noesia-cs-hub-save-bound])').forEach(function (form) {
            form.setAttribute('data-noesia-cs-hub-save-bound', '1');
            form.addEventListener('submit', function (event) {
                if (!window.fetch || !window.FormData || !window.noesiaCommerceSuiteAdmin || !window.noesiaCommerceSuiteAdmin.ajaxUrl) {
                    return;
                }
                event.preventDefault();

                var data = new FormData(form);
                data.set('action', 'noesia_cs_save_settings_ajax');

                var button = form.querySelector('button[type="submit"]');
                var oldText = button ? button.textContent : '';
                form.classList.add('is-saving');
                if (button) {
                    button.disabled = true;
                    button.textContent = window.noesiaCommerceSuiteAdmin.settingsSavingLabel || oldText;
                }

                fetch(window.noesiaCommerceSuiteAdmin.ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: data
                }).then(function (response) {
                    return response.json();
                }).then(function (payload) {
                    if (!payload || !payload.success || !payload.data || !payload.data.return_url) {
                        form.submit();
                        return;
                    }
                    if (button) {
                        button.textContent = window.noesiaCommerceSuiteAdmin.settingsSavedLabel || oldText;
                    }
                    try {
                        window.history.replaceState({ noesiaCommerceSuiteTab: true }, '', payload.data.return_url);
                    } catch (e) {}
                    window.setTimeout(function () {
                        loadTab(payload.data.return_url, false);
                    }, 250);
                }).catch(function () {
                    form.submit();
                }).finally(function () {
                    window.setTimeout(function () {
                        form.classList.remove('is-saving');
                        if (button) {
                            button.disabled = false;
                            button.textContent = oldText;
                        }
                    }, 500);
                });
            });
        });
    }


    function bindReorderSubtabs(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-reorder-subtab]:not([data-noesia-cs-reorder-bound])').forEach(function (link) {
            link.setAttribute('data-noesia-cs-reorder-bound', '1');
            link.addEventListener('click', function (event) {
                event.preventDefault();
                var key = link.getAttribute('data-noesia-cs-reorder-subtab') || 'overview';
                var root = link.closest('.noesia-cs-content') || document;
                root.querySelectorAll('[data-noesia-cs-reorder-subtab]').forEach(function (item) {
                    item.classList.toggle('is-active', item.getAttribute('data-noesia-cs-reorder-subtab') === key);
                });
                root.querySelectorAll('[data-noesia-cs-reorder-section]').forEach(function (section) {
                    var active = section.getAttribute('data-noesia-cs-reorder-section') === key;
                    section.classList.toggle('is-active', active);
                    if (active) {
                        section.removeAttribute('hidden');
                    } else {
                        section.setAttribute('hidden', 'hidden');
                    }
                });
                try {
                    window.history.replaceState({}, '', link.href);
                } catch (e) {}
            });
        });
    }


    function bindCheckoutStylePreview(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-checkout-style-preview]:not([data-noesia-cs-checkout-style-preview-bound])').forEach(function (panel) {
            panel.setAttribute('data-noesia-cs-checkout-style-preview-bound', '1');
            var stage = panel.querySelector('[data-noesia-cs-checkout-preview-stage]');
            var box = panel.querySelector('[data-noesia-cs-checkout-preview-box]');
            var hint = panel.querySelector('[data-noesia-cs-checkout-style-hint]');
            var select = document.querySelector('select[name="noesia_cs_settings[reorder_checkout_style]"]');
            var badgeInput = document.querySelector('[name="noesia_cs_settings[reorder_checkout_badge_label]"]');
            var choices = panel.querySelectorAll('[data-noesia-cs-checkout-style-choice]');
            var styles = ['clean', 'dark', 'glamour'];

            function updateBadgeLabel() {
                if (!box || !badgeInput) {
                    return;
                }
                box.setAttribute('data-noesia-cs-badge-label', badgeInput.value || 'Reorder Reminder');
            }

            function applyStyle(style) {
                if (styles.indexOf(style) === -1) {
                    style = 'clean';
                }
                if (stage) {
                    styles.forEach(function (item) {
                        stage.classList.remove('noesia-cs-checkout-preview-stage--' + item);
                    });
                    stage.classList.add('noesia-cs-checkout-preview-stage--' + style);
                }
                if (box) {
                    updateBadgeLabel();
                    styles.forEach(function (item) {
                        box.classList.remove('noesia-cs-checkout-reorder-request--' + item);
                    });
                    box.classList.add('noesia-cs-checkout-reorder-request--' + style);
                }
                choices.forEach(function (choice) {
                    var active = choice.getAttribute('data-noesia-cs-checkout-style-choice') === style;
                    choice.classList.toggle('is-active', active);
                    choice.setAttribute('aria-pressed', active ? 'true' : 'false');
                    var status = choice.querySelector('span');
                    if (status) {
                        status.textContent = active ? 'Selected' : 'Click to preview';
                    }
                });
                if (select && select.value !== style) {
                    select.value = style;
                    select.dispatchEvent(new Event('change', { bubbles: true }));
                }
                if (hint) {
                    hint.textContent = 'Style selected. Press Save Checkout Request to use it on the real checkout.';
                }
            }

            choices.forEach(function (choice) {
                choice.addEventListener('click', function (event) {
                    event.preventDefault();
                    applyStyle(choice.getAttribute('data-noesia-cs-checkout-style-choice') || 'clean');
                });
            });

            if (select) {
                select.addEventListener('change', function () {
                    applyStyle(select.value || 'clean');
                });
            }
            if (badgeInput) {
                badgeInput.addEventListener('input', updateBadgeLabel);
                updateBadgeLabel();
            }
        });
    }


    function bindCommandSearch(context) {
        context = context || document;
        context.querySelectorAll('[data-noesia-cs-command-search]:not([data-noesia-cs-command-search-bound])').forEach(function (box) {
            box.setAttribute('data-noesia-cs-command-search-bound', '1');
            var input = box.querySelector('[data-noesia-cs-command-input]');
            var results = box.querySelector('[data-noesia-cs-command-results]');
            var timer = null;
            var controller = null;
            if (!input || !results) {
                return;
            }

            function clearResults() {
                results.innerHTML = '';
                results.hidden = true;
                box.classList.remove('is-open', 'is-loading');
            }

            function setNote(message) {
                results.innerHTML = '';
                var note = document.createElement('div');
                note.className = 'noesia-cs-command-search__note';
                note.textContent = message || ((window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.adminSearchEmptyLabel) || 'No results');
                results.appendChild(note);
                results.hidden = false;
                box.classList.add('is-open');
            }

            function makeAction(action) {
                if (!action || (!action.url && !action.copy)) {
                    return null;
                }
                var label = action.label || 'Open';
                if (action.copy) {
                    var button = document.createElement('button');
                    button.type = 'button';
                    button.textContent = label;
                    button.addEventListener('click', function (event) {
                        event.preventDefault();
                        event.stopPropagation();
                        var old = button.textContent;
                        var value = action.copy;
                        function copied() {
                            button.textContent = (window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.adminSearchCopiedLabel) || 'Copied';
                            setTimeout(function () { button.textContent = old; }, 1200);
                        }
                        if (navigator.clipboard && navigator.clipboard.writeText) {
                            navigator.clipboard.writeText(value).then(copied).catch(function () {});
                        } else {
                            var source = document.createElement('input');
                            source.value = value;
                            document.body.appendChild(source);
                            source.select();
                            document.execCommand('copy');
                            document.body.removeChild(source);
                            copied();
                        }
                    });
                    return button;
                }
                var link = document.createElement('a');
                link.href = action.url;
                link.textContent = label;
                if (action.target) {
                    link.target = action.target;
                    link.rel = 'noopener noreferrer';
                }
                return link;
            }

            function renderPayload(payload) {
                results.innerHTML = '';
                var groups = payload && payload.groups ? payload.groups : [];
                if (!groups.length) {
                    setNote((payload && payload.note) || ((window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.adminSearchEmptyLabel) || 'No results'));
                    return;
                }
                groups.forEach(function (group) {
                    var groupNode = document.createElement('div');
                    groupNode.className = 'noesia-cs-command-search__group';
                    var heading = document.createElement('strong');
                    heading.textContent = group.label || '';
                    groupNode.appendChild(heading);

                    (group.items || []).forEach(function (item) {
                        var row = document.createElement(item.url ? 'a' : 'div');
                        row.className = 'noesia-cs-command-search__item';
                        if (item.url) {
                            row.href = item.url;
                            if (item.type === 'passport') {
                                row.target = '_blank';
                                row.rel = 'noopener noreferrer';
                            }
                        }
                        var meta = document.createElement('span');
                        meta.className = 'noesia-cs-command-search__meta';
                        var title = document.createElement('b');
                        title.textContent = item.title || '';
                        var subtitle = document.createElement('small');
                        subtitle.textContent = item.subtitle || '';
                        meta.appendChild(title);
                        meta.appendChild(subtitle);
                        row.appendChild(meta);
                        if (item.badge) {
                            var badge = document.createElement('em');
                            badge.textContent = item.badge;
                            row.appendChild(badge);
                        }
                        groupNode.appendChild(row);

                        if (item.actions && item.actions.length) {
                            var actions = document.createElement('div');
                            actions.className = 'noesia-cs-command-search__actions';
                            item.actions.forEach(function (action) {
                                var actionNode = makeAction(action);
                                if (actionNode) {
                                    actions.appendChild(actionNode);
                                }
                            });
                            groupNode.appendChild(actions);
                        }
                    });

                    results.appendChild(groupNode);
                });
                results.hidden = false;
                box.classList.add('is-open');
            }

            function runSearch() {
                var value = (input.value || '').trim();
                var minChars = parseInt((window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.adminSearchMinChars) || 2, 10);
                if (value.length < minChars) {
                    clearResults();
                    return;
                }
                if (!window.fetch || !window.FormData || !window.noesiaCommerceSuiteAdmin || !window.noesiaCommerceSuiteAdmin.ajaxUrl) {
                    return;
                }
                if (controller && controller.abort) {
                    controller.abort();
                }
                if (window.AbortController) {
                    controller = new AbortController();
                }
                var data = new FormData();
                data.set('action', 'noesia_cs_admin_search');
                data.set('nonce', window.noesiaCommerceSuiteAdmin.adminSearchNonce || '');
                data.set('query', value);
                box.classList.add('is-loading');
                setNote((window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.adminSearchLoadingLabel) || 'Searching');
                fetch(window.noesiaCommerceSuiteAdmin.ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: data,
                    signal: controller ? controller.signal : undefined
                }).then(function (response) {
                    return response.json();
                }).then(function (payload) {
                    if (!payload || !payload.success || !payload.data) {
                        setNote((window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.adminSearchEmptyLabel) || 'No results');
                        return;
                    }
                    renderPayload(payload.data);
                }).catch(function (error) {
                    if (error && error.name === 'AbortError') {
                        return;
                    }
                    setNote((window.noesiaCommerceSuiteAdmin && window.noesiaCommerceSuiteAdmin.adminSearchEmptyLabel) || 'No results');
                }).finally(function () {
                    box.classList.remove('is-loading');
                });
            }

            input.addEventListener('input', function () {
                if (timer) {
                    window.clearTimeout(timer);
                }
                timer = window.setTimeout(runSearch, 260);
            });
            input.addEventListener('focus', function () {
                if ((input.value || '').trim().length >= 2 && results.innerHTML) {
                    results.hidden = false;
                    box.classList.add('is-open');
                }
            });
            document.addEventListener('click', function (event) {
                if (!box.contains(event.target)) {
                    results.hidden = true;
                    box.classList.remove('is-open');
                }
            });
            input.addEventListener('keydown', function (event) {
                if (event.key === 'Escape') {
                    clearResults();
                    input.blur();
                }
            });
        });
    }


    function refreshLastHourOrders() {
        var pill = document.querySelector('[data-noesia-cs-last-hour-pill]');
        if (!pill || !window.fetch || !window.FormData || !window.noesiaCommerceSuiteAdmin || !window.noesiaCommerceSuiteAdmin.ajaxUrl) {
            return;
        }
        var countNode = pill.querySelector('[data-noesia-cs-last-hour-count]');
        if (!countNode) {
            return;
        }
        var data = new FormData();
        data.set('action', 'noesia_cs_last_hour_orders');
        data.set('nonce', window.noesiaCommerceSuiteAdmin.lastHourOrdersNonce || '');
        fetch(window.noesiaCommerceSuiteAdmin.ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            body: data
        }).then(function (response) {
            return response.json();
        }).then(function (payload) {
            if (!payload || !payload.success || !payload.data) {
                return;
            }
            countNode.textContent = String(payload.data.count || 0);
            pill.setAttribute('data-noesia-cs-last-hour-value', String(payload.data.count || 0));
            if (payload.data.label) {
                pill.setAttribute('aria-label', payload.data.label);
            }
        }).catch(function () {});
    }

    function bindLastHourOrdersLive() {
        if (document.body.getAttribute('data-noesia-cs-last-hour-bound')) {
            return;
        }
        var pill = document.querySelector('[data-noesia-cs-last-hour-pill]');
        if (!pill) {
            return;
        }
        document.body.setAttribute('data-noesia-cs-last-hour-bound', '1');
        refreshLastHourOrders();
        window.setInterval(refreshLastHourOrders, 60000);
    }

    document.addEventListener('keydown', function (event) {
        if (event.key !== 'Escape') {
            return;
        }
        document.querySelectorAll('.noesia-cs-modal.is-open').forEach(function (modal) {
            modal.classList.remove('is-open');
            modal.hidden = true;
        });
        closeProLightbox();
    });



    function bindCalculator(context) {
        context = context || document;
        var launcher = context.querySelector('[data-noesia-cs-calculator-open]');
        var layer = document.querySelector('[data-noesia-cs-calculator-layer]');
        var minibar = document.querySelector('[data-noesia-cs-calculator-minibar]');
        var template = document.getElementById('noesia-cs-calculator-template');
        if (!launcher || !layer || !minibar || !template || launcher.getAttribute('data-noesia-cs-calculator-bound')) {
            return;
        }
        launcher.setAttribute('data-noesia-cs-calculator-bound', '1');

        var counter = 0;
        var topZ = 120000;
        var states = new WeakMap();
        var storageKey = 'noesia_cs_shell_calculators_v1';
        var isRestoring = false;

        function isDesktop() {
            return window.matchMedia('(min-width: 961px)').matches;
        }

        function makeId() {
            counter += 1;
            return 'calc-' + Date.now() + '-' + counter;
        }

        function normalizeState(seed) {
            var state = seed && typeof seed === 'object' ? seed : {};
            var memory = state.memory && typeof state.memory === 'object' ? state.memory : {};
            return {
                id: state.id || makeId(),
                expression: typeof state.expression === 'string' ? state.expression : '',
                value: typeof state.value === 'string' ? state.value : '0',
                memory: {
                    cost: typeof memory.cost === 'string' ? memory.cost : '0',
                    margin: typeof memory.margin === 'string' ? memory.margin : '0'
                },
                history: Array.isArray(state.history) ? state.history.slice(0, 10).map(function (item) {
                    return {
                        expression: String(item && item.expression ? item.expression : ''),
                        result: String(item && item.result ? item.result : '0')
                    };
                }) : [],
                minimized: !!state.minimized,
                left: typeof state.left === 'number' ? state.left : null,
                top: typeof state.top === 'number' ? state.top : null,
                tapeOpen: typeof state.tapeOpen === 'boolean' ? state.tapeOpen : isDesktop()
            };
        }

        function formatNumber(value) {
            if (!isFinite(value)) {
                return 'Error';
            }
            var rounded = Math.round((value + Number.EPSILON) * 100000000) / 100000000;
            return String(rounded);
        }

        function safeEvaluate(expression) {
            var cleaned = String(expression || '').replace(/×/g, '*').replace(/÷/g, '/').replace(/−/g, '-').replace(/\s+/g, '');
            if (!cleaned || !/^[0-9+\-*/().%]+$/.test(cleaned)) {
                return null;
            }
            cleaned = cleaned.replace(/(\d+(?:\.\d+)?)%/g, '($1/100)');
            try {
                /* eslint-disable no-new-func */
                var result = Function('"use strict"; return (' + cleaned + ');')();
                /* eslint-enable no-new-func */
                if (typeof result !== 'number' || !isFinite(result)) {
                    return null;
                }
                return result;
            } catch (error) {
                return null;
            }
        }

        function getState(win) {
            return states.get(win) || normalizeState({ id: win.getAttribute('data-noesia-cs-calculator-id') || makeId() });
        }

        function listStates() {
            var saved = [];
            layer.querySelectorAll('[data-noesia-cs-calculator-window]').forEach(function (win) {
                saved.push(getState(win));
            });
            return saved.slice(0, 6);
        }

        function persistAll() {
            if (isRestoring) {
                return;
            }
            try {
                window.localStorage.setItem(storageKey, JSON.stringify(listStates()));
            } catch (error) {}
        }

        function saveState(win, state, skipPersist) {
            states.set(win, normalizeState(state));
            if (!skipPersist) {
                persistAll();
            }
        }

        function refreshWindow(win) {
            var state = getState(win);
            var expression = win.querySelector('[data-noesia-cs-calculator-expression]');
            var value = win.querySelector('[data-noesia-cs-calculator-value]');
            var cost = win.querySelector('[data-noesia-cs-calculator-memory-value="cost"]');
            var margin = win.querySelector('[data-noesia-cs-calculator-memory-value="margin"]');
            var history = win.querySelector('[data-noesia-cs-calculator-history]');
            var tapeToggle = win.querySelector('[data-noesia-cs-calculator-tape-toggle]');

            win.classList.toggle('is-tape-open', state.tapeOpen);
            win.classList.toggle('is-tape-closed', !state.tapeOpen);
            if (tapeToggle) {
                tapeToggle.setAttribute('aria-pressed', state.tapeOpen ? 'true' : 'false');
                tapeToggle.title = state.tapeOpen ? 'Hide calculation tape' : 'Show calculation tape';
            }
            if (expression) {
                expression.textContent = state.expression || '0';
            }
            if (value) {
                value.textContent = state.value || '0';
            }
            if (cost) {
                cost.textContent = state.memory.cost || '0';
            }
            if (margin) {
                margin.textContent = state.memory.margin || '0';
            }
            if (history) {
                history.innerHTML = '';
                state.history.slice(0, 10).forEach(function (item) {
                    var li = document.createElement('li');
                    var exp = document.createElement('span');
                    var res = document.createElement('strong');
                    exp.textContent = item.expression;
                    res.textContent = item.result;
                    li.appendChild(exp);
                    li.appendChild(res);
                    history.appendChild(li);
                });
            }
            var pill = minibar.querySelector('[data-noesia-cs-calculator-pill="' + win.getAttribute('data-noesia-cs-calculator-id') + '"]');
            if (pill && pill.querySelector('strong')) {
                pill.querySelector('strong').textContent = state.value || '0';
            }
        }

        function focusWindow(win) {
            topZ += 1;
            win.style.zIndex = String(topZ);
            layer.querySelectorAll('[data-noesia-cs-calculator-window]').forEach(function (other) {
                other.classList.toggle('is-focused', other === win);
            });
        }

        function createPill(win) {
            var id = win.getAttribute('data-noesia-cs-calculator-id');
            var existing = minibar.querySelector('[data-noesia-cs-calculator-pill="' + id + '"]');
            if (existing) {
                return existing;
            }
            var pill = document.createElement('button');
            pill.type = 'button';
            pill.className = 'noesia-cs-calculator-pill';
            pill.setAttribute('data-noesia-cs-calculator-pill', id);
            pill.innerHTML = '<span>Calculator</span><strong>0</strong>';
            pill.addEventListener('click', function () {
                var state = getState(win);
                state.minimized = false;
                saveState(win, state);
                win.hidden = false;
                pill.remove();
                focusWindow(win);
                refreshWindow(win);
                persistAll();
            });
            minibar.appendChild(pill);
            return pill;
        }

        function minimizeWindow(win) {
            var state = getState(win);
            state.minimized = true;
            saveState(win, state);
            win.hidden = true;
            createPill(win);
            refreshWindow(win);
            persistAll();
        }

        function closeWindow(win) {
            var id = win.getAttribute('data-noesia-cs-calculator-id');
            var pill = minibar.querySelector('[data-noesia-cs-calculator-pill="' + id + '"]');
            if (pill) {
                pill.remove();
            }
            states.delete(win);
            win.remove();
            persistAll();
        }

        function appendInput(win, input) {
            var state = getState(win);
            if (state.value === 'Error') {
                state.expression = '';
                state.value = '0';
            }
            if (/^[0-9.]$/.test(input)) {
                state.expression += input;
            } else if (/^[+\-*/%]$/.test(input)) {
                if (!state.expression && input !== '-') {
                    state.expression = state.value !== '0' ? state.value : '';
                }
                state.expression += input;
            }
            var preview = safeEvaluate(state.expression);
            if (preview !== null) {
                state.value = formatNumber(preview);
            } else if (!state.expression) {
                state.value = '0';
            }
            saveState(win, state);
            refreshWindow(win);
        }

        function calculate(win) {
            var state = getState(win);
            var result = safeEvaluate(state.expression || state.value);
            if (result === null) {
                state.value = 'Error';
            } else {
                state.value = formatNumber(result);
                state.history.unshift({ expression: state.expression || state.value, result: state.value });
                state.history = state.history.slice(0, 10);
                state.expression = state.value;
            }
            saveState(win, state);
            refreshWindow(win);
        }

        function bindWindow(win) {
            win.addEventListener('pointerdown', function () {
                focusWindow(win);
            });
            win.querySelectorAll('[data-noesia-cs-calculator-input]').forEach(function (button) {
                button.addEventListener('click', function () {
                    appendInput(win, button.getAttribute('data-noesia-cs-calculator-input') || '');
                });
            });
            var equals = win.querySelector('[data-noesia-cs-calculator-equals]');
            if (equals) {
                equals.addEventListener('click', function () { calculate(win); });
            }
            var clear = win.querySelector('[data-noesia-cs-calculator-clear]');
            if (clear) {
                clear.addEventListener('click', function () {
                    var state = getState(win);
                    state.expression = '';
                    state.value = '0';
                    saveState(win, state);
                    refreshWindow(win);
                });
            }
            var backspace = win.querySelector('[data-noesia-cs-calculator-backspace]');
            if (backspace) {
                backspace.addEventListener('click', function () {
                    var state = getState(win);
                    state.expression = (state.expression || '').slice(0, -1);
                    var result = safeEvaluate(state.expression);
                    state.value = result === null ? (state.expression ? state.value : '0') : formatNumber(result);
                    saveState(win, state);
                    refreshWindow(win);
                });
            }
            win.querySelectorAll('[data-noesia-cs-calculator-memory-save]').forEach(function (button) {
                button.addEventListener('click', function () {
                    var key = button.getAttribute('data-noesia-cs-calculator-memory-save');
                    var state = getState(win);
                    state.memory[key] = state.value || '0';
                    saveState(win, state);
                    refreshWindow(win);
                });
            });
            win.querySelectorAll('[data-noesia-cs-calculator-memory-use]').forEach(function (button) {
                button.addEventListener('click', function () {
                    var key = button.getAttribute('data-noesia-cs-calculator-memory-use');
                    var state = getState(win);
                    state.expression += state.memory[key] || '0';
                    var preview = safeEvaluate(state.expression);
                    if (preview !== null) {
                        state.value = formatNumber(preview);
                    }
                    saveState(win, state);
                    refreshWindow(win);
                });
            });
            var tape = win.querySelector('[data-noesia-cs-calculator-tape-toggle]');
            if (tape) {
                tape.addEventListener('click', function () {
                    var state = getState(win);
                    state.tapeOpen = !state.tapeOpen;
                    saveState(win, state);
                    refreshWindow(win);
                });
            }
            var duplicate = win.querySelector('[data-noesia-cs-calculator-duplicate]');
            if (duplicate) {
                duplicate.addEventListener('click', function () {
                    var copy = normalizeState(getState(win));
                    copy.id = makeId();
                    copy.minimized = false;
                    openCalculator(copy);
                });
            }
            var minimize = win.querySelector('[data-noesia-cs-calculator-minimize]');
            if (minimize) {
                minimize.addEventListener('click', function () { minimizeWindow(win); });
            }
            var close = win.querySelector('[data-noesia-cs-calculator-close]');
            if (close) {
                close.addEventListener('click', function () { closeWindow(win); });
            }
            bindDragging(win);
        }

        function bindDragging(win) {
            var handle = win.querySelector('[data-noesia-cs-calculator-drag-handle]');
            if (!handle) {
                return;
            }
            var startX = 0;
            var startY = 0;
            var originX = 0;
            var originY = 0;
            var dragging = false;
            handle.addEventListener('pointerdown', function (event) {
                if (!isDesktop() || event.target.closest('button')) {
                    return;
                }
                dragging = true;
                focusWindow(win);
                startX = event.clientX;
                startY = event.clientY;
                var rect = win.getBoundingClientRect();
                originX = rect.left;
                originY = rect.top;
                handle.setPointerCapture(event.pointerId);
                win.classList.add('is-dragging');
            });
            handle.addEventListener('pointermove', function (event) {
                if (!dragging || !isDesktop()) {
                    return;
                }
                var maxLeft = Math.max(12, window.innerWidth - win.offsetWidth - 12);
                var maxTop = Math.max(46, window.innerHeight - win.offsetHeight - 12);
                var left = Math.min(maxLeft, Math.max(12, originX + event.clientX - startX));
                var top = Math.min(maxTop, Math.max(46, originY + event.clientY - startY));
                win.style.left = left + 'px';
                win.style.top = top + 'px';
                win.style.right = 'auto';
                var state = getState(win);
                state.left = left;
                state.top = top;
                saveState(win, state);
            });
            handle.addEventListener('pointerup', function (event) {
                if (!dragging) {
                    return;
                }
                dragging = false;
                win.classList.remove('is-dragging');
                try {
                    handle.releasePointerCapture(event.pointerId);
                } catch (error) {}
                persistAll();
            });
        }

        function openCalculator(seed, restoring) {
            var fragment = template.content.cloneNode(true);
            var win = fragment.querySelector('[data-noesia-cs-calculator-window]');
            var state = normalizeState(seed);
            win.setAttribute('data-noesia-cs-calculator-id', state.id);
            layer.appendChild(fragment);
            if (isDesktop()) {
                if (typeof state.left !== 'number' || typeof state.top !== 'number' || !restoring) {
                    state.left = Math.max(220, window.innerWidth - 560 - ((layer.querySelectorAll('[data-noesia-cs-calculator-window]').length) * 18));
                    state.top = 96 + ((layer.querySelectorAll('[data-noesia-cs-calculator-window]').length) * 18);
                }
                win.style.left = state.left + 'px';
                win.style.top = state.top + 'px';
            }
            saveState(win, state, true);
            bindWindow(win);
            refreshWindow(win);
            if (state.minimized) {
                win.hidden = true;
                createPill(win);
                refreshWindow(win);
            } else {
                focusWindow(win);
            }
            if (!restoring) {
                persistAll();
            }
        }

        function restoreCalculators() {
            var saved = [];
            try {
                saved = JSON.parse(window.localStorage.getItem(storageKey) || '[]');
            } catch (error) {
                saved = [];
            }
            if (!Array.isArray(saved) || !saved.length) {
                return;
            }
            isRestoring = true;
            saved.slice(0, 6).forEach(function (state) {
                openCalculator(state, true);
            });
            isRestoring = false;
            persistAll();
        }

        launcher.addEventListener('click', function () {
            openCalculator();
        });

        window.addEventListener('resize', function () {
            layer.querySelectorAll('[data-noesia-cs-calculator-window]').forEach(function (win) {
                if (!isDesktop()) {
                    win.style.left = '';
                    win.style.top = '';
                    win.style.right = '';
                    return;
                }
                var rect = win.getBoundingClientRect();
                var left = Math.min(Math.max(12, rect.left), Math.max(12, window.innerWidth - win.offsetWidth - 12));
                var top = Math.min(Math.max(46, rect.top), Math.max(46, window.innerHeight - win.offsetHeight - 12));
                win.style.left = left + 'px';
                win.style.top = top + 'px';
                var state = getState(win);
                state.left = left;
                state.top = top;
                saveState(win, state);
            });
        });

        restoreCalculators();
    }

    function init(context) {
        context = context || document;
        renderQrCodes(context);
        bindCopyButtons(context);
        bindAdminShell(context);
        bindDateFilters(context);
        applyBarWidths(context);
        bindModals(context);
        bindWooNavigator(context);
        bindWpChromeFocus(context);
        bindProPageLightbox(context);
        bindDoctorScanLoader(context);
        bindImpactRangeStorage(context);
        bindImpactRefresh(context);
        bindDashboardProductFilters(context);
        bindHubSubtabs(context);
        bindHubAjaxSave(context);
        bindReorderSubtabs(context);
        bindCheckoutStylePreview(context);
        bindMediaUploadButtons(context);
        bindCommandSearch(context);
        bindLastHourOrdersLive();
        bindCalculator(context);
    }

    document.addEventListener('DOMContentLoaded', function () {
        init(document);
        bindAjaxTabs();
        updateTabLinks();
        restoreStoredDateRangeIfNeeded();
    });
}(window, document));
