// Content script that monitors clipboard operations
// This runs on all web pages to detect Google Drive link copies

let lastCheckedClipboard = '';
let clipboardCheckInterval = null;
let isMonitoring = false;
let isOnGoogleDrive = false;

// Check if on Google Drive
function checkIfOnGoogleDrive() {
  const hostname = window.location.hostname.toLowerCase();
  const drivePatterns = [
    'drive.google.com',
    'docs.google.com',
    'sheets.google.com',
    'slides.google.com',
    'forms.google.com'
  ];
  
  isOnGoogleDrive = drivePatterns.some(pattern => hostname.includes(pattern));
  return isOnGoogleDrive;
}

// Initialize
checkIfOnGoogleDrive();

// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'CHECK_DOMAIN') {
    sendResponse({ isGoogleDrive: isOnGoogleDrive });
    return true;
  }
  
  if (request.type === 'START_MONITORING') {
    // Only start monitoring if on Google Drive
    if (isOnGoogleDrive) {
      startMonitoring();
      sendResponse({ success: true });
    } else {
      sendResponse({ success: false, reason: 'Not on Google Drive' });
    }
    return true;
  } else if (request.type === 'STOP_MONITORING') {
    stopMonitoring();
    sendResponse({ success: true });
    return true;
  }
});

// Initialize monitoring based on settings (only if on Google Drive)
if (isOnGoogleDrive) {
  chrome.storage.local.get(['autoConvert', 'extensionEnabled'], (data) => {
    if (data.autoConvert && data.extensionEnabled) {
      startMonitoring();
    }
  });
}

// Listen for settings changes
chrome.storage.onChanged.addListener((changes, namespace) => {
  if (namespace === 'local' && isOnGoogleDrive) {
    chrome.storage.local.get(['autoConvert', 'extensionEnabled'], (data) => {
      if (data.autoConvert && data.extensionEnabled) {
        startMonitoring();
      } else {
        stopMonitoring();
      }
    });
  }
});

// Start monitoring clipboard
function startMonitoring() {
  // Only monitor if on Google Drive
  if (!isOnGoogleDrive) {
    console.log('Directli: Not on Google Drive, monitoring disabled');
    return;
  }
  
  if (isMonitoring) return;
  
  isMonitoring = true;
  console.log('Directli: Clipboard monitoring started on Google Drive');
  
  // Method 1: Listen for copy events
  document.addEventListener('copy', handleCopyEvent);
  
  // Method 2: Listen for cut events
  document.addEventListener('cut', handleCopyEvent);
  
  // Method 3: Periodic clipboard check (every 500ms)
  clipboardCheckInterval = setInterval(checkClipboard, 500);
  
  // Method 4: Listen for focus events (check when user returns to tab)
  window.addEventListener('focus', checkClipboard);
}

// Stop monitoring clipboard
function stopMonitoring() {
  if (!isMonitoring) return;
  
  isMonitoring = false;
  console.log('Directli: Clipboard monitoring stopped');
  
  document.removeEventListener('copy', handleCopyEvent);
  document.removeEventListener('cut', handleCopyEvent);
  window.removeEventListener('focus', checkClipboard);
  
  if (clipboardCheckInterval) {
    clearInterval(clipboardCheckInterval);
    clipboardCheckInterval = null;
  }
}

// Handle copy/cut events
async function handleCopyEvent(e) {
  // Small delay to ensure clipboard is updated
  setTimeout(async () => {
    await checkClipboard();
  }, 100);
}

// Check clipboard content
async function checkClipboard() {
  try {
    // Method 1: Navigator Clipboard API
    const clipboardText = await navigator.clipboard.readText();
    
    if (clipboardText && clipboardText !== lastCheckedClipboard) {
      lastCheckedClipboard = clipboardText;
      
      if (isGoogleDriveLink(clipboardText)) {
        console.log('Directli: Google Drive link detected in clipboard');
        await processGoogleDriveLink(clipboardText);
      }
    }
  } catch (error) {
    // Clipboard API might fail due to permissions
    // This is expected when page is not in focus
    if (error.name !== 'NotAllowedError') {
      console.log('Directli clipboard check:', error.message);
    }
  }
}

