import _ from 'lodash'
import postcss from 'postcss'
import cloneNodes from '../util/cloneNodes'
import buildMediaQuery from '../util/buildMediaQuery'

export default function(config) {
  return function(css) {
    const screens = config().screens
    const responsiveRules = []
    let finalRules = []

    css.walkAtRules('responsive', atRule => {
      const nodes = atRule.nodes
      responsiveRules.push(...cloneNodes(nodes))
      atRule.before(nodes)
      atRule.remove()
    })

    _.keys(screens).forEach(screen => {
      const mediaQuery = postcss.atRule({
        name: 'media',
        params: buildMediaQuery(screens[screen]),
      })

      mediaQuery.append(
        responsiveRules.map(rule => {
          const cloned = rule.clone()
          cloned.selectors = _.map(rule.selectors, selector => `.${screen}\\:${selector.slice(1)}`)
          return cloned
        })
      )

      finalRules.push(mediaQuery)
    })

    const hasScreenRules = finalRules.some(i => i.nodes.length !== 0)
    if (!hasScreenRules) {
      return
    }

    const includesScreensExplicitly = css.some(
      rule => rule.type === 'atrule' && rule.params === 'screens'
    )

    if (!includesScreensExplicitly) {
      css.append(finalRules)
      return
    }

    css.walkAtRules('tailwind', atRule => {
      if (atRule.params === 'screens') {
        atRule.replaceWith(finalRules)
      }
    })
  }
}

@@ -1004,16 +1004,17 @@
  !== 0)%0A
+%0A
     if (
@@ -1056,20 +1056,18 @@
  %7D%0A%0A    
-cons
+le
 t includ
@@ -1092,59 +1092,72 @@
 y = 
-css.some(%0A      rule =%3E rule.type === 'atrule' && r
+false%0A%0A    css.walkAtRules('tailwind', atRule =%3E %7B%0A      if (atR
 ule.
@@ -1180,214 +1180,162 @@
 ens'
+) %7B
 %0A    
-)%0A%0A    if (!includesScreensExplicitly) %7B%0A      css.append(finalRules)
+    atRule.replaceWith(finalRules)%0A        includesScreensExplicitly = true
 %0A      
-return
+%7D
 %0A    %7D
+)
 %0A%0A    
-css.walkAtRules('tailwind', atRule =%3E %7B%0A      if (atRule.params === 'screens') %7B%0A        atRule.replaceWith
+if (!includesScreensExplicitly) %7B%0A      css.append
 (fin
@@ -1349,23 +1349,27 @@
 )%0A      
-%7D
+return
 %0A    %7D
-)
 %0A  %7D%0A%7D%0A

Allow `@tailwind screens` directive inside an at-rule