import type { Component } from "./tui.js";

/**
 * Run `component.render(width)` and return a single fallback line if it throws.
 *
 * Purpose: prevent one broken component or overlay from blanking the entire TUI;
 * surface the error in-band for debugging.
 */
export function tryRender(
	component: Pick<Component, "render">,
	width: number,
	context?: string,
): string[] {
	try {
		return component.render(width);
	} catch (err) {
		const msg = err instanceof Error ? err.message : String(err);
		const tag = context ? ` (${context})` : "";
		if (process.env.NO_COLOR === "1") {
			return [`⚠ Render error${tag}: ${msg}`];
		}
		return [`\x1b[31m⚠ Render error${tag}: ${msg}\x1b[0m`];
	}
}
