(() => {
  const root = document.getElementById("lumi-chat-dock-root");
  const initial = document.getElementById("lumi-chat-dock-state");
  const config = document.getElementById("lumi-chat-dock-config");
  const renderer = window.LumiOverlayRenderer;
  if (!root || !initial || !config || !renderer?.renderChatDock) return;

  let state = null;
  let refreshPromise = null;

  function nearBottom() {
    return window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 48;
  }

  function render(nextState) {
    const shouldFollow = !state || nearBottom();
    state = nextState;
    renderer.renderChatDock(root, nextState?.enabled ? nextState.module : null);
    if (shouldFollow && nextState?.module?.config?.newestAt !== "top") requestAnimationFrame(() => window.scrollTo(0, document.documentElement.scrollHeight));
  }

  function refresh() {
    if (refreshPromise) return refreshPromise;
    refreshPromise = fetch(config.dataset.stateUrl, { cache: "no-store", credentials: "omit" })
      .then((response) => response.ok ? response.json() : { enabled: false, module: null })
      .then(render)
      .catch(() => {})
      .finally(() => { refreshPromise = null; });
    return refreshPromise;
  }

  try { render(JSON.parse(initial.textContent || "{}")); }
  catch { render({ enabled: false, module: null }); }

  const events = new EventSource(config.dataset.eventsUrl, { withCredentials: false });
  events.addEventListener("overlay:changed", refresh);
  events.addEventListener("overlay:chat-message", (event) => {
    try {
      const shouldFollow = nearBottom();
      renderer.handleChatMessage(root, JSON.parse(event.data || "{}"));
      if (shouldFollow && state?.module?.config?.newestAt !== "top") {
        requestAnimationFrame(() => window.scrollTo(0, document.documentElement.scrollHeight));
      }
    } catch {}
  });
  events.addEventListener("server:status", (event) => {
    try {
      if (JSON.parse(event.data || "{}").status === "connected") refresh();
    } catch {}
  });
})();
