const fs = require('fs');
const path = require('path');
const postcss = require('postcss');
const tailwindcss = require('tailwindcss');
const cssnano = require('cssnano');

const pluginRoot = path.resolve(__dirname, '..');
const inputPath = path.join(__dirname, 'tailwind-entry.css');
const outputPath = path.join(pluginRoot, 'assets/css/nexdirectory-tailwind-compiled.css');

const config = {
  important: '.nxd-ui',
  corePlugins: {
    preflight: false,
  },
  content: [
    path.join(pluginRoot, 'templates/**/*.php'),
    path.join(pluginRoot, 'includes/**/*.php'),
    path.join(pluginRoot, 'assets/js/*.js'),
    path.join(pluginRoot, 'nexdirectory.php'),
  ],
  theme: {
    extend: {
      fontFamily: {
        sans: ['Inter', 'sans-serif'],
      },
      colors: {
        brand: {
          50: 'color-mix(in srgb, var(--nexdirectory-primary) 8%, #ffffff)',
          100: 'color-mix(in srgb, var(--nexdirectory-primary) 14%, #ffffff)',
          200: 'color-mix(in srgb, var(--nexdirectory-primary) 24%, #ffffff)',
          300: 'color-mix(in srgb, var(--nexdirectory-primary) 36%, #ffffff)',
          400: 'color-mix(in srgb, var(--nexdirectory-primary) 52%, #ffffff)',
          500: 'var(--nexdirectory-primary)',
          600: 'var(--nexdirectory-primary-hover)',
          700: 'color-mix(in srgb, var(--nexdirectory-primary-hover) 80%, #000000)',
          800: 'color-mix(in srgb, var(--nexdirectory-primary-hover) 64%, #000000)',
          900: 'color-mix(in srgb, var(--nexdirectory-primary-hover) 48%, #000000)',
        },
      },
    },
  },
  plugins: [
    function addNexDirectoryUtilities({ addUtilities }) {
      addUtilities({
        '.scrollbar-hide': {
          '-ms-overflow-style': 'none',
          'scrollbar-width': 'none',
          '&::-webkit-scrollbar': { display: 'none' },
        },
      });
    },
  ],
};

const scopeTailwindDefaults = {
  postcssPlugin: 'scope-nexdirectory-tailwind-defaults',
  Rule(rule) {
    const selectors = Array.isArray(rule.selectors)
      ? rule.selectors.map((selector) => selector.trim())
      : [];

    if (selectors.length > 0 && selectors.every((selector) => ['*', '::before', '::after'].includes(selector))) {
      rule.selectors = [
        '.nxd-ui',
        '.nxd-ui *',
        '.nxd-ui ::before',
        '.nxd-ui ::after',
      ];
      return;
    }

    if (selectors.length === 1 && selectors[0] === '::backdrop') {
      rule.selector = '.nxd-ui ::backdrop';
      return;
    }

    if (selectors.length > 0 && selectors.every((selector) => selector === '.container' || selector === '.\\!container')) {
      rule.selectors = selectors.map((selector) => `.nxd-ui ${selector}`);
    }
  },
};

const source = fs.readFileSync(inputPath, 'utf8');

postcss([
  tailwindcss(config),
  scopeTailwindDefaults,
  cssnano({ preset: 'default' }),
])
  .process(source, { from: inputPath, to: outputPath })
  .then((result) => {
    fs.writeFileSync(outputPath, result.css);
    process.stdout.write(`${outputPath}\n${Buffer.byteLength(result.css)} bytes\n`);
  })
  .catch((error) => {
    process.stderr.write(`${error.stack || error}\n`);
    process.exitCode = 1;
  });
