import { h as head, e as ensure_array_like, b as attr_class, a as attr } from './index2-BuOY2QE4.js';
import { p as page, g as goto } from './index3-DeV2OWZf.js';
import { B as Button } from './Button-Cd4Yzpdy.js';
import { I as Icon } from './Icon-BgknHaZs.js';
import { I as Input } from './Input-BJW36iKz.js';
import { p as persistTelescopeSourceId, T as TelescopeClient, m as mockGenerator } from './source-selection-Dx7LqMVs.js';
import { T as Tabs, a as Tab } from './Tab-DheAG-QC.js';
import { A as AgentSidebar } from './AgentSidebar-BB_yQ9s0.js';
import { g as getAgentsContext } from './agents-context-BrlIlkOW.js';
import { X as escape_html } from './context-zH5kvtGY.js';
import './state.svelte-DtOGaiYC.js';
import './utils-KcIDVAAe.js';
import './index-DxaLoiKh.js';
import 'zod';
import './index-server-CefdgakO.js';

function _layout($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    const client = new TelescopeClient(fetch);
    let conversations = void 0;
    let selectedConversation = null;
    let phoneQuery = "";
    let pageSize = 10;
    let pageSizeStr = "10";
    let sortDesc = true;
    let cursorStack = [];
    let lastConversationId = null;
    let loading = false;
    let error = null;
    let totalLoaded = 0;
    let telescopeSources = [];
    let telescopeSourceId = "";
    let { useMock = false, children } = $$props;
    const { onError } = getAgentsContext();
    function fmtDate(ms) {
      return new Date(ms).toLocaleString();
    }
    function fmtDuration(sec) {
      const mm = Math.floor(sec / 60);
      const ss = sec % 60;
      return `${mm}:${String(ss).padStart(2, "0")}`;
    }
    async function fetchConversationsFromApi(phoneNumber, limit = pageSize, lastConversationId2) {
      if (useMock) {
        return mockGenerator.fetchConversations(limit, phoneNumber, lastConversationId2 ?? void 0);
      } else {
        return client.getConversations({
          phoneNumber,
          limit: Number(limit),
          lastConversationId: lastConversationId2 ?? void 0
        });
      }
    }
    async function loadFirstPage() {
      cursorStack = [];
      lastConversationId = null;
      await loadPage();
    }
    async function onTelescopeSourceChange(e) {
      const next = e.target.value;
      telescopeSourceId = next;
      persistTelescopeSourceId(next);
      client.setSourceId(next);
      selectedConversation = null;
      await goto();
      await loadFirstPage();
    }
    async function loadPage() {
      loading = true;
      error = null;
      try {
        const resp = await fetchConversationsFromApi(phoneQuery || void 0, pageSize, lastConversationId ?? void 0);
        let filteredItems = Array.isArray(resp.items) ? resp.items.slice() : [];
        filteredItems = filteredItems.filter((c) => !!c?.phoneNumber);
        conversations = {
          limit: resp.limit,
          items: filteredItems,
          lastConversationId: resp.lastConversationId
        };
        totalLoaded = filteredItems.length;
        lastConversationId = resp.lastConversationId ?? null;
        loading = false;
      } catch (e) {
        loading = false;
        error = e.message || "Unknown error";
        onError(`Error loading conversations: ${error}`);
        console.error("Load page error:", e);
      }
    }
    async function onNext() {
      if (!conversations?.lastConversationId) return;
      cursorStack.push(conversations.lastConversationId);
      lastConversationId = conversations.lastConversationId;
      await loadPage();
    }
    async function onPrev() {
      if (!cursorStack.length) {
        return;
      }
      cursorStack.pop();
      lastConversationId = cursorStack.length ? cursorStack[cursorStack.length - 1] : null;
      await loadPage();
    }
    function toggleSort() {
      sortDesc = !sortDesc;
      if (conversations?.items) {
        conversations.items.sort((a, b) => sortDesc ? b.createdAt - a.createdAt : a.createdAt - b.createdAt);
      }
    }
    function onPageSizeChange(e) {
      const v = e.target.value;
      pageSizeStr = v;
      pageSize = parseInt(pageSizeStr, 10) || 10;
    }
    async function onSearch() {
      await loadFirstPage();
    }
    const activeTopTab = (() => {
      const head2 = page.url.pathname.split("/")[1];
      return head2 === "traces" ? "view" : head2;
    })();
    (() => page.url.pathname.startsWith("/view") ? "/view" : "/traces")();
    function handleTabChange({ value }) {
      if (value === activeTopTab) return;
      if (value === "edit") return goto();
      if (value === "view") return goto();
      goto();
    }
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      head($$renderer3, ($$renderer4) => {
        $$renderer4.title(($$renderer5) => {
          $$renderer5.push(`<title>Bosun: Telescope</title>`);
        });
      });
      $$renderer3.push(`<div class="flex h-screen">`);
      AgentSidebar($$renderer3, {
        agents: [],
        currentAgent: "",
        onSelect: () => {
        },
        showAgents: false,
        className: "flex-none"
      });
      $$renderer3.push(`<!----> <div class="flex h-full min-w-0 flex-1 flex-col bg-rc-gray-980 pb-3 pr-4 pt-2"><nav class="mb-3 flex flex-none flex-col bg-rc-gray-980"><div class="flex h-14 items-center justify-center">`);
      Tabs($$renderer3, {
        class: "w-fit",
        value: activeTopTab,
        ariaLabel: "Top tabs",
        onChange: handleTabChange,
        children: ($$renderer4) => {
          Tab($$renderer4, {
            value: "edit",
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->Edit`);
            }
          });
          $$renderer4.push(`<!----> `);
          Tab($$renderer4, {
            value: "view",
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->View`);
            }
          });
          $$renderer4.push(`<!---->`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----></div> <div class="flex flex-wrap items-center gap-4"><div class="flex-1"><label class="block"><div class="flex gap-2">`);
      $$renderer3.select(
        {
          class: "select",
          value: telescopeSourceId,
          disabled: !telescopeSources.length,
          onchange: onTelescopeSourceChange,
          "aria-label": "Telescope source",
          title: "Telescope source"
        },
        ($$renderer4) => {
          if (telescopeSources.length) {
            $$renderer4.push("<!--[-->");
            $$renderer4.push(`<!--[-->`);
            const each_array = ensure_array_like(telescopeSources);
            for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
              let source = each_array[$$index];
              $$renderer4.option({ value: source.id }, ($$renderer5) => {
                $$renderer5.push(`${escape_html(source.label)}`);
              });
            }
            $$renderer4.push(`<!--]-->`);
          } else {
            $$renderer4.push("<!--[!-->");
            $$renderer4.option({ value: "" }, ($$renderer5) => {
              $$renderer5.push(`${escape_html("No sources")}`);
            });
          }
          $$renderer4.push(`<!--]-->`);
        },
        "svelte-1uk1thp"
      );
      $$renderer3.push(` <div class="relative">`);
      Input($$renderer3, {
        class: "w-56 rounded-r-none !border !border-rc-gray-500 !p-2 !pr-8 hover:border-rc-gray-400",
        placeholder: "Search by phone...",
        onkeydown: (e) => {
          if (e.key === "Enter") {
            e.preventDefault();
            e.stopPropagation();
            onSearch();
          }
        },
        get value() {
          return phoneQuery;
        },
        set value($$value) {
          phoneQuery = $$value;
          $$settled = false;
        }
      });
      $$renderer3.push(`<!---->`);
      if (phoneQuery) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<button type="button" aria-label="Clear search" class="absolute right-2 top-1/2 flex -translate-y-1/2 items-center justify-center rounded p-1 text-rc-gray-200 hover:bg-rc-gray-600 hover:text-rc-gray-100 focus:outline-none">`);
        Icon($$renderer3, { name: "close", width: 18, height: 18 });
        $$renderer3.push(`<!----></button>`);
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--></div> `);
      Button($$renderer3, {
        onclick: onSearch,
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->Search`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----></div></label></div> <div class="hidden items-center gap-2"><div class="text-rc-gray-200">Sort:</div> `);
      Button($$renderer3, {
        onclick: toggleSort,
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->${escape_html(sortDesc ? "Newest first" : "Oldest first")}`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----></div> <div class="hidden items-center gap-2"><div class="text-rc-gray-200">Page size:</div> `);
      $$renderer3.select(
        {
          class: "rounded-sm border border-rc-gray-300 bg-rc-gray-700 p-2 pr-8 text-rc-gray-100",
          value: pageSizeStr,
          onchange: onPageSizeChange
        },
        ($$renderer4) => {
          $$renderer4.option({ value: "5" }, ($$renderer5) => {
            $$renderer5.push(`5`);
          });
          $$renderer4.option({ value: "10" }, ($$renderer5) => {
            $$renderer5.push(`10`);
          });
          $$renderer4.option({ value: "20" }, ($$renderer5) => {
            $$renderer5.push(`20`);
          });
          $$renderer4.option({ value: "50" }, ($$renderer5) => {
            $$renderer5.push(`50`);
          });
        }
      );
      $$renderer3.push(`</div> <div class="flex items-center gap-3"><div class="flex items-center gap-2">`);
      Button($$renderer3, {
        onclick: onPrev,
        disabled: cursorStack.length === 0 && !lastConversationId,
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->Prev`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> `);
      Button($$renderer3, {
        onclick: onNext,
        disabled: !conversations?.items.length,
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->Next`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> <div class="text-sm text-rc-gray-200">Items: ${escape_html(totalLoaded)}</div></div></div> <div class="ml-auto whitespace-nowrap text-sm"><span class="text-gray-400">API Mode:</span> <span class="font-semibold text-rc-green-200">${escape_html(useMock ? "Mock (local)" : "Live")}</span></div></div></nav> <main class="flex flex-1 overflow-hidden"><div class="flex h-full w-1/3 flex-col"><div class="flex-none border-b border-rc-gray-300/40 p-4"><h2 class="text-lg font-semibold text-rc-gray-100">Conversations</h2></div> <div class="rc-scroll min-h-0 flex-1 overflow-scroll px-3 py-4">`);
      if (loading) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<p class="py-8 text-center text-rc-gray-200">Loading...</p>`);
      } else {
        $$renderer3.push("<!--[!-->");
        if (!conversations?.items?.length) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<p class="py-8 text-center text-rc-gray-300">No conversations found</p>`);
        } else {
          $$renderer3.push("<!--[!-->");
          $$renderer3.push(`<ul class="space-y-2"><!--[-->`);
          const each_array_1 = ensure_array_like(conversations.items);
          for (let $$index_1 = 0, $$length = each_array_1.length; $$index_1 < $$length; $$index_1++) {
            let conversation = each_array_1[$$index_1];
            $$renderer3.push(`<li${attr_class(
              `cursor-pointer rounded-lg p-3 transition-colors ${(page.params.conversationId ? conversation.conversationId === page.params.conversationId : conversation.conversationId === selectedConversation?.conversationId) ? "bg-rc-gray-600" : "bg-rc-gray-700 hover:bg-rc-gray-650"}`,
              "svelte-1uk1thp"
            )}${attr("aria-selected", page.params.conversationId ? conversation.conversationId === page.params.conversationId : conversation.conversationId === selectedConversation?.conversationId)}><div class="flex w-full flex-col gap-2"><div class="flex w-full items-center justify-between"><div class="text-gray-300">${escape_html(fmtDate(conversation.createdAt))}</div> <div class="flex items-center gap-2"><span class="text-xs text-rc-gray-300">${escape_html(conversation.medium)}</span> <span class="font-semibold text-rc-gray-100">${escape_html(conversation.phoneNumber)}</span></div></div> <div class="flex items-center justify-between gap-4"><div class="text-sm"><span class="text-rc-gray-200">Conversation Id:</span> <span class="text-rc-green-200">${escape_html(conversation.conversationId)}</span></div> <p class="text-sm text-gray-400">Duration: ${escape_html(fmtDuration(conversation.duration ?? 0))}</p></div></div></li>`);
          }
          $$renderer3.push(`<!--]--></ul>`);
        }
        $$renderer3.push(`<!--]-->`);
      }
      $$renderer3.push(`<!--]--></div></div> <div class="flex h-full w-2/3 flex-col bg-rc-gray-980">`);
      children($$renderer3);
      $$renderer3.push(`<!----></div></main></div></div>`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
  });
}

export { _layout as default };
//# sourceMappingURL=_layout.svelte-BL8XnK1E.js.map
