import { defineConfig } from 'vite';
import tailwindcss from '@tailwindcss/vite';
import react from '@vitejs/plugin-react';
import { v4wp } from '@kucrut/vite-for-wp';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default defineConfig({
  plugins: [
    tailwindcss(),
    react({
      jsxRuntime: 'classic',
    }),
    v4wp({
      input: {
        admin: 'src/admin/index.jsx',
        editor: 'src/editor/index.js',
        onboarding: 'src/admin/onboarding/index.jsx',
        'meta-box': 'src/editor/meta-box/index.jsx',
        sidebar: 'src/editor/sidebar/index.jsx',
        // Blocks
        'blocks/breadcrumbs': 'src/blocks/breadcrumbs/index.jsx',
        // WordPress shims
        'shims/wp-dom-ready': 'src/shims/wordpress/dom-ready.js',
        'shims/wp-element': 'src/shims/wordpress/element.js',
        'shims/wp-components': 'src/shims/wordpress/components.js',
        'shims/wp-i18n': 'src/shims/wordpress/i18n.js',
        'shims/wp-api-fetch': 'src/shims/wordpress/api-fetch.js',
        'shims/wp-icons': 'src/shims/wordpress/icons.js',
        'shims/wp-data': 'src/shims/wordpress/data.js',
        'shims/wp-hooks': 'src/shims/wordpress/hooks.js',
        'shims/wp-compose': 'src/shims/wordpress/compose.js',
        'shims/wp-date': 'src/shims/wordpress/date.js',
        'shims/wp-block-editor': 'src/shims/wordpress/block-editor.js',
        'shims/wp-url': 'src/shims/wordpress/url.js',
        // React shims
        'shims/react': 'src/shims/react-shim.js',
        'shims/react-dom': 'src/shims/react-dom-shim.js',
        'shims/jsx-runtime': 'src/shims/jsx-runtime-shim.js',
      },
      outDir: 'build',
    }),
  ],

  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@admin': path.resolve(__dirname, 'src/admin'),
      '@editor': path.resolve(__dirname, 'src/editor'),
      '@components': path.resolve(__dirname, 'src/admin/components'),
      '@hooks': path.resolve(__dirname, 'src/admin/hooks'),
      '@utils': path.resolve(__dirname, 'src/admin/utils'),
      '@styles': path.resolve(__dirname, 'src/styles'),
      // Use lodash shim to access WordPress global
      'lodash': path.resolve(__dirname, 'src/shims/wp-utils-shim.js'),
      // WordPress package aliases
      '@wordpress/plugins': path.resolve(__dirname, 'src/shims/wordpress/plugins.js'),
      '@wordpress/editor': path.resolve(__dirname, 'src/shims/wordpress/editor.js'),
      '@wordpress/blocks': path.resolve(__dirname, 'src/shims/wordpress/blocks.js'),
      '@wordpress/block-editor': path.resolve(__dirname, 'src/shims/wordpress/block-editor.js'),
      '@wordpress/components': path.resolve(__dirname, 'src/shims/wordpress/components.js'),
      '@wordpress/element': path.resolve(__dirname, 'src/shims/wordpress/element.js'),
      '@wordpress/data': path.resolve(__dirname, 'src/shims/wordpress/data.js'),
      '@wordpress/i18n': path.resolve(__dirname, 'src/shims/wordpress/i18n.js'),
      '@wordpress/api-fetch': path.resolve(__dirname, 'src/shims/wordpress/api-fetch.js'),
      '@wordpress/compose': path.resolve(__dirname, 'src/shims/wordpress/compose.js'),
      '@wordpress/hooks': path.resolve(__dirname, 'src/shims/wordpress/hooks.js'),
      '@wordpress/icons': path.resolve(__dirname, 'src/shims/wordpress/icons.js'),
      '@wordpress/url': path.resolve(__dirname, 'src/shims/wordpress/url.js'),
      '@wordpress/dom-ready': path.resolve(__dirname, 'src/shims/wordpress/dom-ready.js'),
      '@wordpress/date': path.resolve(__dirname, 'src/shims/wordpress/date.js'),
      '@wordpress/rich-text': path.resolve(__dirname, 'src/shims/wordpress/rich-text.js'),
      '@wordpress/server-side-render': path.resolve(__dirname, 'src/shims/wordpress/server-side-render.js'),
      // React aliases
      'react-dom/client': path.resolve(__dirname, 'src/shims/react-dom-client-shim.js'),
      'react/jsx-runtime': path.resolve(__dirname, 'src/shims/jsx-runtime-shim.js'),
      'react': path.resolve(__dirname, 'src/shims/react-shim.js'),
      'react-dom': path.resolve(__dirname, 'src/shims/react-dom-shim.js'),
    },
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
  },

  css: {
    modules: {
      localsConvention: 'camelCase',
      generateScopedName: '[name]__[local]___[hash:base64:5]',
    },
  },

  build: {
    outDir: 'build',
    emptyOutDir: true,
    manifest: true,
    sourcemap: process.env.NODE_ENV !== 'production',
    modulePreload: false,

    rollupOptions: {
      preserveEntrySignatures: 'strict',

      output: {
        format: 'es',
        preserveModules: false,
        preserveModulesRoot: 'src',
        entryFileNames: '[name].js',
        chunkFileNames: '[name]-[hash].js',
        assetFileNames: (assetInfo) => {
          if (assetInfo.name && assetInfo.name.endsWith('.css')) {
            if (assetInfo.name === '_App.css' || assetInfo.name === 'App.css') {
              return 'App-[hash].css';
            }
            return '[name].css';
          }
          return '[name].[ext]';
        },
        manualChunks: (id) => {
          if (id.includes('node_modules/@wordpress/')) {
            return undefined;
          }
          if (id.includes('node_modules/react') || id.includes('node_modules/react-dom')) {
            return undefined;
          }
          if (id.includes('node_modules/chart.js') ||
              id.includes('node_modules/react-chartjs-2') ||
              id.includes('node_modules/recharts') ||
              id.includes('node_modules/d3')) {
            return 'charts-vendor';
          }
          if (id.includes('node_modules/lodash') ||
              id.includes('node_modules/date-fns') ||
              id.includes('node_modules/framer-motion')) {
            return 'common-vendor';
          }
        },
      },

      external: (id) => {
        if (id === 'jquery') return true;
        if (id.includes('/shims/')) return false;
        return false;
      },
    },

    minify: 'esbuild',
    target: 'es2015',
    chunkSizeWarningLimit: 1000,
  },

  server: {
    host: 'localhost',
    port: 3000,
    strictPort: false,
    cors: true,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization, X-WP-Nonce',
    },
    hmr: {
      host: 'localhost',
      protocol: 'ws',
    },
    watch: {
      usePolling: true,
      interval: 100,
    },
  },

  optimizeDeps: {
    include: [
      'react',
      'react-dom',
      '@heroicons/react/24/outline',
      '@heroicons/react/24/solid',
      'clsx',
      'framer-motion',
      'zustand',
    ],
    exclude: [
      '@wordpress/api-fetch',
      '@wordpress/components',
      '@wordpress/data',
      '@wordpress/element',
      '@wordpress/hooks',
      '@wordpress/i18n',
      '@wordpress/icons',
    ],
    esbuildOptions: {
      loader: {
        '.js': 'jsx',
      },
    },
  },

  esbuild: {
    jsx: 'transform',
    jsxFactory: 'React.createElement',
    jsxFragment: 'React.Fragment',
  },

  define: {
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
  },
});
