export function formatFooterTokens(count: number | undefined): string {
	const n = Number(count) || 0;
	if (n <= 0) return "0";
	if (n < 1000) return String(Math.round(n));
	if (n < 10000) return `${(n / 1000).toFixed(1)}k`;
	if (n < 1_000_000) return `${Math.round(n / 1000)}k`;
	if (n < 10_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
	return `${Math.round(n / 1_000_000)}M`;
}

/** Strip TUI/terminal ANSI and orphaned CSI color codes for web display. */
export function stripAnsi(text: string): string {
	return text
		.replace(/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g, "")
		.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "")
		.replace(/\[(?:\d{1,3};)*\d{0,3}m/g, "")
		.replace(/\s+/g, " ")
		.trim();
}

export function truncateText(text: string, maxLen: number): string {
	const trimmed = text.trim();
	if (trimmed.length <= maxLen) return trimmed;
	return `${trimmed.slice(0, Math.max(0, maxLen - 1))}…`;
}

export function formatTimeAgo(isoStr: string | undefined): string {
	if (!isoStr) return "";
	const d = new Date(isoStr);
	const now = new Date();
	const diffMs = now.getTime() - d.getTime();
	const mins = Math.floor(diffMs / 60000);
	if (mins < 1) return "刚刚";
	if (mins < 60) return `${mins} 分钟前`;
	const hours = Math.floor(mins / 60);
	if (hours < 24) return `${hours} 小时前`;
	const days = Math.floor(hours / 24);
	if (days < 30) return `${days} 天前`;
	return d.toLocaleDateString("zh-CN", { month: "short", day: "numeric" });
}

export function escHtml(s: string): string {
	return s
		.replace(/&/g, "&amp;")
		.replace(/</g, "&lt;")
		.replace(/>/g, "&gt;")
		.replace(/"/g, "&quot;");
}

export function syncViewportHeight(): void {
	const viewportHeight = window.visualViewport?.height || window.innerHeight;
	document.documentElement.style.setProperty("--app-height", `${viewportHeight}px`);
}

export function isTouchLike(): boolean {
	return window.matchMedia("(max-width: 768px)").matches || navigator.maxTouchPoints > 0;
}

let messageIdCounter = 0;
export function nextMessageId(): string {
	messageIdCounter += 1;
	return `msg-${Date.now()}-${messageIdCounter}`;
}
