/*
  Pointing the terminal and the canvas at a chat that does not exist yet.

  Both panels take their identity from the server: the terminal from
  `data-url`, the canvas from URLs rendered inside the fragments it swaps in.
  Neither builds a URL from parts. So all this has to do is get a *draft id* for
  whatever the composer currently has selected, put it where the panels look,
  and ask them to reload.

  Only ever on the new-chat screen -- a chat that exists already has an id and
  nothing here runs. See services/agent/draft.py for what a draft is and how it
  is adopted when the first prompt turns it into a real chat.
*/
(function () {
  "use strict";

  var composer = document.querySelector(".composer");
  if (!composer || composer.dataset.chatId) return;

  var current = "";

  /* The id travels with the first message so the server knows which draft to
     adopt. A hidden field rather than a header, because it has to arrive as
     part of the form that creates the chat. */
  function field() {
    var form = document.querySelector(".composer__form");
    if (!form) return null;
    var found = form.querySelector('input[name="draft_id"]');
    if (!found) {
      found = document.createElement("input");
      found.type = "hidden";
      found.name = "draft_id";
      form.appendChild(found);
    }
    return found;
  }

  function point(id) {
    if (id === current) return;
    current = id;

    var hidden = field();
    if (hidden) hidden.value = id;

    /* The terminal: one write, because every consumer re-reads `dataset.url`
       per call rather than caching it. Reconnecting is the panel's own job --
       it exposes `repoint` so the socket is closed and reopened by the code
       that owns the closing flag. */
    var terminal = document.querySelector("[data-terminal]");
    if (terminal) {
      terminal.dataset.url = id ? "/api/chats/" + id + "/terminal/ws" : "";
      if (window.lembas && window.lembas.repointTerminal) {
        window.lembas.repointTerminal();
      }
    }

    /* The canvas builds no URLs in JavaScript at all -- they are all inside the
       fragment. So re-pointing it is re-issuing the request that fetches that
       fragment, and letting the server render the new id into everything. */
    var inner = document.getElementById("canvas-inner");
    if (inner && id && window.htmx) {
      inner.setAttribute("hx-get", "/api/chats/" + id + "/canvas");
      window.htmx.ajax("GET", "/api/chats/" + id + "/canvas", {
        target: "#canvas-inner",
        swap: "innerHTML"
      });
    }
    var panel = document.querySelector("[data-canvas]");
    if (panel) panel.dataset.chat = id;
  }

  document.addEventListener("lembas:agent-target", function (event) {
    var target = event.detail || {};
    if (!target.profileId) {
      point("");
      return;
    }
    /* One round trip per change of target, and the answer is stable: the id is
       derived from (owner, connection, directory), so coming back to a target
       finds the shell already running there rather than opening a second. */
    fetch(
      "/api/agents/" + encodeURIComponent(target.profileId) +
        "/draft?dir=" + encodeURIComponent(target.projectDir || ""),
      { credentials: "same-origin" }
    )
      .then(function (response) { return response.ok ? response.json() : null; })
      .then(function (body) { if (body && body.id) point(body.id); })
      .catch(function () { /* no panels rather than a broken one */ });
  });
})();
