(function () {
  'use strict';

  if (window.UANumberWheel) return;

  var CANDIDATE_SELECTOR = [
    '[data-ua-counter]:not([data-ua-counter="off"])',
    '[data-ua-count]', '[data-required-count]', '[data-complete-count]',
    '[data-incomplete-count]', '[data-export-count]', '[data-progress-count]',
    '[data-ad-traffic-count]', '[data-ua-number-wheel-ready="1"]',
    '[id*="Count" i]', '[id*="Total" i]', '[id*="Online" i]',
    '[id*="Offline" i]', '[id*="Disabled" i]', '[id*="Unsafe" i]',
    '[id*="Sent" i]', '[id*="Failed" i]', '[id*="Pending" i]',
    '[id*="Processed" i]', '[id*="Percent" i]', '[id*="Balance" i]',
    '[id*="Amount" i]', '[id*="Queue" i]', '[id*="Success" i]',
    '[id*="Warning" i]',
    '[class*="-count"]', '[class*="_count"]',
    '[class*="-counter"]', '[class*="_counter"]',
    '[class*="-number"]', '[class*="_number"]',
    '[class*="-badge"]', '[class*="_badge"]',
    '[class*="-stat"] > strong', '[class*="-stat"] > b',
    '[class*="-stat"] > .value', '[class*="-stat"] > [class*="-value"]',
    '[class*="-stat"] .h1', '[class*="-stat"] .h2', '[class*="-stat"] .h3',
    '[class*="-stat"] .h4', '[class*="-stat"] .h5', '[class*="-stat"] .h6',
    '[class*="_stat"] > strong', '[class*="_stat"] > b',
    '[class*="_stat"] > .value',
    '[class*="-stats"] strong', '[class*="-stats"] b',
    '[class*="_stats"] strong', '[class*="_stats"] b',
    '[class*="-kpi"] > strong', '[class*="-kpi"] > b',
    '[class*="-kpi"] > .value', '[class*="-kpi"] > [class*="-value"]',
    '[class*="-kpi"] strong', '[class*="-kpi"] b',
    '[class*="-kpi"] [class*="-value"]',
    '[class*="_kpi"] > strong', '[class*="_kpi"] > b',
    '[class*="-summary"] > strong', '[class*="-summary"] > b',
    '[class*="-summary-row"] > strong', '[class*="-summary-row"] > b',
    '[class*="-summary"] [class*="-value"]',
    '[class*="-gauge"] b', '[class*="-gauge"] strong',
    '.nocx-stat-chip > strong', '.nocx-secmon-cell > strong',
    '.nocx-band-item > strong', '.nocx-soft-badge > strong'
  ].join(',');

  var DIGIT_RX = /[0-9\u0660-\u0669\u06f0-\u06f9]/;
  var DIGIT_RUN_RX = /[0-9\u0660-\u0669\u06f0-\u06f9]+/g;
  var state = new WeakMap();
  var internal = new WeakSet();
  var pending = new Set();
  var flushFrame = 0;

  var SHADOW_CSS = [
    ':host{display:inline-flex;height:1lh;align-items:baseline;vertical-align:top;',
    'font:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;direction:inherit;',
    'font-variant-numeric:tabular-nums;font-feature-settings:"cv01" 1,"cv02" 1,"tnum" 1}',
    '.display,.run{display:inline-flex;height:1lh;align-items:baseline;line-height:inherit}',
    '.display{white-space:pre}',
    '.text{white-space:pre}.unit{position:relative;top:-4px}',
    '.run{direction:ltr;unicode-bidi:isolate}',
    '.column{position:relative;display:inline-block;width:1ch;height:1lh;line-height:inherit;',
    'contain:layout paint style}',
    '.column:before{content:"0";visibility:hidden}',
    '.viewport{position:absolute;display:block;inset:0;overflow:hidden}',
    '.stack{display:flex;flex-direction:column;width:1ch;height:1lh;line-height:inherit;',
    'contain:layout size style;will-change:transform;',
    'transition:transform .3s cubic-bezier(.16,1,.3,1)}',
    '.stack>span{display:block;flex:0 0 1lh;width:1ch;height:1lh;line-height:inherit}',
    '@media(prefers-reduced-motion:reduce){.stack{transition:none}}'
  ].join('');

  function normalizeDigits(value) {
    return String(value || '')
      .replace(/[\u0660-\u0669]/g, function (digit) { return String(digit.charCodeAt(0) - 0x0660); })
      .replace(/[\u06f0-\u06f9]/g, function (digit) { return String(digit.charCodeAt(0) - 0x06f0); });
  }

  function digitValue(digit) {
    var code = digit.charCodeAt(0);
    if (code >= 0x0660 && code <= 0x0669) return code - 0x0660;
    if (code >= 0x06f0 && code <= 0x06f9) return code - 0x06f0;
    return Number(digit);
  }

  function digitGlyph(number, sample) {
    var code = sample.charCodeAt(0);
    if (code >= 0x0660 && code <= 0x0669) return String.fromCharCode(0x0660 + number);
    if (code >= 0x06f0 && code <= 0x06f9) return String.fromCharCode(0x06f0 + number);
    return String(number);
  }

  function digitFamily(digit) {
    var code = digit.charCodeAt(0);
    if (code >= 0x0660 && code <= 0x0669) return 'arabic';
    if (code >= 0x06f0 && code <= 0x06f9) return 'persian';
    return 'latin';
  }

  function isIdentifierLike(value) {
    var text = normalizeDigits(value).trim();
    return /^(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}$/i.test(text)
      || /^\d{1,3}(?:\.\d{1,3}){3}(?:\/\d{1,2})?$/.test(text)
      || /^\d{4}[-/]\d{1,2}[-/]\d{1,2}(?:\s|$)/.test(text)
      || /^\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AP]M)?$/i.test(text)
      || /^\+?\d[\d\s()-]{7,}$/.test(text);
  }

  function isExplicit(target) {
    return target.hasAttribute('data-ua-counter')
      && target.getAttribute('data-ua-counter') !== 'off';
  }

  function isEligible(target, value) {
    if (!target || target.nodeType !== 1 || !target.isConnected) return false;
    if (target.matches('input,textarea,select,option,code,pre,time,script,style,ua-number-flow')) return false;
    if (target.closest('[data-ua-counter="off"],[data-ua-number-wheel="off"],[contenteditable="true"]')) return false;
    if (!isExplicit(target) && target.closest('tbody,.pagination,.sct-bulk-people,.subs-table')) return false;
    if (!isExplicit(target) && target.children.length && !target.querySelector(':scope > ua-number-flow')) return false;
    value = String(value == null ? '' : value).replace(/\s+/g, ' ').trim();
    return !!value && value.length <= 48 && DIGIT_RX.test(value)
      && (isExplicit(target) || !isIdentifierLike(value));
  }

  function readValue(target, current) {
    if (current && current.host.parentElement === target) return current.value;
    return String(target.textContent == null ? '' : target.textContent).replace(/\s+/g, ' ').trim();
  }

  function partsFor(value) {
    var parts = [];
    var cursor = 0;
    var runIndex = 0;
    var matcher = new RegExp(DIGIT_RUN_RX.source, 'g');
    var match;
    while ((match = matcher.exec(value))) {
      if (match.index > cursor) parts.push({ text: value.slice(cursor, match.index) });
      var glyphs = Array.from(match[0]);
      var run = glyphs.map(function (glyph, index) {
        return { glyph: glyph, key: runIndex + ':' + (glyphs.length - index - 1) };
      });
      parts.push({ run: run });
      cursor = match.index + match[0].length;
      runIndex += 1;
    }
    if (cursor < value.length) parts.push({ text: value.slice(cursor) });
    return parts;
  }

  function makeColumn(sample) {
    var column = document.createElement('span');
    var viewport = document.createElement('span');
    var stack = document.createElement('span');
    column.className = 'column';
    viewport.className = 'viewport';
    stack.className = 'stack';
    for (var number = 0; number < 10; number += 1) {
      var glyph = document.createElement('span');
      glyph.textContent = digitGlyph(number, sample);
      stack.appendChild(glyph);
    }
    viewport.appendChild(stack);
    column.appendChild(viewport);
    return column;
  }

  function makeState() {
    var host = document.createElement('ua-number-flow');
    var shadow = host.attachShadow({ mode: 'open' });
    var style = document.createElement('style');
    var display = document.createElement('span');
    style.textContent = SHADOW_CSS;
    display.className = 'display';
    display.setAttribute('aria-hidden', 'true');
    shadow.append(style, display);
    host.setAttribute('role', 'text');
    return { host: host, display: display, columns: new Map(), signature: '', value: '', updateFrame: 0 };
  }

  function moveStack(stack, glyph) {
    stack.style.transform = 'translateY(-' + digitValue(glyph) + 'lh)';
  }

  function paint(target, value, current) {
    var remounted = current.host.parentElement !== target;
    if (remounted) {
      internal.add(target);
      target.replaceChildren(current.host);
    }

    var parts = partsFor(value);
    var signature = parts.map(function (part) {
      return part.text != null ? 't:' + part.text : 'r:' + part.run.length + ':' + digitFamily(part.run[0].glyph);
    }).join('|');
    var updates = [];

    if (current.signature === signature && current.columns.size) {
      parts.forEach(function (part) {
        if (!part.run) return;
        part.run.forEach(function (item) {
          var column = current.columns.get(item.key);
          if (column) updates.push({ stack: column.querySelector('.stack'), glyph: item.glyph });
        });
      });
    } else {
      var oldColumns = current.columns;
      var nextColumns = new Map();
      var fragment = document.createDocumentFragment();
      parts.forEach(function (part) {
        if (part.text != null) {
          var textPart = document.createElement('span');
          textPart.className = /^\s*Mbps$/i.test(part.text) ? 'text unit' : 'text';
          textPart.textContent = part.text;
          fragment.appendChild(textPart);
          return;
        }
        var run = document.createElement('span');
        run.className = 'run';
        run.setAttribute('dir', 'ltr');
        part.run.forEach(function (item) {
          var column = oldColumns.get(item.key) || makeColumn(item.glyph);
          var stack = column.querySelector('.stack');
          nextColumns.set(item.key, column);
          run.appendChild(column);
          if (oldColumns.has(item.key)) updates.push({ stack: stack, glyph: item.glyph });
          else moveStack(stack, item.glyph);
        });
        fragment.appendChild(run);
      });
      current.display.replaceChildren(fragment);
      current.columns = nextColumns;
      current.signature = signature;
    }

    if (current.updateFrame) cancelAnimationFrame(current.updateFrame);
    if (remounted && updates.length) {
      current.updateFrame = requestAnimationFrame(function () {
        updates.forEach(function (update) { moveStack(update.stack, update.glyph); });
        current.updateFrame = 0;
      });
    } else {
      updates.forEach(function (update) { moveStack(update.stack, update.glyph); });
    }

    current.value = value;
    current.host.setAttribute('aria-label', value);
    target.classList.add('ua-number-wheel-ready');
    target.setAttribute('data-ua-number-wheel-ready', '1');
    window.setTimeout(function () { internal.delete(target); }, 0);
  }

  function render(target) {
    if (!target || internal.has(target)) return;
    var current = state.get(target);
    var value = readValue(target, current);
    if (!isEligible(target, value)) return;
    if (!current) {
      current = makeState();
      state.set(target, current);
    }
    if (current.value === value && current.host.parentElement === target) return;
    paint(target, value, current);
  }

  function enqueue(target) {
    if (!target || internal.has(target)) return;
    pending.add(target);
    if (flushFrame) return;
    flushFrame = requestAnimationFrame(function () {
      flushFrame = 0;
      var batch = Array.from(pending);
      pending.clear();
      batch.forEach(render);
    });
  }

  function closestCandidate(node) {
    var element = node && node.nodeType === 1 ? node : node && node.parentElement;
    if (!element || element.closest('ua-number-flow')) return null;
    return element.matches(CANDIDATE_SELECTOR) ? element : element.closest(CANDIDATE_SELECTOR);
  }

  function scan(root) {
    if (!root) return;
    if (root.nodeType === 1 && root.matches(CANDIDATE_SELECTOR)) render(root);
    if (root.querySelectorAll) root.querySelectorAll(CANDIDATE_SELECTOR).forEach(render);
  }

  function start() {
    var root = document.body || document.documentElement;
    if (!root) return;
    var subscriberPage = document.body && document.body.classList.contains('ua-p-subscribers');
    var subscriberCounterSelector = [
      '#uaShellTotal', '#uaShellOnline', '#uaShellOffline', '#uaShellDisabled', '#uaShellUnsafe',
      '.nocx-alert-line__count', '#mtActiveCount', '#subsOfflineGaugeCount',
      '#subsDisabledGaugeCount', '#unsafeSpeedCount', '#subsTotalGaugeCount', '#selectedCount'
    ].join(',');
    var observedRoot = root;

    // The subscribers table can contain tens of thousands of nodes. Its cells are
    // identifiers and row actions, not animated counters, so do not run the global
    // heuristic selector across it. Keep the shell/live counters registered by an
    // explicit contract and observe those small nodes for their normal live updates.
    if (subscriberPage) {
      var subscriberCounters = Array.from(document.querySelectorAll(subscriberCounterSelector));
      subscriberCounters.forEach(render);
      observedRoot = subscriberCounters;
    } else {
      scan(root);
    }
    var observer = new MutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        var owner = closestCandidate(mutation.target);
        if (owner) enqueue(owner);
        mutation.addedNodes.forEach(function (node) {
          if (!node || node.nodeType !== 1 || node.matches('ua-number-flow')) return;
          var direct = closestCandidate(node);
          if (direct) enqueue(direct);
          if (node.querySelectorAll) node.querySelectorAll(CANDIDATE_SELECTOR).forEach(enqueue);
        });
      });
    });
    if (Array.isArray(observedRoot)) {
      observedRoot.forEach(function (counter) {
        observer.observe(counter, { childList: true, characterData: true, subtree: true });
      });
    } else {
      observer.observe(observedRoot, { childList: true, characterData: true, subtree: true });
    }
    window.UANumberWheel.observer = observer;
    document.dispatchEvent(new CustomEvent('ua:number-wheel:ready'));
  }

  window.UANumberWheel = {
    observer: null,
    refresh: function (root) { scan(root || document.body); },
    register: function (target) {
      if (!target || target.nodeType !== 1) return;
      target.setAttribute('data-ua-counter', '1');
      render(target);
    },
    set: function (target, value) {
      if (!target || target.nodeType !== 1) return;
      if (!target.hasAttribute('data-ua-counter')) target.setAttribute('data-ua-counter', '1');
      var current = state.get(target) || makeState();
      state.set(target, current);
      paint(target, String(value == null ? '' : value), current);
    }
  };

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });
  else start();
})();
