// Chrome 扩展走 chrome.debugger.attach() 后顶部出现"已开始调试此浏览器"黄条，
// 这条不在 DOM 里但占视口，导致 window.outerHeight - innerHeight 异常大（实测 ozon.ru 177px，
// 真实 Chrome ~95px）。反爬模型把这个 ratio 当 fingerprint。
//
// document_start + world MAIN 注入，hook outerHeight / screenY / screenTop getter。
// hook 永远装上，getter 内动态判断：当前 diff > 130 说明黄条出现 → 返校正值；否则返真值。
// 这样不论 debugger 何时 attach（document_start 之前/之后）都能正确修正。

(function () {
  if (window.__rbFpNormalized) return;

  // 拿原始 getter — 调用它能拿到真实 outerHeight / screenY（绕过我们的 hook）
  let getRealOuterHeight, getRealScreenY, getRealScreenTop;
  try {
    const d = Object.getOwnPropertyDescriptor(Window.prototype, 'outerHeight');
    if (d && d.get) getRealOuterHeight = d.get.bind(window);
  } catch (e) {}
  try {
    const d = Object.getOwnPropertyDescriptor(Window.prototype, 'screenY');
    if (d && d.get) getRealScreenY = d.get.bind(window);
  } catch (e) {}
  try {
    const d = Object.getOwnPropertyDescriptor(Window.prototype, 'screenTop');
    if (d && d.get) getRealScreenTop = d.get.bind(window);
  } catch (e) {}

  // fallback：拿不到 prototype getter 就用首次访问值（不理想但兜底）
  if (!getRealOuterHeight) {
    const v = window.outerHeight;
    getRealOuterHeight = () => v;
  }
  if (!getRealScreenY) {
    const v = window.screenY;
    getRealScreenY = () => v;
  }
  if (!getRealScreenTop) {
    const v = window.screenTop;
    getRealScreenTop = () => v;
  }

  const TARGET_DIFF = 95;        // 正常 Chrome (omnibox 60 + tabs 35)
  const DEBUG_BAR_THRESHOLD = 130;  // > 130 即认为 debugger bar 出现

  // outerHeight getter — 黄条出现时返 innerHeight + 95，否则返真值
  try {
    Object.defineProperty(window, 'outerHeight', {
      get: function () {
        const realOuter = getRealOuterHeight();
        const realInner = window.innerHeight;
        const diff = realOuter - realInner;
        if (diff > DEBUG_BAR_THRESHOLD) return realInner + TARGET_DIFF;
        return realOuter;
      },
      configurable: true,
    });
  } catch (e) { /* ignore */ }

  // screenY / screenTop getter — 黄条出现时减去 debug bar 占的高度
  function normalizedScreenY(getReal) {
    const realOuter = getRealOuterHeight();
    const realInner = window.innerHeight;
    const diff = realOuter - realInner;
    const realScY = getReal();
    if (diff > DEBUG_BAR_THRESHOLD) {
      const debugBarPx = diff - TARGET_DIFF;
      return Math.max(0, realScY - debugBarPx);
    }
    return realScY;
  }
  try {
    Object.defineProperty(window, 'screenY', {
      get: function () { return normalizedScreenY(getRealScreenY); },
      configurable: true,
    });
  } catch (e) {}
  try {
    Object.defineProperty(window, 'screenTop', {
      get: function () { return normalizedScreenY(getRealScreenTop); },
      configurable: true,
    });
  } catch (e) {}

  // 标记 hook 已装上 — 不论 debugger 此刻是否 attach
  window.__rbFpNormalized = true;
})();
