/* eslint-disable */
/**
 * Page Protection Helper Script
 * This script creates a protective overlay on the page to prevent user interactions
 * and handles page close warnings
 */

// ===== 幂等性检查：避免重复初始化 =====
if (window.__mcpProtectionInitialized) {
  console.log('[页面保护] 已初始化，跳过重复执行');
  // 如果设置了自动启用标志，仍然尝试启用（可能是重新加入 Group）
  if (window.__mcpAutoProtect === true) {
    console.log('[页面保护] 检测到自动启用标志，尝试重新启用');
    // 此处需要确保后续代码定义的函数可用
    // 或者在消息监听器中处理
  }
  // 跳过后续初始化代码
  // 但仍需定义消息监听器以支持运行时切换
}
window.__mcpProtectionInitialized = true;

const CONFIG = {
  PROTECTION_Z_INDEX: 2147483647,
  SHADOW_ROOT_ID: 'mcp-page-protection-shadow-root',
};

// 保护模式枚举
const PROTECTION_MODES = {
  FULL: 'full', // 完全保护: 遮罩 + 拦截
  VISUAL_ONLY: 'visual', // 仅展示UI: 遮罩 - 拦截
  BLOCKING_ONLY: 'blocking', // 仅禁止点击: 拦截 - 遮罩
  DISABLED: 'disabled', // 完全禁用
};

// 页面保护状态 (新的统一状态管理)
let protectionState = {
  mode: PROTECTION_MODES.DISABLED,
  visualEnabled: false,
  blockingEnabled: false,
  shadowRoot: null,
  overlay: null,
  eventListeners: null,
};

// 兼容性: 保留旧变量作为状态的别名
let shadowRoot = null;
let protectionOverlay = null;
let isProtectionEnabled = false;
let scrollEventListeners = null;

/**
 * Create and setup shadow DOM container for style isolation
 */
function createShadowContainer() {
  if (protectionState.shadowRoot || shadowRoot) {
    return protectionState.shadowRoot || shadowRoot;
  }

  const container = document.createElement('div');
  container.id = CONFIG.SHADOW_ROOT_ID;
  container.style.cssText = `
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 0 !important;
    height: 0 !important;
    z-index: ${CONFIG.PROTECTION_Z_INDEX} !important;
    pointer-events: none !important;
    overflow: visible !important;
  `;

  try {
    protectionState.shadowRoot = container.attachShadow({ mode: 'closed' });
    shadowRoot = protectionState.shadowRoot; // 兼容性
    document.documentElement.appendChild(container);
    return protectionState.shadowRoot;
  } catch (e) {
    console.warn('Failed to create shadow DOM, falling back to regular DOM:', e);
    // Fallback to regular DOM
    protectionState.shadowRoot = container;
    shadowRoot = container; // 兼容性
    document.documentElement.appendChild(container);
    return protectionState.shadowRoot;
  }
}

/**
 * Create protection overlay
 */
