// Content Script for Multi App Dashboard

// Listen for messages from background script
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.action === 'checkForLoginForm') {
      const hasLoginForm = detectLoginForm();
      sendResponse({hasLoginForm: hasLoginForm});
    }
    
    if (message.action === 'fillCredentials') {
      fillCredentials(message.username, message.password);
      sendResponse({success: true});
    }
    
    return true; // Keep the message channel open for async response
  });
  
  // Function to detect login form
  function detectLoginForm() {
    // Check for common login form patterns
    const passwordFields = document.querySelectorAll('input[type="password"]');
    
    if (passwordFields.length > 0) {
      // Found at least one password field, likely a login form
      return true;
    }
    
    // Check for forms with common login-related words
    const forms = document.querySelectorAll('form');
    for (const form of forms) {
      const formHTML = form.innerHTML.toLowerCase();
      if (formHTML.includes('login') || formHTML.includes('sign in') || 
          formHTML.includes('username') || formHTML.includes('email')) {
        return true;
      }
    }
    
    return false;
  }
  
  // Function to fill login credentials
  function fillCredentials(username, password) {
    // Find all forms that might be login forms
    const forms = document.querySelectorAll('form');
    let loginForm = null;
    
    // First, look for forms with password fields
    for (const form of forms) {
      if (form.querySelector('input[type="password"]')) {
        loginForm = form;
        break;
      }
    }
    
    if (!loginForm) return false;
    
    // Find username/email field
    const usernameField = loginForm.querySelector('input[type="text"], input[type="email"], input[name="username"], input[name="email"], input[id="username"], input[id="email"]');
    
    // Find password field
    const passwordField = loginForm.querySelector('input[type="password"]');
    
    // Fill in the fields if found
    if (usernameField) {
      usernameField.value = username;
      // Trigger input events to simulate user typing
      usernameField.dispatchEvent(new Event('input', { bubbles: true }));
      usernameField.dispatchEvent(new Event('change', { bubbles: true }));
    }
    
    if (passwordField) {
      passwordField.value = password;
      // Trigger input events
      passwordField.dispatchEvent(new Event('input', { bubbles: true }));
      passwordField.dispatchEvent(new Event('change', { bubbles: true }));
    }
    
    // Look for login/submit button
    const submitButton = loginForm.querySelector('button[type="submit"], input[type="submit"]');
    if (submitButton) {
      // Option to auto-submit or leave it for the user to click
      // submitButton.click();
    }
    
    return true;
  }
  
  // Listen for form submissions to capture credentials if allowed
  document.addEventListener('submit', function(e) {
    // Check if this is likely a login form
    const form = e.target;
    const passwordField = form.querySelector('input[type="password"]');
    
    if (!passwordField) return; // Not a login form
    
    const usernameField = form.querySelector('input[type="text"], input[type="email"]');
    
    if (usernameField && passwordField) {
      // This appears to be a login form
      // Get the current URL's domain
      const domain = window.location.hostname;
      
      // Check if we should capture credentials for this domain
      chrome.storage.local.get(['multiAppDashboardApps'], function(result) {
        if (!result.multiAppDashboardApps) return;
        
        const apps = JSON.parse(result.multiAppDashboardApps);
        
        // Find app that matches this domain
        const matchingApp = apps.find(app => {
          try {
            const appUrl = new URL(app.url);
            return appUrl.hostname === domain;
          } catch (error) {
            return false;
          }
        });
        
        if (matchingApp && matchingApp.saveCredentials) {
          // This domain matches an app that should save credentials
          const username = usernameField.value;
          const password = passwordField.value;
          
          // Ask user for confirmation before saving
          if (confirm('Do you want to save your login credentials for this site in Multi App Dashboard?')) {
            // Send credentials to background to be saved
            chrome.runtime.sendMessage({
              action: 'saveCredentials',
              appId: matchingApp.id,
              credentials: {
                username: username,
                password: password
              }
            });
          }
        }
      });
    }
  });
  
  // Initialize domain monitoring
  function initDomainMonitoring() {
    // Get current hostname
    const currentDomain = window.location.hostname;
    
    // Check if this domain is in our apps list
    chrome.storage.local.get(['multiAppDashboardApps'], function(result) {
      if (!result.multiAppDashboardApps) return;
      
      const apps = JSON.parse(result.multiAppDashboardApps);
      
      // Find if current domain matches any app
      const matchingApp = apps.find(app => {
        try {
          const appUrl = new URL(app.url);
          return appUrl.hostname === currentDomain;
        } catch (error) {
          return false;
        }
      });
      
      if (matchingApp) {
        // This is a monitored app
        console.log(`Multi App Dashboard: Monitoring ${matchingApp.name}`);
        
        // Add app icon to the page for quick access back to dashboard
        addDashboardIcon(matchingApp.name);
        
        // Add listeners for session tracking
        trackUserSession();
      }
    });
  }
  
  // Add dashboard icon to the page
  function addDashboardIcon(appName) {
    // Create floating icon that shows on hover
    const iconContainer = document.createElement('div');
    iconContainer.style.cssText = `
      position: fixed;
      bottom: 20px;
      right: 20px;
      background-color: #4285f4;
      color: white;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
      z-index: 9999;
      opacity: 0.7;
      transition: opacity 0.3s, transform 0.3s;
    `;
    
    // Add dashboard icon
    iconContainer.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>';
    
    // Show tooltip on hover
    iconContainer.title = `Return to Multi App Dashboard`;
    
    // Make it more visible on hover
    iconContainer.onmouseover = function() {
      this.style.opacity = '1';
      this.style.transform = 'scale(1.1)';
    };
    
    iconContainer.onmouseout = function() {
      this.style.opacity = '0.7';
      this.style.transform = 'scale(1)';
    };
    
    // Open dashboard when clicked
    iconContainer.onclick = function() {
      chrome.runtime.sendMessage({ action: 'openDashboard' });
    };
    
    // Add to page
    document.body.appendChild(iconContainer);
  }
  
  // Track user session for this app
  function trackUserSession() {
    // Record activity periodically
    let lastActivity = Date.now();
    
    // Update last activity when user interacts
    ['click', 'keydown', 'mousemove', 'scroll'].forEach(eventType => {
      document.addEventListener(eventType, function() {
        lastActivity = Date.now();
        
        // Send activity ping to background script
        chrome.runtime.sendMessage({
          action: 'updateActivity',
          timestamp: lastActivity
        });
      }, { passive: true });
    });
    
    // Check if session is still valid periodically
    setInterval(function() {
      chrome.storage.local.get(['multiAppDashboardSettings'], function(result) {
        if (!result.multiAppDashboardSettings) return;
        
        const settings = JSON.parse(result.multiAppDashboardSettings);
        const sessionTimeout = settings.sessionTimeout || 60; // Default 60 minutes
        
        const now = Date.now();
        const inactiveTime = (now - lastActivity) / (1000 * 60); // Convert to minutes
        
        if (inactiveTime > sessionTimeout) {
          // Session timed out
          console.log('Session timed out. User inactive for:', inactiveTime.toFixed(2), 'minutes');
          
          // Notify background script of timeout
          chrome.runtime.sendMessage({
            action: 'sessionTimeout'
          });
        }
      });
    }, 60000); // Check every minute
  }
  
  // Start domain monitoring
  initDomainMonitoring();
  
  // Add listener for URL changes (for single-page applications)
  let lastUrl = location.href; 
  new MutationObserver(() => {
    const url = location.href;
    if (url !== lastUrl) {
      lastUrl = url;
      // URL changed, check if this is a monitored app again
      initDomainMonitoring();
    }
  }).observe(document, {subtree: true, childList: true});