const _ = require('lodash');
const postcss = require('postcss');
const cssnext = require('postcss-cssnext');

function defaultOptions() {
  return {
    breakpoints: {
      sm: '576px',
      md: '768px',
      lg: '992px',
      xl: '1200px',
    },
  }
}

function findMixin(css, mixin) {
  let match;

  css.walkRules((rule) => {
    if (_.trimStart(rule.selector, '.') === mixin) {
      match = rule
      return false
    }
  })

  return match.clone().nodes
}

function addCustomMediaQueries(css, breakpoints) {
  Object.keys(breakpoints).forEach(breakpoint => {
    const variableName = `--breakpoint-${breakpoint}`
    const mediaQuery = `(min-width: ${breakpoints[breakpoint]})`
    const rule = postcss.atRule({
      name: 'custom-media',
      params: `${variableName} ${mediaQuery}`
    })
    css.prepend(rule)
  })
}

function substituteClassMixins(css) {
  css.walkRules(function (rule) {
    rule.walkAtRules('class', atRule => {
      const mixins = _.trim(atRule.params, ` "'`).split(' ')
      const decls = _.flatMap(mixins, (mixin) => {
        return findMixin(css, mixin)
      })

      rule.insertBefore(atRule, decls)
      atRule.remove()
    })
  })
}

module.exports = postcss.plugin('tailwind', function (options) {
  return function (css) {
    options = options || defaultOptions()

    addCustomMediaQueries(css, options.breakpoints)

    // Generate utilities
    // css.

    substituteClassMixins(css)

    // return cssnext.process(css)
  }
})

@@ -513,16 +513,367 @@
 ints) %7B%0A
+  function buildMediaQuery(breakpoint) %7B%0A    if (_.isString(breakpoint)) %7B%0A      breakpoint = %7B min: breakpoint %7D%0A    %7D%0A    return _(breakpoint).toPairs().map((%5Bfeature, value%5D) =%3E %7B%0A      feature = _.get(%7B%0A        min: 'min-width',%0A        max: 'max-width',%0A      %7D, feature, feature)%0A%0A      return %60($%7Bfeature%7D: $%7Bvalue%7D)%60%0A    %7D).join(' and ')%0A  %7D%0A%0A
   Object
@@ -996,23 +996,24 @@
 y = 
-%60(min-width: $%7B
+buildMediaQuery(
 brea
@@ -1031,19 +1031,17 @@
 akpoint%5D
-%7D)%60
+)
 %0A    con

Add support for object based custom media queries