import { Link, useMatchRoute } from "@tanstack/react-router";
import { motion } from "motion/react";
import { useTranslation } from "react-i18next";

import GlassSurface from "@components/surface/GlassSurface";

import classes from "./Navigation.module.css";

const ENTRANCE_DELAYS = [0.2, 0.1, 0, 0.1, 0.2];

const SPRING_ENTRANCE = { type: "spring" as const, stiffness: 400, damping: 20 };
const SPRING_HEIGHT = { type: "spring" as const, stiffness: 500, damping: 25 };

type NavItem =
  | { key: string; route: string; isMenu?: false }
  | { key: string; route?: undefined; isMenu: true };

const NAV_ITEMS: NavItem[] = [
  { key: "nav.shop", route: "/shop/" },
  { key: "nav.apiary", route: "/apiary/" },
  { key: "nav.game", route: "/game/" },
  { key: "nav.cashdesk", route: "/cashdesk/" },
  { key: "nav.menu", isMenu: true },
];

function IconPlaceholder() {
  return <div className={classes.iconPlaceholder} />;
}

type BarProps = {
  labelKey: string;
  active: boolean;
  entranceDelay: number;
};

function NavBar({ labelKey, active, entranceDelay }: BarProps) {
  const { t } = useTranslation();

  return (
    <motion.div
      className={classes.barWrapper}
      initial={{ translateY: "100%" }}
      animate={{ translateY: "0%" }}
      transition={{ ...SPRING_ENTRANCE, delay: entranceDelay }}
    >
      <GlassSurface
        className={[classes.bar, active ? classes.barActive : classes.barInactive]}
        animate={{ minHeight: active ? 74 : 64 }}
        transition={SPRING_HEIGHT}
      >
        <div className={classes.safeContent}>
          <IconPlaceholder />
          <span
            className={
              active
                ? `${classes.label} ${classes.labelActive}`
                : `${classes.label} ${classes.labelInactive}`
            }
          >
            {t(labelKey)}
          </span>
          <IconPlaceholder />
        </div>
      </GlassSurface>
    </motion.div>
  );
}

export default function Navigation() {
  const matchRoute = useMatchRoute();

  return (
    <nav className={classes.navigation}>
      {NAV_ITEMS.map((item, index) => {
        const active = item.isMenu ? false : !!matchRoute({ to: item.route });

        const bar = (
          <NavBar labelKey={item.key} active={active} entranceDelay={ENTRANCE_DELAYS[index]} />
        );

        if (item.isMenu) {
          return (
            <div key={item.key} className={classes.barContainer}>
              {bar}
            </div>
          );
        }

        return (
          <Link key={item.key} to={item.route} className={classes.barContainer}>
            {bar}
          </Link>
        );
      })}
    </nav>
  );
}
