"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";

import { Typography } from "@/components/ui/typography";
import { usePermissions } from "@/hooks/auth/usePermissions";
import { useTranslation } from "@/hooks/useTranslation";
import { filterNavByAccess, getNavForRole } from "@/lib/constants/nav";
import { cn } from "@/lib/utils";
import type { UserRole } from "@/types/auth";

/**
 * Mobile-only bottom tab bar, driven by the same role nav config as the
 * sidebar (items flagged `inBottomNav`). A plain flex row + DOM order handles
 * RTL: the primary item is first in config, so Arabic renders it at the far
 * right automatically — no side branching.
 */
export function BottomNav({ role }: { role: UserRole }) {
  const { t } = useTranslation();
  const pathname = usePathname();
  const { check } = usePermissions();
  const items = filterNavByAccess(getNavForRole(role), check).filter(
    (item) => item.inBottomNav,
  );

  if (items.length === 0) return null;

  return (
    // Fixed by the AppShell viewport lock — the content area scrolls above it
    <nav className="flex shrink-0 border-t border-border bg-white pb-[env(safe-area-inset-bottom)] md:hidden">
      {items.map((item) => {
        const isActive =
          pathname === item.href || pathname.startsWith(item.href + "/");
        return (
          <Link
            key={item.href}
            href={item.href}
            aria-current={isActive ? "page" : undefined}
            className={cn(
              "flex flex-1 flex-col items-center gap-1 py-2",
              isActive ? "text-primary-blue" : "text-secondary-text",
            )}
          >
            <item.icon className="size-5" />
            <Typography as="span" variant="caption" color="inherit">
              {t(item.titleKey)}
            </Typography>
          </Link>
        );
      })}
    </nav>
  );
}
