// Offscreen page UI logic with Quill.js
const recordBtn = document.getElementById('recordBtn');
const timer = document.getElementById('timer');
const statusText = document.getElementById('statusText');
const recordingCount = document.getElementById('recordingCount');
const copyBtn = document.getElementById('copyBtn');
const newBtn = document.getElementById('newBtn');
const syncBtn = document.getElementById('syncBtn');

let isRecording = false;
let timerInterval = null;
let seconds = 0;
let quill = null;
let recordingsCount = 0;

// Initialize Quill editor
function initQuill() {
  quill = new Quill('#editor', {
    theme: 'snow',
    placeholder: 'Your transcriptions will appear here...',
    modules: {
      toolbar: [
        [{ 'header': [1, 2, 3, false] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        ['blockquote', 'code-block'],
        ['link'],
        ['clean']
      ]
    }
  });
}

// Initialize on load
document.addEventListener('DOMContentLoaded', function() {
  initQuill();
});

function formatTime(s) {
  const mins = Math.floor(s / 60);
  const secs = s % 60;
  return mins + ':' + secs.toString().padStart(2, '0');
}

function setStatus(text, type) {
  statusText.textContent = text;
  statusText.className = 'status-text' + (type ? ' ' + type : '');
}

function updateRecordingCount() {
  recordingCount.textContent = recordingsCount + ' recording' + (recordingsCount !== 1 ? 's' : '');
}

function appendTranscript(text) {
  if (!quill) return;

  const currentLength = quill.getLength();
  const now = new Date();
  const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });

  // If there's existing content, add a separator
  if (currentLength > 1) {
    quill.insertText(currentLength - 1, '\n\n');
    const separatorPos = quill.getLength() - 1;
    quill.insertText(separatorPos, '─────── Recording ' + (recordingsCount + 1) + ' • ' + timeStr + ' ───────\n\n', {
      'color': '#64748b',
      'italic': true
    });
  }

  // Add the new transcript text
  const insertPos = quill.getLength() - 1;
  quill.insertText(insertPos, text);

  recordingsCount++;
  updateRecordingCount();

  // Sync to storage
  syncToStorage();
}

function syncToStorage() {
  if (!quill) return;
  const text = quill.getText();
  chrome.storage.local.set({ dictaphoneTranscript: text });
}

recordBtn.addEventListener('click', async function() {
  if (!isRecording) {
    // Start recording
    recordBtn.disabled = true;
    setStatus('Requesting mic...', 'processing');

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

      isRecording = true;
      seconds = 0;
      timer.classList.add('active');
      setStatus('Recording', 'recording');

      recordBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 24 24"><rect x="6" y="6" width="12" height="12" rx="2" /></svg>';
      recordBtn.classList.add('recording');
      recordBtn.disabled = false;

      timerInterval = setInterval(function() {
        seconds++;
        timer.textContent = formatTime(seconds);
      }, 1000);

      // Setup MediaRecorder
      const mimeTypes = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];
      let mimeType = '';
      for (let i = 0; i < mimeTypes.length; i++) {
        if (MediaRecorder.isTypeSupported(mimeTypes[i])) {
          mimeType = mimeTypes[i];
          break;
        }
      }

      window.audioChunks = [];
      window.mediaRecorder = new MediaRecorder(stream, mimeType ? { mimeType: mimeType } : {});

      window.mediaRecorder.ondataavailable = function(event) {
        if (event.data.size > 0) {
          window.audioChunks.push(event.data);
        }
      };

      window.mediaRecorder.start(1000);

    } catch (err) {
      console.error('Error:', err);
      setStatus('Mic access denied', '');
      recordBtn.disabled = false;
    }
  } else {
    // Stop recording
    clearInterval(timerInterval);
    isRecording = false;
    timer.classList.remove('active');
    recordBtn.disabled = true;
    setStatus('Transcribing...', 'processing');

    window.mediaRecorder.onstop = async function() {
      window.mediaRecorder.stream.getTracks().forEach(function(track) { track.stop(); });

      const audioBlob = new Blob(window.audioChunks, { type: window.mediaRecorder.mimeType || 'audio/webm' });

      // Get API key from storage
      const data = await chrome.storage.local.get(['groqApiKey']);
      const groqApiKey = data.groqApiKey;

      if (!groqApiKey) {
        // Try to send to background for transcription
        try {
          const reader = new FileReader();
          reader.onloadend = async function() {
            const result = await chrome.runtime.sendMessage({
              type: 'groqWhisperTranscribe',
              audioData: reader.result,
              fromOffscreen: true
            });

            if (result && result.success) {
              setStatus('', '');
              appendTranscript(result.text);
            } else {
              setStatus(result?.error || 'Failed', '');
            }

            resetRecordButton();
          };
          reader.readAsDataURL(audioBlob);
        } catch (e) {
          setStatus('API key not found', '');
          resetRecordButton();
        }
        return;
      }

      // Transcribe with Groq
      const formData = new FormData();
      formData.append('file', audioBlob, 'audio.webm');
      formData.append('model', 'whisper-large-v3-turbo');

      try {
        const response = await fetch('https://api.groq.com/openai/v1/audio/transcriptions', {
          method: 'POST',
          headers: { 'Authorization': 'Bearer ' + groqApiKey },
          body: formData
        });

        if (!response.ok) throw new Error('Transcription failed');

        const responseData = await response.json();
        setStatus('', '');
        appendTranscript(responseData.text);

      } catch (err) {
        setStatus('Failed: ' + err.message, '');
      }

      resetRecordButton();
    };

    window.mediaRecorder.stop();
  }
});

function resetRecordButton() {
  recordBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="6" /></svg>';
  recordBtn.classList.remove('recording');
  recordBtn.disabled = false;
}

copyBtn.addEventListener('click', async function() {
  if (!quill) return;
  const text = quill.getText();
  await navigator.clipboard.writeText(text);
  copyBtn.classList.add('success');
  syncToStorage();
  setTimeout(function() {
    copyBtn.classList.remove('success');
  }, 2000);
});

newBtn.addEventListener('click', function() {
  if (!quill) return;
  quill.setText('');
  timer.textContent = '0:00';
  setStatus('', '');
  recordingsCount = 0;
  updateRecordingCount();
  chrome.storage.local.remove('dictaphoneTranscript');
});

syncBtn.addEventListener('click', function() {
  syncToStorage();
  syncBtn.classList.add('success');
  setTimeout(function() {
    syncBtn.classList.remove('success');
  }, 2000);
});
