// Library detection patterns
const libraryPatterns = {
  // JavaScript Libraries
  jquery: {
    patterns: [
      /jquery[.-](\d+\.?\d+\.?\d*)/i,
      /\$\.fn\.jquery/i,
      /jQuery\.fn\.jquery/i
    ],
    version: (match) => match[1]
  },
  react: {
    patterns: [
      /react[.-](\d+\.?\d+\.?\d*)/i,
      /React\.version/i
    ],
    version: (match) => match[1]
  },
  angular: {
    patterns: [
      /angular[.-](\d+\.?\d+\.?\d*)/i,
      /angular\.version/i
    ],
    version: (match) => match[1]
  },
  vue: {
    patterns: [
      /vue[.-](\d+\.?\d+\.?\d*)/i,
      /Vue\.version/i
    ],
    version: (match) => match[1]
  },
  bootstrap: {
    patterns: [
      /bootstrap[.-](\d+\.?\d+\.?\d*)/i,
      /Bootstrap\.VERSION/i
    ],
    version: (match) => match[1]
  },
  lodash: {
    patterns: [
      /lodash[.-](\d+\.?\d+\.?\d*)/i,
      /_\.VERSION/i
    ],
    version: (match) => match[1]
  },
  moment: {
    patterns: [
      /moment[.-](\d+\.?\d+\.?\d*)/i,
      /moment\.version/i
    ],
    version: (match) => match[1]
  }
};

// Suspicious content patterns
const suspiciousPatterns = {
  // Form patterns
  forms: {
    patterns: [
      /<form[^>]*>/gi,
      /<input[^>]*type=["'](password|text|email|tel)["'][^>]*>/gi,
      /<input[^>]*name=["'](password|username|email|phone|credit|card|ssn)["'][^>]*>/gi
    ]
  },
  // Script patterns
  scripts: {
    patterns: [
      /<script[^>]*src=["'](?!https?:\/\/[^\/]+\.(googleapis\.com|microsoft\.com|jquery\.com|bootstrapcdn\.com|unpkg\.com|jsdelivr\.net))[^"']*["'][^>]*>/gi,
      /eval\s*\(/gi,
      /Function\s*\(/gi,
      /setTimeout\s*\([^,]*function/gi,
      /setInterval\s*\([^,]*function/gi
    ]
  },
  // Iframe patterns
  iframes: {
    patterns: [
      /<iframe[^>]*>/gi,
      /<frame[^>]*>/gi
    ]
  },
  // Suspicious attributes
  attributes: {
    patterns: [
      /on\w+\s*=/gi,
      /javascript:/gi,
      /data:/gi,
      /vbscript:/gi
    ]
  }
};

// Detect libraries in the page
export async function detectLibraries(document) {
  const libraries = new Set();
  
  // Check script tags
  const scripts = document.getElementsByTagName('script');
  for (const script of scripts) {
    const src = script.src;
    const content = script.textContent;
    
    // Check each library pattern
    for (const [name, { patterns, version }] of Object.entries(libraryPatterns)) {
      for (const pattern of patterns) {
        const match = (src || content).match(pattern);
        if (match) {
          libraries.add({
            name,
            version: version ? version(match) : 'unknown',
            source: src || 'inline'
          });
        }
      }
    }
  }

  // Check global objects
  for (const [name, { patterns, version }] of Object.entries(libraryPatterns)) {
    if (window[name] || window[name.charAt(0).toUpperCase() + name.slice(1)]) {
      libraries.add({
        name,
        version: 'detected',
        source: 'global'
      });
    }
  }

  return libraries;
}

// Analyze page content for suspicious elements
export async function analyzePageContent(document) {
  const suspiciousElements = new Set();
  
  // Check forms
  for (const pattern of suspiciousPatterns.forms.patterns) {
    const matches = document.documentElement.innerHTML.match(pattern);
    if (matches) {
      suspiciousElements.add({
        type: 'form',
        pattern: pattern.toString(),
        matches: matches
      });
    }
  }

  // Check scripts
  for (const pattern of suspiciousPatterns.scripts.patterns) {
    const matches = document.documentElement.innerHTML.match(pattern);
    if (matches) {
      suspiciousElements.add({
        type: 'script',
        pattern: pattern.toString(),
        matches: matches
      });
    }
  }

  // Check iframes
  for (const pattern of suspiciousPatterns.iframes.patterns) {
    const matches = document.documentElement.innerHTML.match(pattern);
    if (matches) {
      suspiciousElements.add({
        type: 'iframe',
        pattern: pattern.toString(),
        matches: matches
      });
    }
  }

  // Check attributes
  for (const pattern of suspiciousPatterns.attributes.patterns) {
    const matches = document.documentElement.innerHTML.match(pattern);
    if (matches) {
      suspiciousElements.add({
        type: 'attribute',
        pattern: pattern.toString(),
        matches: matches
      });
    }
  }

  // Check for password fields
  const passwordFields = document.querySelectorAll('input[type="password"]');
  if (passwordFields.length > 0) {
    suspiciousElements.add({
      type: 'passwordField',
      count: passwordFields.length,
      elements: Array.from(passwordFields).map(el => ({
        id: el.id,
        name: el.name,
        form: el.form ? el.form.id : null
      }))
    });
  }

  // Check for suspicious event listeners
  const elementsWithEvents = document.querySelectorAll('[onclick], [onload], [onerror], [onsubmit]');
  if (elementsWithEvents.length > 0) {
    suspiciousElements.add({
      type: 'inlineEvent',
      count: elementsWithEvents.length,
      elements: Array.from(elementsWithEvents).map(el => ({
        tag: el.tagName,
        id: el.id,
        events: Object.keys(el).filter(key => key.startsWith('on'))
      }))
    });
  }

  return {
    suspiciousElements,
    riskLevel: suspiciousElements.size > 0 ? 'high' : 'low'
  };
} 