function createProtectionOverlay() {
  if (protectionOverlay) {
    return protectionOverlay;
  }

  // Create shadow container first
  const shadowContainer = createShadowContainer();

  const overlay = document.createElement('div');
  overlay.id = 'mcp-page-protection-overlay';
  overlay.style.cssText = `
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100% !important;
    height: 100vh !important;
    pointer-events: none !important;
    z-index: ${CONFIG.PROTECTION_Z_INDEX} !important;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
  `;

  // 创建呼吸灯边框容器
  const breathingBorder = document.createElement('div');
  breathingBorder.style.cssText = `
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border: 2px solid #7171EE;
    border-radius: 8px;
    animation: mcpBreathing 3s ease-in-out infinite;
    box-shadow: none;
  `;

  // 创建顶部状态栏
  const statusBar = document.createElement('div');
  statusBar.style.cssText = `
    position: absolute;
    top: 40px;
    left: 50%;
    transform: translateX(-50%);
    background: #7171EE;
    color: #FFFFFF;
    padding: 12px;
    border-radius: 10px;
    border: 1px solid #E6E7EB;
    font-size: 12px;
    font-weight: 600;
    box-shadow: 0 10px 10px 0 rgba(113, 113, 238, 0.2);
    display: flex;
    align-items: center;
    gap: 8px;
    backdrop-filter: blur(10px);
    pointer-events: auto;
  `;

  // 创建加载动画图标 (SVG)
  const loadingIcon = document.createElement('span');
  loadingIcon.style.cssText = `
    display: inline-flex;
    align-items: center;
    justify-content: center;
    animation: mcpSpinRotate 1s linear infinite;
  `;

  // 内联 SVG 图标
  loadingIcon.innerHTML = `
    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
      <defs>
        <linearGradient id="mcpLoadingGradient" gradientTransform="matrix(10 12 -12 10 9.33333 -3.66667)" gradientUnits="userSpaceOnUse" x1="0" y1="0.5" x2="1" y2="0.5">
          <stop offset="0" stop-color="rgb(113, 113, 238)"/>
          <stop offset="1" stop-color="rgb(255, 255, 255)"/>
        </linearGradient>
      </defs>
      <path d="M16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16C12.4183 16 16 12.4183 16 8ZM13.3333 8C13.3333 5.05448 10.9455 2.66667 8 2.66667C5.05448 2.66667 2.66667 5.05448 2.66667 8C2.66667 10.9455 5.05448 13.3333 8 13.3333C10.9455 13.3333 13.3333 10.9455 13.3333 8Z" fill-rule="evenodd" fill="url(#mcpLoadingGradient)"/>
    </svg>
  `;

  statusBar.appendChild(loadingIcon);
  const extensionName = chrome.runtime?.getManifest?.()?.name || 'DataSaver';
  const text = document.createTextNode(`${extensionName}执行任务中`);
  statusBar.appendChild(text);

  // 添加CSS动画样式到Shadow DOM
  const styleSheet = document.createElement('style');
  styleSheet.id = 'mcp-protection-styles';
  styleSheet.textContent = `
    @keyframes mcpBreathing {
      0%, 100% {
        border-color: #7171EE;
        box-shadow: inset 0 0 40px 0 rgba(113, 113, 238, 0.5);
      }
      50% {
        border-color: #7171EE;
        box-shadow: inset 0 0 179px 0 rgba(113, 113, 238, 0.7);
      }
    }

    @keyframes mcpSpinRotate {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }
  `;

  overlay.appendChild(breathingBorder);
  overlay.appendChild(statusBar);

  // Add to shadow DOM or fallback container
  if (shadowContainer.shadowRoot) {
    shadowContainer.shadowRoot.appendChild(styleSheet);
    shadowContainer.shadowRoot.appendChild(overlay);
  } else {
    shadowContainer.appendChild(styleSheet);
    shadowContainer.appendChild(overlay);
  }

  protectionState.overlay = overlay;
  protectionOverlay = overlay; // 兼容性
  return overlay;
}

// ============ 遮罩管理模块 ============

/**
 * 显示保护遮罩
 * @param {Object} options - 配置选项
 * @param {string} options.statusText - 自定义状态栏文本
 */
function showOverlay(options = {}) {
  if (!protectionState.overlay) {
    createProtectionOverlay();
  }

  const container = document.getElementById(CONFIG.SHADOW_ROOT_ID);
  if (container) {
    container.style.display = 'block';

    // 支持自定义状态文本
    if (options.statusText && protectionState.overlay) {
      const shadowContainer = protectionState.shadowRoot;
      if (shadowContainer) {
        // 查找statusBar (在shadow DOM中)
        const statusBar = shadowContainer.querySelector
          ? shadowContainer.querySelector('#mcp-page-protection-overlay > div:nth-child(2)')
          : null;
        if (statusBar) {
          // 保留加载图标，只更新文本
          const textNode = Array.from(statusBar.childNodes).find(
            (node) => node.nodeType === Node.TEXT_NODE,
          );
          if (textNode) {
            textNode.textContent = options.statusText;
          }
        }
      }
    }
  }

  protectionState.visualEnabled = true;
  updateGlobalFlags();
}

/**
 * 隐藏保护遮罩 (不销毁，仅设置 display: none)
 */
function hideOverlay() {
  const container = document.getElementById(CONFIG.SHADOW_ROOT_ID);
  if (container) {
    container.style.display = 'none';
  }

  protectionState.visualEnabled = false;
  updateGlobalFlags();
}

/**
 * 销毁保护遮罩
 */
