let currentTab = null;
let isRecording = false;

async function getActiveTab() {
  const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
  return tabs[0] || null;
}

function isMeetTab(tab) {
  return tab && tab.url && tab.url.includes("meet.google.com");
}

async function loadSettings() {
  const stored = await chrome.storage.sync.get(["backendUrl", "ingestSecret", "groupId"]);
  document.getElementById("backend-url").value = stored.backendUrl || "http://localhost:8000";
  document.getElementById("ingest-secret").value = stored.ingestSecret || "";
  document.getElementById("group-id").value = stored.groupId || "meet_sessions";
}

async function saveSettings() {
  const backendUrl = document.getElementById("backend-url").value.trim();
  const ingestSecret = document.getElementById("ingest-secret").value.trim();
  const groupId = document.getElementById("group-id").value.trim();
  await chrome.storage.sync.set({ backendUrl, ingestSecret, groupId });
  const btn = document.getElementById("save-btn");
  btn.textContent = "✓ Saved";
  setTimeout(() => { btn.textContent = "Save Settings"; }, 1500);
}

function setRecordingUI(recording, meetingId, chunks) {
  isRecording = recording;
  const dot = document.getElementById("status-dot");
  const label = document.getElementById("status-label");
  const btn = document.getElementById("main-btn");
  const meetLabel = document.getElementById("meeting-id-label");
  const chunksLabel = document.getElementById("chunks-label");

  dot.className = "status-dot " + (recording ? "recording" : "idle");
  label.textContent = recording ? "Recording…" : "Idle";
  btn.className = "btn " + (recording ? "btn-stop" : "btn-start");
  btn.textContent = recording ? "■ Stop Recording" : "▶ Start Recording";
  meetLabel.textContent = meetingId ? `Meeting ID: ${meetingId}` : "Meeting ID: —";
  chunksLabel.textContent = `${chunks || 0} chunks sent`;
}

async function getTabStatus() {
  if (!currentTab) return;
  try {
    const status = await chrome.tabs.sendMessage(currentTab.id, { type: "GET_STATUS" });
    setRecordingUI(status.isRecording, status.meetingId, status.chunkCount);
  } catch {
    setRecordingUI(false, null, 0);
  }
}

async function handleMainBtn() {
  if (!currentTab) return;
  const stored = await chrome.storage.sync.get(["backendUrl", "ingestSecret", "groupId"]);

  if (!isRecording) {
    await chrome.tabs.sendMessage(currentTab.id, {
      type: "START_RECORDING",
      config: {
        backendUrl: stored.backendUrl || "http://localhost:8000",
        ingestSecret: stored.ingestSecret || "thirdeye_meet_secret_change_me",
        groupId: stored.groupId || "meet_sessions",
      },
    });
  } else {
    await chrome.tabs.sendMessage(currentTab.id, { type: "STOP_RECORDING" });
  }

  // Poll for updated status
  setTimeout(getTabStatus, 500);
}

// Listen for status updates from content script
chrome.runtime.onMessage.addListener((msg) => {
  if (msg.type === "STATUS") {
    setRecordingUI(msg.status === "recording", msg.meetingId, null);
  }
  if (msg.type === "CHUNK_SENT") {
    document.getElementById("chunks-label").textContent = `${msg.chunkIndex + 1} chunks sent`;
    document.getElementById("meeting-id-label").textContent = `Meeting ID: ${msg.meetingId}`;
  }
});

// Init
document.addEventListener("DOMContentLoaded", async () => {
  currentTab = await getActiveTab();

  if (!isMeetTab(currentTab)) {
    document.getElementById("not-meet").style.display = "block";
    document.getElementById("meet-ui").style.display = "none";
    return;
  }

  document.getElementById("meet-ui").style.display = "block";
  document.getElementById("not-meet").style.display = "none";

  await loadSettings();
  await getTabStatus();

  document.getElementById("main-btn").addEventListener("click", handleMainBtn);
  document.getElementById("save-btn").addEventListener("click", saveSettings);

  // Poll status every 5s while popup is open
  setInterval(getTabStatus, 5000);
});
