"use client";
import * as React from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
import remarkGfm from 'remark-gfm';
import * as HoverCardPrimitive from '@radix-ui/react-hover-card';
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
import * as CollapsiblePrimitive from '@radix-ui/react-collapsible';
import { visit } from 'unist-util-visit';

function cn(...inputs) {
  return twMerge(clsx(inputs));
}
var SAFE_URL_SCHEMES = ["http:", "https:", "mailto:"];
function safeUrl(raw) {
  if (raw === void 0 || raw === "") return void 0;
  let parsed;
  try {
    parsed = new URL(raw);
  } catch {
    return raw.includes(":") ? void 0 : raw;
  }
  return SAFE_URL_SCHEMES.some((scheme) => scheme === parsed.protocol) ? raw : void 0;
}
function InlineCitation({
  index,
  title,
  url: rawUrl,
  excerpt,
  openDelay = 200,
  className
}) {
  const url = safeUrl(rawUrl);
  const triggerClasses = cn(
    "inline-flex select-none items-center justify-center rounded-sm bg-primary/10 px-1 py-0.5 text-[0.7em] font-mono font-semibold text-primary leading-none",
    "transition-all duration-[var(--duration-normal,200ms)] ease-out",
    "hover:bg-primary/15",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
    className
  );
  const trigger = url ? /* @__PURE__ */ jsxs(
    "a",
    {
      href: url,
      target: "_blank",
      rel: "noreferrer noopener external",
      className: triggerClasses,
      "aria-label": `Source ${index}: ${title}`,
      children: [
        "[",
        index,
        "]"
      ]
    }
  ) : (
    // No URL → still focusable so keyboard users can open the popover.
    // Real <button type="button"> over a styled span so the trigger
    // honors space/enter activation natively.
    /* @__PURE__ */ jsxs(
      "button",
      {
        type: "button",
        className: triggerClasses,
        "aria-label": `Source ${index}: ${title}`,
        children: [
          "[",
          index,
          "]"
        ]
      }
    )
  );
  return /* @__PURE__ */ jsxs(HoverCardPrimitive.Root, { openDelay, children: [
    /* @__PURE__ */ jsx(HoverCardPrimitive.Trigger, { asChild: true, children: /* @__PURE__ */ jsx("sup", { className: "inline-block leading-none", children: trigger }) }),
    /* @__PURE__ */ jsx(HoverCardPrimitive.Portal, { children: /* @__PURE__ */ jsx(
      HoverCardPrimitive.Content,
      {
        side: "top",
        align: "center",
        sideOffset: 4,
        className: cn(
          "z-50 max-w-xs rounded-md border border-border bg-popover p-3 text-popover-foreground shadow-md",
          "data-[state=open]:animate-in data-[state=closed]:animate-out",
          "data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
          "data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
        ),
        children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
          /* @__PURE__ */ jsxs("span", { className: "font-mono text-[10px] text-muted-foreground", children: [
            "[",
            index,
            "]"
          ] }),
          /* @__PURE__ */ jsx("span", { className: "text-sm font-medium leading-snug text-foreground", children: title }),
          excerpt ? /* @__PURE__ */ jsx("span", { className: "text-xs leading-relaxed text-muted-foreground", children: excerpt }) : null,
          url ? /* @__PURE__ */ jsx("span", { className: "truncate text-xs text-primary underline-offset-2 hover:underline", children: inferDisplayUrl(url) }) : null
        ] })
      }
    ) })
  ] });
}
function inferDisplayUrl(href) {
  try {
    const url = new URL(href);
    return url.hostname.replace(/^www\./, "") + url.pathname;
  } catch {
    return href;
  }
}
function Reasoning({
  children,
  defaultOpen = false,
  durationMs,
  label,
  className
}) {
  const headerLabel = label ?? (typeof durationMs === "number" ? formatThoughtFor(durationMs) : "Thinking");
  return /* @__PURE__ */ jsxs(
    CollapsiblePrimitive.Root,
    {
      defaultOpen,
      className: cn("overflow-hidden rounded-md border-l-2 border-foreground/15 bg-muted/20", className),
      children: [
        /* @__PURE__ */ jsxs(
          CollapsiblePrimitive.Trigger,
          {
            className: cn(
              "group flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-muted-foreground",
              "transition-all duration-[var(--duration-normal,200ms)] ease-out",
              "hover:text-foreground",
              "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
            ),
            children: [
              /* @__PURE__ */ jsx(SparkleGlyph, {}),
              /* @__PURE__ */ jsx("span", { className: "font-medium italic", children: headerLabel }),
              /* @__PURE__ */ jsx(Chevron, {})
            ]
          }
        ),
        /* @__PURE__ */ jsx(CollapsiblePrimitive.Content, { className: "overflow-hidden border-t border-foreground/[0.06] px-3 py-2 text-sm text-muted-foreground", children })
      ]
    }
  );
}
function formatThoughtFor(ms) {
  if (ms < 1e3) return `Thought for ${ms}ms`;
  const seconds = ms / 1e3;
  const formatted = seconds >= 10 ? Math.round(seconds).toString() : seconds.toFixed(1);
  return `Thought for ${formatted}s`;
}
function SparkleGlyph() {
  return /* @__PURE__ */ jsx(
    "svg",
    {
      "aria-hidden": true,
      viewBox: "0 0 16 16",
      width: "12",
      height: "12",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: "1.5",
      strokeLinecap: "round",
      strokeLinejoin: "round",
      className: "shrink-0",
      children: /* @__PURE__ */ jsx("path", { d: "M8 1.5l1.5 4 4 1.5-4 1.5L8 12.5 6.5 8.5l-4-1.5 4-1.5L8 1.5z" })
    }
  );
}
function Chevron() {
  return /* @__PURE__ */ jsx(
    "svg",
    {
      "aria-hidden": true,
      viewBox: "0 0 16 16",
      width: "12",
      height: "12",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: "1.5",
      strokeLinecap: "round",
      strokeLinejoin: "round",
      className: "ml-auto shrink-0 transition-transform duration-200 group-data-[state=open]:rotate-180",
      children: /* @__PURE__ */ jsx("path", { d: "M4 6l4 4 4-4" })
    }
  );
}
function Citation({ title, url, page, index, className, children }) {
  const baseClasses = cn(
    "inline-flex items-center gap-1.5 rounded-md border border-foreground/15 bg-card px-2 py-0.5 text-xs",
    "transition-all duration-[var(--duration-normal,200ms)] ease-out",
    className
  );
  const body = /* @__PURE__ */ jsxs(Fragment, { children: [
    typeof index === "number" ? /* @__PURE__ */ jsxs("span", { className: "font-mono text-[10px] font-semibold text-muted-foreground", children: [
      "[",
      index,
      "]"
    ] }) : /* @__PURE__ */ jsx(DocGlyph, {}),
    /* @__PURE__ */ jsx("span", { className: "truncate text-foreground", children: title }),
    typeof page === "number" ? /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
      "p.",
      page
    ] }) : null,
    children
  ] });
  if (url) {
    return /* @__PURE__ */ jsx(
      "a",
      {
        href: url,
        target: "_blank",
        rel: "noreferrer noopener",
        className: cn(
          baseClasses,
          "hover:border-foreground/30 hover:bg-secondary/40 hover:shadow-sm",
          "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
        ),
        children: body
      }
    );
  }
  return /* @__PURE__ */ jsx("span", { className: baseClasses, children: body });
}
function DocGlyph() {
  return /* @__PURE__ */ jsxs(
    "svg",
    {
      "aria-hidden": true,
      viewBox: "0 0 16 16",
      width: "11",
      height: "11",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: "1.5",
      strokeLinecap: "round",
      strokeLinejoin: "round",
      className: "shrink-0 text-muted-foreground",
      children: [
        /* @__PURE__ */ jsx("path", { d: "M9 1.5H4.5A1.5 1.5 0 0 0 3 3v10a1.5 1.5 0 0 0 1.5 1.5h7A1.5 1.5 0 0 0 13 13V5.5L9 1.5z" }),
        /* @__PURE__ */ jsx("path", { d: "M9 1.5V5.5h4" })
      ]
    }
  );
}
function Sources({ sources, defaultOpen = true, className }) {
  if (sources.length === 0) return null;
  const count = sources.length;
  const headerLabel = count === 1 ? "1 source" : `${count} sources`;
  return /* @__PURE__ */ jsxs(
    CollapsiblePrimitive.Root,
    {
      defaultOpen,
      className: cn(
        "overflow-hidden rounded-md border border-border bg-card text-card-foreground",
        className
      ),
      children: [
        /* @__PURE__ */ jsxs(
          CollapsiblePrimitive.Trigger,
          {
            className: cn(
              "group flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-muted-foreground",
              "transition-all duration-[var(--duration-normal,200ms)] ease-out",
              "hover:text-foreground",
              "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
            ),
            children: [
              /* @__PURE__ */ jsx(DocStackGlyph, {}),
              /* @__PURE__ */ jsx("span", { className: "font-medium", children: headerLabel }),
              /* @__PURE__ */ jsx(Chevron2, {})
            ]
          }
        ),
        /* @__PURE__ */ jsx(CollapsiblePrimitive.Content, { className: "overflow-hidden border-t border-foreground/[0.06]", children: /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-1.5 p-2", children: sources.map((s, i) => /* @__PURE__ */ jsx(
          Citation,
          {
            title: s.title,
            url: safeUrl(s.url),
            page: s.page,
            index: s.index ?? i + 1
          },
          `${s.url ?? s.title}-${i}`
        )) }) })
      ]
    }
  );
}
function DocStackGlyph() {
  return /* @__PURE__ */ jsxs(
    "svg",
    {
      "aria-hidden": true,
      viewBox: "0 0 16 16",
      width: "12",
      height: "12",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: "1.5",
      strokeLinecap: "round",
      strokeLinejoin: "round",
      className: "shrink-0",
      children: [
        /* @__PURE__ */ jsx("path", { d: "M5 3h7l1.5 1.5V13H5V3z" }),
        /* @__PURE__ */ jsx("path", { d: "M3 5v8.5L4.5 15H11" })
      ]
    }
  );
}
function Chevron2() {
  return /* @__PURE__ */ jsx(
    "svg",
    {
      "aria-hidden": true,
      viewBox: "0 0 16 16",
      width: "12",
      height: "12",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: "1.5",
      strokeLinecap: "round",
      strokeLinejoin: "round",
      className: "ml-auto shrink-0 transition-transform duration-200 group-data-[state=open]:rotate-180",
      children: /* @__PURE__ */ jsx("path", { d: "M4 6l4 4 4-4" })
    }
  );
}
var STATE_LABEL = {
  pending: "Pending",
  running: "Running",
  result: "Done",
  error: "Error"
};
var STATE_CLASSES = {
  pending: "bg-muted text-muted-foreground",
  // `text-foreground` (12:1) survives axe's mid-pulse capture; the
  // previous `text-primary` (`#7081a8` on dark `--muted`, 4.28:1) was
  // intermittently flagged below AA 4.5:1 at the 10px badge size when
  // `animate-pulse` caught the scan during a low-opacity frame.
  running: "bg-muted text-foreground font-medium animate-pulse",
  result: "bg-accent/30 text-accent-foreground",
  error: "bg-destructive/15 text-destructive"
};
function ToolCall({
  name,
  state,
  args,
  result,
  defaultOpen = false,
  className
}) {
  return /* @__PURE__ */ jsxs(
    CollapsiblePrimitive.Root,
    {
      defaultOpen,
      className: cn(
        "overflow-hidden rounded-md border bg-card text-card-foreground",
        "transition-all duration-[var(--duration-normal,200ms)] ease-out",
        "data-[state=open]:shadow-sm",
        className
      ),
      children: [
        /* @__PURE__ */ jsxs(
          CollapsiblePrimitive.Trigger,
          {
            className: cn(
              "group flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm",
              "hover:bg-muted/40",
              "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
            ),
            children: [
              /* @__PURE__ */ jsxs("span", { className: "flex min-w-0 items-center gap-2", children: [
                /* @__PURE__ */ jsx(ToolGlyph, {}),
                /* @__PURE__ */ jsx("span", { className: "truncate font-mono text-xs text-foreground", children: name }),
                /* @__PURE__ */ jsx(
                  "span",
                  {
                    className: cn(
                      "inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium",
                      STATE_CLASSES[state]
                    ),
                    children: STATE_LABEL[state]
                  }
                )
              ] }),
              /* @__PURE__ */ jsx(Chevron3, {})
            ]
          }
        ),
        /* @__PURE__ */ jsxs(CollapsiblePrimitive.Content, { className: "overflow-hidden border-t bg-muted/20 px-3 py-2 text-xs", children: [
          args !== void 0 ? /* @__PURE__ */ jsx(CodeSection, { label: "Arguments", value: args }) : null,
          result !== void 0 ? /* @__PURE__ */ jsx(CodeSection, { label: "Result", value: result }) : null,
          args === void 0 && result === void 0 ? /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: "No arguments or result yet." }) : null
        ] })
      ]
    }
  );
}
function CodeSection({ label, value }) {
  const text = typeof value === "string" ? value : safeStringify(value);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-1 py-1", children: [
    /* @__PURE__ */ jsx("div", { className: "text-[10px] uppercase tracking-wide text-muted-foreground", children: label }),
    /* @__PURE__ */ jsx("pre", { className: "overflow-x-auto rounded bg-background/60 p-2 font-mono text-[11px] leading-snug", children: text })
  ] });
}
function safeStringify(value) {
  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return String(value);
  }
}
function ToolGlyph() {
  return /* @__PURE__ */ jsxs(
    "svg",
    {
      "aria-hidden": true,
      viewBox: "0 0 16 16",
      width: "14",
      height: "14",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: "1.5",
      strokeLinecap: "round",
      strokeLinejoin: "round",
      className: "shrink-0 text-muted-foreground",
      children: [
        /* @__PURE__ */ jsx("path", { d: "M11.5 1.5l3 3-2.5 2.5-3-3 2.5-2.5z" }),
        /* @__PURE__ */ jsx("path", { d: "M9 4l-7 7v3h3l7-7" })
      ]
    }
  );
}
function Chevron3() {
  return /* @__PURE__ */ jsx(
    "svg",
    {
      "aria-hidden": true,
      viewBox: "0 0 16 16",
      width: "14",
      height: "14",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: "1.5",
      strokeLinecap: "round",
      strokeLinejoin: "round",
      className: "shrink-0 text-muted-foreground transition-transform duration-200 group-data-[state=open]:rotate-180",
      children: /* @__PURE__ */ jsx("path", { d: "M4 6l4 4 4-4" })
    }
  );
}

