import React from 'react';
import path from 'path';
import { Helmet } from 'react-helmet';
import { renderToStaticMarkup, renderToString } from 'react-dom/server';
import { ChunkExtractor } from '@loadable/server';
import { matchesUA as browserlist } from 'browserslist-useragent';
import { Page } from '@game/components/Page/Page';
import { dehydrate, Hydrate, QueryClient, QueryClientProvider } from '@tanstack/react-query';

interface IRenderParams {
  root: string;
  userAgent: string;
}

export default function renderer(params: IRenderParams) {
  const { root = 'main', userAgent } = params;

  let target = 'default';

  if (process.env.NODE_ENV === 'production') {
    const isModern = browserlist(userAgent, { env: 'modern', allowHigherVersions: true });

    if (isModern) {
      target = 'modern';
    } else {
      const isDefault = browserlist(userAgent, { env: 'default', allowHigherVersions: true });

      target = isDefault ? 'default' : 'legacy';
    }
  }

  const statsFile = path.resolve('./build/client', target, 'loadable-stats.json');
  const extractor = new ChunkExtractor({
    statsFile,
    entrypoints: [root]
  });

  const Root = require(`@game/pages/${root}/${root}`).default;

  const queryClient = new QueryClient();
  // Тут какие-то запросы
  const dehydratedState = dehydrate(queryClient);

  const loadableRoot = extractor.collectChunks(
    <QueryClientProvider client={queryClient}>
      <Hydrate state={dehydratedState}>
        <Root />
      </Hydrate>
    </QueryClientProvider>
  );

  const rootHtml = renderToString(loadableRoot);
  const helmet = Helmet.renderStatic();

  queryClient.clear();

  return renderToStaticMarkup(
    <Page extractor={extractor} rootHtml={rootHtml} helmet={helmet} dehydratedState={dehydratedState} />
  );
}
