const fields = {
  match: document.getElementById("match"),
  bridge: document.getElementById("bridge"),
  handoff: document.getElementById("handoff"),
  events: document.getElementById("events"),
  diagHook: document.getElementById("diagHook"),
  diagConstructor: document.getElementById("diagConstructor"),
  diagInstance: document.getElementById("diagInstance"),
  diagCaptured: document.getElementById("diagCaptured"),
  diagLive: document.getElementById("diagLive"),
  diagSent: document.getElementById("diagSent"),
  diagBridgeFetchStarted: document.getElementById("diagBridgeFetchStarted"),
  diagBridgeFetchSuccess: document.getElementById("diagBridgeFetchSuccess"),
  diagBridgeFetchFailed: document.getElementById("diagBridgeFetchFailed"),
  diagFetchStatus: document.getElementById("diagFetchStatus"),
  diagFetchException: document.getElementById("diagFetchException"),
  diagError: document.getElementById("diagError"),
  updated: document.getElementById("updated"),
  refresh: document.getElementById("refresh")
};

fields.refresh.addEventListener("click", refresh);
document.addEventListener("DOMContentLoaded", refresh);

async function refresh() {
  fields.bridge.textContent = "Checking...";
  const state = await chrome.runtime.sendMessage({ type: "GET_POPUP_STATE" }).catch((error) => ({
    bridgeOnline: false,
    lastHandoffStatus: error.message || "Helper unavailable",
    eventCount: 0
  }));

  fields.match.textContent = state.matchId || "Not detected";
  fields.bridge.textContent = state.bridgeOnline ? "Yes" : "No";
  fields.handoff.textContent = friendlyStatus(state);
  fields.events.textContent = String(state.eventCount || 0);
  const diagnostics = state.diagnostics || {};
  fields.diagHook.textContent = formatDiagnostic(diagnostics.pageHookInjectedAt);
  fields.diagConstructor.textContent = formatDiagnostic(diagnostics.constructorHookedAt);
  fields.diagInstance.textContent = formatDiagnostic(diagnostics.websocketInstanceDetectedAt);
  fields.diagCaptured.textContent = formatDiagnostic(diagnostics.websocketUrlCapturedAt);
  fields.diagLive.textContent = formatDiagnostic(diagnostics.liveConnectionDetectedAt);
  fields.diagSent.textContent = formatDiagnostic(diagnostics.websocketHandoffSentAt || diagnostics.sentLiveSessionAt);
  fields.diagBridgeFetchStarted.textContent = formatDiagnostic(diagnostics.bridgeFetchStartedAt);
  fields.diagBridgeFetchSuccess.textContent = formatDiagnostic(diagnostics.bridgeFetchSuccessAt);
  fields.diagBridgeFetchFailed.textContent = formatDiagnostic(diagnostics.bridgeFetchFailedAt);
  fields.diagFetchStatus.textContent = diagnostics.bridgeFetchStatusCode || "None";
  fields.diagFetchException.textContent = diagnostics.bridgeFetchExceptionText || "None";
  fields.diagError.textContent = diagnostics.lastError || "None";
  fields.updated.textContent = state.updatedAt ? `Updated ${new Date(state.updatedAt).toLocaleTimeString()}` : "";
}

function formatDiagnostic(value) {
  return value ? `Yes, ${new Date(value).toLocaleTimeString()}` : "Waiting";
}

function friendlyStatus(state) {
  if (state.bridgeConnected) return "Connected";
  const text = String(state.lastHandoffStatus || "").toLowerCase();
  if (text.includes("failed") || text.includes("error") || text.includes("offline")) return "Waiting for Companion";
  if (text.includes("sent live session") || text.includes("handoff")) return "Connecting";
  if (text.includes("detected") || text.includes("captured") || text.includes("socket")) return "Live connection detected";
  return state.bridgeOnline ? "Waiting for match" : "Waiting for Companion";
}
