'use strict';
// popup.js - 扩展弹窗逻辑 (v0.3)
let state = { discovered: {}, wsReady: false };
let captureStatus = {};  // tabId -> status text

function render() {
  // 服务连接状态
  const dot = document.getElementById('svcDot');
  const txt = document.getElementById('svcText');
  dot.className = 'svc-dot ' + (state.wsReady ? 'on' : 'off');
  txt.textContent = state.wsReady ? '已连接 (localhost:8091)' : '未连接（请先启动本地服务）';

  const list = document.getElementById('list');
  const tabs = Object.keys(state.discovered);
  if (!tabs.length) {
    list.innerHTML = '<div class="empty">未发现媒体流。请先打开正在播放的直播页面。</div>';
    return;
  }
  list.innerHTML = '';

  for (const tabId of tabs) {
    const d = state.discovered[tabId];
    if (!d || !d.url) continue;
    const el = document.createElement('div');
    el.className = 'item';

    const status = captureStatus[tabId] || '';
    const statusHtml = status
      ? '<div class="status ' + (status.includes('❌') || status.includes('⚠️') ? 'err' : '') + '">' + escapeHtml(status) + '</div>'
      : '';
    const isCapturing = status && (status.includes('正在') || status.includes('已推送'));

    el.innerHTML =
      '<div class="t">' + escapeHtml(d.title || '(无标题)') +
        ' <span class="badge">' + (d.format || '?') + '</span>' +
      '</div>' +
      '<div class="u" title="' + escapeHtml(d.url) + '">' + escapeHtml(d.url.slice(0, 90)) + (d.url.length > 90 ? '…' : '') + '</div>' +
      statusHtml +
      '<div class="btns">' +
        '<button class="b-go ' + (isCapturing ? 'running' : '') + '" data-tab="' + tabId + '">' +
          (isCapturing ? '● 捕获中…' : '开始捕获') +
        '</button> ' +
        '<button class="b-stop" data-tab="' + tabId + '">停止</button>' +
      '</div>';
    list.appendChild(el);
  }

  list.querySelectorAll('.b-go').forEach(b => {
    b.onclick = () => {
      const tabId = +b.dataset.tab;
      captureStatus[tabId] = '⏳ 正在连接…';
      const quality = document.getElementById('qualitySel').value || 'orig';
      chrome.runtime.sendMessage({ type: 'enable', tabId, url: state.discovered[tabId].url, quality });
      render();
    };
  });

  list.querySelectorAll('.b-stop').forEach(b => {
    b.onclick = () => {
      const tabId = +b.dataset.tab;
      chrome.runtime.sendMessage({ type: 'disable', tabId });
      delete captureStatus[tabId];
      render();
    };
  });
}

function escapeHtml(s) {
  return String(s).replace(/[&<>"']/g, c =>
    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])
  );
}

document.getElementById('openBtn').onclick = () => {
  chrome.runtime.sendMessage({ type: 'openPlayer' });
};

// 周期性拉取
function refresh() {
  chrome.runtime.sendMessage({ type: 'getDiscovered' }, (r) => {
    if (r) { state = r; render(); }
  });
}

chrome.runtime.onMessage.addListener((msg) => {
  if (msg.type === 'discovered') { state = msg.payload; render(); }

  // 来自 background 的实时捕获状态
  if (msg.type === 'capture_status' || (msg.type === 'svc' && msg.payload)) {
    let payload;
    if (msg.type === 'capture_status') {
      payload = { tabId: msg.tabId, status: msg.status };
    } else {
      payload = msg.payload;
    }

    if (payload.type === 'error' && payload.message) {
      // 错误消息：尝试关联到最近的 tab
      const tabs = Object.keys(state.discovered);
      for (const t of tabs) {
        captureStatus[t] = payload.message;
      }
      render();
      return;
    }

    if (payload.tabId) {
      captureStatus[payload.tabId] = payload.status || (payload.message || '');
      render();
    }
  }
});

refresh();
setInterval(refresh, 2500);
