import type React from "react"; import { useState } from "react"; type JsonValue = string | number | boolean | null | JsonObject | JsonArray; type JsonObject = { [key: string]: JsonValue }; type JsonArray = JsonValue[]; const isJsonString = (str: string): boolean => { if (typeof str !== "string") return false; const trimmed = str.trim(); // Check if it looks like JSON (starts with { or [) if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return false; try { const parsed = JSON.parse(trimmed); // Ensure it's actually an object or array, not just a primitive console.log("JSON parse successful:", parsed); return typeof parsed === "object" && parsed !== null; } catch (error) { console.log("JSON parse failed:", error); return false; } }; const JsonCollapsible: React.FC<{ data: JsonValue; isString?: boolean }> = ({ data, isString = false, }) => { const [isCollapsed, setIsCollapsed] = useState(true); let jsonData: JsonValue; try { jsonData = isString ? JSON.parse(data as string) : data; } catch { // If parsing fails, display as string return (
        {String(data)}
      
); } const isObject = typeof jsonData === "object" && jsonData !== null; if (!isObject) { return {JSON.stringify(jsonData)}; } const keys = Object.keys(jsonData as JsonObject); const preview = Array.isArray(jsonData) ? `[${jsonData.length} items]` : `{${keys.length} keys}`; return (
{!isCollapsed && (
            {JSON.stringify(jsonData, null, 2)}
          
{Array.isArray(jsonData) ? "]" : "}"}
)}
); }; const ResultBlock: React.FC<{ error?: string; result?: unknown }> = ({ error, result, }) => { console.log("ResultBlock component rendered with:", { error, result, type: typeof result, }); const renderContent = () => { console.log("ResultBlock Debug:", { result, type: typeof result, isString: typeof result === "string", isArray: Array.isArray(result), startsWithBracket: typeof result === "string" && result.trim().startsWith("["), isJsonString: typeof result === "string" ? isJsonString(result) : false, }); // Handle objects and arrays directly if (typeof result === "object" && result !== null) { console.log("Rendering as object/array with JsonCollapsible"); return ; } // Handle string that might be JSON if (typeof result === "string") { const trimmed = result.trim(); if (isJsonString(trimmed)) { console.log("Rendering string as JSON with JsonCollapsible"); return ; } } // Fallback to plain text display console.log("Rendering as plain text fallback"); return (
        {String(result)}
      
); }; return (
{error ?

Error: {error}

: null}
{renderContent()}
); }; export default ResultBlock;