// Content Script
import { messaging, ping } from '../shared/messaging.js';
import { initSelectionListener } from './selection.js';
import { logger } from './logger.js';

logger.info('Content script loaded');

// 初始化文本选择监听
initSelectionListener();

// Ping 测试 - 验证通信链路
async function testCommunication() {
  logger.info('Testing communication...');

  const pingResult = await ping();
  logger.info('Ping test:', pingResult ? 'OK' : 'Failed');

  try {
    const echoResult = await messaging.sendToBackground('ECHO', { message: 'Hello from content' });
    logger.info('Echo test:', echoResult);
  } catch (error) {
    logger.error('Echo test failed:', error.message);
  }
}

// 延迟执行测试
setTimeout(testCommunication, 1000);

// 监听来自 Background 的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  logger.info('Content received message:', message);
  sendResponse({ received: true });
  return true;
});
