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

/**
 * Build the storefront widget bundle.
 *
 * Output (into ../assets, the plugin's enqueued assets dir):
 *   - widget.js   (single self-contained bundle, React inlined)
 *   - widget.css  (extracted styles, loaded by bootstrap.js)
 *
 * The bundle reads window.AISTHETIX_CONFIG and mounts into #aisthetix-widget-root.
 */
export default defineConfig( {
	plugins: [
		react(),
		{
			name: 'aisthetix-wrap-classic-script',
			enforce: 'post',
			generateBundle( _options, bundle ) {
				for ( const output of Object.values( bundle ) ) {
					if ( output.type === 'chunk' && output.fileName === 'widget.js' ) {
						output.code = `(function aisthetixWidgetBundle() {\n${ output.code }\n})();`;
					}
				}
			},
		},
	],
	build: {
		outDir: resolve( __dirname, '../assets' ),
		// Library mode gives the widget one stable entry/output. The post-build
		// plugin above adds the final collision boundary after minification, because
		// esbuild may otherwise hoist generated helpers outside Rollup's own IIFE.
		lib: {
			entry: resolve( __dirname, 'src/index.tsx' ),
			name: 'AisthetixTryOnWidget',
			formats: [ 'iife' ],
			fileName: () => 'widget.js',
		},
		// Do NOT empty the dir — bootstrap.js lives there and is hand-authored.
		emptyOutDir: false,
		cssCodeSplit: false,
		rollupOptions: {
			output: {
				entryFileNames: 'widget.js',
				chunkFileNames: '[name].js',
				// Force a stable CSS name (widget.css) regardless of hashing.
				assetFileNames: ( assetInfo ) => {
					if ( assetInfo.name && assetInfo.name.endsWith( '.css' ) ) {
						return 'widget.css';
					}
					return '[name].[ext]';
				},
				manualChunks: undefined,
			},
		},
		minify: 'esbuild',
		sourcemap: true,
	},
	define: {
		'process.env.NODE_ENV': JSON.stringify( process.env.NODE_ENV || 'production' ),
	},
} );
