/// <reference types="vitest" />
import { defineConfig, type Plugin } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
import { visualizer } from 'rollup-plugin-visualizer'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const isProduction = mode === 'production'

  return {
    plugins: [
      react(),
      // Bundle analyzer for production builds
      (isProduction && visualizer({
        filename: 'dist/bundle-analysis.html',
        open: false,
        gzipSize: true,
        brotliSize: true,
      })) as Plugin,
    ].filter(Boolean),
    test: {
      globals: true,
      environment: 'jsdom',
      setupFiles: './src/setupTests.ts',
      css: true,
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '@components': path.resolve(__dirname, './src/components'),
        '@features': path.resolve(__dirname, './src/features'),
        '@services': path.resolve(__dirname, './src/services'),
        '@hooks': path.resolve(__dirname, './src/hooks'),
        '@utils': path.resolve(__dirname, './src/utils'),
        '@types': path.resolve(__dirname, './src/types'),
      },
    },
    server: {
      port: 5173,
      host: true
    },
    build: {
      outDir: 'dist_verification',
      sourcemap: isProduction ? 'hidden' : true,
      target: 'esnext',
      minify: 'esbuild',
      rollupOptions: {
        output: {
          manualChunks: (id) => {
            // Core Vendors
            if (id.includes('node_modules/react/') ||
              id.includes('node_modules/react-dom/') ||
              id.includes('node_modules/react/jsx-runtime')) {
              return 'vendor-react';
            }
            if (id.includes('node_modules')) {
              if (id.includes('react-router')) return 'vendor-router';
              if (id.includes('@tanstack')) return 'vendor-tanstack';
              if (id.includes('lucide-react')) return 'vendor-icons';
              if (id.includes('date-fns')) return 'vendor-utils';
              if (id.includes('zod')) return 'vendor-utils';
              return 'vendor'; // Default vendor chunk
            }
          },
        },
      },
      chunkSizeWarningLimit: 1000,
    },
    // Standard optimization settings usually work best
    optimizeDeps: {
      include: ['react', 'react-dom']
    },
  }
})