import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    react(),
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.svg', 'book_icon.png', 'icons.svg'],
      manifest: {
        name: 'Verse by Verse with Nate',
        short_name: 'VBVN',
        description: 'A journey through Scripture — episodes, Q&A, and Bible study.',
        start_url: '/',
        display: 'standalone',
        background_color: '#13120e',
        theme_color: '#13120e',
        icons: [
          { src: '/pwa-192.png', sizes: '192x192', type: 'image/png' },
          { src: '/pwa-512.png', sizes: '512x512', type: 'image/png', purpose: 'any maskable' },
        ],
      },
      workbox: {
        navigateFallback: '/index.html',
        // Allowlist-only approach: SW only serves index.html for known SPA routes.
        // Everything else (admin-configured redirects, /spotify, /apple, /amazon,
        // feed.xml, robots.txt, etc.) goes to the server so server-side redirects work.
        navigateFallbackAllowlist: [
          /^\/$/, // exact root
          /^\/(start-here|about|contact|resources|thanks|preview|privacy|terms|salvation)(\/.*)?$/,
          /^\/(study|studys|episodes|finished|downloads|subscribe|certificate)(\/.*)?$/,
          /^\/(questions|admin|email|contacts|calendar)(\/.*)?$/,
        ],
        runtimeCaching: [
          {
            urlPattern: /^\/api\/(episodes|questions)/,
            handler: 'StaleWhileRevalidate',
            options: { cacheName: 'api-content', expiration: { maxAgeSeconds: 3600 } },
          },
          {
            urlPattern: /\/images\//,
            handler: 'CacheFirst',
            options: { cacheName: 'images', expiration: { maxEntries: 60, maxAgeSeconds: 86400 * 30 } },
          },
        ],
      },
    }),
  ],
  resolve: {
    alias: {
      'react-simple-maps': 'react-simple-maps/dist/index.es.js',
    },
  },
  server: {
    proxy: {
      '/api': 'http://localhost:4173',
    },
  },
})