// src/ai/markdown/close-unterminated.ts
function closeUnterminated(input) {
  let working = input;
  const suffixes = [];
  if (hasUnclosedFence(working)) {
    suffixes.push("\n```\n");
    working = maskOpenFence(working);
  }
  const masked = maskEscapes(maskClosedFences(working));
  if (/<!--(?![\s\S]*-->)/.test(working)) {
    suffixes.push("-->");
  } else if (/<[a-zA-Z][^<>]*$/.test(working)) {
    suffixes.push(">");
  }
  if (/\[[^[\]]*\]\([^()]*$/.test(working)) {
    suffixes.push(")");
  } else if (/\[[^[\]]*$/.test(working)) {
    suffixes.push("]");
  }
  let backtickOdd = 0;
  for (const line of masked.split("\n")) {
    const count = (line.match(/`/g) ?? []).length;
    if (count % 2 === 1) backtickOdd++;
  }
  if (backtickOdd % 2 === 1) {
    suffixes.push("`");
  }
  const strikeMarkers = countOutsideMaskedFences(masked, /~~/g);
  if (strikeMarkers % 2 === 1) {
    suffixes.push("~~");
  }
  const { boldOdd, italicAsteriskOdd } = countBoldItalic(masked);
  if (boldOdd) suffixes.push("**");
  if (italicAsteriskOdd) suffixes.push("*");
  if (countUnderscoreItalic(masked) % 2 === 1) suffixes.push("_");
  if (suffixes.length === 0) return input;
  return input + suffixes.join("");
}
function hasUnclosedFence(input) {
  const fenceRe = /^[ \t]*```/gm;
  const matches = input.match(fenceRe);
  return matches !== null && matches.length % 2 === 1;
}
function maskOpenFence(input) {
  const fenceRe = /^[ \t]*```/gm;
  const matches = [];
  let m;
  while ((m = fenceRe.exec(input)) !== null) {
    matches.push(m);
  }
  if (matches.length % 2 !== 1) return input;
  const lastOpener = matches[matches.length - 1];
  if (!lastOpener) return input;
  const start = lastOpener.index;
  return input.slice(0, start) + input.slice(start).replace(/[^\n]/g, " ");
}
function maskClosedFences(input) {
  const fenceRe = /^[ \t]*```/gm;
  const indices = [];
  let m;
  while ((m = fenceRe.exec(input)) !== null) {
    indices.push(m.index);
  }
  let out = input;
  const pairCount = Math.floor(indices.length / 2);
  for (let i = 0; i < pairCount; i++) {
    const openIdx = indices[i * 2];
    const closeIdx = indices[i * 2 + 1];
    if (openIdx === void 0 || closeIdx === void 0) continue;
    const closeEnd = out.indexOf("\n", closeIdx);
    const regionEnd = closeEnd < 0 ? out.length : closeEnd;
    const before = out.slice(0, openIdx);
    const region = out.slice(openIdx, regionEnd).replace(/[^\n]/g, " ");
    const after = out.slice(regionEnd);
    out = before + region + after;
  }
  return out;
}
function countOutsideMaskedFences(masked, re) {
  const matches = masked.match(re);
  return matches?.length ?? 0;
}
var ESCAPABLE = "\\`*_~[](){}<>#+-.!|";
function maskEscapes(input) {
  let out = "";
  let i = 0;
  while (i < input.length) {
    if (input[i] === "\\" && i + 1 < input.length && ESCAPABLE.includes(input[i + 1] ?? "")) {
      out += "  ";
      i += 2;
      continue;
    }
    out += input[i];
    i++;
  }
  return out;
}
function countBoldItalic(masked) {
  let bold = 0;
  let italic = 0;
  let i = 0;
  while (i < masked.length) {
    const ch = masked[i];
    if (ch !== "*") {
      i++;
      continue;
    }
    let run = 0;
    while (i + run < masked.length && masked[i + run] === "*") run++;
    bold += Math.floor(run / 2);
    italic += run % 2;
    i += run;
  }
  return { boldOdd: bold % 2 === 1, italicAsteriskOdd: italic % 2 === 1 };
}
function countUnderscoreItalic(masked) {
  let count = 0;
  for (let i = 0; i < masked.length; i++) {
    if (masked[i] !== "_") continue;
    const prev = i === 0 ? " " : masked[i - 1];
    const next = i === masked.length - 1 ? " " : masked[i + 1];
    const prevWs = prev === void 0 || /[\s]/.test(prev);
    const nextWs = next === void 0 || /[\s]/.test(next);
    if (prevWs || nextWs) count++;
  }
  return count;
}
var SUPPORTED = /* @__PURE__ */ new Set(["think"]);
function remarkAdmonitions() {
  return (tree) => {
    visit(tree, "blockquote", (node) => {
      const marker = extractMarker(node);
      if (!marker || !SUPPORTED.has(marker.type)) return;
      stripMarkerText(node, marker.length);
      node.data = node.data ?? {};
      node.data.hProperties = {
        ...node.data.hProperties ?? {},
        dataAdmonition: marker.type
      };
    });
  };
}
function extractMarker(bq) {
  const firstChild = bq.children[0];
  if (!firstChild || firstChild.type !== "paragraph") return null;
  const firstText = firstChild.children[0];
  if (!firstText || firstText.type !== "text") return null;
  const match = /^\[!([a-z]+)\]\s*\n?/.exec(firstText.value);
  if (!match) return null;
  const type = match[1];
  if (!type) return null;
  return { type, length: match[0].length };
}
function stripMarkerText(bq, length) {
  const firstChild = isParagraph(bq.children[0]) ? bq.children[0] : void 0;
  if (!firstChild) return;
  const firstText = isText(firstChild.children[0]) ? firstChild.children[0] : void 0;
  if (!firstText) return;
  const stripped = { ...firstText, value: firstText.value.slice(length) };
  if (stripped.value.length === 0) {
    firstChild.children.shift();
  } else {
    firstChild.children[0] = stripped;
  }
}
function isParagraph(node) {
  return node?.type === "paragraph";
}
function isText(node) {
  return node?.type === "text";
}
var SANITIZE_SCHEMA = {
  ...defaultSchema,
  tagNames: [...defaultSchema.tagNames ?? [], "tool-call", "sources"],
  attributes: {
    ...defaultSchema.attributes ?? {},
    "tool-call": ["name", "state", "args", "result"],
    sources: ["data"],
    blockquote: [
      ...(defaultSchema.attributes ?? {}).blockquote ?? [],
      "dataAdmonition"
    ]
  }
};
var COMPONENTS = {
  code: CodeBlockSlot,
  a: CitationOrLinkSlot,
  blockquote: ReasoningOrQuoteSlot,
  "tool-call": ToolCallSlot,
  sources: SourcesSlot
};
function Markdown({ children, className }) {
  const safe = React.useMemo(() => closeUnterminated(children), [children]);
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: cn(
        "prose prose-sm max-w-none text-foreground",
        "prose-headings:text-foreground prose-strong:text-foreground",
        "prose-a:text-primary prose-a:underline-offset-4 hover:prose-a:underline",
        "prose-code:text-foreground prose-code:before:content-none prose-code:after:content-none",
        className
      ),
      children: /* @__PURE__ */ jsx(
        ReactMarkdown,
        {
          remarkPlugins: [remarkGfm, remarkAdmonitions],
          rehypePlugins: [rehypeRaw, [rehypeSanitize, SANITIZE_SCHEMA]],
          components: COMPONENTS,
          children: safe
        }
      )
    }
  );
}
var FOOTNOTE_RE = /^(\d+)$/;
function CitationOrLinkSlot({
  href,
  children,
  className,
  node: _node,
  ...rest
}) {
  const text = extractText(children);
  const footnote = FOOTNOTE_RE.exec(text);
  if (footnote && href) {
    const index = Number(footnote[1]);
    return /* @__PURE__ */ jsx(InlineCitation, { index, url: href, title: inferCitationTitle(href) });
  }
  return /* @__PURE__ */ jsx(
    "a",
    {
      href,
      className: cn(
        "rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
        className
      ),
      ...rest,
      children
    }
  );
}
function extractText(children) {
  if (typeof children === "string") return children;
  if (Array.isArray(children)) return children.map(extractText).join("");
  return "";
}
function inferCitationTitle(href) {
  try {
    const url = new URL(href);
    const hostname = url.hostname.replace(/^www\./, "");
    return hostname.length > 0 ? hostname : href;
  } catch {
    return href;
  }
}
function CodeBlockSlot({ className, children, node: _node, ...rest }) {
  const langMatch = /language-([a-zA-Z0-9-]+)/.exec(className ?? "");
  const isFenced = Boolean(langMatch) || Array.isArray(children) && children.length > 1 || String(children ?? "").includes("\n");
  if (!isFenced) {
    return /* @__PURE__ */ jsx(
      "code",
      {
        className: cn(
          "rounded bg-muted px-[0.3em] py-[0.15em] font-mono text-[0.85em]",
          className
        ),
        ...rest,
        children
      }
    );
  }
  return /* @__PURE__ */ jsx(
    "code",
    {
      className: cn("font-mono text-sm", className),
      "data-fenced": "true",
      ...rest,
      children
    }
  );
}
function ReasoningOrQuoteSlot({
  children,
  className,
  node: _node,
  ...rest
}) {
  if (rest["data-admonition"] === "think") {
    return /* @__PURE__ */ jsx(Reasoning, { children });
  }
  return /* @__PURE__ */ jsx(
    "blockquote",
    {
      className: cn(
        "my-4 border-l-2 border-border pl-4 italic text-muted-foreground",
        className
      ),
      ...rest,
      children
    }
  );
}
var VALID_TOOL_CALL_STATES = {
  pending: true,
  running: true,
  result: true,
  error: true
};
function ToolCallSlot({ name, state, args, result, children, node: _node }) {
  if (!name) return /* @__PURE__ */ jsx(Fragment, { children });
  const parsedState = isToolCallState(state) ? state : "result";
  return /* @__PURE__ */ jsx(
    ToolCall,
    {
      name,
      state: parsedState,
      args: parseJson(args),
      result: parseJson(result)
    }
  );
}
function isToolCallState(value) {
  return typeof value === "string" && value in VALID_TOOL_CALL_STATES;
}
function parseJson(raw) {
  if (raw === void 0 || raw === "") return void 0;
  try {
    return JSON.parse(raw);
  } catch {
    return raw;
  }
}
function SourcesSlot({ data, children, node: _node }) {
  const sources = React.useMemo(() => parseSources(data), [data]);
  if (!sources) return /* @__PURE__ */ jsx(Fragment, { children });
  return /* @__PURE__ */ jsx(Sources, { sources });
}
function parseSources(raw) {
  if (raw === void 0 || raw === "") return null;
  let parsed;
  try {
    parsed = JSON.parse(raw);
  } catch {
    return null;
  }
  if (!Array.isArray(parsed)) return null;
  const result = [];
  for (const item of parsed) {
    if (!item || typeof item !== "object") continue;
    if (!("title" in item) || typeof item.title !== "string") continue;
    const ref = { title: item.title };
    if ("url" in item && typeof item.url === "string") {
      const url = safeUrl(item.url);
      if (url !== void 0) ref.url = url;
    }
    if ("page" in item && typeof item.page === "number") ref.page = item.page;
    if ("index" in item && typeof item.index === "number") ref.index = item.index;
    result.push(ref);
  }
  return result;
}

export { Markdown, closeUnterminated };
//# sourceMappingURL=markdown.js.map
//# sourceMappingURL=markdown.js.map