import React from 'react'
import { createInertiaApp } from '@inertiajs/react'
import createServer from '@inertiajs/react/server'
import ReactDOMServer from 'react-dom/server'

// Eagerly import every Inertia page component so the SSR server can resolve
// any page name without async dynamic imports (Node.js + Vite SSR requirement).
const pages = import.meta.glob(['./Pages/**/*.jsx', '!./Pages/**/*.test.jsx', '!./Pages/**/__tests__/**'], { eager: true })

// Lightweight server-only placeholder for pages that must remain client-only.
// Returning this prevents an error-level stacktrace while still avoiding
// server-side rendering of browser-dependent components.
const ClientOnlyPlaceholder = () => null

createServer(page =>
    createInertiaApp({
        page,
        render: ReactDOMServer.renderToString,
        resolve: (name) => {
            // Studio news pages are rendered client-side only. Return a minimal
            // placeholder component instead of throwing so the SSR server
            // produces a small, safe HTML shell without logging an error.
            if (name.startsWith('Studio/StudioNews')) {
                return ClientOnlyPlaceholder
            }
            const module = pages[`./Pages/${name}.jsx`]
            if (!module) {
                throw new Error(`[SSR] Unknown Inertia page: "./Pages/${name}.jsx"`)
            }
            return module.default
        },
        setup: ({ App, props }) => <App {...props} />,
    }),
)
