import { renderToString } from 'react-dom/server'
// React Router v7 exports the server-side StaticRouter from the package root
// (v6's 'react-router-dom/server' subpath no longer exists).
import { StaticRouter, useRoutes } from 'react-router-dom'
import { HelmetProvider } from 'react-helmet-async'
import { routes } from './routes.jsx'
import './index.css'

const AppRoutes = () => useRoutes(routes)

/**
 * Renders a single route to static HTML at build time.
 * @param {string} url route path, e.g. '/about'
 * @returns {{ html: string, helmet: object }} markup plus collected head tags
 */
export const render = (url) => {
  const helmetContext = {}

  const html = renderToString(
    <HelmetProvider context={helmetContext}>
      <StaticRouter location={url}>
        <AppRoutes />
      </StaticRouter>
    </HelmetProvider>,
  )

  return { html, helmet: helmetContext.helmet }
}

export default render
