import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import resolve from '@rollup/plugin-node-resolve';
import terser from '@rollup/plugin-terser';
import typescript from '@rollup/plugin-typescript';
import autoprefixer from 'autoprefixer';
import atImport from 'postcss-import';
import copy from 'rollup-plugin-copy';
import postcss from 'rollup-plugin-postcss';
import reactSvg from 'rollup-plugin-react-svg';
import replace from 'rollup-plugin-replace';
import versionInjector from 'rollup-plugin-version-injector';
import svgs from 'svg-slim';

const { NODE_ENV: targetEnv = 'development' } = process.env;
const outDirBase = '../html_ui';
const panelDirBase = `${outDirBase}/InGamePanels/pdf-reader-panel`;

function svgSlim(code, id) {
  if (!id.endsWith('.svg')) return code;
  return svgs(code.toString(), {}).then((res) => res);
}

export default {
  input: 'src/index.ts',
  output: {
    dir: panelDirBase,
    format: 'es',
    sourcemap: targetEnv !== 'production',
  },
  plugins: [
    replace({
      'process.env.NODE_ENV': JSON.stringify(targetEnv),
      'import.meta.env': true,
      'import.meta.env.MODE': JSON.stringify(targetEnv),
    }),
    versionInjector(),
    postcss({
      plugins: [autoprefixer(), atImport()],
      extract: true,
      use: ['sass'],
      sourceMap: 'inline',
      minimize: targetEnv === 'production',
    }),
    reactSvg(),
    resolve(),
    json(),
    typescript(),
    commonjs({
      requireReturnsDefault: 'auto',
    }),
    targetEnv === 'production' && terser(),
    copy({
      targets: [
        { src: ['src/assets/*', '!**/*.svg'], dest: `${panelDirBase}/assets` },
        { src: 'src/assets/img/*', dest: `${panelDirBase}/assets/img`, transform: svgSlim },
        { src: ['src/index.html'], dest: `${panelDirBase}` },
        {
          src: ['src/assets/ICON_PDF_READER.svg'],
          dest: [`${outDirBase}/icons/toolbar`, `${outDirBase}/Textures/Menu/toolbar`],
          transform: svgSlim,
        },
      ],
    }),
  ],
  onwarn: function (warning, warn) {
    if (warning.code === 'MODULE_LEVEL_DIRECTIVE') {
      return;
    }
    warn(warning);
  },
};
