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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    nodePolyfills({
      // Enable polyfills for specific modules
      globals: {
        Buffer: true,
        global: true,
        process: true,
      },
      // Include specific polyfills
      include: ['buffer', 'events', 'stream', 'util', 'crypto', 'vm'],
      // Exclude Node.js built-ins that shouldn't be polyfilled
      exclude: ['https', 'http', 'url', 'path', 'fs', 'os', 'net', 'tls', 'zlib'],
    }),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
    // Dedupe to avoid "multiple instances" warnings from transitive deps (e.g. @emotion/react, Lit)
    dedupe: [
      'react',
      'react-dom',
      '@emotion/react',
      '@emotion/styled',
      'lit',
      'lit-html',
      'lit-element',
    ],
  },
  server: {
    port: 3002,
  },
  optimizeDeps: {
    // Exclude problematic packages from optimization
    exclude: ['https', 'http', 'url', 'stream', 'util', 'crypto', 'path', 'fs', 'os', 'net', 'tls', 'zlib'],
    include: ['@safe-global/protocol-kit'],
  },
  define: {
    global: 'globalThis',
    'process.env': {},
  },
  build: {
    rollupOptions: {
      output: {
        // Add Content Security Policy meta tag via HTML plugin if needed
      },
      external: (id) => {
        // Do NOT externalise crypto, buffer, stream, util, events - vite-plugin-node-polyfills provides them for the browser.
        // Externalise only Node built-ins we don't polyfill (bundling would fail or break in browser).
        const nodeBuiltIns = ['path', 'fs', 'os', 'net', 'tls', 'zlib', 'https', 'http', 'url']
        return nodeBuiltIns.includes(id)
      },
    },
    commonjsOptions: {
      transformMixedEsModules: true,
    },
    chunkSizeWarningLimit: 1000,
  },
})
