I want this extension to be able to recognize automatically the active type on the web page and start typing what I said
 is there any mistake in the files of this extension fix it
// content.js


(function() {
  console.log('Speech to Text Converter: content.js loaded');


  // Create the floating microphone button if it doesn't already exist in this frame
  if (!document.getElementById('speech-to-text-button')) {
    const button = document.createElement('button');
    button.id = 'speech-to-text-button';
    button.innerHTML = '🎤'; // Microphone emoji
    document.body.appendChild(button);


    // Create the transcription display container if it doesn't already exist in this frame
    if (!document.getElementById('speech-to-text-display')) {
      const transcriptionDisplay = document.createElement('div');
      transcriptionDisplay.id = 'speech-to-text-display';
      transcriptionDisplay.innerText = ''; // Initially empty
      document.body.appendChild(transcriptionDisplay);
    }
  }


  const button = document.getElementById('speech-to-text-button');
  const transcriptionDisplay = document.getElementById('speech-to-text-display');
  let isRecording = false;
  let mediaRecorder;
  let audioChunks = [];
  let lastFocusedElement = null;


  // Track the last focused input field
  document.addEventListener('focusin', (event) => {
    const target = event.target;
    if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
      lastFocusedElement = target;
      console.log('Updated lastFocusedElement:', lastFocusedElement);
    }
  });


  // Toggle Recording Function
  function toggleRecording(state, language = 'en') {
    isRecording = state;
    if (isRecording) {
      button.classList.add('active');
      startRecording(language);
      console.log('Recording started');
      transcriptionDisplay.style.display = 'block';
      transcriptionDisplay.innerText = '🎤 Listening...';


      // Automatically focus the last focused element
      if (lastFocusedElement) {
        lastFocusedElement.focus();
        console.log('Focused on lastFocusedElement:', lastFocusedElement);
      } else {
        // Find and focus the first available input field
        const firstInput = document.querySelector('input, textarea, [contenteditable="true"]');
        if (firstInput) {
          firstInput.focus();
          lastFocusedElement = firstInput;
          console.log('Focused on first available input:', firstInput);
        } else {
          alert('No input field found to insert transcription.');
          console.warn('No input field found to insert transcription.');
          toggleRecording(false, language);
          return;
        }
      }
    } else {
      button.classList.remove('active');
      stopRecording();
      console.log('Recording stopped');
      transcriptionDisplay.innerText = '🕒 Processing...';
    }
  }


  // Handle Button Click
  button.addEventListener('click', () => {
    // Retrieve selected language from popup's storage if implemented
    // For now, default to 'en'
    const selectedLanguage = 'en'; // Modify if you implement language selection in content scripts
    toggleRecording(!isRecording, selectedLanguage);
  });


  // Listen for messages from the popup
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'toggleRecording') {
      const language = request.language || 'en';
      toggleRecording(request.state, language);
      sendResponse({ status: 'Recording state changed.' });
    }
  });


  // Start Recording
  async function startRecording(language = 'en') {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      alert('Your browser does not support audio recording.');
      console.error('getUserMedia not supported');
      toggleRecording(false, language);
      return;
    }


    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      mediaRecorder = new MediaRecorder(stream);


      mediaRecorder.start();
      console.log('MediaRecorder started');


      mediaRecorder.onstart = () => {
        audioChunks = [];
        console.log('MediaRecorder started capturing audio');
      };


      mediaRecorder.ondataavailable = (event) => {
        audioChunks.push(event.data);
        console.log('Audio data available:', event.data);
      };


      mediaRecorder.onstop = async () => {
        const audioBlob = new Blob(audioChunks, { type: 'audio/m4a' });
        console.log('MediaRecorder stopped, Blob created:', audioBlob);


        // Convert Blob to Base64
        const base64Audio = await blobToBase64(audioBlob);
        console.log('Audio converted to Base64:', base64Audio.substring(0, 30) + '...'); // Log first 30 chars


        // Send Base64 audio to background for transcription
        sendAudioForTranscription(base64Audio, language);


        // Stop all tracks
        stream.getTracks().forEach(track => track.stop());


        // Reset recording state
        isRecording = false;
        button.classList.remove('active');
      };


      mediaRecorder.onerror = (event) => {
        console.error('MediaRecorder Error:', event.error);
        toggleRecording(false);
        transcriptionDisplay.innerText = '❌ Recording error. Please try again.';
      };
    } catch (err) {
      console.error('Error accessing microphone:', err);
      alert('Error accessing microphone. Please check permissions.');
      toggleRecording(false);
      transcriptionDisplay.innerText = '❌ Microphone access denied.';
    }
  }


  // Stop Recording
  function stopRecording() {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
      mediaRecorder.stop();
      console.log('MediaRecorder stopping...');
    }
  }


  // Helper function to convert Blob to Base64
  function blobToBase64(blob) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = function() {
        const dataUrl = reader.result;
        const base64Data = dataUrl.split(',')[1]; // Remove data:audio/m4a;base64, part
        resolve(base64Data);
      };
      reader.onerror = function(error) {
        console.error('FileReader Error:', error);
        reject(error);
      };
      reader.readAsDataURL(blob);
    });
  }


  // Communication with background script
  function sendAudioForTranscription(base64Audio, language = 'en') {
    // Send the transcription request to background, with no expectation of response
    chrome.runtime.sendMessage({ type: 'transcribe', audio: { base64: base64Audio }, language }, () => {
      if (chrome.runtime.lastError) {
        console.error('Runtime error:', chrome.runtime.lastError.message);
        transcriptionDisplay.innerText = '❌ Transcription request failed.';
      } else {
        console.log('Transcription request acknowledged.');
      }
    });
  }


  // Listen for changes in chrome.storage.local to update transcription display and insert into page
  chrome.storage.onChanged.addListener((changes, area) => {
    if (area === 'local' && changes.latestTranscription && changes.latestTranscription.newValue) {
      const transcription = changes.latestTranscription.newValue;
      console.log('New transcription received via storage:', transcription);


      // Update the on-page display
      transcriptionDisplay.innerText = `📝 ${transcription}`;


      // Insert into active element
      insertTextIntoActiveElement(transcription);
    }
  });


  // Insert text into the active element on the webpage
  function insertTextIntoActiveElement(text) {
    const activeElement = document.activeElement;


    if (!activeElement) {
      console.warn('No active element to insert text into.');
      return;
    }


    // Handle <input> and <textarea> elements
    if (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') {
      const startPos = activeElement.selectionStart;
      const endPos = activeElement.selectionEnd;
      const beforeValue = activeElement.value.substring(0, startPos);
      const afterValue = activeElement.value.substring(endPos, activeElement.value.length);
      activeElement.value = beforeValue + text + afterValue;
      // Move the cursor
      activeElement.selectionStart = activeElement.selectionEnd = startPos + text.length;
      activeElement.focus();
    }
    // Handle contenteditable elements (e.g., Google Docs)
    else if (activeElement.isContentEditable) {
      const selection = window.getSelection();
      if (!selection.rangeCount) return;
      const range = selection.getRangeAt(0);
      range.deleteContents();
      const textNode = document.createTextNode(text);
      range.insertNode(textNode);
      // Move the cursor after the inserted text
      range.setStartAfter(textNode);
      range.setEndAfter(textNode);
      selection.removeAllRanges();
      selection.addRange(range);
    }
    else {
      console.warn('Active element is not an input, textarea, or contenteditable.');
      // Optionally, if no valid element is active, do not attempt insertion
    }
  }


})();
// background.js


