import { basename, extname } from 'node:path';
import cssPlugin from 'esbuild-plugin-react18-css';
// import svgPlugin from 'esbuild-plugin-svgr';
import { glob } from 'glob';
import { defineConfig } from 'tsup';

const entry = glob.sync('./src/components/**/*.{ts,tsx}').reduce(
  (acc, file) => {
    if (file.split('/').length > 3) {
      const name = basename(file.split('/')[3], extname(file)) ?? undefined;
      const folder = file.split('/')[2] ?? undefined;
      acc[`components/${folder}/${name}`] = file;
      return acc;
    }
    return acc;
  },
  {
    index: './src/index.ts',
    'icons/index': './src/icons/index.tsx',
    'styles/index': './src/styles/index.ts',
  },
);

export default defineConfig((options) => ({
  entry,
  format: ['cjs', 'esm'],
  dts: true,
  treeshake: true,
  metafile: true,
  splitting: false,
  bundle: true,
  minify: !options.watch,
  minifyWhitespace: !options.watch,
  sourcemap: true,
  clean: true,
  injectStyle: false,
  loader: {
    '.css': 'copy',
    '.svg': 'copy',
    '.png': 'copy',
  },
  external: ['react'],
  platform: 'node',
  plugins: [
    cssPlugin(),
    // svgPlugin({
    //   typescript: true,
    // }),
  ],
  ...options,
}));
