'use strict';

const REM_VALUE = /(-?(?:\d+|\d*\.\d+))rem\b/g;
const BASE_FONT_SIZE = 16;

function remToPx(value) {
  if (typeof value !== 'string' || !value.includes('rem')) return value;

  return value.replace(REM_VALUE, (_match, rawNumber) => {
    const pixels = Number(rawNumber) * BASE_FONT_SIZE;
    if (!Number.isFinite(pixels)) return _match;
    return `${Number(pixels.toFixed(4))}px`;
  });
}

function asukaRemIsolation() {
  return {
    postcssPlugin: 'asuka-rem-isolation',
    Declaration(declaration) {
      declaration.value = remToPx(declaration.value);
    },
    AtRule(atRule) {
      atRule.params = remToPx(atRule.params);
    },
  };
}

asukaRemIsolation.postcss = true;
asukaRemIsolation.remToPx = remToPx;

module.exports = asukaRemIsolation;
