// Make everything *outside* a modal's subtree inert while it's open, so screen
// readers and tab order can't reach the background (focus-trap only covers
// keyboard focus; `inert` also hides the content from assistive tech).
//
// Walks from the node up to <body> and marks every sibling along the path as
// inert, then restores exactly those it changed on teardown. Applying it to a
// `display: contents` wrapper keeps the modal's own backdrop + dialog interactive.
export function modalInert(node: HTMLElement) {
	const changed: HTMLElement[] = [];

	let el: HTMLElement | null = node;
	while (el && el !== document.body) {
		const parent: HTMLElement | null = el.parentElement;
		if (!parent) break;
		for (const sib of Array.from(parent.children)) {
			if (sib !== el && sib instanceof HTMLElement && !sib.hasAttribute('inert')) {
				sib.setAttribute('inert', '');
				changed.push(sib);
			}
		}
		el = parent;
	}

	return {
		destroy() {
			for (const sib of changed) sib.removeAttribute('inert');
		}
	};
}
