import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  
  build: {
    // Output to assets/dist/admin
    outDir: '../assets/dist/admin',
    emptyOutDir: true,
    
    // Generate manifest for PHP
    manifest: true,
    
    rollupOptions: {
      input: path.resolve(__dirname, 'src/index.tsx'),
      output: {
        // IIFE format for WordPress compatibility
        format: 'iife',
        // Consistent filenames (no hash for main file)
        entryFileNames: 'boostbot-admin.js',
        chunkFileNames: 'chunks/[name]-[hash].js',
        assetFileNames: (assetInfo) => {
          // CSS file without hash
          if (assetInfo.name?.endsWith('.css')) {
            return 'boostbot-admin.css'
          }
          return 'assets/[name]-[hash][extname]'
        },
        // Global name for IIFE
        name: 'BoostBotAdmin',
        // Don't split chunks in IIFE format
        inlineDynamicImports: true,
      }
    },
    
    // Use terser for better minification
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,     // Remove console.log in production
        drop_debugger: true,    // Remove debugger statements
        pure_funcs: ['console.log', 'console.debug'],
        passes: 2,
      },
      mangle: {
        safari10: true,
      },
      format: {
        comments: false,
      },
    },
    
    // Target modern browsers
    target: 'es2020',
    
    // CSS optimization
    cssMinify: true,
    
    // Extract CSS to separate file
    cssCodeSplit: false,
    
    // Report compressed size
    reportCompressedSize: true,
  },
  
  // Optimize dependencies
  optimizeDeps: {
    include: ['react', 'react-dom', 'react-router-dom', 'zustand'],
  },
  
  // WordPress compatibility
  define: {
    'process.env': {}
  },
  
  // Path aliases
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@components': path.resolve(__dirname, 'src/components'),
      '@pages': path.resolve(__dirname, 'src/pages'),
      '@hooks': path.resolve(__dirname, 'src/hooks'),
      '@store': path.resolve(__dirname, 'src/store'),
      '@api': path.resolve(__dirname, 'src/api'),
      '@types': path.resolve(__dirname, 'src/types'),
      '@utils': path.resolve(__dirname, 'src/utils'),
      '@shared': path.resolve(__dirname, '../shared')
    }
  },
  
  // Dev server
  server: {
    port: 3001,
    open: false
  }
})

