function ensureToastRoot(): HTMLElement {
	let root = document.getElementById('stockbeacon-toast-root');
	if (root) return root as HTMLElement;
	root = document.createElement('div');
	root.id = 'stockbeacon-toast-root';
	root.className = 'stockbeacon-toast-root';
	root.setAttribute('aria-live', 'polite');
	root.setAttribute('aria-atomic', 'true');
	document.body.appendChild(root);
	return root as HTMLElement;
}

export function showToast(message: string, tone: 'success' | 'error' | 'warn' = 'success', durationMs = 2600): void {
	if (!message) return;
	const root = ensureToastRoot();
	const safeTone = tone === 'error' || tone === 'warn' ? tone : 'success';
	const defaultDuration = safeTone === 'error' ? 5000 : safeTone === 'warn' ? 3600 : 3000;
	const timeout = Math.max(1600, Number(durationMs) || defaultDuration);

	const toast = document.createElement('div');
	toast.className = 'stockbeacon-toast stockbeacon-toast--' + safeTone;
	const text = document.createElement('div');
	text.className = 'stockbeacon-toast__message';
	text.textContent = String(message);
	const progress = document.createElement('span');
	progress.className = 'stockbeacon-toast__progress';
	progress.style.animationDuration = timeout + 'ms';
	toast.appendChild(text);
	toast.appendChild(progress);
	root.appendChild(toast);

	requestAnimationFrame(() => toast.classList.add('is-visible'));
	window.setTimeout(() => {
		toast.classList.remove('is-visible');
		window.setTimeout(() => toast.parentNode?.removeChild(toast), 220);
	}, timeout);
}