// Process detected Google Drive link
async function processGoogleDriveLink(link) {
  try {
    // Get current settings
    const settings = await chrome.storage.local.get(['conversionType', 'autoConvert', 'extensionEnabled']);
    
    if (!settings.autoConvert || !settings.extensionEnabled) {
      return;
    }
    
    const conversionType = settings.conversionType || 'image';
    
    // Convert the link
    const convertedLink = convertDriveLink(link, conversionType);
    
    if (convertedLink) {
      // Method 1: Write to clipboard using navigator API
      try {
        await navigator.clipboard.writeText(convertedLink);
        console.log('Directli: Link converted and copied!');
        showNotification('Directli: Link Auto-Converted!', `Converted to ${conversionType === 'image' ? 'Direct View' : 'Direct Download'} link`);
      } catch (clipError) {
        // Method 2: Send to background script to copy
        chrome.runtime.sendMessage({
          type: 'COPY_TO_CLIPBOARD',
          text: convertedLink
        });
      }
      
      // Update last checked to prevent re-processing
      lastCheckedClipboard = convertedLink;
    }
  } catch (error) {
    console.error('Directli: Error processing link:', error);
  }
}

// Check if link is a Google Drive link
function isGoogleDriveLink(link) {
  if (!link || typeof link !== 'string') return false;
  
  const patterns = [
    /drive\.google\.com\/file\/d\//,
    /drive\.google\.com\/open\?id=/,
    /docs\.google\.com\/.*\/d\//,
    /drive\.google\.com\/.*id=/,
    /drive\.google\.com\/uc\?/
  ];
  
  return patterns.some(pattern => pattern.test(link));
}

// Extract file ID from Drive link
function extractFileId(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: /file/d/ pattern
  match = link.match(/\/file\/d\/([a-zA-Z0-9_-]+)/);
  if (match) return match[1];
  
  // Method 5: Extract from any position
  match = link.match(/\/([a-zA-Z0-9_-]{25,})(?:[/?]|$)/);
  if (match) return match[1];
  
  // Method 6: Split and find
  const parts = link.split(/[/?&=#]/);
  for (const part of parts) {
    if (/^[a-zA-Z0-9_-]{25,}$/.test(part)) {
      return part;
    }
  }
  
  return null;
}

// Convert Drive link
function convertDriveLink(link, type) {
  const fileId = extractFileId(link);
  
  if (!fileId) {
    console.error('Directli: Could not extract file ID');
    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}`;
  }
}

// Show notification to user
function showNotification(title, message) {
  // Method 1: Create visual notification on page
  const notification = document.createElement('div');
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: #4285f4;
    color: white;
    padding: 12px 16px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15), 0 1px 3px rgba(0,0,0,0.3);
    z-index: 999999;
    font-family: 'Google Sans', 'Product Sans', 'Roboto', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    font-size: 14px;
    max-width: 320px;
    animation: slideIn 0.3s cubic-bezier(0.4, 0.0, 0.2, 1);
    display: flex;
    align-items: flex-start;
    gap: 12px;
  `;
  
  notification.innerHTML = `
    <svg style="width: 20px; height: 20px; flex-shrink: 0; margin-top: 1px;" fill="white" viewBox="0 0 24 24">
      <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
    </svg>
    <div style="flex: 1;">
      <div style="font-weight: 500; margin-bottom: 2px; font-size: 14px; letter-spacing: 0.2px;">${title}</div>
      <div style="font-size: 13px; opacity: 0.95; font-weight: 400; letter-spacing: 0.2px;">${message}</div>
    </div>
  `;
  
  document.body.appendChild(notification);
  
  // Auto-remove after 3 seconds
  setTimeout(() => {
    notification.style.animation = 'slideOut 0.3s cubic-bezier(0.4, 0.0, 0.2, 1)';
    setTimeout(() => {
      if (notification.parentNode) {
        notification.parentNode.removeChild(notification);
      }
    }, 300);
  }, 3000);
  
  // Method 2: Try Chrome notifications API (requires permission)
  try {
    chrome.runtime.sendMessage({
      type: 'SHOW_NOTIFICATION',
      title: title,
      message: message
    });
  } catch (error) {
    // Notification API not available
  }
}

// Add CSS animation
const style = document.createElement('style');
style.textContent = `
  @keyframes slideIn {
    from {
      transform: translateX(400px);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }
  
  @keyframes slideOut {
    from {
      transform: translateX(0);
      opacity: 1;
    }
    to {
      transform: translateX(400px);
      opacity: 0;
    }
  }
`;
document.head.appendChild(style);

console.log('Directli content script loaded');