(function () {
  const HOOK_VERSION = 'v5';
  const postHookStatus = (status, detail) => {
    try {
      window.postMessage({
        type: 'MW_HOOK_STATUS',
        payload: { status, detail: { ...detail, version: HOOK_VERSION }, at: Date.now() }
      }, '*');
    } catch (_) {}
  };
  try {
    const host = location.hostname || '';
    const path = location.pathname || '';
    const hostOk = /(^|\.)gomining\.com$/i.test(host);
    const pathOk = /\/miner-wars(\/|$)/.test(path);
    let topPathOk = false;
    if (window.top && window.top !== window) {
      try {
        topPathOk = /\/miner-wars(\/|$)/.test(window.top.location.pathname || '');
      } catch (_) {
        topPathOk = false;
      }
    }
    const referrer = document.referrer || '';
    const referrerOk = /\/miner-wars(\/|$)/.test(referrer);
    const isFrame = window.top && window.top !== window;
    const allowFrame = isFrame && referrerOk;
    if (!hostOk) {
      console.log(`[MW] WS hook ${HOOK_VERSION} skipped (not GoMining host)`);
      postHookStatus('skipped', { host, path, topPathOk, referrer, referrerOk, isFrame });
      return;
    }
    if (!(pathOk || topPathOk || allowFrame)) {
      postHookStatus('forced', { host, path, topPathOk, referrer, referrerOk, isFrame });
    }
  } catch (_) {
    return;
  }
  try {
    if (window.__MW_WS_HOOKED__) {
      postHookStatus('already', { href: location.href });
      return;
    }
    window.__MW_WS_HOOKED__ = true;
    console.log(`[MW] Injecting WS hook ${HOOK_VERSION}`);
    postHookStatus('ready', { href: location.href, frame: window.top !== window, referrer: document.referrer || '' });

    const WS_THROTTLE_MS = 20000;
    const WS_LOG_THROTTLE_MS = 20000;
    const NAME_THROTTLE_MS = 15000;
    const MW_DEBUG_WS = false;
    const wsEventThrottle = new Map();
    const wsLogThrottle = new Map();
    const wsNameThrottle = new Map();
    const shouldThrottleWsEvent = (eventName) => {
      if (!eventName) return false;
      const key = String(eventName).toLowerCase();
      if (key !== 'allusersstatev2' && key !== 'allusersstate') return false;
      const now = Date.now();
      const last = wsEventThrottle.get(key) || 0;
      if (now - last < WS_THROTTLE_MS) return true;
      wsEventThrottle.set(key, now);
      return false;
    };
    const shouldLogWsEvent = (eventName) => {
      if (!MW_DEBUG_WS) return false;
      if (!eventName) return false;
      const key = String(eventName).toLowerCase();
      const now = Date.now();
      const last = wsLogThrottle.get(key) || 0;
      if (now - last < WS_LOG_THROTTLE_MS) return false;
      wsLogThrottle.set(key, now);
      return true;
    };
    const shouldForwardWsEvent = (eventName) => {
      if (!eventName) return false;
      const key = String(eventName).toLowerCase();
      if (key.startsWith('chat:')) return false;
      return true;
    };

    const displayWsName = (name) => {
      if (!name) return name;
      const key = String(name);
      if (key === 'allUsersStateV2' || key === 'allUsersState') return 'WEBSOCKET_SCORE';
      return key;
    };

    const shouldAnnounceName = (name) => {
      if (!name) return false;
      const key = String(name);
      const now = Date.now();
      const last = wsNameThrottle.get(key) || 0;
      if (now - last < NAME_THROTTLE_MS) return false;
      wsNameThrottle.set(key, now);
      return true;
    };

    const announceName = (name) => {
      if (!shouldAnnounceName(name)) return;
      try {
        window.postMessage({ type: 'MW_WS_NAME', payload: { name: String(name), at: Date.now() } }, '*');
      } catch (_) {}
    };

    const extractSocketArray = (text) => {
      if (!text || typeof text !== 'string') return null;
      let candidate = text.trim();
      if (!candidate) return null;
      const arrayStart = candidate.indexOf('[');
      if (arrayStart >= 0 && candidate[0] !== '[') {
        candidate = candidate.slice(arrayStart);
      }
      if (candidate[0] !== '[') return null;
      try {
        const arr = JSON.parse(candidate);
        if (Array.isArray(arr) && typeof arr[0] === 'string') return arr;
      } catch (_) { }
      return null;
    };

    let lastRawPostAt = 0;
    const RAW_POST_MIN_MS = 20000;
    const postRaw = (kind, preview) => {
      const now = Date.now();
      if (now - lastRawPostAt < RAW_POST_MIN_MS) return;
      lastRawPostAt = now;
      try {
        window.postMessage({ type: 'MW_WS_RAW', payload: { kind, preview, at: now } }, '*');
      } catch (_) { }
    };
    const postRecv = (text, meta = {}) => {
      if (!text || typeof text !== 'string') return;
      try {
        window.postMessage({ type: 'MW_WS_RECV', data: text, meta }, '*');
      } catch (_) {}
    };
    try {
      const originalSend = WebSocket.prototype.send;
      WebSocket.prototype.send = function (data) {
        try {
          window.postMessage({ type: 'MW_WS_SEND', data }, '*');
        } catch (_) {}
        return originalSend.call(this, data);
      };
    } catch (_) {}

    const seenWsUrls = new Set();
    const postWsUrl = (url, meta = {}) => {
      if (!url) return;
      const key = String(url);
      if (seenWsUrls.has(key)) return;
      seenWsUrls.add(key);
      try {
        window.postMessage({
          type: 'MW_WS_URL',
          payload: { url: key, at: Date.now(), ...meta }
        }, '*');
      } catch (_) {}
    };

    const handleArr = (arr, wsInstance = null) => {
      if (!Array.isArray(arr)) return;
      const name = arr[0];
      const data = arr[1];
      announceName(name);
      const throttled = shouldThrottleWsEvent(name);
      if (!shouldForwardWsEvent(name)) return;
      if (shouldLogWsEvent(name)) {
        console.log('[MW] WS event', displayWsName(name), data);
      }
      let postedMini = false;
      try {
        const key = String(name || '').toLowerCase();
        if (key === 'allusersstatev2' || key === 'allusersstate') {
          const pickFields = [
            'clanId',
            'clan_id',
            'clanName',
            'clan_name',
            'score',
            'currentScore',
            'totalScore',
            'activeBoostScore',
            'basePoints',
            'usedAbilities',
            'abilityUsage',
            'clanLogo',
            'chance',
            'power',
            'rosterPower'
          ];
          let list = null;
          if (Array.isArray(data)) {
            list = data;
          } else if (data && typeof data === 'object') {
            if (Array.isArray(data.array)) list = data.array;
            else if (Array.isArray(data.participants)) list = data.participants;
            else if (Array.isArray(data.data)) list = data.data;
            else if (data.data && typeof data.data === 'object') {
              if (Array.isArray(data.data.array)) list = data.data.array;
              else if (Array.isArray(data.data.participants)) list = data.data.participants;
            }
          }
          if (Array.isArray(list)) {
            const miniData = list.map((item) => {
              if (!item || typeof item !== 'object') return item;
              const trimmed = {};
              pickFields.forEach((field) => {
                if (item[field] !== undefined) trimmed[field] = item[field];
              });
              return trimmed;
            });
            window.postMessage({ type: 'MW_WS_EVENT_MINI', payload: [name, miniData], throttled }, '*');
            postedMini = true;
          } else {
            window.postMessage({
              type: 'MW_WS_META',
              payload: {
                name,
                dataType: data === null ? 'null' : typeof data,
                keys: data && typeof data === 'object' ? Object.keys(data) : [],
                hasArray: Array.isArray(data),
                listType: list === null ? 'none' : typeof list
              }
            }, '*');
          }
        }
      } catch (_) {}
      if (!postedMini) {
        try {
          window.postMessage({
            type: 'MW_WS_META',
            payload: {
              name,
              dataType: data === null ? 'null' : typeof data,
              keys: data && typeof data === 'object' ? Object.keys(data) : [],
              hasArray: Array.isArray(data)
            }
          }, '*');
        } catch (_) {}
      }
      let sent = false;
      try {
        window.postMessage({ type: 'MW_WS_EVENT', payload: arr, throttled }, '*');
        sent = true;
      } catch (err) {
        try {
          window.postMessage({
            type: 'MW_WS_ERROR',
            payload: { name: String(name || ''), message: err?.message || String(err || ''), at: Date.now() }
          }, '*');
        } catch (_) {}
      }
      if (!sent) {
        try {
          const safe = JSON.parse(JSON.stringify(arr, (key, value) => {
            if (typeof value === 'bigint') return value.toString();
            if (typeof value === 'function') return undefined;
            return value;
          }));
          window.postMessage({ type: 'MW_WS_EVENT_SAFE', payload: safe, throttled }, '*');
        } catch (_) {}
      }
      try {
        window.dispatchEvent(new CustomEvent('MW_WS_EVENT_BRIDGE', { detail: arr }));
      } catch (_) { }
      if ((name === 'abilityUsage' || name === 'abilityUsageV2' || name === 'abilityUsageV3') && data) {
        window.postMessage({ type: 'MW_ABILITY_USAGE', payload: data }, '*');
        try {
          window.dispatchEvent(new CustomEvent('MW_ABILITY_USAGE_BRIDGE', { detail: data }));
        } catch (_) { }
      }
      if ((name === 'roundOpened' || name === 'roundClosed' || name === 'roundEnded') && data) {
        window.postMessage({ type: 'MW_ROUND_EVENT', payload: { name, data } }, '*');
        try {
          window.dispatchEvent(new CustomEvent('MW_ROUND_EVENT_BRIDGE', { detail: { name, data } }));
        } catch (_) { }
        if (name === 'roundOpened') {
          window.postMessage({ type: 'MW_ROUND_RESET' }, '*');
          try {
            window.dispatchEvent(new CustomEvent('MW_ROUND_RESET_BRIDGE'));
          } catch (_) { }
        }
      }
    };

    const processMessage = (d, wsInstance = null) => {
      if (wsInstance && wsInstance.url) {
        postWsUrl(wsInstance.url, { source: 'message' });
      }
      if (typeof d === 'string') {
        postRecv(d, { kind: 'string' });
        const arr = extractSocketArray(d);
        if (arr) {
          handleArr(arr, wsInstance);
        } else {
          postRaw('string', d.slice(0, 160));
        }
        return;
      }
      if (d instanceof ArrayBuffer) {
        try {
          const text = new TextDecoder().decode(d);
          postRecv(text, { kind: 'arraybuffer' });
          const arr = extractSocketArray(text);
          if (arr) {
            handleArr(arr, wsInstance);
          } else {
            postRaw('arraybuffer', text.slice(0, 160));
          }
        } catch (_) { }
        return;
      }
      if (typeof Blob !== 'undefined' && d instanceof Blob) {
        d.text().then((text) => {
          postRecv(text, { kind: 'blob' });
          const arr = extractSocketArray(text);
          if (arr) {
            handleArr(arr, wsInstance);
          } else {
            postRaw('blob', text.slice(0, 160));
          }
        }).catch(() => {});
      }
    };

    const attachWorkerBridge = (worker, label = 'worker') => {
      if (!worker || worker.__mwBridgeAttached) return;
      worker.__mwBridgeAttached = true;
      try {
        worker.addEventListener('message', (ev) => {
          const data = ev?.data;
          if (!data) return;
          if (data.__mw_ws_arr) {
            handleArr(data.__mw_ws_arr);
            return;
          }
          if (data.__mw_ws_raw) {
            postRaw(label, String(data.__mw_ws_raw).slice(0, 160));
          }
          if (data.__mw_ws_error) {
            postRaw(`${label}-error`, String(data.__mw_ws_error.error || '').slice(0, 160));
          }
          if (data.__mw_ws_url) {
            postWsUrl(data.__mw_ws_url.url, { workerId: data.__mw_ws_url.workerId, label });
          }
        });
      } catch (_) {}
    };

    const shouldWrapWorker = (url, options) => {
      if (!url) return false;
      if (typeof url !== 'string') return false;
      const lowered = url.toLowerCase();
      if (lowered.startsWith('blob:') || lowered.startsWith('data:') || lowered.startsWith('chrome-extension:')) {
        return false;
      }
      if (options && options.type === 'module') return false;
      try {
        const abs = new URL(url, location.href);
        return abs.origin === location.origin;
      } catch (_) {
        return false;
      }
    };

    const createWorkerWrapperUrl = (originalUrl, workerId) => {
      const absUrl = new URL(originalUrl, location.href).href;
      const wrapper = `
        (() => {
          const workerId = ${JSON.stringify(workerId)};
          const originalUrl = ${JSON.stringify(absUrl)};
          const postRaw = (kind, preview) => {
            try { self.postMessage({ __mw_ws_raw: { kind, preview, at: Date.now(), workerId } }); } catch (_) {}
          };
          const postUrl = (url) => {
            try { self.postMessage({ __mw_ws_url: { url, at: Date.now(), workerId } }); } catch (_) {}
          };
          const extractSocketArray = (text) => {
            if (!text || typeof text !== 'string') return null;
            let candidate = text.trim();
            if (!candidate) return null;
            const arrayStart = candidate.indexOf('[');
            if (arrayStart >= 0 && candidate[0] !== '[') {
              candidate = candidate.slice(arrayStart);
            }
            if (candidate[0] !== '[') return null;
            try {
              const arr = JSON.parse(candidate);
              if (Array.isArray(arr) && typeof arr[0] === 'string') return arr;
            } catch (_) {}
            return null;
          };
          const processMessage = (d) => {
            if (typeof d === 'string') {
              const arr = extractSocketArray(d);
              if (arr) {
                try { self.postMessage({ __mw_ws_arr: arr, __mw_worker_id: workerId }); } catch (_) {}
              } else {
                postRaw('string', d.slice(0, 160));
              }
              return;
            }
            if (d instanceof ArrayBuffer) {
              try {
                const text = new TextDecoder().decode(d);
                const arr = extractSocketArray(text);
                if (arr) {
                  try { self.postMessage({ __mw_ws_arr: arr, __mw_worker_id: workerId }); } catch (_) {}
                } else {
                  postRaw('arraybuffer', text.slice(0, 160));
                }
              } catch (_) {}
              return;
            }
            if (typeof Blob !== 'undefined' && d instanceof Blob) {
              d.text().then((text) => {
                const arr = extractSocketArray(text);
                if (arr) {
                  try { self.postMessage({ __mw_ws_arr: arr, __mw_worker_id: workerId }); } catch (_) {}
                } else {
                  postRaw('blob', text.slice(0, 160));
                }
              }).catch(() => {});
            }
          };
          try {
            const OriginalWS = self.WebSocket;
            if (OriginalWS && !OriginalWS.__mwWrapped) {
              const WrappedWS = function (...args) {
                const ws = new OriginalWS(...args);
                try {
                  const url = args && args.length ? args[0] : '';
                  if (url) postUrl(String(url));
                } catch (_) {}
                try {
                  ws.addEventListener('message', (ev) => {
                    processMessage(ev.data, ws);
                  });
                } catch (_) {}
                return ws;
              };
              WrappedWS.prototype = OriginalWS.prototype;
              OriginalWS.__mwWrapped = true;
              self.WebSocket = WrappedWS;
            }
          } catch (_) {}
          try {
            importScripts(originalUrl);
          } catch (err) {
            try { self.postMessage({ __mw_ws_error: { workerId, error: err?.message || String(err || ''), url: originalUrl } }); } catch (_) {}
            throw err;
          }
        })();
      `;
      return URL.createObjectURL(new Blob([wrapper], { type: 'application/javascript' }));
    };

    const OriginalWorker = window.Worker;
    if (typeof OriginalWorker === 'function') {
      window.Worker = function (scriptURL, options) {
        const urlString = typeof scriptURL === 'string' ? scriptURL : (scriptURL?.toString ? scriptURL.toString() : '');
        let workerUrl = scriptURL;
        if (shouldWrapWorker(urlString, options)) {
          const workerId = `mw_worker_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
          workerUrl = createWorkerWrapperUrl(urlString, workerId);
        }
        const worker = new OriginalWorker(workerUrl, options);
        attachWorkerBridge(worker, 'worker');
        return worker;
      };
      window.Worker.prototype = OriginalWorker.prototype;
    }

    const OriginalSharedWorker = window.SharedWorker;
    if (typeof OriginalSharedWorker === 'function') {
      window.SharedWorker = function (scriptURL, options) {
        const urlString = typeof scriptURL === 'string' ? scriptURL : (scriptURL?.toString ? scriptURL.toString() : '');
        let workerUrl = scriptURL;
        if (shouldWrapWorker(urlString, options)) {
          const workerId = `mw_shared_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
          workerUrl = createWorkerWrapperUrl(urlString, workerId);
        }
        const worker = new OriginalSharedWorker(workerUrl, options);
        try {
          if (worker && worker.port && !worker.port.__mwBridgeAttached) {
            worker.port.__mwBridgeAttached = true;
            worker.port.addEventListener('message', (ev) => {
              const data = ev?.data;
              if (!data) return;
              if (data.__mw_ws_arr) {
                handleArr(data.__mw_ws_arr);
                return;
              }
              if (data.__mw_ws_raw) {
                postRaw('sharedworker', String(data.__mw_ws_raw).slice(0, 160));
              }
              if (data.__mw_ws_error) {
                postRaw('sharedworker-error', String(data.__mw_ws_error.error || '').slice(0, 160));
              }
            });
            if (typeof worker.port.start === 'function') {
              worker.port.start();
            }
          }
        } catch (_) {}
        return worker;
      };
      window.SharedWorker.prototype = OriginalSharedWorker.prototype;
    }

    const originalAdd = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function (type, listener, ...args) {
      if (type === 'message' && listener) {
        const wrapped = function (ev) {
          if (ev && !ev.__mwProcessed) {
            ev.__mwProcessed = true;
            processMessage(ev.data, this);
          }
          return listener.apply(this, arguments);
        };
        return originalAdd.call(this, type, wrapped, ...args);
      }
      return originalAdd.call(this, type, listener, ...args);
    };

    const desc = Object.getOwnPropertyDescriptor(WebSocket.prototype, 'onmessage');
    if (desc && desc.set) {
      Object.defineProperty(WebSocket.prototype, 'onmessage', {
        configurable: true,
        enumerable: true,
        get: desc.get,
        set: function (handler) {
          const wrapped = function (ev) {
            if (ev && !ev.__mwProcessed) {
              ev.__mwProcessed = true;
            processMessage(ev.data, this);
          }
          if (typeof handler === 'function') {
            return handler.apply(this, arguments);
          }
          };
          return desc.set.call(this, wrapped);
        }
      });
    }

    const originalDispatch = WebSocket.prototype.dispatchEvent;
    if (originalDispatch) {
      WebSocket.prototype.dispatchEvent = function (ev) {
        try {
          if (ev && ev.type === 'message' && !ev.__mwProcessed) {
            ev.__mwProcessed = true;
            processMessage(ev.data, this);
          }
        } catch (_) { }
        return originalDispatch.call(this, ev);
      };
    }

    const OriginalWebSocket = window.WebSocket;
    if (typeof OriginalWebSocket === 'function' && !OriginalWebSocket.__mwWrapped) {
      const WrappedWebSocket = function (...args) {
        const ws = new OriginalWebSocket(...args);
        try {
          const url = args && args.length ? args[0] : '';
          if (url) postWsUrl(String(url));
        } catch (_) {}
        try {
          ws.addEventListener('message', (ev) => {
            if (ev && !ev.__mwProcessed) {
              ev.__mwProcessed = true;
              processMessage(ev.data, ws);
            }
          });
        } catch (_) {}
        return ws;
      };
      WrappedWebSocket.prototype = OriginalWebSocket.prototype;
      OriginalWebSocket.__mwWrapped = true;
      window.WebSocket = WrappedWebSocket;
    }
  } catch (err) {
    postHookStatus('error', { message: err?.message || String(err || '') });
    console.warn('[MW] WS hook failed to init', err);
  }

  // API call monitoring
  try {
    const normalizeHeaders = (headers) => {
      if (!headers) return null;
      const result = {};
      if (typeof headers.forEach === 'function') {
        headers.forEach((value, key) => {
          result[key] = value;
        });
        return result;
      }
      if (Array.isArray(headers)) {
        headers.forEach(([key, value]) => {
          result[key] = value;
        });
        return result;
      }
      if (typeof headers === 'object') {
        Object.keys(headers).forEach((key) => {
          const value = headers[key];
          if (value != null) result[key] = value;
        });
        return result;
      }
      return null;
    };

    const parseRequestBody = (value) => {
      if (value == null) return null;
      if (typeof value === 'string') {
        const trimmed = value.trim();
        if (!trimmed) return null;
        try {
          return JSON.parse(trimmed);
        } catch (_) {
          return trimmed;
        }
      }
      if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
        const params = {};
        value.forEach((val, key) => {
          if (params[key] == null) {
            params[key] = val;
          } else if (Array.isArray(params[key])) {
            params[key].push(val);
          } else {
            params[key] = [params[key], val];
          }
        });
        return params;
      }
      if (typeof FormData !== 'undefined' && value instanceof FormData) {
        const params = {};
        value.forEach((val, key) => {
          if (params[key] == null) {
            params[key] = val;
          } else if (Array.isArray(params[key])) {
            params[key].push(val);
          } else {
            params[key] = [params[key], val];
          }
        });
        return params;
      }
      return value;
    };

    const sendApiCallMessage = (url, method, body, headers) => {
      if (!url) return;
      const safeUrl = typeof url === 'string' ? url.split('?')[0] : url;
      const payload = {
        url: safeUrl,
        method: (method || 'GET').toUpperCase()
      };
      if (headers && Object.keys(headers).length) {
        payload.headers = headers;
      }
      if (body !== undefined && body !== null) {
        payload.body = body;
      }
      window.postMessage({ type: 'MW_API_CALL', payload }, '*');
    };

    if (!window.__mw_api_monitoring_hooked__) {
      window.__mw_api_monitoring_hooked__ = true;
      const originalFetch = window.fetch;
      if (typeof originalFetch === 'function') {
        window.fetch = function (input, init) {
          try {
            const normalizedInit = init || {};
            const url = typeof input === 'string' ? input : input?.url;
            const method = (normalizedInit.method || (typeof input === 'object' ? input?.method : 'GET')).toUpperCase();
            const headerSource = normalizedInit.headers || (typeof input === 'object' ? input?.headers : null);
            const headers = normalizeHeaders(headerSource);
            const bodySource = normalizedInit.body ?? (typeof input === 'object' ? input?.body : null);
            const parsedBody = parseRequestBody(bodySource);
            sendApiCallMessage(url, method, parsedBody, headers);
          } catch (_) {}
          return originalFetch.apply(this, arguments);
        };
      }

      const originalXHROpen = window.XMLHttpRequest?.prototype?.open;
      const originalXHRSend = window.XMLHttpRequest?.prototype?.send;
      if (originalXHROpen && originalXHRSend) {
        window.XMLHttpRequest.prototype.open = function (method, url, ...args) {
          this.__mw_api_call_meta = { method, url };
          return originalXHROpen.call(this, method, url, ...args);
        };
        window.XMLHttpRequest.prototype.send = function (...args) {
          try {
            const meta = this.__mw_api_call_meta || {};
            const parsedBody = parseRequestBody(args[0]);
            sendApiCallMessage(meta.url, meta.method, parsedBody, null);
          } catch (_) {}
          return originalXHRSend.apply(this, args);
        };
      }
    }
  } catch (err) {
    console.warn('[MW] API monitoring hook failed', err);
  }

  // Hook into the companion messaging layer (if present) to auto-forward clan rosters
  try {
    let tries = 0;
    const maxTries = 20;
    const timer = setInterval(() => {
      tries += 1;
      const bus = window.$;
      if (bus && typeof bus.onMessage === 'function') {
        if (bus.__mw_roster_hooked) {
          clearInterval(timer);
          return;
        }
        bus.__mw_roster_hooked = true;
        console.log('[MW] Hooking clan roster from companion bus');
        bus.onMessage((action, data) => {
          const roster = data?.clanData?.usersForClient || data?.usersForClient;
          if (roster && Array.isArray(roster) && roster.length) {
            try {
              window.postMessage({ type: 'MW_CLAN_ROSTER', payload: roster }, '*');
              window.dispatchEvent(new CustomEvent('MW_CLAN_ROSTER_BRIDGE', { detail: roster }));
              console.log('[MW] Forwarded clan roster', roster.length);
            } catch (e) {
              console.warn('[MW] Failed to forward clan roster', e);
            }
          }
        });
        // Proactively request clan data if the API is available
        if (typeof bus.sendDataToBackground === 'function') {
          try {
            bus.sendDataToBackground('getClanData', {});
          } catch (_) { }
        }
        clearInterval(timer);
      } else if (tries >= maxTries) {
        clearInterval(timer);
      }
    }, 500);
  } catch (e) {
    console.warn('[MW] Failed to hook clan roster bus', e);
  }
})();
