const $ = (id) => document.getElementById(id);
const show = (id) => { for (const name of ["loading", "signedOut", "signedIn", "deleted"]) $(name).hidden = name !== id; };
const send = (message) => chrome.runtime.sendMessage(message).catch(() => null);
let pollTimer = 0;
function renderAccount(state) {
  if (state?.deleted || state?.notice === "USER_DELETED") return show("deleted");
  if (!state?.authenticated) return show("signedOut");
  show("signedIn");
  const user = state.user || {};
  $("accountName").textContent = user.name || "Usuario HIRO PLAY";
  $("accountUser").textContent = user.username ? `@${user.username}` : "";
  $("avatar").textContent = String(user.name || user.username || "H").trim().charAt(0).toUpperCase();
}
async function loadAd() {
  const response = await send({ type: "GET_HIRO_AD", placement: "extension_popup" }), ad = response?.ad;
  if (!ad?.image_url) return;
  $("adImage").src = ad.image_url; $("adLink").href = ad.target_url || "https://hiroplay.lat"; $("adSlot").hidden = false;
}
async function loadUpdate() {
  const response = await send({ type: "CHECK_REMOTE_VERSION" });
  if (!response?.available) return;
  $("updateNotice").hidden = false; $("updateMessage").textContent = response.message || `Versión ${response.latest} disponible.`;
  $("updateNow").onclick = () => response.downloadUrl && chrome.tabs.create({ url: response.downloadUrl });
  $("installHelp").onclick = () => chrome.tabs.create({ url: response.helpUrl || "https://hiroplay.lat/instalar" });
}
async function startPairing() {
  clearInterval(pollTimer); $("connectAccount").disabled = true; $("pairingStatus").textContent = "Preparando conexión segura…";
  const response = await send({ type: "START_HIRO_PAIRING" });
  if (!response?.ok) { $("connectAccount").disabled = false; $("pairingStatus").textContent = response?.error || "No pudimos conectar con hiroplay.lat."; return; }
  chrome.tabs.create({ url: response.connectUrl }); $("pairingStatus").textContent = "Completa el acceso en la pestaña que acabamos de abrir.";
  pollTimer = setInterval(async () => { const state = await send({ type: "POLL_HIRO_PAIRING" }); if (!state?.authenticated) return; clearInterval(pollTimer); renderAccount(state); }, 2500);
}
$("connectAccount").onclick = startPairing;
$("registerAgain").onclick = () => chrome.tabs.create({ url: "https://hiroplay.lat/registro" });
$("logout").onclick = async () => { await send({ type: "LOGOUT_HIRO" }); show("signedOut"); };
$("openExplore").onclick = () => { send({ type: "OPEN_SITE_EXPLORER" }); window.close(); };
$("openCatalog").onclick = () => { send({ type: "OPEN_USER_CATALOG" }); window.close(); };
$("openDownloads").onclick = () => { send({ type: "OPEN_DOWNLOADS" }); window.close(); };
$("refreshCatalog").onclick = async () => { const button = $("refreshCatalog"); button.disabled = true; $("refreshStatus").textContent = "Actualizando desde HIRO PLAY…"; const response = await send({ type: "REFRESH_EXPLORE_CATALOG" }); button.disabled = false; $("refreshStatus").textContent = response?.ok ? `${response.count || 0} contenidos disponibles.` : response?.error || "Conservamos la última copia disponible."; };
$("version").textContent = `v${chrome.runtime.getManifest().version}`;
Promise.all([send({ type: "GET_HIRO_AUTH_STATE", verify: true }), loadAd(), loadUpdate()]).then(([state]) => renderAccount(state)).catch(() => show("signedOut"));
