// NOTICE: This file is generated by Rollup. To modify it,
// please instead edit the ESM counterpart and rebuild with Rollup (npm run build).
'use strict';

const resolveNestedSelector = require('postcss-resolve-nested-selector');
const getRuleSelector = require('./getRuleSelector.cjs');
const isStandardSyntaxSelector = require('./isStandardSyntaxSelector.cjs');
const parseSelector = require('./parseSelector.cjs');

/**
 * @typedef {import('postcss-selector-parser').Selector} Selector
 * @typedef {import('postcss-selector-parser').Root} Root
 *
 * @param {import('postcss').Rule} rule
 * @param {import('stylelint').PostcssResult} result
 * @returns {Array<{selector: Selector, resolvedSelectors: Root}>}
 */
function flattenNestedSelectorsForRule(rule, result) {
	const ownAST = parseSelector(getRuleSelector(rule), result, rule);

	if (!ownAST) return [];

	const flattenedSelectors = [];

	for (const selectorAST of ownAST.nodes) {
		const resolvedSelectors = resolveNestedSelector(selectorAST.toString(), rule);

		for (const resolvedSelector of resolvedSelectors) {
			if (!isStandardSyntaxSelector(resolvedSelector)) return [];

			const resolvedRoot = parseSelector(resolvedSelector, result, rule);

			if (!resolvedRoot) {
				continue;
			}

			flattenedSelectors.push({
				selector: selectorAST,
				resolvedSelectors: resolvedRoot,
			});
		}
	}

	return flattenedSelectors;
}

module.exports = flattenNestedSelectorsForRule;