// Listen for messages from content scripts
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  if (request.type === 'transcribe' && request.audio && request.audio.base64) {
    console.log('Audio data received in background script:', request.audio.base64.substring(0, 30) + '...');
    try {
      const transcription = await transcribeAudio(request.audio.base64, request.language);
      console.log('Transcription successful:', transcription);
      
      // Store transcription in chrome.storage.local
      await chrome.storage.local.set({ latestTranscription: transcription });
      console.log('Transcription saved to storage.');
      
      // Send a minimal response to prevent message port errors
      sendResponse({ status: 'Transcription processed and saved.' });
    } catch (error) {
      console.error('Transcription Error:', error);
      // Send a minimal response even in case of error
      sendResponse({ status: 'Transcription failed.' });
    }
    // Indicates that the response is sent asynchronously
    return true;
  }
});


// Function to transcribe audio using Groq API
async function transcribeAudio(base64Audio, language = 'en') {
  const apiKey = '<TRUFFLEHOG_REDACTED_GROQ>'; // **IMPORTANT:** Replace with your actual Groq API key.
  const url = 'https://api.groq.com/openai/v1/audio/transcriptions'; // Correct Groq API endpoint


  // Convert Base64 back to Blob
  const audioBlob = base64ToBlob(base64Audio, 'audio/m4a');


  const formData = new FormData();
  formData.append('file', audioBlob, 'audio.m4a');
  formData.append('model', 'whisper-large-v3'); // Correct model name as per documentation
  formData.append('response_format', 'json'); // You can set this to 'text' or 'verbose_json' if needed
  formData.append('language', language); // Add language parameter if supported


  console.log('Sending transcription request to:', url, 'Language:', language);


  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`
      },
      body: formData
    });


    console.log('Received response status:', response.status);


    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`Groq API Error: ${response.status} ${response.statusText} - ${errorText}`);
    }


    const data = await response.json();
    console.log('Transcription data received:', data);
    return data.text || 'No transcription available.';
  } catch (error) {
    console.error('Error in transcribeAudio:', error);
    throw error;
  }
}


// Helper function to convert Base64 to Blob
function base64ToBlob(base64, mime) {
  const byteCharacters = atob(base64);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type: mime });
}

/* styles.css */


/* Floating Microphone Button */
#speech-to-text-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 60px;
  height: 60px;
  border: none;
  border-radius: 50%;
  background-color: #0078D7;
  color: white;
  font-size: 30px; /* Larger font size for the emoji */
  cursor: pointer;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 10000; /* Ensure it stays on top */
  transition: background-color 0.3s, transform 0.3s;
}


#speech-to-text-button:hover {
  transform: scale(1.1);
}


#speech-to-text-button.active {
  background-color: #D70022; /* Red color when active */
}


/* Transcribed Text Display */
#speech-to-text-display {
  position: fixed;
  bottom: 90px; /* Positioned above the button */
  right: 20px;
  width: 300px;
  max-height: 200px;
  overflow-y: auto;
  background-color: rgba(0, 0, 0, 0.85);
  color: #ffffff;
  padding: 15px;
  border-radius: 8px;
  z-index: 9999; /* Below the button */
  font-size: 14px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  display: none; /* Hidden by default */
  white-space: pre-wrap; /* Preserve formatting */
  opacity: 0;
  transition: opacity 0.3s ease;
}


#speech-to-text-display.show {
  display: block;
  opacity: 1;
}


/* Scrollbar Styling for Transcription Display */
#speech-to-text-display::-webkit-scrollbar {
  width: 6px;
}


#speech-to-text-display::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}


#speech-to-text-display::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}


#speech-to-text-display::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

// popup.js


document.addEventListener('DOMContentLoaded', () => {
  const button = document.getElementById('toggle-recording');
  const statusDiv = document.getElementById('status');
  const transcriptionTextarea = document.getElementById('transcription');
  const copyButton = document.getElementById('copy-transcription');
  const downloadButton = document.getElementById('download-transcription');
  const languageSelect = document.getElementById('language-select');
  let isRecording = false;


  button.addEventListener('click', () => {
    isRecording = !isRecording;
    if (isRecording) {
      button.classList.add('active');
      button.textContent = '🎤 Stop Recording';
      statusDiv.textContent = 'Recording...';
      startRecording().catch(error => {
        console.error('Error starting recording:', error);
        statusDiv.textContent = '❌ Failed to start recording.';
        isRecording = false;
        button.classList.remove('active');
      });
    } else {
      button.classList.remove('active');
      button.textContent = '🎤 Start Recording';
      statusDiv.textContent = 'Stopped.';
      stopRecording().catch(error => {
        console.error('Error stopping recording:', error);
        statusDiv.textContent = '❌ Failed to stop recording.';
      });
    }
  });


  function startRecording() {
    const selectedLanguage = languageSelect.value || 'en';
    return new Promise((resolve, reject) => {
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0].id) {
          chrome.tabs.sendMessage(tabs[0].id, { type: 'toggleRecording', state: true, language: selectedLanguage }, response => {
            if (chrome.runtime.lastError) {
              console.error('Error sending message to content script:', chrome.runtime.lastError.message);
              statusDiv.textContent = '❌ Could not start recording. Ensure the extension is active on this page.';
              reject(chrome.runtime.lastError);
            } else {
              resolve(response);
            }
          });
        } else {
          statusDiv.textContent = '❌ No active tab found.';
          reject(new Error('No active tab found.'));
        }
      });
    });
  }


  function stopRecording() {
    return new Promise((resolve, reject) => {
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0].id) {
          chrome.tabs.sendMessage(tabs[0].id, { type: 'toggleRecording', state: false }, response => {
            if (chrome.runtime.lastError) {
              console.error('Error sending message to content script:', chrome.runtime.lastError.message);
              statusDiv.textContent = '❌ Could not stop recording. Ensure the extension is active on this page.';
              reject(chrome.runtime.lastError);
            } else {
              resolve(response);
            }
          });
        } else {
          statusDiv.textContent = '❌ No active tab found.';
          reject(new Error('No active tab found.'));
        }
      });
    });
  }


  // Retrieve the latest transcription from storage when the popup is opened
  chrome.storage.local.get('latestTranscription', (result) => {
    if (result.latestTranscription) {
      transcriptionTextarea.value = result.latestTranscription;
      statusDiv.textContent = 'Transcription loaded.';
    } else {
      transcriptionTextarea.value = '';
      statusDiv.textContent = 'No transcription available.';
    }
  });


  // Copy to Clipboard
  copyButton.addEventListener('click', () => {
    const transcription = transcriptionTextarea.value;
    if (transcription) {
      navigator.clipboard.writeText(transcription).then(() => {
        alert('Transcription copied to clipboard.');
      }).catch(err => {
        console.error('Failed to copy transcription:', err);
        alert('❌ Failed to copy transcription.');
      });
    }
  });


  // Download Transcription
  downloadButton.addEventListener('click', () => {
    const transcription = transcriptionTextarea.value;
    if (transcription) {
      const blob = new Blob([transcription], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'transcription.txt';
      a.click();
      URL.revokeObjectURL(url);
    }
  });
});

{
  "manifest_version": 3,
  "name": "Speech to Text Converter",
  "version": "1.0",
  "description": "Convert spoken words into text using the Groq API.",
  "permissions": [
    "activeTab",
    "scripting",
    "storage",
    "tabs"
  ],
  "host_permissions": [
    "<all_urls>"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "css": ["styles.css"],
      "run_at": "document_idle",
      "all_frames": true
    }
  ],
  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icons/icon16.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    }
  },
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'self'"
  }
}

<!DOCTYPE html>
<html>
<head>
  <title>Speech to Text Converter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      min-width: 220px;
      padding: 15px;
      background-color: #f5f5f5;
    }
    button {
      width: 100%;
      padding: 10px;
      font-size: 16px;
      background-color: #0078D7;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    button.active {
      background-color: #D70022;
    }
    #status {
      margin-top: 15px;
      font-size: 14px;
      color: #333333;
    }
    #transcription {
      margin-top: 15px;
      width: 100%;
      height: 120px;
      font-size: 14px;
      padding: 10px;
      box-sizing: border-box;
      border: 1px solid #cccccc;
      border-radius: 4px;
      resize: none;
      background-color: #ffffff;
    }
    /* Additional buttons for copy and download */
    .action-buttons {
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
    }
    .action-buttons button {
      width: 48%;
      padding: 8px;
      font-size: 14px;
      background-color: #555555;
      border: none;
      border-radius: 4px;
      color: white;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    .action-buttons button:hover {
      background-color: #333333;
    }
    /* Language Selection */
    #language-label {
      margin-top: 15px;
      display: block;
      font-size: 14px;
      color: #333333;
    }
    #language-select {
      width: 100%;
      padding: 8px;
      font-size: 14px;
      border: 1px solid #cccccc;
      border-radius: 4px;
      margin-top: 5px;
    }
  </style>
</head>
<body>
  <button id="toggle-recording">🎤 Start Recording</button>
  
  <!-- Language Selection -->
  <label for="language-select" id="language-label">Language:</label>
  <select id="language-select">
    <option value="en">English</option>
    <option value="es">Spanish</option>
    <option value="fr">French</option>
    <!-- Add more languages as supported by the Groq API -->
  </select>


  <div id="status">Click the button to start recording.</div>
  <textarea id="transcription" placeholder="Transcription will appear here..." readonly></textarea>
  
  <!-- Action Buttons -->
  <div class="action-buttons">
    <button id="copy-transcription">Copy</button>
    <button id="download-transcription">Download</button>
  </div>


  <script src="popup.js"></script>
</body>
</html>