// craco.config.js
const prefixSelector = require("postcss-prefix-selector");

const prefixPlugin = prefixSelector({
	prefix: "#arena-scheduler-root",
	transform(prefix, selector) {
		// :root variables → apply directly to #arena-scheduler-root
		if (selector === ":root" || selector === "[data-bs-theme=light]") {
			return prefix;
		}
		if (selector.includes(":root")) {
			return prefix;
		}
		// body resets → apply to #arena-scheduler-root
		if (selector === "body") {
			return prefix;
		}
		if (selector.startsWith("body ")) {
			return prefix + " " + selector.substring(5);
		}
		// Don't double-prefix
		if (selector.includes("#arena-scheduler-root")) {
			return selector;
		}
		// Keyframes should not be prefixed
		if (selector.startsWith("%") || selector.startsWith("from") || selector.startsWith("to")) {
			return selector;
		}
		return prefix + " " + selector;
	},
});

function addPostCSSPlugin(webpackConfig) {
	const rules = webpackConfig.module.rules.find((r) => r.oneOf);
	if (rules) {
		rules.oneOf.forEach((rule) => {
			if (rule.use) {
				rule.use.forEach((loader) => {
					if (
						loader.loader &&
						loader.loader.includes("postcss-loader")
					) {
						const plugins =
							loader.options &&
							loader.options.postcssOptions &&
							loader.options.postcssOptions.plugins;
						if (plugins) {
							plugins.push(prefixPlugin);
						}
					}
				});
			}
		});
	}
	return webpackConfig;
}

module.exports = {
	webpack: {
		configure: (webpackConfig) => {
			webpackConfig.output.filename = "static/js/[name].js";
			webpackConfig.optimization.runtimeChunk = false;
			webpackConfig.optimization.splitChunks = {
				chunks() {
					return false;
				},
			};
			addPostCSSPlugin(webpackConfig);
			return webpackConfig;
		},
	},
	plugins: [
		{
			plugin: {
				overrideWebpackConfig: ({ webpackConfig }) => {
					webpackConfig.plugins[5].options.filename =
						"static/css/[name].css";
					return webpackConfig;
				},
			},
			options: {},
		},
	],
};
