// Content script that runs on the course evaluation pages
console.log('UNIMA Lecturer Feedback Auto-Fill extension loaded');

// Listen for messages from the popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'fillForm') {
    fillFormWithSettings(request.settings);
    sendResponse({ success: true });
  }
  return true;
});

// Auto-fill functionality when enabled
chrome.storage.sync.get(['autoFillOnLoad'], function(result) {
  if (result.autoFillOnLoad) {
    // Wait for page to fully load
    if (document.readyState === 'complete') {
      autoFillIfEnabled();
    } else {
      window.addEventListener('load', autoFillIfEnabled);
    }
  }
});

function autoFillIfEnabled() {
  chrome.storage.sync.get(['ratingPreference', 'autoSubmit', 'fillComments'], function(result) {
    const settings = {
      ratingPreference: result.ratingPreference || 'random',
      autoSubmit: result.autoSubmit || false,
      fillComments: result.fillComments !== false
    };
    
    // Only auto-fill if we're on an evaluation form page
    if (isEvaluationPage()) {
      console.log('Auto-filling evaluation form...');
      // Wait a bit for any dynamic content to load
      setTimeout(() => {
        fillFormWithSettings(settings);
      }, 1000);
    }
  });
}

function isEvaluationPage() {
  // Check if we're on an evaluation page
  return window.location.href.includes('course_evaluation') &&
         (document.querySelector('input[type="radio"]') || 
          document.querySelector('select') ||
          document.querySelector('textarea'));
}

function fillFormWithSettings(settings) {
  console.log('Filling form with settings:', settings);
  
  // Generate random rating based on preference
  function getRandomRating() {
    switch (settings.ratingPreference) {
      case 'high':
        return Math.random() < 0.5 ? 5 : 4;
      case 'medium':
        return Math.random() < 0.5 ? 4 : 3;
      case 'low':
        return Math.random() < 0.5 ? 2 : 1;
      case 'neutral':
        return 3;
      case 'random':
      default:
        return Math.floor(Math.random() * 5) + 1;
    }
  }

  // Random comments for text fields
  const comments = [
    'Good teaching methods and clear communication',
    'Clear explanations and well-structured content',
    'Well organized course with helpful materials',
    'Helpful and approachable instructor',
    'Engaging lectures with practical examples',
    'Fair assessment and timely feedback',
    'Knowledgeable and passionate about the subject',
    'Good use of examples and real-world applications',
    'Encourages student participation and questions',
    'Effective teaching style and good course management'
  ];

  function getRandomComment() {
    return comments[Math.floor(Math.random() * comments.length)];
  }

  // Fill radio buttons (common in evaluation forms)
  const radioGroups = {};
  document.querySelectorAll('input[type="radio"]').forEach(radio => {
    const name = radio.name;
    if (!radioGroups[name]) {
      radioGroups[name] = [];
    }
    radioGroups[name].push(radio);
  });

  // Select random radio button for each group
  let filledCount = 0;
  Object.keys(radioGroups).forEach(groupName => {
    const radios = radioGroups[groupName];
    if (radios.length > 0) {
      // Try to find radio with value matching our rating
      const rating = getRandomRating();
      let selectedRadio = radios.find(r => r.value == rating || r.value == String(rating));
      
      // If not found, select random
      if (!selectedRadio) {
        selectedRadio = radios[Math.floor(Math.random() * radios.length)];
      }
      
      selectedRadio.checked = true;
      selectedRadio.dispatchEvent(new Event('change', { bubbles: true }));
      selectedRadio.dispatchEvent(new Event('click', { bubbles: true }));
      filledCount++;
    }
  });

  // Fill select dropdowns
  document.querySelectorAll('select').forEach(select => {
    // Skip if it's a date/month/year selector
    if (select.name && (select.name.includes('date') || select.name.includes('month') || select.name.includes('year'))) {
      return;
    }
    
    if (select.options.length > 1) {
      // Skip the first option if it's empty or "Select..."
      const validOptions = Array.from(select.options).filter(opt => opt.value && opt.value !== '');
      if (validOptions.length > 0) {
        const rating = getRandomRating();
        // Try to select based on rating
        let selectedOption = validOptions.find(opt => opt.value == rating || opt.value == String(rating));
        
        if (!selectedOption) {
          selectedOption = validOptions[Math.floor(Math.random() * validOptions.length)];
        }
        
        select.value = selectedOption.value;
        select.dispatchEvent(new Event('change', { bubbles: true }));
        filledCount++;
      }
    }
  });

  // Fill text areas and text inputs (if fillComments is enabled)
  if (settings.fillComments) {
    document.querySelectorAll('textarea').forEach(field => {
      if (field.offsetParent !== null) { // Only visible fields
        field.value = getRandomComment();
        field.dispatchEvent(new Event('input', { bubbles: true }));
        field.dispatchEvent(new Event('change', { bubbles: true }));
        filledCount++;
      }
    });

    // Fill text inputs (but skip username, password, email, etc.)
    document.querySelectorAll('input[type="text"]').forEach(field => {
      const name = (field.name || '').toLowerCase();
      const id = (field.id || '').toLowerCase();
      const skipFields = ['user', 'pass', 'email', 'login', 'date', 'search'];
      
      if (!skipFields.some(skip => name.includes(skip) || id.includes(skip))) {
        if (field.offsetParent !== null) { // Only visible fields
          field.value = getRandomComment();
          field.dispatchEvent(new Event('input', { bubbles: true }));
          field.dispatchEvent(new Event('change', { bubbles: true }));
          filledCount++;
        }
      }
    });
  }

  console.log(`Filled ${filledCount} form fields`);

  // Show notification
  showNotification(`✓ Filled ${filledCount} fields`, 'success');

  // Auto-submit if enabled
  if (settings.autoSubmit) {
    setTimeout(() => {
      const submitButton = document.querySelector(
        'input[type="submit"], button[type="submit"], ' +
        'button.submit, input.submit, ' +
        'button[name="submit"], input[name="submit"]'
      );
      if (submitButton) {
        showNotification('Submitting form...', 'info');
        submitButton.click();
      }
    }, 1000);
  }
}

// Show notification on the page
function showNotification(message, type) {
  // Remove existing notification if any
  const existing = document.getElementById('unima-autofill-notification');
  if (existing) {
    existing.remove();
  }

  const notification = document.createElement('div');
  notification.id = 'unima-autofill-notification';
  notification.textContent = message;
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 15px 20px;
    background: ${type === 'success' ? '#4CAF50' : type === 'error' ? '#f44336' : '#2196F3'};
    color: white;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    z-index: 10000;
    font-family: Arial, sans-serif;
    font-size: 14px;
    font-weight: 500;
    animation: slideIn 0.3s ease-out;
  `;

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

  document.body.appendChild(notification);

  // Remove after 3 seconds
  setTimeout(() => {
    notification.style.animation = 'slideIn 0.3s ease-out reverse';
    setTimeout(() => notification.remove(), 300);
  }, 3000);
}
