import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import { visualizer } from 'rollup-plugin-visualizer';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import { resolveDevApiTarget } from '../../scripts/resolve-dev-api-target.mjs';

const devApiTarget = resolveDevApiTarget();

export default defineConfig(({ mode }) => {
  const analyze = process.env.ANALYZE === '1' || mode === 'analyze';

  return {
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver({ importStyle: false })],
    }),
    analyze &&
      visualizer({
        filename: 'dist/stats.html',
        gzipSize: true,
        brotliSize: true,
        open: false,
      }),
  ].filter(Boolean),
  resolve: {
    extensions: ['.mjs', '.ts', '.mts', '.tsx', '.vue', '.js', '.jsx', '.json'],
    alias: {
      '@thebet365/shared': resolve(__dirname, '../../packages/shared/src/index.ts'),
    },
    dedupe: ['echarts', 'vue-echarts', 'vue'],
  },
  optimizeDeps: {
    include: ['echarts', 'vue-echarts'],
  },
  build: {
    chunkSizeWarningLimit: 600,
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (!id.includes('node_modules')) {
            if (id.includes('/src/i18n/bundles/')) {
              const m = id.match(/bundles\/(zh-CN|en-US|ms-MY)/);
              if (m) return `i18n-${m[1]}`;
            }
            // 按语言分别归入各自 chunk，避免 zh/en pages 合并进同一个共享 chunk
            if (id.includes('/src/i18n/pages/zh')) return 'i18n-zh-CN';
            if (id.includes('/src/i18n/pages/en')) return 'i18n-en-US';
            if (id.includes('/src/i18n/admin-pages-ms')) return 'i18n-ms-MY';
            // admin-pages.ts 如仍被引用，归入共享 chunk（当前已无引用，保留规则作兜底）
            if (id.includes('/src/i18n/admin-pages')) return 'i18n-pages';
            if (id.includes('/src/views/AgentManager.vue')) return 'admin-users';
            if (id.includes('/src/views/Bets.vue')) return 'admin-bets';
            if (id.includes('/src/views/Matches.vue')) return 'admin-matches';
            if (id.includes('/src/views/MatchesOutrights.vue')) return 'admin-matches-outrights';
            if (id.includes('echarts-setup') || id.includes('vue-echarts') || id.includes('node_modules/echarts')) {
              return 'echarts';
            }
            return undefined;
          }
          if (id.includes('element-plus')) return 'element-plus';
          if (id.includes('echarts')) return 'echarts';
          if (id.includes('vue-i18n')) return 'vue-i18n';
          if (id.includes('vue-router')) return 'vue-router';
          if (id.includes('vue/') || id.includes('vue/dist')) return 'vue';
          return undefined;
        },
      },
    },
  },
  publicDir: resolve(__dirname, '../../packages/shared/public'),
  server: {
    host: true,
    port: 5174,
    proxy: {
      '/api': { target: devApiTarget, changeOrigin: true },
      '/uploads': { target: devApiTarget, changeOrigin: true },
    },
  },
};
});
