import type { PureScopedStyleSheet } from "../createStylesheet.js";

const INTENT = 4;

/**
 * Efficiently convert a structured CSS JS object into a plain CSS string.
 */
function objectToCss(rules: PureScopedStyleSheet["rules"], level = 1) {
    const intentStr = " ".repeat(level * INTENT);
    return [...rules.keys()]
        .map((selector) => {
            const definition = rules.get(selector);
            const thisRules = Object.keys(definition);
            const result = thisRules
                .map((rule: string) => {
                    const ruleValue = definition[rule];

                    // Nested scope
                    if (typeof ruleValue === "object") {
                        const m: PureScopedStyleSheet["rules"] = new Map();
                        m.set(rule, ruleValue);
                        return `${intentStr}${objectToCss(m, level + 1)}\n`;
                    } else {
                        return `${intentStr}${rule}:${" ".repeat(1)}${ruleValue};\n`;
                    }
                })
                .join("");
            return `${selector} {\n${result}${level > 1 ? " ".repeat((level - 1) * INTENT) : ""}}`;
        })
        .join("\n");
}

export { objectToCss };
