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() ],
	build: {
		outDir: resolve( __dirname, '../assets' ),
		// Do NOT empty the dir — bootstrap.js lives there and is hand-authored.
		emptyOutDir: false,
		cssCodeSplit: false,
		rollupOptions: {
			input: {
				widget: resolve( __dirname, 'src/index.tsx' ),
			},
			output: {
				entryFileNames: '[name].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' ),
	},
} );
