// Chat helper functions — parseContent and renderMd

function parseContent(raw) {
  if (!raw) return { segments: [{ type: "text", text: "" }] };
  try {
    const parsed = JSON.parse(raw);
    if (parsed.blocks) {
      const segments = [];
      let toolGroup = [];
      for (const b of parsed.blocks) {
        if (b.type === "tool_use" || b.type === "tool_result") {
          toolGroup.push(b);
        } else {
          if (toolGroup.length > 0) {
            segments.push({ type: "tools", toolCalls: [...toolGroup] });
            toolGroup = [];
          }
          const v = b.text || b.content || "";
          const text = typeof v === "string" ? v : JSON.stringify(v);
          if (text.trim()) segments.push({ type: "text", text });
        }
      }
      if (toolGroup.length > 0) segments.push({ type: "tools", toolCalls: toolGroup });
      if (segments.length === 0) segments.push({ type: "text", text: parsed.text || "" });
      return { segments };
    }
    if (parsed.text) return { segments: [{ type: "text", text: parsed.text }] };
  } catch {}
  return { segments: [{ type: "text", text: raw }] };
}

function renderMd(text) {
  if (!text) return "";
  let html = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  html = html.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) => {
    return `<pre style="background:rgba(128,128,128,0.1);padding:12px;border-radius:4px;overflow-x:auto;font-size:12px;line-height:1.5;margin:8px 0"><code>${code.trim()}</code></pre>`;
  });
  html = html.replace(/((?:^\|.+\|[ ]*$\n?)+)/gm, (tableBlock) => {
    const rows = tableBlock.trim().split("\n").filter(r => r.trim());
    if (rows.length < 2) return tableBlock;
    const isSep = /^\|[\s\-:|]+\|$/.test(rows[1].trim());
    const dataRows = isSep ? [rows[0], ...rows.slice(2)] : rows;
    const parseRow = r => r.replace(/^\|/, "").replace(/\|$/, "").split("|").map(c => c.trim());
    const headerCells = parseRow(dataRows[0]);
    const bodyRows = dataRows.slice(1);
    let tbl = '<table style="border-collapse:collapse;margin:8px 0;font-size:12.5px;width:100%;overflow-x:auto">';
    tbl += "<thead><tr>";
    headerCells.forEach(c => { tbl += `<th style="border:1px solid rgba(128,128,128,0.3);padding:6px 10px;text-align:left;font-weight:600">${c}</th>`; });
    tbl += "</tr></thead><tbody>";
    bodyRows.forEach(r => {
      const cells = parseRow(r);
      tbl += "<tr>";
      cells.forEach(c => { tbl += `<td style="border:1px solid rgba(128,128,128,0.2);padding:5px 10px">${c}</td>`; });
      tbl += "</tr>";
    });
    tbl += "</tbody></table>";
    return tbl;
  });
  html = html.replace(/`([^`]+)`/g, '<code style="background:rgba(128,128,128,0.15);padding:1px 4px;border-radius:3px;font-size:12px">$1</code>');
  html = html.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
  html = html.replace(/\*(.+?)\*/g, "<em>$1</em>");
  html = html.replace(/^### (.+)$/gm, '<div style="font-size:14px;font-weight:600;margin:12px 0 4px">$1</div>');
  html = html.replace(/^## (.+)$/gm, '<div style="font-size:15px;font-weight:600;margin:14px 0 6px">$1</div>');
  html = html.replace(/^# (.+)$/gm, '<div style="font-size:17px;font-weight:700;margin:16px 0 8px">$1</div>');
  html = html.replace(/^- (.+)$/gm, '<div style="padding-left:16px;margin:2px 0">&#x2022; $1</div>');
  html = html.replace(/^(\d+)\. (.+)$/gm, '<div style="padding-left:16px;margin:2px 0">$1. $2</div>');
  html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" style="color:inherit;text-decoration:underline">$1</a>');
  html = html.replace(/\n{3,}/g, "\n\n");
  html = html.replace(/\n\n(?!<\/?(pre|code|div|table|thead|tbody|tr|th|td))/g, '<div style="margin:8px 0"></div>');
  html = html.replace(/\n(?!<\/?(pre|code|div|table|thead|tbody|tr|th|td))/g, "<br>");
  return html;
}

window.parseContent = parseContent;
window.renderMd = renderMd;
