// Focus management for modals/sheets. On mount: focuses the first focusable
// (or the node itself) and stores the previously-focused element. Tab/Shift+Tab
// wrap inside the node. Escape calls `onclose` when set. On destroy: restores
// focus to the originating element so screen-reader / keyboard users land back
// where they were.

import type { ActionReturn } from 'svelte/action';

export interface FocusTrapOptions {
	onclose?: () => void;
	closeOnEscape?: boolean;
	/** When true, focus the first focusable on mount. Defaults true. */
	autoFocus?: boolean;
}

const FOCUSABLE =
	'a[href], area[href], input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';

function focusables(root: HTMLElement): HTMLElement[] {
	// `offsetParent` is null for any `position: fixed` element (and our sheets/modals
	// are fixed), so it would wrongly drop their buttons. `getClientRects().length`
	// is true whenever the element is actually rendered — fixed or not.
	return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
		(el) => !el.hasAttribute('disabled') && el.getClientRects().length > 0
	);
}

export function focusTrap(
	node: HTMLElement,
	options: FocusTrapOptions = {}
): ActionReturn<FocusTrapOptions> {
	let opts = options;
	const previouslyFocused = (
		typeof document !== 'undefined' ? document.activeElement : null
	) as HTMLElement | null;

	function onKeyDown(e: KeyboardEvent) {
		if (e.key === 'Escape' && opts.closeOnEscape !== false && opts.onclose) {
			e.preventDefault();
			opts.onclose();
			return;
		}
		if (e.key !== 'Tab') return;
		const list = focusables(node);
		if (list.length === 0) {
			e.preventDefault();
			node.focus();
			return;
		}
		const first = list[0];
		const last = list[list.length - 1];
		const active = document.activeElement as HTMLElement | null;
		if (e.shiftKey) {
			if (active === first || !node.contains(active)) {
				e.preventDefault();
				last.focus();
			}
		} else {
			if (active === last) {
				e.preventDefault();
				first.focus();
			}
		}
	}

	node.addEventListener('keydown', onKeyDown);

	if (opts.autoFocus !== false) {
		// Focus the container synchronously on mount so the trap owns the keyboard
		// immediately — otherwise an Escape pressed before the deferred focus below
		// lands on an element *outside* the node, where this node-scoped listener
		// never sees it (the keystroke is silently dropped). Then defer one frame to
		// move focus onto the first control once the sheet has laid out / animated in.
		if (!node.hasAttribute('tabindex')) node.setAttribute('tabindex', '-1');
		node.focus({ preventScroll: true });
		requestAnimationFrame(() => {
			const list = focusables(node);
			const target = list[0] ?? node;
			target.focus({ preventScroll: true });
		});
	}

	return {
		update(newOptions) {
			opts = newOptions;
		},
		destroy() {
			node.removeEventListener('keydown', onKeyDown);
			if (previouslyFocused && typeof previouslyFocused.focus === 'function') {
				try {
					previouslyFocused.focus({ preventScroll: true });
				} catch {
					/* element may have unmounted */
				}
			}
		}
	};
}
