import { Background } from '@/components/background';
import { Layout } from '@/components/layout';
import { NotFoundPage } from '@/features/not-found/not-found-page';
import { ServerErrorPage } from '@/features/server-error/server-error-page';
import type { ApiClient } from '@/lib/api-client';
import type { AuthContextValue } from '@/lib/auth';
import { Outlet, createRootRouteWithContext, useLocation } from '@tanstack/react-router';

type RouterContext = {
  auth: AuthContextValue;
  api: ApiClient;
};

export const Route = createRootRouteWithContext<RouterContext>()({
  component: RootRoute,
  errorComponent: ServerErrorPage,
  notFoundComponent: NotFoundPage,
});

const AUTH_PAGE_REGEX =
  /^\/(login|select-complex|reset-password|onboard|invite|auth-callback)(?:\/|$)/;

function RootRoute() {
  const location = useLocation();
  const isPublicBookingRoute = /^\/[^/]+\/booking(?:\/|$)/.test(location.pathname);
  const isAuthPage = AUTH_PAGE_REGEX.test(location.pathname);

  if (isPublicBookingRoute) {
    return <Outlet />;
  }

  if (isAuthPage) {
    return (
      <div className="relative min-h-dvh overflow-x-hidden bg-background text-foreground">
        <Background />
        <Outlet />
      </div>
    );
  }

  return (
    <Layout>
      <div className="flex flex-col">
        <Outlet />
      </div>
    </Layout>
  );
}
