"use client";

import { useModules } from "@/lib/modules";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { Home, Search, Clapperboard, Bell, MessageCircle } from "lucide-react";
import { useAuth } from "@/lib/auth-context";
import { useBadges } from "@/lib/badge-context";
import clsx from "clsx";

const tabs = [
  { href: "/", label: "Home", icon: Home },
  { href: "/search", label: "Search", icon: Search },
  { href: "/reels", label: "Reels", icon: Clapperboard },
  { href: "/activity", label: "Activity", icon: Bell, badgeKey: "activity" as const },
  { href: "/messages", label: "Messages", icon: MessageCircle, badgeKey: "messages" as const },
];

// Routes that already render their own fixed-bottom input — the mobile nav
// would visually collide with them, so it hides itself there instead.
const HIDE_ON = [/^\/post\/[^/]+$/, /^\/messages\/[^/]+$/];

export function MobileNav() {
  // Hide anything whose module is switched off in admin.
  const modules = useModules();

  const pathname = usePathname();
  const { user } = useAuth();
  const { unreadNotifications, unreadMessages } = useBadges();

  if (!user) return null;
  if (HIDE_ON.some((re) => re.test(pathname))) return null;

  const badgeCounts = { activity: unreadNotifications, messages: unreadMessages };

  return (
    <nav className="md:hidden fixed bottom-0 left-0 right-0 z-40 bg-white/95 dark:bg-black/95 backdrop-blur border-t border-neutral-200 dark:border-neutral-800 flex items-center justify-around px-2 py-2 pb-[calc(0.5rem+env(safe-area-inset-bottom))]">
      {tabs.filter((i) => !("module" in i) || modules[(i as { module: string }).module] !== false).map(({ href, label, icon: Icon, badgeKey }) => {
        const active = pathname === href;
        const count = badgeKey ? badgeCounts[badgeKey] : 0;
        return (
          <Link
            key={href}
            href={href}
            className={clsx(
              "flex flex-col items-center gap-0.5 px-3 py-1 rounded-xl",
              active ? "text-black dark:text-white" : "text-neutral-400"
            )}
          >
            <span className="relative">
              <Icon size={22} strokeWidth={active ? 2.4 : 1.8} />
              {count > 0 && (
                <span className="absolute -top-1.5 -right-2 min-w-[14px] h-3.5 px-1 rounded-full bg-rose-500 text-white text-[9px] font-bold flex items-center justify-center">
                  {count > 9 ? "9+" : count}
                </span>
              )}
            </span>
            <span className="text-[10px] font-medium">{label}</span>
          </Link>
        );
      })}
    </nav>
  );
}
