// Create and manage overlay elements for loading and completion states
let overlay = null;
let messageElement = null;

// Flag to indicate content script is ready
let isInitialized = false;

// Initialize the content script
function initialize() {
  if (isInitialized) return;
  isInitialized = true;
  
  // Let the background script know we're ready
  chrome.runtime.sendMessage({ action: 'contentScriptReady' });
  console.log('Real ChatGPT Extension: Content script initialized');
}

// Initialize immediately
initialize();

// Create the overlay element with loading spinner
function createOverlay() {
  // Remove any existing overlay
  removeOverlay();
  
  // Create main overlay container
  overlay = document.createElement('div');
  overlay.id = 'real-chatgpt-overlay';
  
  // Create message container
  messageElement = document.createElement('div');
  messageElement.id = 'real-chatgpt-message';
  
  // Create loading spinner
  const spinner = document.createElement('div');
  spinner.id = 'real-chatgpt-spinner';
  
  // Add loading message
  messageElement.textContent = 'Processing with ChatGPT...';
  
  // Assemble the overlay
  overlay.appendChild(spinner);
  overlay.appendChild(messageElement);
  document.body.appendChild(overlay);
}

// Remove the overlay from the DOM
function removeOverlay() {
  const existingOverlay = document.getElementById('real-chatgpt-overlay');
  if (existingOverlay) {
    existingOverlay.remove();
  }
}

// Show completion message and remove after delay
function showCompletionMessage() {
  if (!overlay) {
    createOverlay();
  }
  
  // Update the overlay to show completion message
  const spinner = document.getElementById('real-chatgpt-spinner');
  if (spinner) {
    spinner.style.display = 'none';
  }
  
  // Update message
  if (messageElement) {
    messageElement.textContent = 'Finished, please paste from clipboard';
    messageElement.classList.add('completion');
  }
  
  // Remove after 1 second
  setTimeout(removeOverlay, 1000);
}

// Listen for messages from the background script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // Make sure we're initialized
  initialize();
  if (message.action === 'showLoading') {
    createOverlay();
    sendResponse({ status: 'overlay_created' });
    return true;
  } else if (message.action === 'showCompletion') {
    showCompletionMessage();
    sendResponse({ status: 'completion_shown' });
    return true;
  } else if (message.action === 'removeOverlay') {
    removeOverlay();
    sendResponse({ status: 'overlay_removed' });
    return true;
  }
});
