const path = require('path');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = {
  webpack: {
    configure: (webpackConfig, { env, paths }) => {
      // Production optimizations
      if (env === 'production') {
        // Enhanced tree shaking and optimization
        webpackConfig.optimization = {
          ...webpackConfig.optimization,
          usedExports: true,
          sideEffects: false,
          providedExports: true,
          innerGraph: true,
          mangleExports: true,
          concatenateModules: true,
          flagIncludedChunks: true,
          mergeDuplicateChunks: true,
          removeAvailableModules: true,
          removeEmptyChunks: true,
          splitChunks: {
            chunks: 'all',
            minSize: 20000,
            minRemainingSize: 0,
            minChunks: 1,
            maxAsyncRequests: 30,
            maxInitialRequests: 30,
            enforceSizeThreshold: 50000,
            cacheGroups: {
              // React and React-DOM
              react: {
                test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
                name: 'react',
                chunks: 'all',
                priority: 30,
                enforce: true,
              },
              // React Router
              router: {
                test: /[\\/]node_modules[\\/]react-router(-dom)?[\\/]/,
                name: 'router',
                chunks: 'all',
                priority: 25,
              },
              // Testing libraries (should be excluded in production)
              testing: {
                test: /[\\/]node_modules[\\/](@testing-library|jest)[\\/]/,
                name: 'testing',
                chunks: 'all',
                priority: 20,
                enforce: false,
              },
              // Other vendor libraries
              vendor: {
                test: /[\\/]node_modules[\\/]/,
                name: 'vendors',
                chunks: 'all',
                priority: 10,
                minChunks: 1,
              },
              // Common code between components
              common: {
                name: 'common',
                minChunks: 2,
                chunks: 'all',
                priority: 5,
                reuseExistingChunk: true,
                enforce: false,
              },
              // Default group
              default: {
                minChunks: 2,
                priority: -20,
                reuseExistingChunk: true,
              },
            },
          },
          // Minimize and mangle
          minimize: true,
          minimizer: [
            ...webpackConfig.optimization.minimizer,
          ],
        };

        // Enhanced resolve configuration
        webpackConfig.resolve = {
          ...webpackConfig.resolve,
          alias: {
            ...webpackConfig.resolve.alias,
            '@': path.resolve(__dirname, 'src'),
            '@components': path.resolve(__dirname, 'src/components'),
            '@services': path.resolve(__dirname, 'src/services'),
            '@hooks': path.resolve(__dirname, 'src/hooks'),
            '@utils': path.resolve(__dirname, 'src/utils'),
          },
          // Optimize module resolution
          modules: ['node_modules', path.resolve(__dirname, 'src')],
          extensions: ['.js', '.jsx', '.json'],
        };

        // Remove source maps in production for smaller bundles
        webpackConfig.devtool = false;

        // Fix CSS minimizer issues
        if (webpackConfig.optimization && webpackConfig.optimization.minimizer) {
          webpackConfig.optimization.minimizer = webpackConfig.optimization.minimizer.filter(
            minimizer => minimizer.constructor.name !== 'CssMinimizerPlugin'
          );
        }

        // Add bundle analyzer if ANALYZE=true
        if (process.env.ANALYZE === 'true') {
          webpackConfig.plugins.push(
            new BundleAnalyzerPlugin({
              analyzerMode: 'static',
              openAnalyzer: false,
              reportFilename: 'bundle-report.html',
            })
          );
        }
      }

      // Development optimizations
      if (env === 'development') {
        // Faster source maps for development
        webpackConfig.devtool = 'eval-cheap-module-source-map';
        
        // Optimize dev server
        webpackConfig.optimization = {
          ...webpackConfig.optimization,
          removeAvailableModules: false,
          removeEmptyChunks: false,
          splitChunks: {
            chunks: 'all',
            cacheGroups: {
              vendor: {
                test: /[\\/]node_modules[\\/]/,
                name: 'vendors',
                chunks: 'all',
              },
            },
          },
        };
      }

      return webpackConfig;
    },
  },
  babel: {
    plugins: [
      // Remove unused imports in production
      ...(process.env.NODE_ENV === 'production' ? [
        ['babel-plugin-transform-remove-console', { exclude: ['error', 'warn'] }],
      ] : []),
    ],
    presets: [
      [
        '@babel/preset-react',
        {
          // Enable automatic JSX runtime for smaller bundles
          runtime: 'automatic',
        },
      ],
    ],
  },
  devServer: {
    // Optimize dev server
    compress: true,
    hot: true,
    client: {
      overlay: {
        errors: true,
        warnings: false,
      },
    },
  },
};