function destroyOverlay() {
  const container = document.getElementById(CONFIG.SHADOW_ROOT_ID);
  if (container) {
    container.remove();
  }

  protectionState.overlay = null;
  protectionState.shadowRoot = null;
  protectionState.visualEnabled = false;
  protectionOverlay = null; // 兼容性
  shadowRoot = null; // 兼容性
  updateGlobalFlags();
}

// ============ 事件拦截模块 ============

/**
 * 启用事件拦截
 */
function enableEventBlocking() {
  if (protectionState.blockingEnabled) return;

  // 确保overlay存在，用于拦截overlay上的事件
  if (!protectionState.overlay) {
    createProtectionOverlay();
  }

  // 在overlay上设置pointer-events以拦截点击
  if (protectionState.overlay) {
    protectionState.overlay.style.pointerEvents = 'auto';

    // 添加事件监听器
    protectionState.overlay.addEventListener('click', preventDefault, true);
    protectionState.overlay.addEventListener('mousedown', preventDefault, true);
    protectionState.overlay.addEventListener('mouseup', preventDefault, true);
    protectionState.overlay.addEventListener('keydown', preventDefault, true);
    protectionState.overlay.addEventListener('keyup', preventDefault, true);
  }

  // 全局滚动拦截
  const wheelHandler = (e) => preventDefault(e);
  const touchmoveHandler = (e) => preventDefault(e);

  document.addEventListener('wheel', wheelHandler, { passive: false, capture: true });
  document.addEventListener('touchmove', touchmoveHandler, { passive: false, capture: true });

  protectionState.eventListeners = {
    wheel: wheelHandler,
    touchmove: touchmoveHandler,
  };
  scrollEventListeners = protectionState.eventListeners; // 兼容性

  protectionState.blockingEnabled = true;
  updateGlobalFlags();
}

/**
 * 禁用事件拦截
 */
function disableEventBlocking() {
  if (!protectionState.blockingEnabled) return;

  // 移除overlay事件监听
  if (protectionState.overlay) {
    protectionState.overlay.style.pointerEvents = 'none';
    protectionState.overlay.removeEventListener('click', preventDefault, true);
    protectionState.overlay.removeEventListener('mousedown', preventDefault, true);
    protectionState.overlay.removeEventListener('mouseup', preventDefault, true);
    protectionState.overlay.removeEventListener('keydown', preventDefault, true);
    protectionState.overlay.removeEventListener('keyup', preventDefault, true);
  }

  // 移除全局滚动拦截
  if (protectionState.eventListeners) {
    document.removeEventListener('wheel', protectionState.eventListeners.wheel, { capture: true });
    document.removeEventListener('touchmove', protectionState.eventListeners.touchmove, {
      capture: true,
    });
    protectionState.eventListeners = null;
    scrollEventListeners = null; // 兼容性
  }

  protectionState.blockingEnabled = false;
  updateGlobalFlags();
}

// ============ 模式管理 ============

/**
 * 设置保护模式
 * @param {string} mode - 保护模式 ('full' | 'visual' | 'blocking' | 'disabled')
 * @param {Object} options - 配置选项
 */
function setProtectionMode(mode, options = {}) {
  switch (mode) {
    case PROTECTION_MODES.FULL:
      showOverlay(options);
      enableEventBlocking();
      setupNavigationProtection();
      enableCloseWarning();
      break;

    case PROTECTION_MODES.VISUAL_ONLY:
      showOverlay(options);
      disableEventBlocking();
      restoreNavigationProtection();
      disableCloseWarning();
      break;

    case PROTECTION_MODES.BLOCKING_ONLY:
      hideOverlay();
      enableEventBlocking();
      setupNavigationProtection();
      enableCloseWarning();
      break;

    case PROTECTION_MODES.DISABLED:
      hideOverlay();
      disableEventBlocking();
      restoreNavigationProtection();
      disableCloseWarning();
      break;

    default:
      console.warn('Unknown protection mode:', mode);
      return;
  }

  protectionState.mode = mode;
  updateGlobalFlags();
}

/**
 * 更新全局标志（兼容性）
 */
function updateGlobalFlags() {
  // window.isPageProtected 为 true 当任意一个功能启用时
  const isProtected = protectionState.visualEnabled || protectionState.blockingEnabled;
  window.isPageProtected = isProtected;
  isProtectionEnabled = isProtected; // 兼容性
}

/**
 * Enable page protection (strict mode only)
 * 兼容性函数：映射到 setProtectionMode
 */
