// Background service worker

// Keep track of the side panel state
let sidePanelOpen = false;

// Listen for extension icon click
chrome.action.onClicked.addListener(async (tab) => {
  // Toggle side panel
  try {
    await chrome.sidePanel.open({ windowId: tab.windowId });
    sidePanelOpen = true;
  } catch (error) {
    console.error('Failed to open side panel:', error);
  }
});

// Handle messages from content script or popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'CHECK_CONNECTION') {
    checkBackendConnection().then(sendResponse);
    return true; // Keep channel open for async
  }
  
  if (request.type === 'EXECUTE_COMMAND') {
    executeCommand(request.command).then(sendResponse);
    return true;
  }
  
  if (request.type === 'TAKE_SCREENSHOT') {
    takeScreenshot().then(sendResponse);
    return true;
  }
});

// Check if backend is running
async function checkBackendConnection() {
  try {
    const response = await fetch('http://localhost:8000/health', {
      method: 'GET',
      mode: 'cors',
    });
    
    if (response.ok) {
      const data = await response.json();
      return { connected: true, data };
    } else {
      return { connected: false, error: 'Backend returned error' };
    }
  } catch (error) {
    return { connected: false, error: error.message };
  }
}

// Execute command via backend
async function executeCommand(command) {
  try {
    const response = await fetch('http://localhost:8000/execute', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      mode: 'cors',
      body: JSON.stringify({ command }),
    });
    
    const data = await response.json();
    return { success: true, data };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

// Take screenshot via backend
async function takeScreenshot() {
  try {
    const response = await fetch('http://localhost:8000/screenshot', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      mode: 'cors',
      body: JSON.stringify({ full_page: true }),
    });
    
    const data = await response.json();
    return { success: true, data };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

// Handle installation
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === 'install') {
    console.log('SurfAI Extension installed');
    
    // Show welcome notification
    chrome.notifications.create({
      type: 'basic',
      iconUrl: 'icons/icon128.png',
      title: 'SurfAI 已安装',
      message: '点击扩展图标打开侧边栏，开始自动化操作！',
    });
  }
});
