import bundleAnalyzer from '@next/bundle-analyzer';

const withBundleAnalyzer = bundleAnalyzer({ enabled: process.env.ANALYZE === 'true' });

/** @type {import('next').NextConfig} */
const baseConfig = {
  output: 'standalone',
  // Enable compression for better performance
  compress: true,
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "api.telegram.org",
      },
      {
        protocol: "https",
        hostname: "telegram.org",
      },
      ...(process.env.API_HOSTNAME ? [{
        protocol: "https",
        hostname: process.env.API_HOSTNAME,
      }] : []),
    ],
  },
  async rewrites() {
    const apiBaseUrl = process.env.API_BASE_URL;

    if (!apiBaseUrl || apiBaseUrl === 'undefined') {
      console.warn('⚠️  API_BASE_URL not set! Set it to your backend domain');
      console.warn('⚠️  Using localhost fallback - this will fail in production!');
      return [
        {
          source: '/api/:path*',
          destination: 'http://localhost:3001/api/:path*',
        },
      ];
    }

    console.log(`🔗 API rewrites pointing to: ${apiBaseUrl}`);
    return [
      {
        source: '/api/:path*',
        destination: `${apiBaseUrl}/api/:path*`,
      },
    ];
  },
  compiler: {
    removeConsole: process.env.NODE_ENV === 'production' ? {
      exclude: ['error', 'warn'],
    } : false,
  },
  poweredByHeader: false,
  // Modularize imports for better tree-shaking (only for libraries that benefit from it)
  modularizeImports: {
    // date-fns: function-level imports for better tree-shaking
    'date-fns': {
      transform: 'date-fns/{{member}}',
    },
  },
  // Enhanced webpack config for better bundle splitting
  webpack: (config, { isServer, dev }) => {
    if (!isServer && !dev) {
      // Enhanced code splitting for better performance
      config.optimization = {
        ...config.optimization,
        moduleIds: 'deterministic',
        splitChunks: {
          chunks: 'all',
          cacheGroups: {
            default: false,
            vendors: false,
            // Separate React and related libraries
            react: {
              test: /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/,
              name: 'react',
              chunks: 'all',
              priority: 50,
              enforce: true,
            },
            // Separate UI library components
            radix: {
              test: /[\\/]node_modules[\\/]@radix-ui[\\/]/,
              name: 'radix-ui',
              chunks: 'all',
              priority: 40,
            },
            // Separate charting libraries
            charts: {
              test: /[\\/]node_modules[\\/](recharts|d3-.*)[\\/]/,
              name: 'charts',
              chunks: 'all',
              priority: 35,
            },
            // Separate icon libraries
            icons: {
              test: /[\\/]node_modules[\\/]lucide-react[\\/]/,
              name: 'icons',
              chunks: 'all',
              priority: 30,
            },
            // Separate date utilities
            dateUtils: {
              test: /[\\/]node_modules[\\/]date-fns[\\/]/,
              name: 'date-utils',
              chunks: 'all',
              priority: 25,
            },
            // Separate form libraries
            forms: {
              test: /[\\/]node_modules[\\/](react-hook-form|@hookform)[\\/]/,
              name: 'forms',
              chunks: 'all',
              priority: 20,
            },
            // Group remaining vendor libraries
            vendor: {
              test: /[\\/]node_modules[\\/]/,
              name: 'vendor',
              chunks: 'all',
              priority: 10,
              enforce: true,
            },
            // Common application code
            common: {
              name: 'common',
              minChunks: 3,
              priority: 5,
            },
          },
        },
      };
    }
    return config;
  },
  productionBrowserSourceMaps: false,
  typescript: {
    ignoreBuildErrors: true,
  },
  // Turbopack configuration for optimal bundle sizes
  // Turbopack automatically handles code splitting and tree-shaking
  turbopack: {},
};

const nextConfig = withBundleAnalyzer(baseConfig);

export default nextConfig;
