// Background Script for Multi App Dashboard

// Listen for installation
chrome.runtime.onInstalled.addListener(function(details) {
    if (details.reason === 'install') {
      // First time installation
      console.log('Extension installed');
      
      // Open onboarding page
      chrome.tabs.create({
        url: 'onboarding.html'
      });
    }
  });
  
  // Listen for messages from popup or content scripts
  chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.action === 'openApp') {
      openApplication(message.appId, message.url, message.inNewTab);
      sendResponse({success: true});
      return true;
    }
    
    if (message.action === 'injectCredentials') {
      injectCredentials(message.tabId, message.credentials);
      sendResponse({success: true});
      return true;
    }
  });
  
  // Function to open an application
  function openApplication(appId, url, inNewTab) {
    // Check if we need to handle auto-login
    chrome.storage.session.get(['currentAppOpening'], function(result) {
      if (result.currentAppOpening === appId) {
        // App needs auto-login
        
        // First open the URL
        if (inNewTab) {
          chrome.tabs.create({url: url}, function(tab) {
            handleAutoLogin(tab.id, appId);
          });
        } else {
          chrome.tabs.update({url: url}, function(tab) {
            handleAutoLogin(tab.id, appId);
          });
        }
        
        // Clear the session variable
        chrome.storage.session.remove(['currentAppOpening']);
      } else {
        // Just open the URL without auto-login
        if (inNewTab) {
          chrome.tabs.create({url: url});
        } else {
          chrome.tabs.update({url: url});
        }
      }
    });
  }
  
  // Function to handle auto-login
  function handleAutoLogin(tabId, appId) {
    // Wait for page to load
    chrome.tabs.onUpdated.addListener(function listener(updatedTabId, changeInfo) {
      if (updatedTabId === tabId && changeInfo.status === 'complete') {
        // Remove the listener
        chrome.tabs.onUpdated.removeListener(listener);
        
        // Execute a content script to check if this page has a login form
        chrome.scripting.executeScript({
          target: {tabId: tabId},
          function: detectLoginForm,
          args: [appId]
        });
      }
    });
  }
  
  // Function to detect login form and inject credentials
  function detectLoginForm(appId) {
    // Check if page has a login form
    const forms = document.querySelectorAll('form');
    let loginForm = null;
    
    for (const form of forms) {
      const hasPasswordField = form.querySelector('input[type="password"]') !== null;
      const hasTextField = form.querySelector('input[type="text"], input[type="email"]') !== null;
      
      if (hasPasswordField && hasTextField) {
        loginForm = form;
        break;
      }
    }
    
    if (loginForm) {
      // Notify background script to inject credentials
      chrome.runtime.sendMessage({
        action: 'injectCredentials',
        tabId: tabId,
        appId: appId
      });
    }
  }
  
  // Function to inject credentials
  function injectCredentials(tabId, credentials) {
    // Execute script to fill in credentials
    chrome.scripting.executeScript({
      target: {tabId: tabId},
      function: fillCredentials,
      args: [credentials.username, credentials.password]
    });
  }
  
  // Function to fill in credentials
  function fillCredentials(username, password) {
    // Find login form
    const forms = document.querySelectorAll('form');
    let loginForm = null;
    
    for (const form of forms) {
      const hasPasswordField = form.querySelector('input[type="password"]') !== null;
      const hasTextField = form.querySelector('input[type="text"], input[type="email"]') !== null;
      
      if (hasPasswordField && hasTextField) {
        loginForm = form;
        break;
      }
    }
    
    if (loginForm) {
      // Fill in username
      const usernameField = loginForm.querySelector('input[type="text"], input[type="email"]');
      if (usernameField) {
        usernameField.value = username;
        // Trigger input event to notify the form that the value has changed
        usernameField.dispatchEvent(new Event('input', { bubbles: true }));
      }
      
      // Fill in password
      const passwordField = loginForm.querySelector('input[type="password"]');
      if (passwordField) {
        passwordField.value = password;
        // Trigger input event
        passwordField.dispatchEvent(new Event('input', { bubbles: true }));
      }
      
      // Optionally submit the form automatically
      // loginForm.submit();
    }
  }
  
  // Handle session management and storage sync
  chrome.storage.onChanged.addListener(function(changes, namespace) {
    if (namespace === 'local' && changes.multiAppDashboardUser) {
      // User data changed, update session status
      const userData = changes.multiAppDashboardUser.newValue;
      
      if (userData) {
        // User logged in or updated profile
        console.log('User session updated');
        
        // Update session storage for quick access
        chrome.storage.session.set({ userLoggedIn: true });
      } else {
        // User logged out
        console.log('User logged out');
        
        // Update session storage
        chrome.storage.session.set({ userLoggedIn: false });
      }
    }
  });