(() => {
  const params = new URLSearchParams(window.location.search);
  const token = params.get("token") || localStorage.getItem("iuve_ui_bridge_token") || "";
  if (token) localStorage.setItem("iuve_ui_bridge_token", token);

  const i18n = {
    en: {
      refresh: "Refresh",
      lede: "Describe an objective in plain language. Phase C.2 wires Avatar to the local agent / Orchestra.",
      placeholder: "Ask IuVe about objectives on this device…",
      working: "{n} in progress",
      footnote: "IuVeAI can make mistakes. Confirmations may need Connect until C.3.",
      ctx: "Device Context",
      fullHelp: "Full help",
      you: "You",
      avatar: "IuVe",
    },
    ro: {
      refresh: "Reîmprospătare",
      lede: "Descrie un obiectiv în cuvinte simple. C.2 leagă Avatar de agentul local / Orchestra.",
      placeholder: "Întreabă IuVe despre obiective pe acest dispozitiv...",
      working: "{n} în lucru",
      footnote: "IuVeAI poate greși. Confirmările pot necesita Connect până la C.3.",
      ctx: "Device Context",
      fullHelp: "Ajutor complet",
      you: "Tu",
      avatar: "IuVe",
    },
    ru: {
      refresh: "Обновить",
      lede: "Опишите цель простыми словами. C.2 связывает Avatar с локальным агентом / Orchestra.",
      placeholder: "Спросите IuVe о задачах на этом устройстве…",
      working: "{n} в работе",
      footnote: "IuVeAI может ошибаться. Подтверждения могут требовать Connect до C.3.",
      ctx: "Контекст устройства",
      fullHelp: "Полная помощь",
      you: "Вы",
      avatar: "IuVe",
    },
  };

  function t() {
    const lang = document.getElementById("lang").value;
    return i18n[lang] || i18n.en;
  }

  function authHeaders() {
    const tok = localStorage.getItem("iuve_ui_bridge_token") || "";
    return tok
      ? { Authorization: `Bearer ${tok}`, "Content-Type": "application/json" }
      : { "Content-Type": "application/json" };
  }

  async function api(path, options = {}) {
    const lang = document.getElementById("lang").value;
    const sep = path.includes("?") ? "&" : "?";
    const url = path.startsWith("/v1/") ? `${path}${sep}lang=${encodeURIComponent(lang)}` : path;
    const res = await fetch(url, {
      ...options,
      headers: { ...authHeaders(), ...(options.headers || {}) },
    });
    const data = await res.json().catch(() => ({ ok: false, error: "invalid_json" }));
    if (!res.ok) throw Object.assign(new Error(data.error || `http_${res.status}`), { data, status: res.status });
    return data;
  }

  function appendBubble(role, text) {
    const box = document.getElementById("transcript");
    const el = document.createElement("div");
    el.className = `bubble ${role}`;
    const who = role === "user" ? t().you : role === "assistant" ? t().avatar : "";
    el.textContent = who ? `${who}: ${text}` : text;
    box.appendChild(el);
    box.scrollTop = box.scrollHeight;
  }

  function showErr(e) {
    let banner = document.getElementById("error-banner");
    if (!banner) {
      banner = document.createElement("div");
      banner.id = "error-banner";
      document.querySelector(".chat-shell").appendChild(banner);
    }
    banner.textContent = String(e && e.message ? e.message : e);
    banner.classList.add("visible");
  }

  function clearErr() {
    const banner = document.getElementById("error-banner");
    if (banner) banner.classList.remove("visible");
  }

  function applyLang(lang) {
    const dict = i18n[lang] || i18n.en;
    document.getElementById("btn-refresh").textContent = dict.refresh;
    document.getElementById("avatar-lede").textContent = dict.lede;
    document.getElementById("prompt").placeholder = dict.placeholder;
    document.getElementById("footnote").textContent = dict.footnote;
    document.getElementById("ctx-title").textContent = dict.ctx;
    const chips = document.getElementById("chips");
    chips.innerHTML = "";
    const chip = document.createElement("span");
    chip.className = "chip";
    chip.innerHTML = `${dict.fullHelp} <button type="button" aria-label="Remove">×</button>`;
    chip.querySelector("button").addEventListener("click", () => chip.remove());
    chips.appendChild(chip);
    localStorage.setItem("iuve_ui_lang", lang);
  }

  function setText(sel, text) {
    const el = document.querySelector(sel);
    if (el) el.textContent = text;
  }

  async function refresh() {
    const status = await api("/v1/status");
    const ctx = await api("/v1/device_context");
    const session = await api("/v1/avatar/session");

    setText('[data-field="device_id"]', `Device: ${status.device_id || "—"}`);
    setText('[data-field="trust"]', `Trust: ${status.trust_state || "—"}`);
    setText('[data-field="avatar_mode"]', `Avatar: ${status.avatar_mode || "Inactive"}`);
    setText('[data-field="perms"]', `Permissions: ${status.active_permissions ?? 0}`);
    setText('[data-field="connectivity"]', `Connection: ${status.connectivity || "—"}`);
    setText('[data-field="account"]', `Account: ${status.account_email || "—"}`);
    document.getElementById("orchestra-pill").textContent = status.orchestra_label || "—";

    Object.entries(ctx.fields || {}).forEach(([k, v]) => {
      setText(`[data-ctx="${k}"]`, v == null ? "—" : String(v));
    });

    const badge = document.getElementById("working-badge");
    const n = session.working_count || 0;
    badge.textContent = t().working.replace("{n}", String(n));
    badge.classList.toggle("hidden", n <= 0);

    document.getElementById("statusbar").innerHTML = [
      `Connected: <strong>${status.connectivity || "—"}</strong>`,
      `Trusted: <strong>${status.trust_state || "—"}</strong>`,
      `Heartbeat: <strong>${status.heartbeat_age_sec ?? "—"}</strong>`,
      `Backend: <strong>${status.backend_base_url || "—"}</strong>`,
      `UI: <strong>${status.ui_surface || "native_console"}</strong>`,
      `Source: <strong>${status.source || "—"}</strong>`,
      `Phase: <strong>${status.phase || "C.2"}</strong>`,
    ].join(" · ");

    document.getElementById("diag-json").textContent = JSON.stringify({ status, ctx, session }, null, 2);
  }

  async function loadSecondary() {
    try {
      const presets = await api("/v1/permissions/presets");
      const ul = document.getElementById("preset-list");
      ul.innerHTML = (presets.presets || [])
        .map((p) => `<li><code>${p.id}</code> — ${p.label}</li>`)
        .join("");
      const link = document.getElementById("connect-link");
      if (presets.connect_url) link.href = presets.connect_url;
    } catch (e) {
      document.getElementById("preset-list").innerHTML = `<li>${e.message}</li>`;
    }
    try {
      const updates = await api("/v1/updates");
      document.getElementById("updates-json").textContent = JSON.stringify(updates, null, 2);
    } catch (e) {
      document.getElementById("updates-json").textContent = String(e.message);
    }
  }

  document.querySelectorAll(".nav-item").forEach((btn) => {
    btn.addEventListener("click", () => {
      document.querySelectorAll(".nav-item").forEach((b) => b.classList.remove("active"));
      document.querySelectorAll(".panel").forEach((p) => p.classList.remove("active"));
      btn.classList.add("active");
      document.getElementById(`panel-${btn.dataset.panel}`).classList.add("active");
    });
  });

  document.getElementById("lang").addEventListener("change", (e) => applyLang(e.target.value));
  document.getElementById("btn-refresh").addEventListener("click", () => refresh().catch(showErr));
  document.getElementById("btn-diagnostics").addEventListener("click", () => {
    document.querySelector('.nav-item[data-panel="diagnostics"]').click();
  });
  document.getElementById("btn-permissions").addEventListener("click", () => {
    document.querySelector('.nav-item[data-panel="security"]').click();
  });
  document.getElementById("btn-cancel").addEventListener("click", () => {
    document.getElementById("prompt").value = "";
  });

  document.getElementById("btn-send").addEventListener("click", async () => {
    const prompt = document.getElementById("prompt").value.trim();
    if (!prompt) return;
    clearErr();
    appendBubble("user", prompt);
    document.getElementById("prompt").value = "";
    try {
      const res = await api("/v1/avatar/prompt", {
        method: "POST",
        body: JSON.stringify({
          prompt,
          mode: document.getElementById("mode").value,
          tags: ["full_help"],
          language: document.getElementById("lang").value,
        }),
      });
      const msg = res.message || (res.ok ? "OK" : res.error || "error");
      appendBubble("assistant", msg);
      if (res.auto_started) {
        appendBubble("meta", `Auto-started session ${res.session_id || ""}`.trim());
      } else if (res.execution_deferred) {
        appendBubble("meta", "Plan ready — Trusted + grants required for auto-exec.");
      }
      await refresh();
    } catch (e) {
      showErr(e);
    }
  });

  const savedLang = localStorage.getItem("iuve_ui_lang") || "en";
  document.getElementById("lang").value = savedLang;
  applyLang(savedLang);

  if (!token) {
    showErr(new Error("Missing bridge token. Start: python -m iuve_connect_agents.desktop.ui_bridge --open"));
    return;
  }
  refresh().then(loadSecondary).catch(showErr);
  setInterval(() => refresh().catch(() => {}), 5000);
})();
