let apiHost = "http://localhost:3000";

function $(id) { return document.getElementById(id); }

async function checkServer() {
  const host = $("api-host").value.trim() || apiHost;
  apiHost = host;
  try {
    const res = await fetch(`${host}/api/health`, { signal: AbortSignal.timeout(3000) });
    if (res.ok) {
      const data = await res.json();
      $("server-status").textContent = `✓ 已連線 (knowledge: ${data.knowledge ? "✓" : "✕"})`;
      $("server-badge").textContent = "OK";
      $("server-badge").className = "badge badge-ok";
    } else {
      $("server-status").textContent = `✕ 伺服器回應 ${res.status}`;
      $("server-badge").className = "badge badge-warn";
    }
  } catch (err) {
    $("server-status").textContent = `✕ 無法連線: ${err.message.slice(0, 30)}`;
    $("server-badge").className = "badge badge-warn";
  }
}

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

async function updatePageInfo() {
  const tab = await getCurrentTab();
  if (!tab) return;

  const url = tab.url || "";
  const title = tab.title || "";

  if (url.includes("youtube.com/watch") || url.includes("youtu.be")) {
    $("page-info").innerHTML = `🎬 YouTube 影片<br/><span class="text-dim">${title.slice(0, 60)}</span>`;
    $("btn-capture").style.display = "block";
    $("btn-capture").textContent = "📥 擷取此影片";
    $("btn-capture").onclick = async () => {
      try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        await chrome.tabs.sendMessage(tab.id, { action: "capture" });
        $("capture-result").textContent = "✓ 已觸發擷取，請查看頁面按鈕狀態";
      } catch (err) {
        $("capture-result").textContent = `✕ ${err.message}`;
      }
    };
  } else if (url.includes("hyread")) {
    $("page-info").innerHTML = `📖 HyRead 閱讀器<br/><span class="text-dim">${title.slice(0, 60)}</span>`;
    $("btn-capture").style.display = "block";
    $("btn-capture").textContent = "📖 擷取此書籍";
    $("btn-capture").onclick = async () => {
      try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        await chrome.tabs.sendMessage(tab.id, { action: "capture" });
        $("capture-result").textContent = "✓ 已觸發擷取，請查看頁面按鈕狀態";
      } catch (err) {
        $("capture-result").textContent = `✕ ${err.message}`;
      }
    };
  } else {
    $("page-info").textContent = `目前頁面: ${title.slice(0, 40)} (不支援此頁面)`;
    $("btn-capture").style.display = "none";
  }
}

$("api-host").addEventListener("change", checkServer);

document.addEventListener("DOMContentLoaded", async () => {
  const stored = await chrome.storage.local.get("apiHost");
  if (stored.apiHost) {
    $("api-host").value = stored.apiHost;
  }
  checkServer();
  updatePageInfo();
});
