import { createRouter } from '@tanstack/react-router'<% if (addOnEnabled['tanstack-query']) { %>
import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query'
import * as TanstackQuery from "./integrations/tanstack-query/root-provider";
<% } %><% if (addOnEnabled['apollo-client']) { %>
import {
  routerWithApolloClient,
  ApolloClient,
  InMemoryCache,
} from "@apollo/client-integration-tanstack-start";
import { HttpLink } from "@apollo/client";
<% } %>
<% if (addOnEnabled.sentry) { %>
import * as Sentry from "@sentry/tanstackstart-react";
<% } %><% if (addOnEnabled.paraglide) { %>
import { deLocalizeUrl, localizeUrl } from "./paraglide/runtime";
<% } %>

// Import the generated route tree
import { routeTree } from './routeTree.gen'

// Create a new router instance
export const getRouter = () => {
<% if (addOnEnabled['apollo-client']) { %>
  // Configure Apollo Client
  const apolloClient = new ApolloClient({
    cache: new InMemoryCache(),
    link: new HttpLink({
      uri: import.meta.env.VITE_GRAPHQL_ENDPOINT || "https://countries.trevorblades.com/"
    }),
  });
<% } %>
<% if (addOnEnabled['tanstack-query']) { %>
  const rqContext = TanstackQuery.getContext();
<% } %>

  const router = createRouter({
    routeTree,
    context: {
<% if (addOnEnabled['apollo-client']) { %>
      ...routerWithApolloClient.defaultContext,
<% } %>
<% if (addOnEnabled['tanstack-query']) { %>
      ...rqContext,
<% } %>
    },
<% if (addOnEnabled.paraglide) { %>
    // Paraglide URL rewrite docs: https://github.com/TanStack/router/tree/main/examples/react/i18n-paraglide#rewrite-url
    rewrite: {
      input: ({ url }) => deLocalizeUrl(url),
      output: ({ url }) => localizeUrl(url),
    },
<% } %>
<% if (addOnEnabled['tanstack-query'] || addOnEnabled['apollo-client']) { %>
    defaultPreload: "intent",
<% } else { %>
    scrollRestoration: true,
    defaultPreloadStaleTime: 0,
<% } %>
  })

<% if (addOnEnabled['tanstack-query']) { %>
  setupRouterSsrQueryIntegration({router, queryClient: rqContext.queryClient})
<% } %>

<% if (addOnEnabled.sentry) { %>
  if (!router.isServer) {
    Sentry.init({
      dsn: import.meta.env.VITE_SENTRY_DSN,
      integrations: [],
      tracesSampleRate: 1.0,
      sendDefaultPii: true,
    });
  }
<% } %>

  return <% if (addOnEnabled['apollo-client']) { %>routerWithApolloClient(router, apolloClient)<% } else { %>router<% } %>;
}
