import { useSyncExternalStore } from "react"
import { messageLog } from "../bridge/sandboxClient.js"

export function DebugMessageLog() {
	const log = useSyncExternalStore(messageLog.subscribe, messageLog.getSnapshot)
	const text = log
		.map(
			entry =>
				`[${entry.timestamp}] ${entry.direction}: ${JSON.stringify(entry.data)}`,
		)
		.join("\n")
	return (
		<pre data-testid="debug-message-log" style={DEBUG_PRE_STYLE}>
			{text || "(no messages yet)"}
		</pre>
	)
}

const DEBUG_PRE_STYLE = {
	margin: 0,
	padding: "8px 12px",
	fontSize: 12,
	fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
	lineHeight: 1.5,
	whiteSpace: "pre-wrap" as const,
	wordBreak: "break-all" as const,
	userSelect: "text" as const,
	background: "#1e1e1e",
	color: "#d4d4d4",
}