function enablePageProtection() {
  try {
    setProtectionMode(PROTECTION_MODES.FULL);
    return {
      success: true,
      message: 'Page protection enabled successfully (strict mode)',
    };
  } catch (error) {
    return {
      success: false,
      message: `Failed to enable protection: ${error.message}`,
    };
  }
}

/**
 * Disable page protection
 * 兼容性函数：映射到 setProtectionMode
 */
function disablePageProtection() {
  try {
    // 完全禁用并销毁遮罩
    setProtectionMode(PROTECTION_MODES.DISABLED);
    destroyOverlay();
    return {
      success: true,
      message: 'Page protection disabled successfully',
    };
  } catch (error) {
    return {
      success: false,
      message: `Failed to disable protection: ${error.message}`,
    };
  }
}

/**
 * Enable close warning
 */
function enableCloseWarning() {
  console.log('enableCloseWarning called, isProtectionEnabled:', isProtectionEnabled);

  // Remove existing handler if any
  if (window.mcpBeforeUnloadHandler) {
    console.log('Removing existing beforeunload handler');
    window.removeEventListener('beforeunload', window.mcpBeforeUnloadHandler);
  }

  const beforeUnloadHandler = function (e) {
    console.log('beforeunload event triggered! isProtectionEnabled:', isProtectionEnabled);
    if (isProtectionEnabled) {
      console.log('Preventing page close - protection is enabled');
      // 现代浏览器需要用户交互后才能显示确认对话框
      // 设置returnValue会触发浏览器的默认确认对话框
      const message = '页面保护已启用，确定要离开吗？';
      e.returnValue = message;
      return message;
    } else {
      console.log('Allowing page close - protection is disabled');
    }
  };

  console.log('Adding beforeunload event listener');
  window.addEventListener('beforeunload', beforeUnloadHandler);

  // Store handler for potential cleanup
  window.mcpBeforeUnloadHandler = beforeUnloadHandler;

  // 确保页面有用户交互标记（这对beforeunload很重要）
  const ensureUserInteraction = () => {
    console.log('Ensuring user interaction for beforeunload');
    document.removeEventListener('click', ensureUserInteraction);
    document.removeEventListener('keydown', ensureUserInteraction);
  };

  document.addEventListener('click', ensureUserInteraction, { once: true });
  document.addEventListener('keydown', ensureUserInteraction, { once: true });

  console.log('Close warning setup completed');
  return {
    success: true,
    message: 'Close warning enabled successfully',
  };
}

/**
 * Disable close warning
 */
function disableCloseWarning() {
  // Remove beforeunload handler if it exists
  if (window.mcpBeforeUnloadHandler) {
    window.removeEventListener('beforeunload', window.mcpBeforeUnloadHandler);
    delete window.mcpBeforeUnloadHandler;
  }

  return {
    success: true,
    message: 'Close warning disabled successfully',
  };
}

/**
 * Get protection status
 * 增强版：返回更详细的状态信息
 */
function getProtectionStatus() {
  return {
    success: true,
    protectionEnabled: isProtectionEnabled, // 兼容字段
    mode: protectionState.mode,
    visualEnabled: protectionState.visualEnabled,
    blockingEnabled: protectionState.blockingEnabled,
    hasOverlay: !!protectionState.overlay,
  };
}

// Smart event filtering removed - only strict mode supported

/**
 * Legacy prevent default (for compatibility)
 * 只拦截真实用户事件，允许程序化触发的事件通过
 */
function preventDefault(e) {
  // 只拦截真实用户事件（由用户操作触发的事件）
  // 程序化触发的事件（isTrusted = false）将被允许通过
  if (!e.isTrusted) return;

  e.preventDefault();
  e.stopPropagation();
  return false;
}

// DOM API interception removed - no longer needed

// Smart protection removed - only strict mode supported

/**
 * Temporarily disable protection overlay for MCP tools
 */
