/**
 * This plugin merges duplicate CSS rules to reduce file size
 * and improve browser rendering performance
 */
const mergeDuplicateRules = (pluginOptions = {}) => {
  return {
    postcssPlugin: 'postcss-merge-duplicate-rules',
    OnceExit(root) {
      const ruleMap = new Map();
      const rulesToRemove = [];

      root.walkRules((rule) => {
        // Skip rules inside @keyframes, @font-face, etc.
        if (rule.parent.type === 'atrule' && ['keyframes', 'font-face'].includes(rule.parent.name)) {
          return;
        }

        const selector = rule.selector;
        const declarations = rule.nodes
          .filter(node => node.type === 'decl')
          .map(decl => `${decl.prop}:${decl.value}`)
          .sort()
          .join(';');

        const ruleKey = `${selector}::${declarations}`;

        if (ruleMap.has(ruleKey)) {
          // Mark duplicate for removal
          rulesToRemove.push(rule);
        } else {
          ruleMap.set(ruleKey, rule);
        }
      });

      // Remove duplicates
      rulesToRemove.forEach(rule => rule.remove());
    },
  };
};

mergeDuplicateRules.postcss = true;

module.exports = mergeDuplicateRules;
