/*! © 2026 Yahoo, Inc. UDS Tailwind and Purger v0.0.0-development */
import { hasAllowedEntryFileExtension } from "../utils/entryPoints.js";
import { iconPruneVarsSafelist } from "../icons/src/safelist.js";
import { tailwindPlugin } from "../plugin.js";
import { optimizeCSS } from "../utils/optimizeCSS.js";
import { preserveVars, preserveVarsCleanup } from "../utils/postcssPreserveVars.js";
import { fixScopedColorModeSelectorsPlugin } from "./postcss.js";
import { formatBytes } from "./utils.js";
import path from "node:path";
import postcss from "postcss";
import autoprefixer from "autoprefixer";
import pruneVar from "postcss-prune-var";
import postcssScope from "postcss-scope";
import tailwindcss from "tailwindcss";

//#region src/css/generate.helpers.ts
const getPruneVarSafelist = (cssOptions) => {
	const pruneVars = cssOptions?.optimization?.pruneVars;
	const configuredSafelist = pruneVars && typeof pruneVars === "object" ? pruneVars.safelist ?? [] : [];
	return [...iconPruneVarsSafelist, ...configuredSafelist];
};
const getCssFeatureFlags = (cssOptions) => {
	const optimizationConfig = cssOptions?.optimization;
	const shouldOptimize = optimizationConfig?.enabled !== false;
	const pruneVars = optimizationConfig?.pruneVars;
	return {
		enablePreflight: cssOptions?.preflight !== false,
		enableFontFaceDeclarations: cssOptions?.fontFaceDeclarations !== false,
		shouldOptimize,
		shouldPruneVars: shouldOptimize && pruneVars !== false
	};
};
const getContentGlobs = (contentDir) => {
	return (Array.isArray(contentDir) ? contentDir : [contentDir]).map((dir) => hasAllowedEntryFileExtension(dir) ? dir : path.join(dir, "**/*.{js,jsx,ts,tsx}"));
};
const getRawContentEntries = (rawContents) => rawContents.map((rawContent) => ({
	raw: rawContent,
	extension: "html"
}));
const createTailwindPlugin = (options) => {
	return tailwindcss({
		content: [...getContentGlobs(options.contentDir), ...getRawContentEntries(options.rawContents ?? [])],
		safelist: options.safelist,
		corePlugins: { preflight: options.enablePreflight },
		plugins: [tailwindPlugin({
			config: options.config,
			disableFontFaceDeclarations: !options.enableFontFaceDeclarations,
			ignorePluginSafelists: true
		})]
	});
};
const getPruneVarPlugins = (safeVarPrefixes) => {
	if (safeVarPrefixes.length === 0) return [pruneVar()];
	return [
		preserveVars({ preserve: safeVarPrefixes }),
		pruneVar(),
		preserveVarsCleanup()
	];
};
const buildPostcssPlugins = (options) => {
	const plugins = [options.tailwindPlugin, autoprefixer()];
	if (options.shouldPruneVars) plugins.push(...getPruneVarPlugins(options.safeVarPrefixes));
	if (options.scopeClass) plugins.push(postcssScope(options.scopeClass));
	return plugins;
};
const applyScopedColorModeFix = async (css, scopeClass) => {
	if (!scopeClass) return css;
	return (await postcss([fixScopedColorModeSelectorsPlugin(scopeClass)]).process(css, { from: void 0 })).css;
};
const optimizeGeneratedCss = async (options) => {
	if (!options.shouldOptimize) return { css: options.css };
	const optimizationOptions = {
		removeUnusedFonts: options.optimizationConfig?.removeUnusedFonts,
		removeEmptyRules: options.optimizationConfig?.removeEmptyRules,
		aggregateDuplicateSelectors: options.optimizationConfig?.aggregateDuplicateSelectors,
		referenceCss: options.referenceCss,
		scopeClass: options.scopeClass
	};
	const optimized = await optimizeCSS(options.css, optimizationOptions);
	return {
		css: optimized.css,
		optimizationStats: {
			originalSize: optimized.stats.originalSize,
			originalSizeGzip: optimized.stats.originalSizeGzip,
			fontFacesRemoved: optimized.stats.fontFacesRemoved,
			emptyRulesRemoved: optimized.stats.emptyRulesRemoved,
			validationErrors: optimized.validation.errors
		}
	};
};
const printSimpleModeStats = (options) => {
	const { print, magenta, cyan, yellow } = options;
	print("");
	print(`${magenta("Output:")} ${cyan(options.outputPath)}`);
	print(`${magenta("Stats:")}`);
	print(`   Files scanned: ${options.totalFilesScanned}`);
	print(`   Classes: ${options.classCount}`);
	print(`   Size: ${formatBytes(options.sizeBytes)} (${formatBytes(options.sizeGzipBytes)} gzipped)`);
	const optimizationStats = options.optimizationStats;
	if (optimizationStats) {
		const savedBytesGzip = optimizationStats.originalSizeGzip - options.sizeGzipBytes;
		if (savedBytesGzip > 0) print(`   Optimized: saved ${formatBytes(savedBytesGzip)} gzip (${optimizationStats.fontFacesRemoved} unused @font-face, ${optimizationStats.emptyRulesRemoved} empty rules removed)`);
		if (optimizationStats.validationErrors.length > 0) {
			print(`   ${yellow("Validation warnings:")}`);
			optimizationStats.validationErrors.forEach((error) => print(`      ${yellow("•")} ${error}`));
		}
	}
	print(`   Time: ${options.duration}ms`);
	if (options.scope) print(`   Scope: ${cyan(options.scope)}`);
};

//#endregion
export { applyScopedColorModeFix, buildPostcssPlugins, createTailwindPlugin, getCssFeatureFlags, getPruneVarSafelist, optimizeGeneratedCss, printSimpleModeStats };
//# sourceMappingURL=generate.helpers.js.map