/**
 * Find the rendered Store List item for an id without interpolating the id into
 * a CSS selector. Store ids supplied by integrations therefore need no CSS
 * escaping merely to participate in map/list coordination.
 */
export const findStoreResult = ( locator, storeId ) => {
	if ( ! locator?.querySelectorAll || storeId == null ) return null;
	const id = String( storeId );
	return Array.from( locator.querySelectorAll( '[data-cliq-store-id]' ) )
		.find( ( node ) => String( node.dataset?.cliqStoreId ?? node.getAttribute?.( 'data-cliq-store-id' ) ) === id ) || null;
};

export const scrollStoreResultIntoView = ( locator, storeId ) => {
	const result = findStoreResult( locator, storeId );
	if ( ! result ) return false;
	result.scrollIntoView?.( {
		behavior: 'smooth',
		block: 'nearest',
		inline: 'nearest',
	} );
	return true;
};

/**
 * Marker selection can also open an accordion/group during the following
 * render. Two animation frames let both selected and reveal state settle
 * before measuring and scrolling the final result item.
 */
export const scheduleStoreResultScroll = ( locator, storeId, win = globalThis ) => {
	const frame = typeof win?.requestAnimationFrame === 'function'
		? win.requestAnimationFrame.bind( win )
		: ( callback ) => win?.setTimeout?.( callback, 0 );
	if ( ! frame ) return;
	frame( () => frame( () => scrollStoreResultIntoView( locator, storeId ) ) );
};
