// Stub for @oh-my-pi/pi-tui — provides minimal UI primitives for pi-coding-agent
// used in Vividra's SDK context. Real TUI rendering is not needed.

export type AutocompleteItem = { label: string; detail?: string; kind?: string };

export interface BoxSymbols {
	topLeft: string;
	topRight: string;
	bottomLeft: string;
	bottomRight: string;
	horizontal: string;
	vertical: string;
	teeDown: string;
	teeUp: string;
	teeLeft: string;
	teeRight: string;
	cross: string;
}

export interface SymbolTheme {
	cursor: string;
	inputCursor: string;
	boxRound: Omit<BoxSymbols, "teeDown" | "teeUp" | "teeLeft" | "teeRight" | "cross">;
	boxSharp: BoxSymbols;
	table: BoxSymbols;
	quoteBorder: string;
	hrChar: string;
	colorSwatch?: string;
	spinnerFrames: string[];
}

export type KeyId = string;
export type Keybinding = string;

export interface KeybindingDefinition {
	modes?: string[];
	key?: string;
	preventDefault?: boolean;
}

export type KeybindingsConfig = Record<string, KeyId | KeyId[] | undefined>;

export class KeybindingsManager {
	constructor() {}
	get(key: string): KeybindingDefinition | undefined { return undefined; }
	all(): Record<string, KeybindingDefinition> { return {}; }
}

export function canonicalKeyId(key: string): string { return key; }
export function addKeyAliases(_keys: Set<string>, _key: KeyId): void {}
export function parseKey(_data: string, _kittyProtocolActive: boolean): string | null { return null; }
export function parseKittySequence(_data: string): ParsedKittyResult | null { return null; }
export function getKeybindings(): KeybindingsManager { return new KeybindingsManager(); }
export function setKeybindings(_manager: KeybindingsManager): void {}

export interface ParsedKittyResult {
	codepoint: number;
	shiftedKey?: number;
	baseLayoutKey?: number;
	modifier: number;
	eventType?: KeyEventType;
}

export enum KeyEventType {
	Press = 1,
	Repeat = 2,
	Release = 3,
}

export function matchesKey(_data: string, _keyId: string, _kittyProtocolActive: boolean): boolean { return false; }
export function matchesKittySequence(_data: string, _expectedCodepoint: number, _expectedModifier: number): boolean { return false; }
export function matchesLegacySequence(_data: string, _keyName: string): boolean { return false; }

export interface FuzzyMatch {
	matches: boolean;
	score: number;
}

export function fuzzyMatch(query: string, text: string): FuzzyMatch {
	const ql = query.toLowerCase();
	const tl = text.toLowerCase();
	let qi = 0;
	let score = 0;
	let last = -1;
	for (let i = 0; i < tl.length && qi < ql.length; i++) {
		if (tl[i] === ql[qi]) {
			if (last >= 0) score += (i - last - 1) * 2;
			if (i === 0 || /[\s\-_./:]/.test(tl[i - 1]!)) score -= 10;
			last = i;
			qi++;
		}
	}
	return { matches: qi === ql.length, score };
}

export function fuzzyFilter<T>(items: T[], query: string, getText: (item: T) => string): T[] {
	if (!query.trim()) return items;
	const tokens = query.trim().split(/\s+/).filter(t => t.length > 0);
	const results: { item: T; totalScore: number }[] = [];
	for (const item of items) {
		const text = getText(item);
		let totalScore = 0;
		let allMatch = true;
		for (const token of tokens) {
			const match = fuzzyMatch(token, text);
			if (match.matches) totalScore += match.score;
			else { allMatch = false; break; }
		}
		if (allMatch) results.push({ item, totalScore });
	}
	results.sort((a, b) => a.totalScore - b.totalScore);
	return results.map(r => r.item);
}

export function padding(n: number): string { return " ".repeat(n); }

export function replaceTabs(text: string, _file?: string): string { return text.replace(/\t/g, "  "); }

export function sliceWithWidth(line: string, startCol: number, length: number, _strict?: boolean | null): SliceResult {
	const text = line.slice(startCol, startCol + length);
	return { text, width: text.length };
}

export function truncateToWidth(text: string, maxWidth: number, _ellipsisKind?: unknown | null, _pad?: boolean | null, _tabWidth?: number): string {
	if (text.length <= maxWidth) return text;
	return text.slice(0, Math.max(0, maxWidth - 1)) + "…";
}

