import { jsxs as s, jsx as a, Fragment as R } from "react/jsx-runtime";
import { useTools as j } from "../../hooks/useTools.es.js";
import { useThread as E } from "../../providers/Thread.es.js";
import { useChatRuntime as D } from "../../providers/ChatRuntime.es.js";
import { getContentString as k, formatRelativeTime as M } from "../../utils/utils.es.js";
import { PanelLeftClose as $, MoreVertical as F, Pencil as V, Share2 as A, Trash2 as I } from "lucide-react";
import { useState as b, useEffect as z, useRef as L } from "react";
function J({ header: m, isSidebar: h, onClose: d }) {
  const [u, f] = b(!1), [c, C] = b(""), { threads: _, getThreads: p, setThreadId: N, setThreads: y, setThreadsLoading: w } = E(), { identity: x } = D(), { tool: g, userDefinedTools: T } = j();
  z(() => {
    typeof window > "u" || (w(!0), p().then(y).catch(console.error).finally(() => w(!1)));
  }, [x?.authToken]);
  const v = _.filter((t) => {
    if (!c.trim()) return !0;
    const l = c.toLowerCase();
    if ((t.metadata?.name || t.metadata?.threadName || t.metadata?.thread_name || "").toLowerCase().includes(l)) return !0;
    const e = t.values;
    return !!(e?.messages?.[0] && k(e.messages[0].content).toLowerCase().includes(l));
  }).sort((t, l) => {
    const o = new Date(t.updated_at).getTime();
    return new Date(l.updated_at).getTime() - o;
  });
  return /* @__PURE__ */ s(
    "aside",
    {
      className: `flex h-full flex-col ${h ? "" : "border-r"} border-white/10 border-l border-white bg-zinc w-72`,
      children: [
        /* @__PURE__ */ s("div", { className: "flex h-14 items-center justify-between border-b border-white/10 px-2", children: [
          /* @__PURE__ */ s("div", { className: "flex items-center gap-3", children: [
            d && /* @__PURE__ */ a("div", { className: "cursor-pointer p-2 hover:bg-white/10 rounded-md", children: /* @__PURE__ */ a($, { className: "h-5 w-5 text-white/70", onClick: d }) }),
            m && /* @__PURE__ */ a("div", { className: "text-white/70 text-lg font-medium", children: m.title })
          ] }),
          /* @__PURE__ */ a("div", { className: "flex items-center gap-1", children: g.map((t, l) => {
            let o = t.onClick;
            return t.label === "Chat" ? o = () => N(null) : t.label === "Search" && (o = () => f(!0)), t.label === "Search" && u ? null : /* @__PURE__ */ a(
              S,
              {
                icon: t.icon,
                label: t.label,
                alt: t.alt,
                onClick: o,
                showText: !1
              },
              l
            );
          }) })
        ] }),
        u && /* @__PURE__ */ a("div", { className: "p-2 mr-2", children: /* @__PURE__ */ a(
          "input",
          {
            type: "text",
            placeholder: "Search chats...",
            value: c,
            onChange: (t) => C(t.target.value),
            onBlur: () => {
              c.trim() || f(!1);
            },
            autoFocus: !0,
            className: "w-full bg-zinc-800 text-white/80 text-sm px-3 py-2 rounded-md outline-none focus:ring-1 focus:ring-zinc-600 placeholder:text-white/40"
          }
        ) }),
        /* @__PURE__ */ a("div", { className: "flex-1 flex flex-col p-2 mr-2 overflow-hidden", children: /* @__PURE__ */ s(R, { children: [
          T.map((t, l) => /* @__PURE__ */ a(
            S,
            {
              icon: t.icon,
              label: t.label,
              alt: t.alt,
              onClick: t.onClick,
              showText: !0
            },
            l
          )),
          /* @__PURE__ */ a("div", { className: "flex-1 space-y-1 overflow-y-auto overflow-x-hidden thread-scrollbar", children: /* @__PURE__ */ a(P, { threads: v }) })
        ] }) })
      ]
    }
  );
}
function S({
  icon: m,
  label: h,
  alt: d,
  onClick: u,
  showText: f = !0
}) {
  return /* @__PURE__ */ s(
    "button",
    {
      className: `flex items-center gap-3 rounded-md px-2 py-2
        text-white/70 hover:bg-white/10 cursor-pointer`,
      onClick: u,
      title: d || h,
      children: [
        m,
        f && /* @__PURE__ */ a("span", { className: "text-md font-medium", children: h })
      ]
    }
  );
}
function P({
  threads: m,
  onThreadClick: h
}) {
  const { threadId: d, setThreadId: u, deleteThread: f, updateThread: c } = E(), [C, _] = b(null), [p, N] = b(null), [y, w] = b(null), [x, g] = b(""), T = L(null), v = L(null);
  z(() => {
    const e = (r) => {
      T.current && !T.current.contains(r.target) && N(null);
    };
    return p && document.addEventListener("mousedown", e), () => {
      document.removeEventListener("mousedown", e);
    };
  }, [p]), z(() => {
    y && v.current && (v.current.focus(), v.current.select());
  }, [y]);
  const t = async (e) => {
    const r = e.values, i = e.metadata?.name || e.metadata?.threadName || e.metadata?.thread_name || (r?.messages?.[0] ? k(r.messages[0].content) : e.thread_id);
    if (x.trim() && x.trim() !== i)
      try {
        await c(e.thread_id, {
          ...e.metadata,
          name: x.trim()
        });
      } catch (n) {
        console.error("Failed to rename thread:", n), alert("Failed to rename thread. Please try again.");
      }
    w(null), g("");
  }, l = () => {
    w(null), g("");
  }, o = async (e, r) => {
    N(null);
    try {
      switch (e) {
        case "rename": {
          const i = r.values, n = r.metadata?.name || r.metadata?.threadName || r.metadata?.thread_name || (i?.messages?.[0] ? k(i.messages[0].content) : r.thread_id);
          g(n), w(r.thread_id);
          break;
        }
        case "share": {
          const i = `${window.location.origin}${window.location.pathname}?thread=${r.thread_id}`;
          await navigator.clipboard.writeText(i), alert("Thread link copied to clipboard!");
          break;
        }
        case "archive": {
          await c(r.thread_id, {
            ...r.metadata,
            archived: !0
          });
          break;
        }
        case "delete": {
          confirm("Are you sure you want to delete this thread? This action cannot be undone.") && await f(r.thread_id);
          break;
        }
      }
    } catch (i) {
      console.error(`Failed to ${e} thread:`, i), alert(`Failed to ${e} thread. Please try again.`);
    }
  };
  return /* @__PURE__ */ a("div", { className: "flex h-full w-full flex-col items-start justify-start gap-2", children: m.map((e) => {
    let r = e.metadata?.name || e.metadata?.threadName || e.metadata?.thread_name;
    if (!r && typeof e.values == "object" && e.values && "messages" in e.values && Array.isArray(e.values.messages) && e.values.messages?.length > 0) {
      const n = e.values.messages[0];
      r = k(n.content);
    }
    r || (r = e.thread_id);
    const i = y === e.thread_id;
    return /* @__PURE__ */ s(
      "div",
      {
        className: `relative w-full rounded-md group ${e.thread_id === d ? "bg-zinc-700/60" : "hover:bg-zinc-800"}`,
        onMouseEnter: () => _(e.thread_id),
        onMouseLeave: () => _(null),
        children: [
          /* @__PURE__ */ s("div", { className: "flex items-center gap-1 px-2 py-1", children: [
            i ? /* @__PURE__ */ a(
              "input",
              {
                ref: v,
                type: "text",
                value: x,
                onChange: (n) => g(n.target.value),
                onKeyDown: (n) => {
                  n.key === "Enter" ? t(e) : n.key === "Escape" && l();
                },
                onBlur: () => t(e),
                className: "flex-1 bg-zinc-700 text-white/80 text-sm px-2 py-1 rounded outline-none focus:ring-1 focus:ring-zinc-500"
              }
            ) : /* @__PURE__ */ s("div", { className: "flex-1 flex items-center justify-between min-w-0", children: [
              /* @__PURE__ */ a(
                "button",
                {
                  className: "flex-1 items-start justify-start text-left font-normal min-w-0",
                  onClick: (n) => {
                    n.preventDefault(), h?.(e.thread_id), e.thread_id !== d && u(e.thread_id);
                  },
                  children: /* @__PURE__ */ a("p", { className: "truncate text-ellipsis text-sm text-white/80", children: r })
                }
              ),
              /* @__PURE__ */ a("span", { className: "flex-shrink-0 text-xs text-white/40 ml-2", children: M(e.updated_at) })
            ] }),
            !i && C === e.thread_id && /* @__PURE__ */ a(
              "button",
              {
                className: "flex-shrink-0 p-2 rounded-md hover:bg-zinc-700",
                onClick: (n) => {
                  n.stopPropagation(), N(p === e.thread_id ? null : e.thread_id);
                },
                children: /* @__PURE__ */ a(F, { className: "h-4 w-4 text-white/60" })
              }
            )
          ] }),
          p === e.thread_id && /* @__PURE__ */ s(
            "div",
            {
              ref: T,
              className: "absolute right-2 top-8 z-50 w-48 rounded-md bg-zinc-800 border border-white/10 shadow-lg py-1",
              children: [
                /* @__PURE__ */ s(
                  "button",
                  {
                    className: "w-full flex items-center gap-2 px-3 py-2 text-sm text-white/80 hover:bg-zinc-700",
                    onClick: () => o("rename", e),
                    children: [
                      /* @__PURE__ */ a(V, { className: "h-4 w-4" }),
                      "Rename"
                    ]
                  }
                ),
                /* @__PURE__ */ s(
                  "button",
                  {
                    className: "w-full flex items-center gap-2 px-3 py-2 text-sm text-white/80 hover:bg-zinc-700",
                    onClick: () => o("share", e),
                    children: [
                      /* @__PURE__ */ a(A, { className: "h-4 w-4" }),
                      "Share"
                    ]
                  }
                ),
                /* @__PURE__ */ a("div", { className: "my-1 border-t border-white/10" }),
                /* @__PURE__ */ s(
                  "button",
                  {
                    className: "w-full flex items-center gap-2 px-3 py-2 text-sm text-red-400 hover:bg-zinc-700",
                    onClick: () => o("delete", e),
                    children: [
                      /* @__PURE__ */ a(I, { className: "h-4 w-4" }),
                      "Delete"
                    ]
                  }
                )
              ]
            }
          )
        ]
      },
      e.thread_id
    );
  }) });
}
export {
  J as default
};
//# sourceMappingURL=ThreadHistory.es.js.map
