import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import { VitePWA } from 'vite-plugin-pwa';
import { fileURLToPath, URL } from 'node:url';

// Strict CSP injected at build time only. In dev, Vite's react-refresh needs
// inline scripts, so we leave the placeholder empty there.
const PROD_CSP =
  "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; " +
  "script-src 'self'; connect-src 'self'; font-src 'self' data:; worker-src 'self' blob:; " +
  "manifest-src 'self'; object-src 'none'; base-uri 'self'";

function cspPlugin() {
  return {
    name: 'inject-csp',
    transformIndexHtml(html: string) {
      const tag = `<meta http-equiv="Content-Security-Policy" content="${PROD_CSP}" />`;
      return html.replace('<!--CSP-PLACEHOLDER-->', tag);
    },
    apply: 'build' as const,
  };
}

export default defineConfig({
  plugins: [
    react(),
    tailwindcss(),
    cspPlugin(),
    VitePWA({
      registerType: 'prompt',
      includeAssets: ['favicon.svg'],
      manifest: {
        name: 'TTRPG Manager',
        short_name: 'TTRPG',
        description: 'A local-first manager for D&D 5e and Pathfinder 2e campaigns.',
        theme_color: '#0f0f17',
        background_color: '#0f0f17',
        display: 'standalone',
        icons: [
          { src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
          { src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
          { src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
        ],
      },
      workbox: {
        globPatterns: ['**/*.{js,css,html,svg,png,woff2}'],
        // SRD data chunks can be large; allow them to be precached.
        maximumFileSizeToCacheInBytes: 6 * 1024 * 1024,
      },
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
});