export function visibleWidth(str: string, _tabWidth?: number): number {
	return str.replace(/\x1b\[[0-9;]*m/g, "").length;
}

export function wrapTextWithAnsi(text: string, width: number, _tabWidth?: number): string[] {
	const lines: string[] = [];
	let start = 0;
	while (start < text.length) {
		lines.push(text.slice(start, start + width));
		start += width;
	}
	return lines.length ? lines : [""];
}

export interface SliceResult {
	text: string;
	width: number;
}

export enum Ellipsis {
	Unicode = 0,
	Ascii = 1,
	Omit = 2,
}

export interface ExtractSegmentsResult {
	before: string;
	beforeWidth: number;
	after: string;
	afterWidth: number;
}

export function extractSegments(_line: string, _beforeEnd: number, _afterStart: number, _afterLen: number, _strictAfter: boolean, _tabWidth: number): ExtractSegmentsResult {
	return { before: "", beforeWidth: 0, after: "", afterWidth: 0 };
}

export type TextSizingScale = 1 | 2 | 3;
export type TextSizingVerticalAlign = "top" | "bottom" | "center";
export type TextSizingHorizontalAlign = "left" | "right" | "center";

export interface TextSizingOptions {
	scale?: TextSizingScale;
	widthCells?: number;
	verticalAlign?: TextSizingVerticalAlign;
	horizontalAlign?: TextSizingHorizontalAlign;
}

export function encodeTextSized(text: string, _options?: TextSizingOptions): string { return text; }

// ---------------------------------------------------------------------------
// Component types and stubs
// ---------------------------------------------------------------------------

export type Component = unknown;

export type TUI = unknown;

export type EditorTheme = unknown;
export type MarkdownTheme = unknown;
export type SelectListTheme = unknown;
export type SymbolTheme_Alias = unknown;

// Terminal ID — critical for session-manager.ts:876,898
export function getTerminalId(): string { return process.env.TERM_SESSION_ID ?? process.env.TMUX_PANE ?? "stub-terminal"; }
export const TERMINAL = { id: getTerminalId() };

// ---------------------------------------------------------------------------
// Box component
// ---------------------------------------------------------------------------
export function Box(_props: { children?: unknown; width?: number; height?: number } & Record<string, unknown>): unknown { return null; }

// ---------------------------------------------------------------------------
// CancellableLoader / Loader
// ---------------------------------------------------------------------------
export type Loader = unknown;
export function CancellableLoader(_props: { title?: string } & Record<string, unknown>): unknown { return null; }

// ---------------------------------------------------------------------------
// Container
// ---------------------------------------------------------------------------
export function Container(_props: { children?: unknown; direction?: string; gap?: number } & Record<string, unknown>): unknown { return null; }

// ---------------------------------------------------------------------------
// Editor
// ---------------------------------------------------------------------------
export interface EditorProps {
	onKeystroke?: (key: string) => void;
	onFocus?: () => void;
	onBlur?: () => void;
	text?: string;
	placeholder?: string;
	readonly?: boolean;
	language?: string;
}

export const Editor = (_props: EditorProps): unknown => null;

// ---------------------------------------------------------------------------
// Image
// ---------------------------------------------------------------------------
export type ImageBudget = unknown;
export type ImageProtocol = unknown;
export const Image = (_props: { src?: string; alt?: string; budget?: ImageBudget; protocol?: ImageProtocol; width?: number; height?: number } & Record<string, unknown>): unknown => null;

// ---------------------------------------------------------------------------
// Input
// ---------------------------------------------------------------------------
export const Input = (_props: { value?: string; placeholder?: string; onInput?: (text: string) => void; readonly?: boolean; password?: boolean } & Record<string, unknown>): unknown => null;

// ---------------------------------------------------------------------------
// Markdown
// ---------------------------------------------------------------------------
export function Markdown(_props: { content?: string; theme?: MarkdownTheme } & Record<string, unknown>): unknown { return _props.content ?? ""; }

// ---------------------------------------------------------------------------
// ScrollView
// ---------------------------------------------------------------------------
export function ScrollView(_props: { children?: unknown; offset?: number } & Record<string, unknown>): unknown { return null; }

// ---------------------------------------------------------------------------
// SelectList / SelectItem
// ---------------------------------------------------------------------------
export type SelectItem = { label: string; value?: string; detail?: string };
export function SelectList(_props: { items?: SelectItem[]; selected?: number; onSelect?: (index: number) => void; theme?: SelectListTheme } & Record<string, unknown>): unknown { return null; }

// ---------------------------------------------------------------------------
// SettingsList
// ---------------------------------------------------------------------------
export function SettingsList(_props: { children?: unknown } & Record<string, unknown>): unknown { return null; }

// ---------------------------------------------------------------------------
// Spacer
// ---------------------------------------------------------------------------
export function Spacer(_props?: Record<string, unknown>): unknown { return null; }

// ---------------------------------------------------------------------------
// TabBar
// ---------------------------------------------------------------------------
export function TabBar(_props: { tabs?: string[]; selected?: number; onSelect?: (index: number) => void } & Record<string, unknown>): unknown { return null; }

// ---------------------------------------------------------------------------
// Text
// ---------------------------------------------------------------------------
export function Text(_props: { children?: string; color?: string; bold?: boolean; dim?: boolean; italic?: boolean; underline?: boolean; strikethrough?: boolean;ansi?: string; } & Record<string, unknown>): unknown { return _props.children ?? ""; }

// ---------------------------------------------------------------------------
// TruncatedText
// ---------------------------------------------------------------------------
export function TruncatedText(_props: { text?: string; maxWidth?: number; ellipsis?: string } & Record<string, unknown>): unknown { return _props.text ?? ""; }

// ---------------------------------------------------------------------------
// Editor component interface
// ---------------------------------------------------------------------------
export type EditorComponent = unknown;