// Popup script for the extension
document.addEventListener('DOMContentLoaded', function() {
  const fillCurrentBtn = document.getElementById('fill-current');
  // const fillAllBtn = document.getElementById('fill-all'); // Coming soon!
  const statusDiv = document.getElementById('status');
  const ratingPreference = document.getElementById('rating-preference');
  const autoSubmit = document.getElementById('auto-submit');
  const fillComments = document.getElementById('fill-comments');

  // Load saved settings
  chrome.storage.sync.get(['ratingPreference', 'autoSubmit', 'fillComments'], function(result) {
    if (result.ratingPreference) {
      ratingPreference.value = result.ratingPreference;
    }
    if (result.autoSubmit !== undefined) {
      autoSubmit.checked = result.autoSubmit;
    }
    if (result.fillComments !== undefined) {
      fillComments.checked = result.fillComments;
    }
  });

  // Save settings when changed
  ratingPreference.addEventListener('change', function() {
    chrome.storage.sync.set({ ratingPreference: this.value });
  });

  autoSubmit.addEventListener('change', function() {
    chrome.storage.sync.set({ autoSubmit: this.checked });
  });

  fillComments.addEventListener('change', function() {
    chrome.storage.sync.set({ fillComments: this.checked });
  });

  // Fill current form
  fillCurrentBtn.addEventListener('click', async function() {
    showStatus('Filling current form...', 'info');
    
    const settings = {
      ratingPreference: ratingPreference.value,
      autoSubmit: autoSubmit.checked,
      fillComments: fillComments.checked,
      fillAll: false
    };

    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: fillForm,
        args: [settings]
      });

      showStatus('✓ Form filled successfully!', 'success');
    } catch (error) {
      showStatus('✗ Error: ' + error.message, 'error');
    }
  });

  // Fill all lecturers - Coming soon!
  /*
  fillAllBtn.addEventListener('click', async function() {
    showStatus('Filling all forms...', 'info');
    
    const settings = {
      ratingPreference: ratingPreference.value,
      autoSubmit: autoSubmit.checked,
      fillComments: fillComments.checked,
      fillAll: true
    };

    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: fillAllForms,
        args: [settings]
      });

      showStatus('✓ Processing all forms...', 'success');
    } catch (error) {
      showStatus('✗ Error: ' + error.message, 'error');
    }
  });
  */

  function showStatus(message, type) {
    statusDiv.textContent = message;
    statusDiv.className = 'status ' + type;
    
    if (type === 'success' || type === 'error') {
      setTimeout(() => {
        statusDiv.className = 'status hidden';
      }, 3000);
    }
  }
});

// This function will be injected into the page
function fillForm(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',
    'Clear explanations',
    'Well organized course',
    'Helpful and approachable',
    'Engaging lectures',
    'Fair assessment',
    'Timely feedback',
    'Good use of examples',
    'Encourages participation',
    'Knowledgeable instructor'
  ];

  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
  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);
      
      // 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 }));
    }
  });

  // Fill select dropdowns
  document.querySelectorAll('select').forEach(select => {
    if (select.options.length > 1) {
      // Skip the first option (usually "Select..." or empty)
      const validOptions = Array.from(select.options).slice(1);
      if (validOptions.length > 0) {
        const rating = getRandomRating();
        // Try to select based on rating
        let selectedOption = validOptions.find(opt => opt.value == rating);
        
        if (!selectedOption) {
          selectedOption = validOptions[Math.floor(Math.random() * validOptions.length)];
        }
        
        select.value = selectedOption.value;
        select.dispatchEvent(new Event('change', { bubbles: true }));
      }
    }
  });

  // Fill checkboxes (randomly check/uncheck)
  document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
    checkbox.checked = Math.random() > 0.5;
    checkbox.dispatchEvent(new Event('change', { bubbles: true }));
  });

  // Fill text areas and text inputs (if fillComments is enabled)
  if (settings.fillComments) {
    document.querySelectorAll('textarea, input[type="text"]').forEach(field => {
      // Skip username/password fields
      if (!field.name.toLowerCase().includes('user') && 
          !field.name.toLowerCase().includes('pass') &&
          !field.id.toLowerCase().includes('user') &&
          !field.id.toLowerCase().includes('pass')) {
        field.value = getRandomComment();
        field.dispatchEvent(new Event('input', { bubbles: true }));
        field.dispatchEvent(new Event('change', { bubbles: true }));
      }
    });
  }

  // Auto-submit if enabled
  if (settings.autoSubmit) {
    setTimeout(() => {
      const submitButton = document.querySelector('input[type="submit"], button[type="submit"], button.submit, input.submit');
      if (submitButton) {
        submitButton.click();
      }
    }, 500);
  }

  return { success: true, message: 'Form filled successfully' };
}

// Function to fill all forms (navigate through all lecturers)
async function fillAllForms(settings) {
  console.log('Filling all forms...');
  
  // First, fill the current form
  fillForm(settings);
  
  // Wait a bit for the form to be filled
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  // Look for "Next" button or similar navigation
  const nextButton = document.querySelector(
    'button:contains("Next"), input[value*="Next"], a:contains("Next"), ' +
    'button:contains("Continue"), input[value*="Continue"], ' +
    'input[type="submit"], button[type="submit"]'
  );
  
  if (nextButton && settings.autoSubmit) {
    nextButton.click();
    
    // After navigation, the content script will run again and fill the next form
    setTimeout(() => {
      if (window.location.href.includes('course_evaluation')) {
        fillAllForms(settings);
      }
    }, 2000);
  }
  
  return { success: true, message: 'Processing all forms' };
}