function temporaryDisableOverlay(duration = 500, manual = false) {
  if (!isProtectionEnabled || !protectionOverlay) {
    return { success: true, message: 'No protection to disable' };
  }

  try {
    // Hide shadow container temporarily
    const shadowContainer = document.getElementById(CONFIG.SHADOW_ROOT_ID);
    if (shadowContainer) {
      shadowContainer.style.display = 'none';
    }

    // Set global flag for tools to detect
    window.mcpToolsActive = true;

    // Only use automatic restore if not in manual mode
    if (!manual && duration > 0) {
      // Restore after duration
      setTimeout(() => {
        if (shadowContainer && isProtectionEnabled) {
          shadowContainer.style.display = 'block';
        }
        window.mcpToolsActive = false;
      }, duration);
    }

    return {
      success: true,
      message: manual
        ? 'Protection overlay hidden (manual restore mode)'
        : `Protection overlay hidden for ${duration}ms`,
      manual: manual,
    };
  } catch (error) {
    return {
      success: false,
      message: `Failed to disable overlay: ${error.message}`,
    };
  }
}

/**
 * Restore protection overlay (for manual mode)
 */
function restoreOverlay() {
  if (!isProtectionEnabled) {
    return { success: true, message: 'Protection not enabled' };
  }

  try {
    const shadowContainer = document.getElementById(CONFIG.SHADOW_ROOT_ID);
    if (shadowContainer) {
      shadowContainer.style.display = 'block';
    }
    window.mcpToolsActive = false;

    return {
      success: true,
      message: 'Protection overlay restored',
    };
  } catch (error) {
    return {
      success: false,
      message: `Failed to restore overlay: ${error.message}`,
    };
  }
}

/**
 * Enhanced message handler for communication with background script
 */
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  try {
    let result;

    switch (message.action) {
      // ========== 新增：细粒度控制 ==========
      case 'SET_PROTECTION_MODE':
        setProtectionMode(message.mode, message.options || {});
        sendResponse({
          success: true,
          mode: protectionState.mode,
          visualEnabled: protectionState.visualEnabled,
          blockingEnabled: protectionState.blockingEnabled,
        });
        return true;

      case 'UPDATE_VISUAL_OVERLAY':
        if (message.enabled) {
          showOverlay(message.options || {});
        } else {
          hideOverlay();
        }
        sendResponse({
          success: true,
          visualEnabled: protectionState.visualEnabled,
        });
        return true;

      case 'UPDATE_EVENT_BLOCKING':
        if (message.enabled) {
          enableEventBlocking();
        } else {
          disableEventBlocking();
        }
        sendResponse({
          success: true,
          blockingEnabled: protectionState.blockingEnabled,
        });
        return true;

      // ========== 兼容性：原有消息 ==========
      case 'ENABLE_PAGE_PROTECTION':
        result = enablePageProtection();
        sendResponse(result);
        return true;

      case 'DISABLE_PAGE_PROTECTION':
        result = disablePageProtection();
        window.isPageProtected = false;
        sendResponse(result);
        return true;

      case 'ENABLE_CLOSE_WARNING':
        result = enableCloseWarning();
        sendResponse(result);
        return true;

      case 'DISABLE_CLOSE_WARNING':
        result = disableCloseWarning();
        sendResponse(result);
        return true;

      case 'GET_PROTECTION_STATUS':
        result = getProtectionStatus();
        sendResponse(result);
        return true;

      case 'TEMPORARY_DISABLE_OVERLAY':
        result = temporaryDisableOverlay(message.duration, message.manual);
        sendResponse(result);
        return true;

      case 'RESTORE_OVERLAY':
        result = restoreOverlay();
        sendResponse(result);
        return true;

      default:
        // Not a protection-related message, let other handlers process it
        return false;
    }
  } catch (error) {
    sendResponse({
      success: false,
      message: error.message,
    });
    return true;
  }
});

/**
 * Setup navigation protection to prevent browser navigation operations
 */
