"use client";

/** ناوبری پایین موبایل: خانه، دسته‌ها، AI Beauty، سبد، حساب */
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { useCart } from "@/lib/client/store";
import { faNumber } from "@/lib/format";
import { Icon, type IconName } from "@/components/ui/Icon";
import { Sheet } from "@/components/ui/Sheet";
import { AiBeautyMark, openAiBeauty, useAiBeautyOpen } from "@/components/ai/AiBeauty";
import type { NavCategory } from "./types";

export function BottomNav({ nav }: { nav: NavCategory[] }) {
  const pathname = usePathname();
  const [catsOpen, setCatsOpen] = useState(false);
  const [expanded, setExpanded] = useState<string | null>(null);
  const count = useCart().reduce((s, l) => s + l.qty, 0);
  const aiOpen = useAiBeautyOpen();

  const items: { href: string; label: string; icon: IconName; badge?: number }[] = [
    { href: "/", label: "خانه", icon: "home" },
    { href: "#categories", label: "دسته‌ها", icon: "grid" },
    { href: "#ai", label: "AI Beauty", icon: "sparkle" },
    { href: "/cart", label: "سبد", icon: "bag", badge: count },
    { href: "/account", label: "من", icon: "user" },
  ];

  const isActive = (href: string) =>
    href === "/" ? pathname === "/" : href === "#categories" ? catsOpen || pathname.startsWith("/c/") : href === "#ai" ? aiOpen : pathname.startsWith(href);

  return (
    <>
      <nav aria-label="ناوبری اصلی" className="pb-safe fixed inset-x-0 bottom-0 z-40 border-t border-line bg-paper/95 backdrop-blur md:hidden">
        <ul className="grid h-16 grid-cols-5">
          {items.map((item) => {
            const active = isActive(item.href);
            const content = (
              <>
                <span className="relative">
                  {item.href === "#ai" ? <AiBeautyMark strokeWidth={active ? 2 : 1.5} /> : <Icon name={item.icon} strokeWidth={active ? 2 : 1.5} />}
                  {!!item.badge && (
                    <span className="absolute -end-2.5 -top-2 grid min-w-[18px] place-items-center rounded-full bg-cta px-1 text-[10px] leading-[18px] font-bold text-paper ring-2 ring-paper">
                      {faNumber(item.badge)}
                    </span>
                  )}
                </span>
                <span className={active ? "font-bold" : "text-muted"} dir={item.href === "#ai" ? "ltr" : undefined}>{item.label}</span>
              </>
            );
            const cls = "flex h-full w-full flex-col items-center justify-center gap-1 text-[10px]";
            return (
              <li key={item.href}>
                {item.href.startsWith("#") ? (
                  <button type="button" className={cls} onClick={item.href === "#ai" ? openAiBeauty : () => setCatsOpen(true)} aria-current={active ? "page" : undefined}>
                    {content}
                  </button>
                ) : (
                  <Link href={item.href} className={cls} aria-current={active ? "page" : undefined}>
                    {content}
                  </Link>
                )}
              </li>
            );
          })}
        </ul>
      </nav>

      <Sheet open={catsOpen} onClose={() => setCatsOpen(false)} title="دسته‌بندی‌ها">
        <ul className="divide-y divide-line px-5">
          {nav.map((c) => (
            <li key={c.id}>
              <button
                type="button"
                className="flex w-full items-center justify-between py-4 text-sm font-medium"
                onClick={() => setExpanded(expanded === c.id ? null : c.id)}
                aria-expanded={expanded === c.id}
              >
                {c.name}
                <Icon name="chevron-down" size={18} className={`transition-transform ${expanded === c.id ? "rotate-180" : ""}`} />
              </button>
              {expanded === c.id && (
                <ul className="grid grid-cols-2 gap-2 pb-4">
                  <li>
                    <Link href={c.href} onClick={() => setCatsOpen(false)} className="block rounded-xl bg-mist px-3 py-3 text-xs font-bold">
                      همه {c.name}
                    </Link>
                  </li>
                  {c.children.map((ch) => (
                    <li key={ch.id}>
                      <Link href={ch.href} onClick={() => setCatsOpen(false)} className="block rounded-xl bg-mist px-3 py-3 text-xs">
                        {ch.name}
                      </Link>
                    </li>
                  ))}
                </ul>
              )}
            </li>
          ))}
          <li>
            <Link href="/brands" onClick={() => setCatsOpen(false)} className="flex items-center justify-between py-4 text-sm font-medium">
              برندها
              <Icon name="chevron-left" size={18} />
            </Link>
          </li>
          <li>
            <Link href="/mag" onClick={() => setCatsOpen(false)} className="flex items-center justify-between py-4 text-sm font-medium">
              مجله زیبایی
              <Icon name="chevron-left" size={18} />
            </Link>
          </li>
          <li>
            <Link href="/track" onClick={() => setCatsOpen(false)} className="flex items-center justify-between py-4 text-sm font-medium">
              پیگیری سفارش
              <Icon name="chevron-left" size={18} />
            </Link>
          </li>
        </ul>
      </Sheet>
    </>
  );
}
