import { Button, Container, Flex } from "@radix-ui/themes"
import { createRootRoute, useMatch, useMatches, useNavigate } from "@tanstack/react-router"
import { AnimatePresence } from "framer-motion"
import { Suspense, lazy } from "react"
import { AnimatedOutlet } from "../AnimatedOutlet"


const TanStackRouterDevtools = process.env.NODE_ENV === "production"
    ? () => null
    : lazy(() => import("@tanstack/router-devtools").then(res => ({
        default: res.TanStackRouterDevtools
    })))

const ThemePanel = process.env.NODE_ENV === "production"
    ? () => null
    : lazy(() => import("@radix-ui/themes").then(res => ({
        default: res.ThemePanel
    })))


export function Root() {

    const matches   = useMatches()
    const match     = useMatch({ strict: false })
    const nextMatch = matches[ matches.findIndex(d => d.id === match.id) + 1 ]

    const navigate  = useNavigate()


    return <>
        <Container pt="8" pb="4">
            <Flex
                gap="4"
                justify="center"
                align="center"
            >
                <Button
                    variant="soft"
                    onClick={() => navigate({ to: "/" })}
                >
                    Home
                </Button>

                <Button
                    variant="soft"
                    onClick={() => navigate({ to: "/about" })}
                >
                    About
                </Button>
            </Flex>
        </Container>

        <AnimatePresence mode="popLayout">
            <AnimatedOutlet
                key={nextMatch.id}

                transition={{ x: { type: "spring", stiffness: 300, damping: 30 } }}

                initial={{ x: "100vw", opacity: 0 }}
                animate={{ x: "0", opacity: 1 }}
                exit={{ x: "-100vw", opacity: 0 }}
            />
        </AnimatePresence>

        <Suspense>
            <TanStackRouterDevtools />
            <ThemePanel />
        </Suspense>
    </>

}

export const Route = createRootRoute({ component: Root })
