import * as fs from 'node:fs';
import * as path from 'node:path';
import { wayfinder } from '@laravel/vite-plugin-wayfinder';
import tailwindcss from '@tailwindcss/vite';
import react from '@vitejs/plugin-react';
import laravel from 'laravel-vite-plugin';
import { defineConfig } from 'vite';

function getPageInputs(): string[] {
    const pagesDir = path.resolve(__dirname, 'resources/js/pages');
    const entries: string[] = [];
    function walk(dir: string, base = ''): void {
        if (!fs.existsSync(dir)) return;
        for (const f of fs.readdirSync(dir, { withFileTypes: true })) {
            const rel = base ? `${base}/${f.name}` : f.name;
            const full = path.join(dir, f.name);
            if (f.isDirectory()) {
                walk(full, rel);
            } else if (f.name.endsWith('.tsx')) {
                entries.push(`resources/js/pages/${rel}`);
            }
        }
    }
    walk(pagesDir);
    return entries;
}

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.tsx', ...getPageInputs()],
            ssr: 'resources/js/ssr.tsx',
            refresh: true,
        }),
        react({
            babel: {
                plugins: ['babel-plugin-react-compiler'],
            },
        }),
        tailwindcss(),
        wayfinder({
            formVariants: true,
        }),
    ],
    esbuild: {
        jsx: 'automatic',
    },
});
