import type { AtRule, Plugin, Rule } from "postcss";

/** Selectors that name the document root; they become the scope element. */
const ROOT_SELECTOR = /^(?:html|body|:root|:host)(?![\w-])/;

function scopeSelector(selector: string, scope: string): string {
  const s = selector.trim();
  if (ROOT_SELECTOR.test(s)) return s.replace(ROOT_SELECTOR, scope);
  return `${scope} ${s}`;
}

type Parent = Rule["parent"];

function* ancestors(rule: Rule): Generator<NonNullable<Parent>> {
  for (let p: Parent = rule.parent; p; p = p.parent as Parent) yield p;
}

const insideKeyframes = (rule: Rule): boolean =>
  [...ancestors(rule)].some(
    (p) => p.type === "atrule" && /keyframes$/i.test((p as AtRule).name),
  );

const nestedInRule = (rule: Rule): boolean =>
  [...ancestors(rule)].some((p) => p.type === "rule");

const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

/**
 * Confines a stylesheet to one element, for CSS shipped into a page we do not
 * own (wp-admin):
 * - every selector is prefixed with `scope`; one naming the document root
 *   (`html`, `body`, `:root`, `:host`) becomes `scope` itself, so the theme's
 *   custom properties and preflight's root rules land on the scope element;
 * - cascade layers are flattened, in place. Unlayered CSS beats layered CSS
 *   whatever the specificity, and the page's own CSS is unlayered, so a
 *   layered utility would lose to any bare `select { … }` in wp-admin;
 * - keyframes are renamed with `keyframePrefix`, and every `animation`,
 *   `animation-name` and custom property that names them follows, because
 *   keyframe names are global whatever their selectors.
 *
 * Keyframe steps and rules nested in another rule (scoped through their
 * parent) are left alone. `@property` registrations stay global: they cannot
 * be scoped, and Tailwind's are identical in every Tailwind 4 build.
 */
export function scopeCss(scope: string, keyframePrefix: string): Plugin {
  return {
    postcssPlugin: "accessibit-scope-css",
    OnceExit(root) {
      root.walkAtRules("layer", (atRule) => {
        if (atRule.nodes) atRule.replaceWith(atRule.nodes);
        else atRule.remove();
      });
      root.walkRules((rule) => {
        if (insideKeyframes(rule) || nestedInRule(rule)) return;
        rule.selectors = [
          ...new Set(rule.selectors.map((s) => scopeSelector(s, scope))),
        ];
      });

      const names = new Set<string>();
      root.walkAtRules(/keyframes$/i, (atRule) => {
        names.add(atRule.params.trim());
        atRule.params = `${keyframePrefix}${atRule.params.trim()}`;
      });
      if (names.size === 0) return;
      const name = new RegExp(
        `(^|[\\s,(])(${[...names].map(escapeRegExp).join("|")})(?=$|[\\s,)])`,
        "g",
      );
      root.walkDecls((decl) => {
        if (/^(?:animation|animation-name|--.*)$/i.test(decl.prop)) {
          decl.value = decl.value.replace(name, `$1${keyframePrefix}$2`);
        }
      });
    },
  };
}
