// Popup: connection status + the friendly "Record this tab" button (no share-picker).
async function renderStatus() {
  const { connected, since } = await chrome.storage.session.get(['connected', 'since']);
  const dot = document.getElementById('dot');
  const status = document.getElementById('status');
  const detail = document.getElementById('detail');
  if (connected) {
    dot.classList.add('on');
    status.textContent = 'Connected to Bridge';
    detail.textContent = since ? `since ${new Date(since).toLocaleTimeString()}` : '';
  } else {
    dot.classList.remove('on');
    status.textContent = 'Not connected';
    detail.textContent = 'Is Bridge running with the native-browser bridge installed?';
  }
}
renderStatus();
chrome.storage.session.onChanged.addListener(renderStatus);

const recBtn = document.getElementById('rec');
const recMsg = document.getElementById('recmsg');

async function refreshRec() {
  const st = await chrome.runtime.sendMessage({ type: 'popup-record-state' }).catch(() => null);
  const recording = st && st.state === 'recording';
  recBtn.dataset.recording = recording ? '1' : '';
  recBtn.textContent = recording ? '⏹ Stop & save' : '⏺ Record this tab';
  recBtn.classList.toggle('rec', recording);
  if (recording && st.elapsedMs) recMsg.textContent = `recording… ${Math.round(st.elapsedMs / 1000)}s`;
}

recBtn.onclick = async () => {
  recBtn.disabled = true;
  try {
    if (recBtn.dataset.recording) {
      recMsg.textContent = 'saving…';
      const r = await chrome.runtime.sendMessage({ type: 'popup-record-stop' });
      recMsg.textContent = r && r.ok ? (r.downloaded ? `saved (${r.sizeKB} KB) to Downloads` : 'stopped') : `stop failed: ${(r && r.error) || ''}`;
    } else {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      recMsg.textContent = 'starting…';
      const r = await chrome.runtime.sendMessage({ type: 'popup-record-start', tabId: tab.id });
      recMsg.textContent = r && r.ok ? 'recording this tab — no picker!' : `failed: ${(r && r.error) || ''} ${(r && r._hint) || ''}`;
    }
  } catch (e) { recMsg.textContent = String((e && e.message) || e); }
  recBtn.disabled = false;
  refreshRec();
};

refreshRec();
setInterval(refreshRec, 1000);
