// background.js

// 마우스 이벤트를 모니터링하기 위한 content script 주입
chrome.runtime.onInstalled.addListener(() => {
  chrome.tabs.query({}, (tabs) => {
    tabs.forEach((tab) => {
      if (tab.url.startsWith('http')) {
        chrome.scripting.executeScript({
          target: { tabId: tab.id },
          function: injectMouseTracking,
        });
      }
    });
  });
});

// 새로운 탭이 로드될 때마다 content script 주입
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete' && tab.url.startsWith('http')) {
    chrome.scripting.executeScript({
      target: { tabId },
      function: injectMouseTracking,
    });
  }
});

// Content script에서 실행될 함수
function injectMouseTracking() {
  let isMouseDown = false;
  let startX = 0;
  let startY = 0;
  let hasGestured = false;
  let lastGestureTime = 0;
  let hasMoved = false; // 마우스가 움직였는지 추적하는 새로운 플래그

  document.addEventListener('mousedown', (e) => {
    if (e.button === 2) { // 오른쪽 마우스 버튼
      isMouseDown = true;
      hasGestured = false;
      hasMoved = false; // 마우스 다운시 초기화
      startX = e.clientX;
      startY = e.clientY;
    }
  });

  document.addEventListener('mousemove', (e) => {
    if (isMouseDown) {
      const currentX = e.clientX;
      const currentY = e.clientY;
      const deltaX = currentX - startX;
      const deltaY = currentY - startY;
      
      // 작은 움직임도 감지
      if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
        hasMoved = true;
      }

      const currentTime = Date.now();
      if (!hasGestured && currentTime - lastGestureTime > 500) {
        // 수평 이동이 수직 이동보다 크고, 일정 거리 이상 이동했을 때
        if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 100) {
          const gesture = deltaX < 0 ? 'left' : 'right';
          chrome.runtime.sendMessage({ type: 'GESTURE', gesture });
          hasGestured = true;
          lastGestureTime = currentTime;
        }
      }
    }
  });

  document.addEventListener('mouseup', (e) => {
    if (e.button === 2) {
      isMouseDown = false;
    }
  });

  // 컨텍스트 메뉴 방지 로직 개선
  document.addEventListener('contextmenu', (e) => {
    // 마우스가 조금이라도 움직였거나 제스처가 감지된 경우 컨텍스트 메뉴 방지
    if (hasMoved || hasGestured) {
      e.preventDefault();
      return false;
    }
  });

  // 페이지를 벗어날 때도 이벤트 처리
  document.addEventListener('mouseleave', () => {
    isMouseDown = false;
    hasGestured = false;
    hasMoved = false;
  });
}

// 제스처 메시지 수신 및 처리
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'GESTURE') {
    const tabId = sender.tab.id;
    
    if (message.gesture === 'left') {
      chrome.tabs.goBack(tabId);
    } else if (message.gesture === 'right') {
      chrome.tabs.goForward(tabId);
    }
  }
});