(function () {
  if (window.__clNavFastInstalled) return;
  window.__clNavFastInstalled = true;
  window.__pageLeaving = false;

  var nativeSetInterval = window.setInterval.bind(window);
  var nativeClearInterval = window.clearInterval.bind(window);
  var nativeSetTimeout = window.setTimeout.bind(window);
  var nativeClearTimeout = window.clearTimeout.bind(window);
  var activeIntervals = new Set();
  var activeTimeouts = new Set();
  var activeFetchControllers = new Set();

  window.setInterval = function () {
    var id = nativeSetInterval.apply(window, arguments);
    activeIntervals.add(id);
    return id;
  };

  window.clearInterval = function (id) {
    activeIntervals.delete(id);
    return nativeClearInterval(id);
  };

  window.setTimeout = function () {
    var args = Array.prototype.slice.call(arguments);
    var fn = args[0];
    var id;
    args[0] = function () {
      activeTimeouts.delete(id);
      if (typeof fn === 'function') return fn.apply(this, arguments);
      return (0, eval)(fn);
    };
    id = nativeSetTimeout.apply(window, args);
    activeTimeouts.add(id);
    return id;
  };

  window.clearTimeout = function (id) {
    activeTimeouts.delete(id);
    return nativeClearTimeout(id);
  };

  if (window.fetch && window.AbortController) {
    var nativeFetch = window.fetch.bind(window);
    window.fetch = function (input, init) {
      init = init || {};
      if (init.signal || window.__pageLeaving) {
        return nativeFetch(input, init);
      }
      var controller = new AbortController();
      activeFetchControllers.add(controller);
      var nextInit = Object.assign({}, init, { signal: controller.signal });
      return nativeFetch(input, nextInit).finally(function () {
        activeFetchControllers.delete(controller);
      });
    };
  }

  var style = document.createElement('style');
  style.textContent = [
    '.tabs{height:48px!important;min-height:48px!important;padding:6px 12px!important;gap:8px!important;display:flex!important;align-items:center!important;flex-wrap:nowrap!important;overflow-x:auto!important;overflow-y:hidden!important;background:#094a80!important;border-bottom:1px solid rgba(0,0,0,.18)!important;box-sizing:border-box!important;}',
    '.tabs .brand-mark{height:36px!important;min-width:138px!important;flex:0 0 138px!important;padding:0 10px 0 2px!important;display:inline-flex!important;align-items:center!important;gap:8px!important;font-size:18px!important;font-weight:800!important;color:#fff!important;line-height:36px!important;white-space:nowrap!important;box-sizing:border-box!important;}',
    '.tabs .brand-mark img{width:24px!important;height:24px!important;object-fit:contain!important;display:block!important;flex:0 0 24px!important;}',
    '.tabs a{height:36px!important;min-width:88px!important;padding:0 14px!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;flex:0 0 88px!important;box-sizing:border-box!important;border-radius:6px!important;color:#e8f1fb!important;text-decoration:none!important;font-size:14px!important;font-weight:700!important;line-height:1!important;white-space:nowrap!important;background:rgba(255,255,255,.08)!important;border:1px solid rgba(255,255,255,.14)!important;transition:background .12s ease,border-color .12s ease,transform .12s ease!important;}',
    '.tabs a:hover{background:rgba(255,255,255,.16)!important;color:#fff!important;border-color:rgba(255,255,255,.28)!important;}',
    '.tabs a:active{transform:translateY(1px)!important;}',
    '.tabs a.nav-loading{pointer-events:none!important;opacity:.82!important;filter:saturate(.95)!important;}',
    '.tabs a.active{background:#35b653!important;color:#fff!important;border-color:#35b653!important;font-weight:800!important;box-shadow:inset 0 1px rgba(255,255,255,.22)!important;}',
    '.tabs a[href="/admin_chat.html"]{display:none!important;}',
    '.tabs .top-tool-actions{margin-left:auto!important;height:36px!important;display:inline-flex!important;align-items:center!important;gap:8px!important;flex:0 0 auto!important;}',
    '.top-tool-btn{height:36px!important;min-width:92px!important;padding:0 16px!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;border-radius:6px!important;color:#fff!important;font-size:14px!important;font-weight:800!important;line-height:1!important;white-space:nowrap!important;box-sizing:border-box!important;}',
    '.top-tool-btn.update{background:#147cc0!important;border-color:rgba(255,255,255,.18)!important;}',
    '.top-tool-btn.service{background:#35b653!important;border-color:#35b653!important;}',
    '@media (max-width:1180px){.tabs{gap:6px!important;padding:6px 8px!important;}.tabs .brand-mark{min-width:130px!important;flex-basis:130px!important;font-size:17px!important;}.tabs a{min-width:82px!important;flex-basis:82px!important;font-size:13px!important;padding:0 10px!important;}.top-tool-btn{min-width:82px!important;padding:0 12px!important;font-size:13px!important;}}'
  ].join('');
  document.head.appendChild(style);

  var dialogStyle = document.createElement('style');
  dialogStyle.textContent = [
    '.cl-dialog-overlay{position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(15,23,42,.42);padding:24px;box-sizing:border-box;}',
    '.cl-dialog-card{width:420px;max-width:calc(100vw - 48px);background:#fff;border-radius:10px;box-shadow:0 22px 60px rgba(15,23,42,.26);overflow:hidden;color:#102033;font-family:"Microsoft YaHei",-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;}',
    '.cl-dialog-head{padding:20px 22px 8px;display:flex;align-items:center;gap:10px;}',
    '.cl-dialog-icon{width:34px;height:34px;border-radius:10px;background:#eaf4ff;color:#0b599b;display:inline-flex;align-items:center;justify-content:center;font-weight:900;font-size:18px;flex:0 0 auto;}',
    '.cl-dialog-title{font-size:17px;font-weight:800;color:#111827;line-height:1.35;}',
    '.cl-dialog-body{padding:8px 22px 18px;color:#526274;font-size:14px;line-height:1.7;white-space:pre-line;word-break:break-word;}',
    '.cl-dialog-input{width:100%;height:38px;margin-top:12px;padding:8px 10px;border:1px solid #cfd8e3;border-radius:6px;font-size:14px;box-sizing:border-box;}',
    '.cl-dialog-input:focus{outline:none;border-color:#0b599b;box-shadow:0 0 0 3px rgba(11,89,155,.10);}',
    '.cl-dialog-actions{display:flex;justify-content:flex-end;gap:10px;padding:14px 22px 20px;background:#fbfdff;border-top:1px solid #edf1f5;}',
    '.cl-dialog-btn{min-width:78px;height:34px;border-radius:6px;border:1px solid #d7e1ec;background:#fff;color:#42526a;font-size:14px;font-weight:700;cursor:pointer;}',
    '.cl-dialog-btn:hover{background:#f4f7fb;}',
    '.cl-dialog-btn.primary{background:#0b599b;border-color:#0b599b;color:#fff;}',
    '.cl-dialog-btn.primary:hover{background:#0a4f89;}'
  ].join('');
  document.head.appendChild(dialogStyle);

  function ensureDialogRoot() {
    var root = document.getElementById('clDialogRoot');
    if (!root) {
      root = document.createElement('div');
      root.id = 'clDialogRoot';
      document.body.appendChild(root);
    }
    return root;
  }

  function runWhenBodyReady(fn) {
    if (document.body) return fn();
    document.addEventListener('DOMContentLoaded', fn, { once: true });
  }

  function ensureOddsNavigation() {
    document.querySelectorAll('.tabs').forEach(function (tabs) {
      if (tabs.querySelector('a[href="/odds.html"]')) return;
      var settingsLink = tabs.querySelector('a[href="/settings.html"]');
      if (!settingsLink) return;
      var oddsLink = document.createElement('a');
      oddsLink.href = '/odds.html';
      oddsLink.setAttribute('data-i18n', '\u8d54\u7387\u8bbe\u7f6e');
      oddsLink.textContent = '\u8d54\u7387\u8bbe\u7f6e';
      settingsLink.insertAdjacentElement('afterend', oddsLink);
    });
    if (/\/odds\.html$/i.test(window.location.pathname)) {
      document.querySelectorAll('.tabs a').forEach(function (link) {
        link.classList.toggle('active', link.getAttribute('href') === '/odds.html');
      });
    }
  }
  runWhenBodyReady(ensureOddsNavigation);

  function openAppDialog(options) {
    options = options || {};
    return new Promise(function (resolve) {
      runWhenBodyReady(function () {
        var root = ensureDialogRoot();
        var overlay = document.createElement('div');
        overlay.className = 'cl-dialog-overlay';
        var hasInput = options.mode === 'prompt';
        overlay.innerHTML =
          '<div class="cl-dialog-card" role="dialog" aria-modal="true">' +
            '<div class="cl-dialog-head">' +
              '<div class="cl-dialog-icon">' + (options.icon || '!') + '</div>' +
              '<div class="cl-dialog-title"></div>' +
            '</div>' +
            '<div class="cl-dialog-body"><div class="cl-dialog-message"></div>' +
              (hasInput ? '<input class="cl-dialog-input" type="text">' : '') +
            '</div>' +
            '<div class="cl-dialog-actions">' +
              (options.showCancel ? '<button class="cl-dialog-btn cancel" type="button"></button>' : '') +
              '<button class="cl-dialog-btn primary ok" type="button"></button>' +
            '</div>' +
          '</div>';
        root.appendChild(overlay);
        var titleEl = overlay.querySelector('.cl-dialog-title');
        var msgEl = overlay.querySelector('.cl-dialog-message');
        var inputEl = overlay.querySelector('.cl-dialog-input');
        var okBtn = overlay.querySelector('.ok');
        var cancelBtn = overlay.querySelector('.cancel');
        titleEl.textContent = options.title || '\u8bf7\u786e\u8ba4';
        msgEl.textContent = options.message || '';
        okBtn.textContent = options.okText || '\u786e\u5b9a';
        if (cancelBtn) cancelBtn.textContent = options.cancelText || '\u53d6\u6d88';
        if (inputEl) {
          inputEl.value = options.defaultValue || '';
          nativeSetTimeout(function () { inputEl.focus(); inputEl.select(); }, 0);
        } else {
          nativeSetTimeout(function () { okBtn.focus(); }, 0);
        }
        function close(result) {
          overlay.remove();
          resolve(result);
        }
        okBtn.addEventListener('click', function () {
          close(hasInput ? inputEl.value : true);
        });
        if (cancelBtn) cancelBtn.addEventListener('click', function () {
          close(hasInput ? null : false);
        });
        overlay.addEventListener('click', function (event) {
          if (event.target === overlay && options.showCancel) close(hasInput ? null : false);
        });
        overlay.addEventListener('keydown', function (event) {
          if (event.key === 'Escape' && options.showCancel) close(hasInput ? null : false);
          if (event.key === 'Enter' && (!hasInput || document.activeElement === inputEl)) {
            event.preventDefault();
            close(hasInput ? inputEl.value : true);
          }
        });
      });
    });
  }

  window.appConfirm = function (message, options) {
    options = Object.assign({ message: message, showCancel: true, icon: '?' }, options || {});
    return openAppDialog(options);
  };
  window.appAlert = function (message, options) {
    options = Object.assign({ message: message, showCancel: false, icon: 'i', title: '\u63d0\u793a' }, options || {});
    return openAppDialog(options);
  };
  window.appPrompt = function (message, defaultValue, options) {
    options = Object.assign({ message: message, defaultValue: defaultValue || '', mode: 'prompt', showCancel: true, icon: '?' }, options || {});
    return openAppDialog(options);
  };
  window.alert = function (message) {
    window.appAlert(String(message == null ? '' : message));
  };


  // ── Editable-field context menu (WebView2 disables its native menu in release builds) ──
  var editContextTarget = null;
  var editContextMenu = null;
  var nonTextInputTypes = {
    button: true, checkbox: true, color: true, file: true, hidden: true,
    image: true, radio: true, range: true, reset: true, submit: true
  };

  var editMenuStyle = document.createElement('style');
  editMenuStyle.textContent = [
    '.cl-edit-menu{position:fixed;z-index:1000000;display:none;min-width:156px;padding:6px;background:#fff;border:1px solid #d8e0e8;border-radius:8px;box-shadow:0 12px 34px rgba(15,23,42,.22);font-family:"Microsoft YaHei",-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;user-select:none;}',
    '.cl-edit-menu.open{display:block;}',
    '.cl-edit-menu button{width:100%;height:32px;padding:0 12px;display:flex;align-items:center;border:0;border-radius:5px;background:transparent;color:#17283b;font-size:13px;text-align:left;cursor:pointer;}',
    '.cl-edit-menu button:hover{background:#eaf4ff;color:#075a9d;}',
    '.cl-edit-menu button.disabled{color:#aeb7c1;pointer-events:none;}',
    '.cl-edit-menu-separator{height:1px;margin:5px 4px;background:#e8edf2;}'
  ].join('');
  document.head.appendChild(editMenuStyle);

  function editableContextTarget(origin) {
    if (!origin || !origin.closest) return null;
    var target = origin.closest('input, textarea, [contenteditable]');
    if (!target || target.disabled) return null;
    if (target.tagName === 'INPUT') {
      var type = String(target.type || 'text').toLowerCase();
      if (nonTextInputTypes[type]) return null;
    }
    if (target.tagName !== 'INPUT' && target.tagName !== 'TEXTAREA' && !target.isContentEditable) {
      return null;
    }
    return target;
  }

  function isWritableEditTarget(target) {
    return !!target && !target.disabled && !target.readOnly &&
      (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable);
  }

  function isPasswordEditTarget(target) {
    return !!target && target.tagName === 'INPUT' &&
      String(target.type || '').toLowerCase() === 'password';
  }

  function selectedEditText(target) {
    if (!target) return '';
    if (target.isContentEditable) {
      var selection = window.getSelection();
      if (!selection || !selection.rangeCount) return '';
      var range = selection.getRangeAt(0);
      if (!target.contains(range.commonAncestorContainer)) return '';
      return selection.toString();
    }
    try {
      if (typeof target.selectionStart === 'number' && typeof target.selectionEnd === 'number') {
        return String(target.value || '').slice(target.selectionStart, target.selectionEnd);
      }
    } catch (error) {}
    return '';
  }

  function dispatchEditedInput(target) {
    try {
      target.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
    } catch (error) {}
  }

  function replaceEditSelection(target, text) {
    if (!isWritableEditTarget(target)) return;
    target.focus({ preventScroll: true });
    var value = String(text == null ? '' : text);
    if (target.isContentEditable) {
      if (!document.execCommand('insertText', false, value)) {
        var selection = window.getSelection();
        if (selection && selection.rangeCount) {
          var range = selection.getRangeAt(0);
          range.deleteContents();
          range.insertNode(document.createTextNode(value));
          range.collapse(false);
        }
      }
      dispatchEditedInput(target);
      return;
    }
    try {
      if (typeof target.selectionStart === 'number' && typeof target.selectionEnd === 'number' &&
          typeof target.setRangeText === 'function') {
        target.setRangeText(value, target.selectionStart, target.selectionEnd, 'end');
      } else {
        target.value = value;
      }
    } catch (error) {
      target.value = value;
    }
    dispatchEditedInput(target);
  }

  async function writeAppClipboard(text) {
    var value = String(text == null ? '' : text);
    try {
      if (window.pywebview && window.pywebview.api &&
          typeof window.pywebview.api.clipboard_write === 'function') {
        var nativeResult = await window.pywebview.api.clipboard_write(value);
        if (nativeResult && nativeResult.success) return true;
      }
    } catch (error) {}
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(value);
        return true;
      }
    } catch (error) {}
    var helper = document.createElement('textarea');
    helper.value = value;
    helper.style.cssText = 'position:fixed;left:-10000px;top:-10000px;opacity:0;';
    document.body.appendChild(helper);
    helper.select();
    var copied = false;
    try { copied = document.execCommand('copy'); } catch (error) {}
    helper.remove();
    return copied;
  }

  async function readAppClipboard() {
    try {
      if (window.pywebview && window.pywebview.api &&
          typeof window.pywebview.api.clipboard_read === 'function') {
        var nativeResult = await window.pywebview.api.clipboard_read();
        if (nativeResult && nativeResult.success) {
          return { success: true, text: String(nativeResult.text || '') };
        }
      }
    } catch (error) {}
    try {
      if (navigator.clipboard && navigator.clipboard.readText) {
        return { success: true, text: await navigator.clipboard.readText() };
      }
    } catch (error) {}
    return { success: false, text: '' };
  }

  function ensureEditContextMenu() {
    if (editContextMenu) return editContextMenu;
    editContextMenu = document.createElement('div');
    editContextMenu.id = 'clEditContextMenu';
    editContextMenu.className = 'cl-edit-menu';
    editContextMenu.setAttribute('role', 'menu');
    editContextMenu.innerHTML =
      '<button type="button" data-cl-edit-command="undo">撤销</button>' +
      '<div class="cl-edit-menu-separator"></div>' +
      '<button type="button" data-cl-edit-command="cut">剪切</button>' +
      '<button type="button" data-cl-edit-command="copy">复制</button>' +
      '<button type="button" data-cl-edit-command="paste">粘贴</button>' +
      '<button type="button" data-cl-edit-command="delete">删除</button>' +
      '<div class="cl-edit-menu-separator"></div>' +
      '<button type="button" data-cl-edit-command="selectAll">全选</button>';
    editContextMenu.addEventListener('mousedown', function (event) {
      event.preventDefault();
    });
    editContextMenu.addEventListener('contextmenu', function (event) {
      event.preventDefault();
    });
    editContextMenu.addEventListener('click', async function (event) {
      var button = event.target.closest('[data-cl-edit-command]');
      if (!button || button.classList.contains('disabled') || !editContextTarget) return;
      var command = button.getAttribute('data-cl-edit-command');
      var target = editContextTarget;
      if (command === 'undo') {
        target.focus({ preventScroll: true });
        document.execCommand('undo');
      } else if (command === 'copy') {
        await writeAppClipboard(selectedEditText(target));
      } else if (command === 'cut') {
        var cutText = selectedEditText(target);
        if (cutText && await writeAppClipboard(cutText)) replaceEditSelection(target, '');
      } else if (command === 'paste') {
        var clipboard = await readAppClipboard();
        if (clipboard.success) {
          replaceEditSelection(target, clipboard.text);
        } else {
          window.appAlert('无法读取剪贴板，请使用 Ctrl+V 粘贴。');
        }
      } else if (command === 'delete') {
        replaceEditSelection(target, '');
      } else if (command === 'selectAll') {
        target.focus({ preventScroll: true });
        if (target.isContentEditable) {
          var range = document.createRange();
          range.selectNodeContents(target);
          var selection = window.getSelection();
          selection.removeAllRanges();
          selection.addRange(range);
        } else if (typeof target.select === 'function') {
          target.select();
        }
      }
      hideEditContextMenu();
    });
    document.body.appendChild(editContextMenu);
    return editContextMenu;
  }

  function setEditCommandEnabled(command, enabled) {
    var button = editContextMenu.querySelector('[data-cl-edit-command="' + command + '"]');
    if (!button) return;
    button.classList.toggle('disabled', !enabled);
    button.setAttribute('aria-disabled', enabled ? 'false' : 'true');
  }

  function showEditContextMenu(event, target) {
    var menu = ensureEditContextMenu();
    editContextTarget = target;
    var writable = isWritableEditTarget(target);
    var password = isPasswordEditTarget(target);
    var hasSelection = selectedEditText(target).length > 0;
    setEditCommandEnabled('undo', writable);
    setEditCommandEnabled('cut', writable && hasSelection && !password);
    setEditCommandEnabled('copy', hasSelection && !password);
    setEditCommandEnabled('paste', writable);
    setEditCommandEnabled('delete', writable && hasSelection);
    setEditCommandEnabled('selectAll', true);
    menu.classList.add('open');
    menu.style.left = '0px';
    menu.style.top = '0px';
    var width = menu.offsetWidth;
    var height = menu.offsetHeight;
    var left = Math.min(event.clientX, Math.max(6, window.innerWidth - width - 6));
    var top = Math.min(event.clientY, Math.max(6, window.innerHeight - height - 6));
    menu.style.left = Math.max(6, left) + 'px';
    menu.style.top = Math.max(6, top) + 'px';
  }

  function hideEditContextMenu() {
    if (editContextMenu) editContextMenu.classList.remove('open');
    editContextTarget = null;
  }

  document.addEventListener('contextmenu', function (event) {
    var target = editableContextTarget(event.target);
    if (!target) {
      hideEditContextMenu();
      return;
    }
    event.preventDefault();
    event.stopImmediatePropagation();
    try { target.focus({ preventScroll: true }); } catch (error) { target.focus(); }
    showEditContextMenu(event, target);
  }, true);

  document.addEventListener('click', function (event) {
    if (!editContextMenu || editContextMenu.contains(event.target)) return;
    hideEditContextMenu();
  }, true);
  document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') hideEditContextMenu();
  }, true);
  window.addEventListener('blur', hideEditContextMenu);
  window.addEventListener('resize', hideEditContextMenu);
  document.addEventListener('scroll', hideEditContextMenu, true);
  var lastNavHref = '';
  var lastNavAt = 0;
  var duplicateWindowMs = 300;
  var navUnlockTimer = null;

  function getNavLink(event) {
    return event && event.target && event.target.closest
      ? event.target.closest('.tabs a[href]')
      : null;
  }

  function isPrimaryPlainClick(event) {
    if (event.button && event.button !== 0) return false;
    return !(event.ctrlKey || event.shiftKey || event.altKey || event.metaKey);
  }

  document.addEventListener('click', function (event) {
    var link = getNavLink(event);
    if (!link || event.defaultPrevented || !isPrimaryPlainClick(event)) return;

    var href = link.href;
    if (!href) return;

    var current = window.location.href.split('#')[0];
    var next = href.split('#')[0];
    if (current === next) {
      event.preventDefault();
      event.stopImmediatePropagation();
      return;
    }

    var now = Date.now();
    if (href === lastNavHref && now - lastNavAt < duplicateWindowMs) {
      event.preventDefault();
      event.stopImmediatePropagation();
      return;
    }
    lastNavHref = href;
    lastNavAt = now;
    event.preventDefault();
    event.stopImmediatePropagation();
    link.classList.add('nav-loading');
    if (navUnlockTimer) nativeClearTimeout(navUnlockTimer);
    navUnlockTimer = nativeSetTimeout(function () {
      link.classList.remove('nav-loading');
    }, 5000);
    cleanupPageRuntime();
    // Jump immediately after cleanup.  Deferring this by one event-loop turn
    // lets page polling/render work get ahead of navigation on busy pages and
    // makes the top menu feel unresponsive.
    window.location.assign(href);
  }, true);

  document.addEventListener('dblclick', function (event) {
    var link = getNavLink(event);
    if (!link) return;
    event.preventDefault();
    event.stopImmediatePropagation();
  }, true);

  function cleanupPageRuntime() {
    if (window.__clPageRuntimeCleaned) return;
    window.__pageLeaving = true;
    window.__clPageRuntimeCleaned = true;
    activeIntervals.forEach(function (id) { nativeClearInterval(id); });
    activeIntervals.clear();
    activeTimeouts.forEach(function (id) { nativeClearTimeout(id); });
    activeTimeouts.clear();
    activeFetchControllers.forEach(function (controller) {
      try { controller.abort(); } catch (err) {}
    });
    activeFetchControllers.clear();
    try {
      if (window.ws && window.ws.readyState <= WebSocket.OPEN) window.ws.close(1000, 'page leaving');
      if (window.groupWs && window.groupWs.readyState <= WebSocket.OPEN) window.groupWs.close(1000, 'page leaving');
    } catch (err) {}
  }

  window.addEventListener('pagehide', cleanupPageRuntime, { capture: true });
  window.addEventListener('beforeunload', function () {
    cleanupPageRuntime();
  }, { capture: true });
})();
