import inertia from '@inertiajs/vite';
import { wayfinder } from '@laravel/vite-plugin-wayfinder';
import tailwindcss from '@tailwindcss/vite';
import vue from '@vitejs/plugin-vue';
import laravel from 'laravel-vite-plugin';
import { defineConfig, loadEnv } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';

const manifestIcons = [
    {
        src: '/assets/pwa-64x64.png',
        sizes: '64x64',
        type: 'image/png',
    },
    {
        src: '/assets/pwa-192x192.png',
        sizes: '192x192',
        type: 'image/png',
    },
    {
        src: '/assets/pwa-512x512.png',
        sizes: '512x512',
        type: 'image/png',
        purpose: 'any',
    },
    {
        src: '/assets/maskable-icon-512x512.png',
        sizes: '512x512',
        type: 'image/png',
        purpose: 'maskable',
    },
] as const;

export default defineConfig(({ mode }) => {
    const env = loadEnv(mode, process.cwd(), '');
    const appName = env.VITE_APP_NAME || 'DST Collection';

    return {
        plugins: [
            laravel({
                input: ['resources/css/app.css', 'resources/js/app.ts'],
                refresh: false,
            }),
            inertia(),
            tailwindcss(),
            vue({
                template: {
                    transformAssetUrls: {
                        base: null,
                        includeAbsolute: false,
                    },
                },
            }),
            wayfinder({
                formVariants: true,
            }),
            VitePWA({
                buildBase: '/build/',
                scope: '/',
                base: '/',
                registerType: 'autoUpdate',
                // Kita daftarkan SW manual di app.ts (public/sw.js yang support push)
                // VitePWA hanya generate manifest di sini
                injectRegister: null,
                devOptions: {
                    enabled: false,
                },
                workbox: {
                    globPatterns: [
                        '**/*.{js,css,html,ico,jpg,png,svg,woff,woff2,ttf,eot}',
                    ],
                    navigateFallback: '/',
                    navigateFallbackDenylist: [/^\/telescope/],
                    maximumFileSizeToCacheInBytes: 3_000_000,
                },
                manifest: {
                    name: appName,
                    short_name: appName,
                    description: `${appName} - Progressive Web App`,
                    theme_color: '#171717',
                    background_color: '#ffffff',
                    display: 'standalone',
                    orientation: 'portrait',
                    scope: '/',
                    start_url: '/',
                    id: '/',
                    icons: [...manifestIcons],
                },
            }),
        ],
    };
});
