(function() {
  if (window.__YIXH_BRIDGE_LOADED__) return;
  window.__YIXH_BRIDGE_LOADED__ = true;
  
  // Silence verbose debug logs
  const originalLog = console.log;
  console.log = function(...args) {
    if (args[0] && typeof args[0] === 'string' && args[0].indexOf('[yixh') !== -1) {
      return;
    }
    return originalLog.apply(console, args);
  };

  // console.log('[yixh-bridge] Initializing bridge...');
  function getXhsState() {
    try {
      if (window.__INITIAL_STATE__) {
        const state = window.__INITIAL_STATE__;
        
        // Check if we are on a note detail page. If so, make sure __INITIAL_STATE__ actually has the detail of the current note.
        // Otherwise, client-side navigation (SPA) makes __INITIAL_STATE__ stale and wrong for the current note.
        const path = window.location.pathname;
        const isNotePage = path.includes('/explore/') || path.includes('/discovery/item/');
        if (isNotePage) {
          const currentNoteId = path.split('/').filter(p => p).pop()?.split('?')[0] || '';
          if (currentNoteId && (!state.note || !state.note.noteDetailMap || !state.note.noteDetailMap[currentNoteId])) {
            // State is stale and doesn't have the current note's detail. Do not send stale/incorrect state data.
            return;
          }
        }

        const data = {};
        
        // 1. Note Detail
        if (state.note && state.note.noteDetailMap) {
          const cleanMap = {};
          for (const id in state.note.noteDetailMap) {
            const detail = state.note.noteDetailMap[id];
            if (detail && detail.note) {
              const n = detail.note;
              cleanMap[id] = {
                note: {
                  title: n.title,
                  desc: n.desc,
                  time: n.time,
                  type: n.type,
                  imageList: n.imageList ? n.imageList.map(img => ({ 
                    ...img,
                    urlDefault: img.urlDefault, 
                    url: img.url,
                    infoList: img.infoList 
                  })) : [],
                  video: n.video,
                  user: n.user ? { nickname: n.user.nickname, avatar: n.user.avatar, userId: n.user.userId } : null,
                  interactInfo: n.interactInfo,
                  ipLocation: n.ipLocation,
                  xsecToken: n.xsecToken,
                  id: id
                }
              };
            }
          }
          data.note = { noteDetailMap: cleanMap };
        }

        // 2. User Page Data
        if (state.user) {
          const upd = state.user.userPageData || {};
          const rawNotes = state.user.notes?._value || state.user.notes || (state.notesQueries && state.notesQueries[0] && state.notesQueries[0].notes) || (state.user && state.user.notesQueries && state.user.notesQueries[0] && state.user.notesQueries[0].notes) || upd.notes || [];
          const flattenedNotes = Array.isArray(rawNotes) ? rawNotes.flatMap(g => Array.isArray(g) ? g : [g]) : [];
          data.user = {
            userPageData: {
              basicInfo: upd.basicInfo,
              interactions: upd.interactions,
              notesCount: upd.notesCount,
              notes: flattenedNotes
            }
          };
        }

        // 3. Comment List
        if (state.comment && state.comment.commentList) {
          data.comment = {
            commentList: state.comment.commentList.slice(0, 100).map(c => ({
              content: c.content,
              createTime: c.createTime,
              time: c.time,
              subCommentCount: c.subCommentCount,
              user: c.user ? { userId: c.user.userId } : null
            }))
          };
        }

        const safeData = JSON.parse(JSON.stringify(data));
        (window.top || window).postMessage({ type: 'YIXH_STATE_DATA', data: safeData }, '*');
      }
    } catch (e) {
      console.error('[yixh] Failed to get XHS state safely:', e);
    }
  }

  function findTokensInObject(obj, map = {}, visited = new WeakSet()) {
    if (!obj || typeof obj !== 'object') return map;
    if (visited.has(obj)) return map;
    visited.add(obj);

    if (obj instanceof Node || obj === window || obj === document) return map;

    const id = obj.id || obj.noteId || obj.note_id;
    const token = obj.xsec_token || obj.xsecToken || obj.xsec_Token;
    if (typeof id === 'string' && id.length === 24 && typeof token === 'string' && token) {
      map[id] = token;
    }
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key) && !key.startsWith('__')) {
        try {
          const val = obj[key];
          if (val && typeof val === 'object') {
            findTokensInObject(val, map, visited);
          }
        } catch (e) {}
      }
    }
    return map;
  }

  function extractSearchPageNotes() {
    try {
      const path = window.location.pathname;
      const isSearchPage = path.includes('search_result') || path.includes('search_result_ai');
      const isProfilePage = path.includes('/user/profile/');
      if (!isSearchPage && !isProfilePage) return;

      if (window.__INITIAL_STATE__) {
        const tokenMap = findTokensInObject(window.__INITIAL_STATE__);
        // console.log('[yixh-bridge] Recursively extracted tokens from __INITIAL_STATE__:', tokenMap);
        
        const items = [];
        for (const id in tokenMap) {
          items.push({
            model_type: 'note',
            note_card: {
              id: id,
              xsec_token: tokenMap[id]
            }
          });
        }
        
        if (items.length > 0) {
          // console.log('[yixh-bridge] Posting extracted initial state note items:', items.length);
          (window.top || window).postMessage({
            type: 'YIXH_API_DATA',
            api: 'search_notes',
            data: { items: items }
          }, '*');
        }
      }
    } catch (e) {
      console.error('[yixh-bridge] Failed to recursively extract tokens:', e);
    }
  }

  // Initial check
  getXhsState();
  extractSearchPageNotes();

  if (document.readyState === 'complete' || document.readyState === 'interactive') {
    extractSearchPageNotes();
  } else {
    window.addEventListener('DOMContentLoaded', extractSearchPageNotes);
  }
  setTimeout(extractSearchPageNotes, 500);
  setTimeout(extractSearchPageNotes, 1500);

  // Override history methods to detect SPA navigation instantly
  const originalPushState = window.history.pushState;
  window.history.pushState = function(...args) {
    originalPushState.apply(this, args);
    (window.top || window).postMessage({ type: 'YIXH_URL_CHANGED', url: window.location.href }, '*');
  };

  const originalReplaceState = window.history.replaceState;
  window.history.replaceState = function(...args) {
    originalReplaceState.apply(this, args);
    (window.top || window).postMessage({ type: 'YIXH_URL_CHANGED', url: window.location.href }, '*');
  };

  window.addEventListener('popstate', () => {
    (window.top || window).postMessage({ type: 'YIXH_URL_CHANGED', url: window.location.href }, '*');
  });

  // Listen for requests from content script
  window.addEventListener('message', (event) => {
    if (event.data && event.data.type === 'YIXH_GET_STATE') {
      getXhsState();
    }
    if (event.data && event.data.type === 'YIXH_TRIGGER_SEARCH') {
      // 只有顶层窗口才负责触发搜索，防止 iframe 递归触发
      if (window !== window.top) return;
      const { nickname } = event.data;
      if (nickname) {
        const iframe = document.createElement('iframe');
        iframe.id = 'yixh-search-trigger';
        Object.assign(iframe.style, {
          position: 'fixed',
          left: '-10000px',
          top: '-10000px',
          width: '1px',
          height: '1px'
        });
        // console.log('[yixh-bridge] Triggering search with keyword:', nickname);
        iframe.src = `https://www.xiaohongshu.com/search_result/?keyword=${encodeURIComponent(nickname)}&source=web_explore_feed`;
        document.body.appendChild(iframe);
        setTimeout(() => { if (iframe.parentNode) iframe.remove(); }, 15000);
      }
    }
    if (event.data && event.data.type === 'YIXH_FETCH_USER_STATS') {
      // 只有顶层窗口负责抓取，防止重复
      if (window !== window.top) return;
      const { userId } = event.data;
      if (userId) {
        const profileUrl = `https://www.xiaohongshu.com/user/profile/${userId}`;
        originalFetch(profileUrl).then(res => res.text()).then(html => {
          const statePrefix = 'window.__INITIAL_STATE__=';
          const startIdx = html.indexOf(statePrefix);
          if (startIdx !== -1) {
            let jsonStr = '';
            let depth = 0;
            let foundStart = false;
            for (let i = startIdx + statePrefix.length; i < html.length; i++) {
              const char = html[i];
              if (char === '{') {
                foundStart = true;
                depth++;
              } else if (char === '}') {
                depth--;
              }
              if (foundStart) {
                jsonStr += char;
                if (depth === 0) break;
              }
            }

            if (jsonStr) {
              try {
                const state = (new Function(`return ${jsonStr}`))();
                const upd = state.user?.userPageData;
                if (upd) {
                  (window.top || window).postMessage({ 
                    type: 'YIXH_API_DATA', 
                    api: 'hover_card', 
                    data: {
                      notesCount: upd.notesCount,
                      interact_info: {
                        follows: upd.interactions?.find(i => i.type === 'follows')?.count || '0',
                        fans: upd.interactions?.find(i => i.type === 'fans')?.count || '0',
                        interaction: upd.interactions?.find(i => i.type === 'interaction')?.count || '0'
                      },
                      notes: upd.notes,
                      basic_info: upd.basicInfo || {}
                    },
                    targetUserId: userId
                  }, '*');
                }
              } catch (err) {}
            }
          }
        }).catch(() => {});
      }
    }
    if (event.data && event.data.type === 'YIXH_API_REQUEST') {
      const { url, requestId, api, method, body } = event.data;
      const fetchFn = window.fetch || originalFetch;
      const reqMethod = (method || 'GET').toUpperCase();
      const isPost = reqMethod === 'POST' || reqMethod === 'PUT';
      const options = {
        method: reqMethod,
        credentials: 'include',
        headers: isPost ? {
          'Content-Type': 'application/json;charset=UTF-8'
        } : {}
      };
      if (body && isPost) {
        options.body = typeof body === 'string' ? body : JSON.stringify(body);
      }
      fetchFn(url, options).then(async (res) => {
        const contentType = res.headers.get('content-type') || '';
        let resultData = null;
        if (contentType.includes('application/json')) {
          resultData = await res.json();
        } else {
          resultData = await res.text();
        }
        const targetUserId = api === 'hover_card' ? new URL(url, window.location.href).searchParams.get('target_user_id') : undefined;
        (window.top || window).postMessage({ 
          type: 'YIXH_API_DATA', 
          api: api || 'generic', 
          data: (resultData && typeof resultData === 'object' && resultData.data) ? resultData.data : resultData,
          requestId,
          targetUserId
        }, '*');
      }).catch(err => {
        console.error('[yixh-bridge] API request failed:', err);
      });
    }
  });

  setInterval(() => {
    getXhsState();
  }, 3000);

  // --- API Interception ---
  // Disguise hooks to prevent anti-bot script verification errors
  const originalToString = Function.prototype.toString;
  Function.prototype.toString = function() {
    if (this === window.fetch) return 'function fetch() { [native code] }';
    if (this === window.XMLHttpRequest) return 'font XMLHttpRequest() { [native code] }'.replace('font', 'function');
    if (this === Function.prototype.toString) return 'function toString() { [native code] }';
    return originalToString.apply(this, arguments);
  };

  const originalFetch = window.fetch;
  const getUrl = (a) => {
    if (!a) return '';
    if (typeof a === 'string') return a;
    if (typeof a === 'object') return a.url || a.href || '';
    return String(a);
  };

  window.fetch = async function(input, init) {
    if (init && init.__yixh_internal) {
       return originalFetch.apply(this, arguments);
    }

    const response = await originalFetch.apply(this, arguments);
    const url = getUrl(input);
    
    if (url) {
      try {
        if (url.includes('search/onebox')) {
          const clone = response.clone();
          const json = await clone.json();
          if (json.success && json.data?.onebox_list) {
            const userBox = json.data.onebox_list.find(item => item.user_one_box)?.user_one_box;
            if (userBox) {
              (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'search_onebox', data: JSON.parse(JSON.stringify(userBox)), queryKeyword: new URL(window.location.href).searchParams.get('keyword') || '' }, '*');
            }
          }
        }
        if (url.includes('/api/sns/web/v1/search/notes') || url.includes('/api/sns/web/v1/search/notes_ai')) {
          const clone = response.clone();
          const json = await clone.json();
          if (json.success && json.data) {
            (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'search_notes', data: JSON.parse(JSON.stringify(json.data)) }, '*');
          }
        }
        if (url.includes('/api/sns/web/v1/search/usersearch')) {
          const clone = response.clone();
          const json = await clone.json();
          if (json.success && json.data) {
            (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'search_users', data: JSON.parse(JSON.stringify(json.data)) }, '*');
          }
        }
        if (url.includes('user_posted') || url.includes('user/posted')) {
          const clone = response.clone();
          const json = await clone.json();
          if (json.success && json.data) {
            (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'user_posted', data: JSON.parse(JSON.stringify(json.data)) }, '*');
          }
        }
        if (url.includes('/api/sns/web/v1/feed')) {
          const clone = response.clone();
          const json = await clone.json();
          if (json.success && json.data?.items?.[0]?.note_card) {
            (window.top || window).postMessage({ 
              type: 'YIXH_API_DATA', 
              api: 'feed',
              data: JSON.parse(JSON.stringify(json.data.items[0].note_card)) 
            }, '*');
          }
        }
        
        if (url.includes('/api/sns/web/v1/user/hover_card')) {
          const clone = response.clone();
          const json = await clone.json();
          if (json.success && json.data) {
            (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'hover_card', data: JSON.parse(JSON.stringify(json.data)), targetUserId: new URL(url, window.location.href).searchParams.get('target_user_id') || '' }, '*');
          }
        }

        if (url.includes('/api/sns/web/v2/comment/page')) {
          const clone = response.clone();
          const json = await clone.json();
          if (json.success && json.data) {
            (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'comments', data: JSON.parse(JSON.stringify(json.data)) }, '*');
          }
        }
      } catch (e) {}
    }
    return response;
  };

  const originalXHR = window.XMLHttpRequest;
  const XHRProxy = function() {
    const xhr = new originalXHR();
    const originalOpen = xhr.open;
    let requestUrl = '';

    xhr.open = function(method, url) {
      requestUrl = url;
      return originalOpen.apply(this, arguments);
    };

    xhr.addEventListener('load', function() {
      if (typeof requestUrl === 'string') {
        try {
          if (requestUrl.includes('search/onebox')) {
            const json = JSON.parse(xhr.responseText);
            if (json.success && json.data?.onebox_list) {
              const userBox = json.data.onebox_list.find(item => item.user_one_box)?.user_one_box;
              if (userBox) {
                (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'search_onebox', data: JSON.parse(JSON.stringify(userBox)), queryKeyword: new URL(window.location.href).searchParams.get('keyword') || '' }, '*');
              }
            }
          }
          if (requestUrl.includes('/api/sns/web/v1/search/notes') || requestUrl.includes('/api/sns/web/v1/search/notes_ai')) {
            const json = JSON.parse(xhr.responseText);
            if (json.success && json.data) {
              (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'search_notes', data: JSON.parse(JSON.stringify(json.data)) }, '*');
            }
          }
          if (requestUrl.includes('/api/sns/web/v1/search/usersearch')) {
            const json = JSON.parse(xhr.responseText);
            if (json.success && json.data) {
              (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'search_users', data: JSON.parse(JSON.stringify(json.data)) }, '*');
            }
          }
          if (requestUrl.includes('user_posted') || requestUrl.includes('user/posted')) {
            const json = JSON.parse(xhr.responseText);
            if (json.success && json.data) {
              (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'user_posted', data: JSON.parse(JSON.stringify(json.data)) }, '*');
            }
          }
          if (requestUrl.includes('/api/sns/web/v1/feed')) {
            const json = JSON.parse(xhr.responseText);
            if (json.success && json.data?.items?.[0]?.note_card) {
              (window.top || window).postMessage({ 
                type: 'YIXH_API_DATA', 
                api: 'feed',
                data: JSON.parse(JSON.stringify(json.data.items[0].note_card)) 
              }, '*');
            }
          }
          if (requestUrl.includes('/api/sns/web/v1/user/hover_card')) {
            const json = JSON.parse(xhr.responseText);
            if (json.success && json.data) {
              (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'hover_card', data: JSON.parse(JSON.stringify(json.data)), targetUserId: new URL(requestUrl, window.location.href).searchParams.get('target_user_id') || '' }, '*');
            }
          }
          if (requestUrl.includes('/api/sns/web/v2/comment/page')) {
            const json = JSON.parse(xhr.responseText);
            if (json.success && json.data) {
              (window.top || window).postMessage({ type: 'YIXH_API_DATA', api: 'comments', data: JSON.parse(JSON.stringify(json.data)) }, '*');
            }
          }
        } catch (e) {}
      }
    });

    return xhr;
  };

  // Configure prototype chain correctly
  XHRProxy.prototype = originalXHR.prototype;
  XHRProxy.prototype.constructor = XHRProxy;
  
  // Copy static properties of XMLHttpRequest
  Object.getOwnPropertyNames(originalXHR).forEach(key => {
    try {
      const desc = Object.getOwnPropertyDescriptor(originalXHR, key);
      if (desc) {
        Object.defineProperty(XHRProxy, key, desc);
      }
    } catch (e) {
      XHRProxy[key] = originalXHR[key];
    }
  });

  // Ensure function name is correct
  try {
    Object.defineProperty(XHRProxy, 'name', { value: 'XMLHttpRequest', writable: false, configurable: true });
  } catch (e) {}
  
  window.XMLHttpRequest = XHRProxy;
})();