function setupNavigationProtection() {
  // Prevent keyboard shortcuts for navigation
  const navigationKeyHandler = (e) => {
    // Block common navigation shortcuts
    if (
      (e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) || // Alt+Left/Right (back/forward)
      (e.ctrlKey && e.key === 'r') || // Ctrl+R (refresh)
      (e.ctrlKey && e.shiftKey && e.key === 'R') || // Ctrl+Shift+R (hard refresh)
      e.key === 'F5' || // F5 (refresh)
      (e.ctrlKey && e.shiftKey && e.key === 'F5') || // Ctrl+Shift+F5 (hard refresh)
      (e.ctrlKey && e.key === 'l') || // Ctrl+L (address bar focus)
      (e.ctrlKey && e.key === 't') || // Ctrl+T (new tab)
      (e.ctrlKey && e.key === 'w') || // Ctrl+W (close tab)
      (e.ctrlKey && e.shiftKey && e.key === 'T') // Ctrl+Shift+T (restore tab)
    ) {
      e.preventDefault();
      e.stopPropagation();
      return false;
    }
  };

  // Add global keyboard listener
  document.addEventListener('keydown', navigationKeyHandler, true);

  // Store handler for cleanup
  window.mcpNavigationKeyHandler = navigationKeyHandler;

  // Override history methods
  if (!window.mcpOriginalHistoryMethods) {
    window.mcpOriginalHistoryMethods = {
      pushState: history.pushState,
      replaceState: history.replaceState,
      back: history.back,
      forward: history.forward,
      go: history.go,
    };

    // Override history.back()
    history.back = function () {
      if (!confirm('页面当前处于保护状态，确定要执行后退操作吗？')) {
        return false;
      }
      return window.mcpOriginalHistoryMethods.back.apply(this, arguments);
    };

    // Override history.forward()
    history.forward = function () {
      if (!confirm('页面当前处于保护状态，确定要执行前进操作吗？')) {
        return false;
      }
      return window.mcpOriginalHistoryMethods.forward.apply(this, arguments);
    };

    // Override history.go()
    history.go = function (delta) {
      const action = delta < 0 ? '后退' : delta > 0 ? '前进' : '刷新';
      if (!confirm(`页面当前处于保护状态，确定要执行${action}操作吗？`)) {
        return false;
      }
      return window.mcpOriginalHistoryMethods.go.apply(this, arguments);
    };

    // Override pushState and replaceState
    history.pushState = function () {
      if (!confirm('页面当前处于保护状态，确定要执行页面导航操作吗？')) {
        return false;
      }
      return window.mcpOriginalHistoryMethods.pushState.apply(this, arguments);
    };

    history.replaceState = function () {
      if (!confirm('页面当前处于保护状态，确定要修改页面状态吗？')) {
        return false;
      }
      return window.mcpOriginalHistoryMethods.replaceState.apply(this, arguments);
    };
  }
}

/**
 * Get navigation action name from keyboard event
 */
function getNavigationActionName(e) {
  if (e.altKey && e.key === 'ArrowLeft') return '页面后退';
  if (e.altKey && e.key === 'ArrowRight') return '页面前进';
  if ((e.ctrlKey && e.key === 'r') || e.key === 'F5') return '页面刷新';
  if (e.ctrlKey && e.key === 'l') return '地址栏聚焦';
  if (e.ctrlKey && e.key === 't') return '新建标签页';
  if (e.ctrlKey && e.key === 'w') return '关闭标签页';
  if (e.ctrlKey && e.shiftKey && e.key === 'T') return '恢复标签页';
  return '页面导航';
}

/**
 * Restore navigation functionality
 */
function restoreNavigationProtection() {
  // Remove keyboard listener
  if (window.mcpNavigationKeyHandler) {
    document.removeEventListener('keydown', window.mcpNavigationKeyHandler, true);
    delete window.mcpNavigationKeyHandler;
  }

  // Restore original history methods
  if (window.mcpOriginalHistoryMethods) {
    history.pushState = window.mcpOriginalHistoryMethods.pushState;
    history.replaceState = window.mcpOriginalHistoryMethods.replaceState;
    history.back = window.mcpOriginalHistoryMethods.back;
    history.forward = window.mcpOriginalHistoryMethods.forward;
    history.go = window.mcpOriginalHistoryMethods.go;
    delete window.mcpOriginalHistoryMethods;
  }
}

// Auto-cleanup on page unload
window.addEventListener('unload', () => {
  disablePageProtection();
});

// ===== 自执行初始化逻辑 =====

/**
 * 自动启用保护
 * 这个 IIFE 会在脚本加载时立即执行
 */
(function autoInitPageProtection() {
  console.log('[页面保护] 检测到自动启用标志，立即启用保护');

  // 立即启用完整保护模式
  try {
    const result = setProtectionMode(PROTECTION_MODES.FULL);
    if (result.success) {
      console.log('[页面保护] ✅ 自动启用成功');
    } else {
      console.warn('[页面保护] ⚠️ 自动启用失败:', result.error);
    }
  } catch (error) {
    console.error('[页面保护] ❌ 自动启用异常:', error);
  }
})();
