/**
 * Content Script - Entry Point
 * 
 * Runs in the context of Filevine pages to detect and extract auth tokens.
 * This is the "hybrid" approach where we piggyback on the active session.
 * 
 * Note: Uses dynamic imports because Chrome MV3 content scripts don't support static ES6 imports
 */

console.log('[Filevine Plugin] Content script loaded');

// Use dynamic imports (Chrome MV3 content scripts require this)
let MESSAGE_TYPES, TokenDetector, TokenExtractor, UIInjector, detectCurrentOrg, watchForOrgChanges;
let detector, extractor, uiInjector;

// Load modules dynamically
// Note: Chrome MV3 content scripts require dynamic imports and proper module paths
(async function loadModules() {
  try {
    // Use chrome.runtime.getURL() to get the correct extension-relative path
    const baseUrl = chrome.runtime.getURL('');
    const constantsModule = await import(`${baseUrl}src/lib/constants.js`);
    const detectorModule = await import(`${baseUrl}src/content/detector.js`);
    const extractorModule = await import(`${baseUrl}src/content/extractor.js`);
    const uiInjectorModule = await import(`${baseUrl}src/content/ui-injector.js`);
    const orgDetectorModule = await import(`${baseUrl}src/content/org-detector.js`);

    MESSAGE_TYPES = constantsModule.MESSAGE_TYPES;
    TokenDetector = detectorModule.TokenDetector;
    TokenExtractor = extractorModule.TokenExtractor;
    UIInjector = uiInjectorModule.UIInjector;
    detectCurrentOrg = orgDetectorModule.detectCurrentOrg;
    watchForOrgChanges = orgDetectorModule.watchForOrgChanges;

    // Initialize components
    detector = new TokenDetector();
    extractor = new TokenExtractor();
    uiInjector = new UIInjector();

    // Watch for org changes and notify background
    watchForOrgChanges((orgInfo) => {
      console.log('[Filevine Plugin] Org changed:', orgInfo);
      chrome.runtime.sendMessage({
        type: 'ORG_CHANGED',
        orgInfo: orgInfo
      }).catch(err => {
        console.log('[Filevine Plugin] Could not notify background of org change');
      });
    });

    // Now initialize the extension
    initialize();
  } catch (error) {
    console.error('[Filevine Plugin] Failed to load modules:', error);
    console.error('[Filevine Plugin] Error details:', error.message, error.stack);
  }
})();

/**
 * Main initialization
 */
async function initialize() {
  console.log('[Filevine Plugin] Initializing session detection...');

  // Check if we're on a Filevine page
  if (!isFilevineUrl(window.location.href)) {
    console.log('[Filevine Plugin] Not a Filevine page, skipping');
    return;
  }

  // Set up token interception
  extractor.setupInterception();

  // Try to extract existing tokens
  const tokens = await extractor.extractTokens();
  
  if (tokens?.accessToken) {
    console.log('[Filevine Plugin] Found existing auth tokens');
    await sendTokensToBackground(tokens);
  } else {
    console.log('[Filevine Plugin] No existing tokens, waiting for auth...');
  }

  // Listen for token events
  extractor.onTokenReceived((tokens) => {
    console.log('[Filevine Plugin] New tokens received');
    sendTokensToBackground(tokens);
  });

  // Watch for page changes (SPA navigation)
  detector.watchForChanges(() => {
    console.log('[Filevine Plugin] Page change detected, rechecking tokens');
    extractor.extractTokens().then(tokens => {
      if (tokens?.accessToken) {
        sendTokensToBackground(tokens);
      }
    });

    // Also send page context update to background/sidebar
    const pageContext = detector.getPageContext();
    chrome.runtime.sendMessage({
      type: 'PAGE_CONTEXT_UPDATE',
      context: pageContext
    }).catch(err => {
      console.log('[Filevine Plugin] Could not send page context update:', err);
    });
  });

  // Start UI injection (adds buttons to Filevine UI)
  uiInjector.start();
}

/**
 * Check if URL is a Filevine URL
 */
function isFilevineUrl(url) {
  try {
    const parsed = new URL(url);
    return parsed.hostname.includes('filevineapp.com');
  } catch {
    return false;
  }
}

/**
 * Send extracted tokens to background script
 */
async function sendTokensToBackground(tokens) {
  try {
    const response = await chrome.runtime.sendMessage({
      type: MESSAGE_TYPES.AUTH_DETECTED,
      ...tokens
    });
    
    if (response?.authenticated) {
      console.log('[Filevine Plugin] Background confirmed auth');
      showConnectionStatus('connected');
    } else if (response?.error) {
      console.error('[Filevine Plugin] Auth error:', response.error);
      showConnectionStatus('error', response.error);
    }
  } catch (error) {
    console.error('[Filevine Plugin] Failed to send tokens:', error);
  }
}

/**
 * Show visual indicator of connection status (optional)
 */
function showConnectionStatus(status, message = '') {
  // This could inject a small visual indicator on the page
  // For now, just log it
  console.log(`[Filevine Plugin] Connection status: ${status}`, message);
}

// Listen for messages from background
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === MESSAGE_TYPES.GET_AUTH_STATE) {
    extractor.extractTokens().then(tokens => {
      sendResponse({ hasTokens: !!tokens?.accessToken });
    });
    return true; // Async response
  }

  if (message.type === MESSAGE_TYPES.GET_CURRENT_PROJECT) {
    // Get current project ID from page URL
    const pageContext = detector.getPageContext();
    console.log('[Filevine Plugin] Current page context:', pageContext);
    sendResponse({
      projectId: pageContext.projectId,
      projectTypeId: pageContext.projectTypeId,
      orgId: pageContext.orgId,
      pageType: pageContext.pageType,
      url: pageContext.url
    });
    return true; // Async response
  }

  // New: Handle org detection request from background
  if (message.type === 'GET_CURRENT_ORG') {
    const orgInfo = detectCurrentOrg();
    console.log('[Filevine Plugin] Background requested org info:', orgInfo);
    sendResponse(orgInfo);
    return true; // Async response
  }
});

// Initialization is called after modules load (see loadModules above)
