import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import svgr from 'vite-plugin-svgr';
import tsconfigPaths from 'vite-tsconfig-paths';
import path from 'path';

const coreDir = path.resolve(__dirname, '..');

// Absolute path to the original session file we want to replace
const originalSessionPath = path.resolve(coreDir, 'src/contexts/session');
// Absolute path to our CF shim
const cfSessionShimPath = path.resolve(__dirname, 'frontend-shims/session.ts');

export default defineConfig({
  root: coreDir, // blocklets/core/ — where index.html and src/ live
  plugins: [
    // Redirect contexts/session imports to CF shim (must be first plugin)
    {
      name: 'cf-session-redirect',
      enforce: 'pre' as const,
      resolveId(source: string, importer: string | undefined) {
        if (!importer) return null;
        // Match relative imports that resolve to src/contexts/session
        if (source.endsWith('/contexts/session') || source.endsWith('/contexts/session.ts')) {
          const resolved = path.resolve(path.dirname(importer), source).replace(/\.ts$/, '');
          if (resolved === originalSessionPath) {
            return cfSessionShimPath;
          }
        }
        return null;
      },
    },
    // Inject window.blocklet + global polyfills into HTML
    {
      name: 'cf-inject-blocklet',
      transformIndexHtml(html: string) {
        const injection = `<script>
window.global = globalThis;
// Minimal bootstrap — full config loaded from __blocklet__.js
if (!window.blocklet) {
  window.blocklet = {
    prefix: '/',
    groupPrefix: '/',
    appUrl: window.location.origin,
    componentMountPoints: [{did:'z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9',name:'Media Kit',mountPoint:'/media-kit',appId:'z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9',status:'running',capabilities:{component:true}}],
    navigation: [
      {id:'payments',title:{en:'Payments',zh:'支付管理'},icon:'ion:card-outline',link:'/admin',section:['dashboard','sessionManager'],role:['admin','owner']},
      {id:'integrations',title:{en:'Integrations',zh:'快速集成'},icon:'ion:flash-outline',link:'/integrations',section:['dashboard','sessionManager'],role:['admin','owner']},
      {id:'billing',title:{en:'Billing',zh:'我的账单'},icon:'ion:receipt-outline',link:'/customer',private:true,section:['userCenter','sessionManager'],role:['owner','admin','member','guest']},
    ],
  };
}
// Load full config from /__blocklet__.js?type=json (served by worker, includes auth/branding/theme from AUTH_SERVICE).
// Using type=json lets us JSON.parse the response directly instead of slicing out a { } substring from a JS assignment.
(function() {
  try {
    var xhr = new XMLHttpRequest();
    var pfx = (window.blocklet && window.blocklet.prefix) || '/';
    xhr.open('GET', pfx + '__blocklet__.js?type=json&_t=' + Date.now(), false);
    xhr.send();
    if (xhr.status === 200) {
      var remote = JSON.parse(xhr.responseText);
      // navigation / componentMountPoints are owned by this blocklet — AUTH_SERVICE
      // doesn't know about them, so we never want remote values to clobber the
      // ones the bootstrap above set.
      var localOnly = ['navigation', 'componentMountPoints'];
      Object.keys(remote).forEach(function(k) {
        if (localOnly.indexOf(k) === -1) {
          window.blocklet[k] = remote[k];
        }
      });
      if (!window.blocklet.env) window.blocklet.env = {};
      window.blocklet.env.appName = window.blocklet.appName || '';
      window.blocklet.env.appDescription = window.blocklet.appDescription || '';
      window.blocklet.env.appLogo = window.blocklet.appLogo || '';
      window.blocklet.env.appUrl = window.blocklet.appUrl || '';
    }
  } catch(e) { /* ignore */ }
})();
</script>`;
        return html.replace('<head>', '<head>' + injection);
      },
    },
    // Inject Buffer polyfill at the top of the entry file
    {
      name: 'cf-buffer-polyfill',
      enforce: 'pre' as const,
      transform(code: string, id: string) {
        if (id.endsWith('/src/index.tsx')) {
          return `import '${path.resolve(__dirname, 'frontend-shims/buffer-polyfill.ts').replace(/\\/g, '/')}';\n` + code;
        }
        return undefined;
      },
    },
    tsconfigPaths({ root: coreDir }),
    react(),
    svgr(),
  ],
  resolve: {
    alias: {
      // Point to source code (workspace packages)
      '@blocklet/payment-react': path.resolve(coreDir, '../../packages/react/src'),
      '@blocklet/payment-react-headless': path.resolve(coreDir, '../../packages/payment-react-headless/src'),
      '@blocklet/payment-js': path.resolve(coreDir, '../../packages/client/src'),

      // Replace @blocklet/js-sdk with a simple axios wrapper
      '@blocklet/js-sdk': path.resolve(__dirname, 'frontend-shims/js-sdk.ts'),

      // Fix mime-types CJS interop for @blocklet/uploader
      'mime-types': path.resolve(__dirname, 'frontend-shims/mime-types.ts'),

      // lodash aliases
      'lodash.assign': 'lodash/assign',
      'lodash.clonedeep': 'lodash/cloneDeep',
      'lodash.isequal': 'lodash/isEqual',
      'lodash.merge': 'lodash/merge',
      'lodash.find': 'lodash/find',
    },
    dedupe: [
      '@arcblock/ux',
      '@arcblock/did-connect-react',
      '@blocklet/ui-react',
      '@mui/material',
      '@mui/icons-material',
      'react',
      'react-dom',
      'lodash',
    ],
  },
  build: {
    outDir: path.resolve(__dirname, 'public'),
    emptyOutDir: true,
    cssCodeSplit: false,
    modulePreload: false,
    commonjsOptions: {
      include: [/node_modules/],
      transformMixedEsModules: true,
    },
  },
  define: {
    'global': 'globalThis',
  },
  optimizeDeps: {
    include: ['react', 'react-dom', 'react/jsx-runtime', 'buffer'],
    esbuildOptions: {
      mainFields: ['module', 'main'],
      resolveExtensions: ['.ts', '.tsx', '.js', '.jsx'],
    },
  },
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8800',
        changeOrigin: true,
      },
      '/.well-known': {
        target: 'http://localhost:8800',
        changeOrigin: true,
      },
    },
  },
});
