import React, { Suspense } from "react";
import {
  createBrowserRouter,
  RouterProvider,
  RouteObject,
} from "react-router-dom";
import { EntranceCard } from "./components/EntranceCard";
import { AppContextProvider } from "../react-app/src/contexts/AppContext";
import mock from "@/mock";

// @ts-ignore
const pages = import.meta.glob(`../react-app/src/pages/*/App.tsx`, {
  eager: true,
});

const routesList = Object.entries(pages).map(([path, component]) => {
  const name = path.split("/").slice(-2)[0];
  return {
    path: `/${name}`,
    name,
    mockProps: mock[name], // the mock props from lwc component. for local development.
    Component: (component as any).default as React.ComponentType,
  };
});

function Home() {
  return (
    <div className="slds-p-around_medium">
      <h1 className="slds-text-heading_large slds-p-bottom_medium">
        Available Entrances
      </h1>
      <div className="slds-grid slds-grid_pull-padded slds-wrap">
        {routesList.map(({ path, name }) => (
          <div
            key={path}
            className="slds-col slds-size_1-of-1 slds-medium-size_1-of-2 slds-large-size_1-of-3 slds-p-around_small"
          >
            <EntranceCard
              name={name}
              path={path}
              description={`Navigate to ${name}`}
            />
          </div>
        ))}
      </div>
    </div>
  );
}

const router = createBrowserRouter(
  [
    {
      path: "/",
      element: <Home />,
    },
    ...routesList.map(({ path, Component, mockProps }) => ({
      path,
      element: (
        <div
          className="slds-grid slds-grid_vertical-align-center slds-grid_align-center"
          style={{ minHeight: "100vh" }}
        >
          <AppContextProvider {...mockProps}>
            <Component />
          </AppContextProvider>
        </div>
      ),
    })),
  ] satisfies RouteObject[],
  {
    future: {
      v7_relativeSplatPath: true,
    },
  }
);

export default function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <RouterProvider router={router} future={{
        v7_startTransition: true,
      }} />
    </Suspense>
  );
}