import { useChatContext } from "../../context/ChatContext";
import { formatFooterTokens } from "../../utils/format";
import styles from "./SessionContextBar.module.css";

export function SessionContextBar() {
	const { sessionState, isStreaming } = useChatContext();
	const data = sessionState;

	if (!data || data.error || !data.stats || !data.model) {
		return null;
	}

	const liveStreaming = isStreaming || data.isStreaming;
	if (liveStreaming || data.isCompacting) {
		return null;
	}

	const cx = data.stats.contextUsage;
	const cw = cx?.contextWindow ?? data.model.contextWindow ?? 0;
	if (!cw) return null;

	const pctRaw = cx?.percent;
	const pctStr = pctRaw != null ? Number(pctRaw).toFixed(1) : "?";
	const pctNum = pctRaw != null ? Number(pctRaw) : null;
	const autoInd = data.autoCompactionEnabled ? " auto" : "";
	const ctxTxt =
		pctStr === "?"
			? `?/${formatFooterTokens(cw)}${autoInd}`
			: `${pctStr}%/${formatFooterTokens(cw)}${autoInd}`;

	let ctxClass = styles.ctxChip;
	if (pctNum != null) {
		if (pctNum > 90) ctxClass = `${styles.ctxChip} ${styles.ctxDanger}`;
		else if (pctNum > 70) ctxClass = `${styles.ctxChip} ${styles.ctxWarn}`;
	}

	return (
		<div className={styles.bar}>
			<span className={ctxClass} title="上下文占用">{ctxTxt}</span>
		</div>
	);
}
