/**
 * Simplified Background Service Worker for Hero Vault Extension
 * 
 * This is a version that doesn't use WASM to avoid service worker limitations
 * with dynamic imports. It only handles basic messaging between components.
 */

console.log('Background script initialized');

// Store session state
let sessionActive = false;
let activeWebSocket: WebSocket | null = null;

// Listen for messages from popup or content scripts
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('Background received message:', message.type);
  
  if (message.type === 'SESSION_STATUS') {
    sendResponse({ active: sessionActive });
    return true;
  }
  
  if (message.type === 'SESSION_UNLOCK') {
    sessionActive = true;
    sendResponse({ success: true });
    return true;
  }
  
  if (message.type === 'SESSION_LOCK') {
    sessionActive = false;
    if (activeWebSocket) {
      activeWebSocket.close();
      activeWebSocket = null;
    }
    sendResponse({ success: true });
    return true;
  }
  
  if (message.type === 'CONNECT_WEBSOCKET' && message.serverUrl && message.publicKey) {
    // Simplified WebSocket handling
    try {
      if (activeWebSocket) {
        activeWebSocket.close();
      }
      
      activeWebSocket = new WebSocket(message.serverUrl);
      
      activeWebSocket.onopen = () => {
        console.log('WebSocket connection established');
        // Send public key to identify this client
        if (activeWebSocket) {
          activeWebSocket.send(JSON.stringify({
            type: 'IDENTIFY',
            publicKey: message.publicKey
          }));
        }
      };
      
      activeWebSocket.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          console.log('WebSocket message received:', data);
          
          // Forward message to popup
          chrome.runtime.sendMessage({
            type: 'WEBSOCKET_MESSAGE',
            data
          }).catch(error => {
            console.error('Failed to forward WebSocket message:', error);
          });
        } catch (error) {
          console.error('Failed to parse WebSocket message:', error);
        }
      };
      
      activeWebSocket.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
      
      activeWebSocket.onclose = () => {
        console.log('WebSocket connection closed');
        activeWebSocket = null;
      };
      
      sendResponse({ success: true });
    } catch (error) {
      console.error('Failed to connect to WebSocket:', error);
      sendResponse({ success: false, error: error.message });
    }
    
    return true;
  }
  
  if (message.type === 'DISCONNECT_WEBSOCKET') {
    if (activeWebSocket) {
      activeWebSocket.close();
      activeWebSocket = null;
      sendResponse({ success: true });
    } else {
      sendResponse({ success: false, error: 'No active WebSocket connection' });
    }
    return true;
  }
  
  // If we don't handle the message, return false
  return false;
});

// Handle notifications if available
if (chrome.notifications && chrome.notifications.onClicked) {
  chrome.notifications.onClicked.addListener((notificationId) => {
    // Open the extension popup when a notification is clicked
    chrome.action.openPopup();
  });
}
