"use client";
 
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { useT } from "@/components/locale-provider";
 
export type ConsoleValue = {
kind: string;
value?: string;
name?: string;
length?: number;
entries?: { key: string; value: ConsoleValue }[];
truncated?: boolean;
stack?: string;
};
 
function Summary({ node }: { node: ConsoleValue }) {
const entries = node.entries || [];
const array = node.kind === "array";
const prefix = array ? `Array(${node.length ?? entries.length})` : node.name === "Object" ? "" : node.name || "Object";
const open = array ? "[" : "{";
const close = array ? "]" : "}";
const sample = entries.slice(0, 3).map(({ key, value }) => array ? preview(value) : `${key}: ${preview(value)}`).join(", ");
return <span className="console-summary">{prefix && <span className="console-constructor">{prefix} </span>}{open}{sample}{entries.length > 3 || node.truncated ? ", …" : ""}{close}</span>;
}
 
function preview(node: ConsoleValue): string {
if (node.kind === "string") return JSON.stringify(node.value || "").slice(0, 80);
if (node.kind === "array") return `Array(${node.length ?? 0})`;
if (node.kind === "object") return node.name === "Object" ? "{…}" : `${node.name} {…}`;
return (node.value || node.kind).slice(0, 80);
}
 
export function ConsoleValueView({ node, nested = false }: { node: ConsoleValue; nested?: boolean }) {
const t = useT();
const [expanded, setExpanded] = useState(false);
if (node.kind !== "object" && node.kind !== "array") {
const label = node.kind === "string" && nested ? JSON.stringify(node.value || "") : node.value || node.kind;
return <span className={`console-value console-value-${node.kind}`}>{label}</span>;
}
const entries = node.entries || [];
return <span className="console-tree">
<Button type="button" variant="ghost" size="xs" className="justify-start" aria-expanded={expanded} aria-label={expanded ? t("Свернуть объект", "Collapse object") : t("Раскрыть объект", "Expand object")} onClick={() => setExpanded(!expanded)}><span className={`console-arrow ${expanded ? "expanded" : ""}`} /><Summary node={node} /></Button>
{expanded && <span className="console-children">{entries.map(({ key, value }, index) => <span className="console-property" key={`${key}-${index}`}><span className="console-key">{key}: </span><ConsoleValueView node={value} nested /></span>)}{node.truncated && <span className="console-property console-muted">{t("… остальные свойства скрыты", "… remaining properties hidden")}</span>}{entries.length === 0 && <span className="console-property console-muted">{t("Нет свойств", "No properties")}</span>}</span>}
</span>;
}