// Background service worker for Directli extension
// Handles persistent operations and cross-context communication

// Initialize extension on install
chrome.runtime.onInstalled.addListener(async (details) => {
    console.log('Directli extension installed:', details.reason);
    
    // Set default settings
    try {
      const existingSettings = await chrome.storage.local.get(['theme', 'extensionEnabled', 'autoConvert', 'conversionType']);
      
      if (!existingSettings.theme) {
        await chrome.storage.local.set({
          theme: 'light',
          extensionEnabled: true,
          autoConvert: false,
          conversionType: 'image'
        });
      }
    } catch (error) {
      console.error('Error initializing settings:', error);
    }
    
    // Inject content script into all existing tabs
    if (details.reason === 'install' || details.reason === 'update') {
      const tabs = await chrome.tabs.query({});
      for (const tab of tabs) {
        if (tab.url && !tab.url.startsWith('chrome://')) {
          try {
            await chrome.scripting.executeScript({
              target: { tabId: tab.id },
              files: ['content.js']
            });
          } catch (error) {
            // Some tabs can't be injected (chrome:// pages, etc.)
          }
        }
      }
    }
  });
  
  // Listen for messages from popup or content scripts
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('Background received message:', request);
    
    if (request.type === 'SAVE_SETTINGS') {
      // Backup method to save settings
      saveSettingsBackup(request.data)
        .then(() => {
          // Notify all content scripts about settings change
          notifyContentScripts(request.data);
          sendResponse({ success: true });
        })
        .catch((error) => sendResponse({ success: false, error: error.message }));
      return true; // Will respond asynchronously
    }
    
    if (request.type === 'GET_SETTINGS') {
      // Backup method to get settings
      getSettingsBackup()
        .then((settings) => sendResponse({ success: true, settings }))
        .catch((error) => sendResponse({ success: false, error: error.message }));
      return true; // Will respond asynchronously
    }
    
    if (request.type === 'CONVERT_LINK') {
      // Convert link in background
      const converted = convertDriveLinkBackground(request.link, request.conversionType || 'image');
      sendResponse({ success: true, link: converted });
    }
    
    if (request.type === 'COPY_TO_CLIPBOARD') {
      // Copy to clipboard via offscreen document or active tab
      copyToClipboardBackground(request.text)
        .then(() => sendResponse({ success: true }))
        .catch((error) => sendResponse({ success: false, error: error.message }));
      return true;
    }
    
    if (request.type === 'SHOW_NOTIFICATION') {
      // Show notification
      showNotificationBackground(request.title, request.message);
      sendResponse({ success: true });
    }
  });
  
  // Backup storage methods
  async function saveSettingsBackup(settings) {
    try {
      await chrome.storage.local.set(settings);
      console.log('Settings saved via background:', settings);
    } catch (error) {
      console.error('Background save error:', error);
      throw error;
    }
  }
  
  async function getSettingsBackup() {
    try {
      const settings = await chrome.storage.local.get(['theme', 'extensionEnabled', 'autoConvert', 'conversionType']);
      return {
        theme: settings.theme || 'light',
        extensionEnabled: settings.extensionEnabled !== undefined ? settings.extensionEnabled : true,
        autoConvert: settings.autoConvert || false,
        conversionType: settings.conversionType || 'image'
      };
    } catch (error) {
      console.error('Background get error:', error);
      throw error;
    }
  }
  
  // Background conversion function (multiple extraction methods)
  function convertDriveLinkBackground(link, type) {
    const fileId = extractFileIdBackground(link);
    
    if (!fileId) {
      console.error('Could not extract file ID from:', link);
      return null;
    }
    
    if (type === 'image') {
      return `https://drive.google.com/uc?export=view&id=${fileId}`;
    } else {
      return `https://drive.google.com/uc?export=download&id=${fileId}`;
    }
  }
  
  // Background file ID extraction (multiple methods)
  function extractFileIdBackground(link) {
    // Method 1: Standard /d/ pattern
    let match = link.match(/\/d\/([a-zA-Z0-9_-]+)/);
    if (match) return match[1];
    
    // Method 2: id= parameter
    match = link.match(/[?&]id=([a-zA-Z0-9_-]+)/);
    if (match) return match[1];
    
    // Method 3: open?id= pattern
    match = link.match(/open\?id=([a-zA-Z0-9_-]+)/);
    if (match) return match[1];
    
    // Method 4: Direct ID validation
    if (/^[a-zA-Z0-9_-]{25,}$/.test(link)) {
      return link;
    }
    
    // Method 5: Extract from any position
    match = link.match(/\/([a-zA-Z0-9_-]{25,})[/?]/);
    if (match) return match[1];
    
    // Method 6: Last resort - find longest alphanumeric string
    const parts = link.split(/[/?&=]/);
    for (const part of parts) {
      if (/^[a-zA-Z0-9_-]{25,}$/.test(part)) {
        return part;
      }
    }
    
    return null;
  }
  
  // Context menu integration (optional enhancement)
  try {
    chrome.contextMenus.create({
      id: 'Directli-convert-view',
      title: 'Convert to Direct View Link',
      contexts: ['selection'],
      documentUrlPatterns: ['*://drive.google.com/*']
    });
    
    chrome.contextMenus.create({
      id: 'Directli-convert-download',
      title: 'Convert to Direct Download Link',
      contexts: ['selection'],
      documentUrlPatterns: ['*://drive.google.com/*']
    });
  } catch (error) {
    console.log('Context menu not available:', error);
  }
  
  chrome.contextMenus?.onClicked?.addListener(async (info, tab) => {
    const selectedText = info.selectionText;
    let convertedLink;
    
    if (info.menuItemId === 'Directli-convert-view') {
      convertedLink = convertDriveLinkBackground(selectedText, 'image');
    } else if (info.menuItemId === 'Directli-convert-download') {
      convertedLink = convertDriveLinkBackground(selectedText, 'file');
    }
    
    if (convertedLink) {
      // Copy to clipboard via content script injection
      try {
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          func: (text) => {
            navigator.clipboard.writeText(text);
          },
          args: [convertedLink]
        });
      } catch (error) {
        console.error('Could not copy to clipboard:', error);
      }
    }
  });
  
  // Keep service worker alive (Chrome extension best practice)
  chrome.runtime.onStartup.addListener(() => {
    console.log('Directli extension started');
  });
  
  // Handle extension updates
  chrome.runtime.onUpdateAvailable.addListener((details) => {
    console.log('Update available:', details);
  });
  
  // Notify all content scripts about settings changes
  async function notifyContentScripts(settings) {
    try {
      const tabs = await chrome.tabs.query({});
      for (const tab of tabs) {
        try {
          chrome.tabs.sendMessage(tab.id, {
            type: settings.autoConvert && settings.extensionEnabled ? 'START_MONITORING' : 'STOP_MONITORING'
          });
        } catch (error) {
          // Tab might not have content script
        }
      }
    } catch (error) {
      console.error('Error notifying content scripts:', error);
    }
  }
  
  // Copy to clipboard in background
  async function copyToClipboardBackground(text) {
    try {
      // Method 1: Use active tab to copy
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (tab) {
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          func: (textToCopy) => {
            navigator.clipboard.writeText(textToCopy);
          },
          args: [text]
        });
      }
    } catch (error) {
      console.error('Background copy error:', error);
      throw error;
    }
  }
  
  // Show notification
  function showNotificationBackground(title, message) {
    // Chrome notifications require 'notifications' permission
    // For now, we'll just log it
    console.log(`Notification: ${title} - ${message}`);
  }
  
  console.log('Directli background service worker loaded');