import { h as head, e as ensure_array_like, a as attr_class, b as attr, c as bind_props } from './index2-CzosXNJA.js';
import { p as page, g as goto } from './index3-DWsxdehH.js';
import { B as Button } from './Button-Byk8IDvI.js';
import { I as Icon } from './Link-BxAwzNX6.js';
import { I as Input } from './Input-CN285S9J.js';
import { m as mockGenerator, T as TelescopeClient, C as CollapseExpand } from './client-DtDK0-V3.js';
import { X as escape_html, Y as fallback } from './context-BZ_07CFR.js';
import { T as Tabs, a as Tab } from './Tab-Bkjowzww.js';
import { A as AgentSidebar } from './AgentSidebar-DRTSgEv8.js';
import './state.svelte-Yu4RD6aK.js';
import './utils-KcIDVAAe.js';
import './index-FgxKh3J4.js';
import './html-FW6Ia4bL.js';
import 'zod';

function CopyButton($$renderer, $$props) {
  let text = fallback($$props["text"], "");
  let label = fallback($$props["label"], "Copy");
  let copiedLabel = fallback($$props["copiedLabel"], "Copied!");
  let className = fallback($$props["className"], "");
  $$renderer.push(`<button type="button"${attr_class(`group inline-flex items-center gap-1 rounded border border-rc-gray-300/60 bg-rc-gray-600/60
          px-2 py-1 text-xs text-rc-gray-100
          transition hover:bg-rc-gray-500 hover:text-white ${className}`)} aria-live="polite"${attr("title", label)}>`);
  {
    $$renderer.push("<!--[!-->");
    Icon($$renderer, { name: "copy", width: 14, height: 14, class: "shrink-0" });
    $$renderer.push(`<!----> <span>${escape_html(label)}</span>`);
  }
  $$renderer.push(`<!--]--></button>`);
  bind_props($$props, { text, label, copiedLabel, className });
}
function _layout($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    const client = new TelescopeClient(fetch);
    let calls = void 0;
    let selectedCall = null;
    let phoneQuery = "";
    let pageSize = 10;
    let pageSizeStr = "10";
    let sortDesc = true;
    let cursorStack = [];
    let lastCallId = null;
    let loading = false;
    let totalLoaded = 0;
    let sidebarCollapsed = false;
    let { useMock = false, children } = $$props;
    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 fetchCallsFromApi(phoneNumber, limit = pageSize, lastCallId2) {
      if (useMock) {
        return mockGenerator.fetchCalls(limit, phoneNumber, lastCallId2 ?? void 0);
      } else {
        return client.getCalls({
          phoneNumber,
          limit: Number(limit),
          lastCallId: lastCallId2 ?? void 0
        });
      }
    }
    async function loadFirstPage() {
      cursorStack = [];
      lastCallId = null;
      await loadPage();
    }
    async function loadPage() {
      loading = true;
      try {
        const resp = await fetchCallsFromApi(void 0, pageSize, lastCallId ?? void 0);
        let filteredItems = Array.isArray(resp.items) ? resp.items.slice() : [];
        if (filteredItems.length) {
          filteredItems.sort((a, b) => {
            const ax = Number(a?.createdAt ?? 0);
            const bx = Number(b?.createdAt ?? 0);
            return sortDesc ? bx - ax : ax - bx;
          });
        }
        const normalize = (s) => s.replace(/\D/g, "");
        if (phoneQuery && filteredItems.length) {
          const q = normalize(String(phoneQuery).trim());
          filteredItems = filteredItems.filter((call) => {
            const pn = normalize(String(call?.phoneNumber ?? ""));
            return q === "" ? true : pn.includes(q);
          });
        }
        calls = {
          limit: resp.limit,
          items: filteredItems,
          lastCallId: resp.lastCallId
        };
        totalLoaded = filteredItems.length;
        lastCallId = resp.lastCallId ?? null;
        if (calls?.items) {
          calls.items.sort((a, b) => sortDesc ? b.createdAt - a.createdAt : a.createdAt - b.createdAt);
        }
        loading = false;
      } catch (e) {
        loading = false;
        e.message;
        console.error("Load page error:", e);
      }
    }
    async function onNext() {
      if (!calls?.lastCallId) return;
      cursorStack.push(calls.lastCallId);
      lastCallId = calls.lastCallId;
      await loadPage();
    }
    async function onPrev() {
      if (!cursorStack.length) {
        return;
      }
      cursorStack.pop();
      lastCallId = cursorStack.length ? cursorStack[cursorStack.length - 1] : null;
      await loadPage();
    }
    function toggleSort() {
      sortDesc = !sortDesc;
      if (calls?.items) {
        calls.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 = (() => {
      return page.url.pathname.split("/")[1];
    })();
    function handleTabChange({ value }) {
      if (value === activeTopTab) return;
      if (value === "roleplay") return goto();
      if (value === "tests") return goto();
      if (value === "traces") 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: () => {
        },
        onToggle: () => sidebarCollapsed = !sidebarCollapsed,
        isCollapsed: sidebarCollapsed,
        showAgents: false,
        className: "flex-none"
      });
      $$renderer3.push(`<!----> <div class="flex h-full min-w-0 flex-1 flex-col bg-rc-gray-700 py-2 pr-lg"><nav class="flex h-14 flex-none items-center justify-between bg-rc-gray-700"><div class="flex items-center">`);
      Tabs($$renderer3, {
        value: activeTopTab,
        ariaLabel: "Top tabs",
        onChange: handleTabChange,
        children: ($$renderer4) => {
          Tab($$renderer4, {
            value: "roleplay",
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->Roleplay`);
            }
          });
          $$renderer4.push(`<!----> `);
          Tab($$renderer4, {
            value: "tests",
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->Tests`);
            }
          });
          $$renderer4.push(`<!----> `);
          Tab($$renderer4, {
            value: "traces",
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->Traces`);
            }
          });
          $$renderer4.push(`<!---->`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----></div> <div class="flex items-center gap-4"><div class="flex-1"><label class="block"><div class="flex gap-2"><div class="relative">`);
      Input($$renderer3, {
        class: "w-80 rounded-r-none border-rc-gray-300 !p-2 !pr-8",
        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 && !lastCallId,
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->Prev`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> `);
      Button($$renderer3, {
        onclick: onNext,
        disabled: !calls?.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> <div class="ml-3"><span class="text-gray-400">API Mode:</span> <span class="font-semibold text-rc-green-200">${escape_html(useMock ? "Mock (local)" : "Live")}</span></div></nav> <main class="flex flex-1 gap-1 overflow-hidden border-thin border-rc-gray-300/40"><div class="flex h-full w-1/3 flex-col border-r-thin border-r-rc-gray-300 bg-rc-gray-800"><div class="flex-none border-b border-rc-gray-300/40 p-4"><h2 class="text-lg font-semibold text-rc-gray-100">Calls</h2></div> <div class="flex-1 overflow-auto p-4">`);
      if (loading) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<p class="py-8 text-center text-rc-gray-200">Loading...</p>`);
      } else {
        $$renderer3.push("<!--[!-->");
        if (!calls?.items?.length) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<p class="py-8 text-center text-rc-gray-300">No calls found</p>`);
        } else {
          $$renderer3.push("<!--[!-->");
          $$renderer3.push(`<ul class="space-y-3"><!--[-->`);
          const each_array = ensure_array_like(calls.items);
          for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
            let call = each_array[$$index];
            $$renderer3.push(`<li${attr_class(`cursor-pointer rounded-lg border border-rc-gray-300 p-4 transition-colors ${(page.params.callId ? call.callId === page.params.callId : call.callId === selectedCall?.callId) ? "bg-rc-gray-600" : "bg-rc-gray-700"}`)}${attr("aria-selected", page.params.callId ? call.callId === page.params.callId : call.callId === selectedCall?.callId)}><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(call.createdAt))}</div> <div class="flex flex-wrap-reverse items-center justify-end gap-2"><span class="font-semibold text-rc-gray-100">${escape_html(call.phoneNumber)}</span> `);
            CopyButton($$renderer3, {
              text: call.phoneNumber,
              label: "Copy",
              copiedLabel: "Copied!",
              className: "ml-1"
            });
            $$renderer3.push(`<!----></div></div> <div class="flex items-center justify-between gap-4"><div class="text-sm"><span class="text-rc-gray-200">Call Id:</span> <span class="text-rc-green-200">${escape_html(call.callId)}</span></div> <p class="text-sm text-gray-400">Duration: ${escape_html(fmtDuration(call.duration ?? 0))}</p></div> `);
            if (call?.audioUrl) {
              $$renderer3.push("<!--[-->");
              $$renderer3.push(`<div><audio controls preload="none" class="mt-1 w-full rounded-4xl border border-rc-gray-300 color-scheme-dark"><source${attr("src", call.audioUrl)}/></audio></div>`);
            } else {
              $$renderer3.push("<!--[!-->");
              $$renderer3.push(`<div class="hidden"></div>`);
            }
            $$renderer3.push(`<!--]--> <div><p class="text-sm text-rc-gray-200">${escape_html(call.__expanded ? "Transcript:" : "Transcript preview:")}</p> `);
            CollapseExpand($$renderer3, {
              value: call.transcript,
              limit: 130,
              get expanded() {
                return call.__expanded;
              },
              set expanded($$value) {
                call.__expanded = $$value;
                $$settled = false;
              }
            });
            $$renderer3.push(`<!----></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-700">`);
      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-BX14puY4.js.map
