"use client";

import { useEffect, useState } from "react";
import useSWR from "swr";
import { motion, LayoutGroup, AnimatePresence } from "framer-motion";
import Link from "next/link";
import {
  Home,
  Smartphone,
  HeartHandshake,
  Footprints,
  PackageSearch,
  Flame,
  Percent,
  Phone,
  ChevronLeft,
  ChevronRight,
  ChevronDown,
  Loader2,
  AlertCircle,
} from "lucide-react";
import ResponsiveSearchTopNav from "@/components/jsxFiles/ResponsiveSearchTopNav";
import BottomNavigation from "@/components/jsxFiles/BottomNavigation";

const mainCategories = [
  {
    id: "64369f180e0bb98ed2124604",
    title: "لوازم خانگی",
    href: "/category/homeApplianceProduct/64369f180e0bb98ed2124604",
    icon: Home,
    image: "componentsImages/catagories/Home_Appliances.jpg",
  },
  {
    id: "6436f62b729f9d9140060c88",
    title: "لوازم الکترونیک",
    href: "/category/mobileAccessoryProduct/6436f62b729f9d9140060c88",
    icon: Smartphone,
    image: "componentsImages/catagories/Phone_accessories.jpg",
  },
  {
    id: "6436f628729f9d9140060c86",
    title: "آرایشی بهداشتی",
    href: "/category/healthBeautyProduct/6436f628729f9d9140060c86",
    icon: HeartHandshake,
    image: "componentsImages/catagories/Cosmetic.jpg",
  },
  {
    id: "64369234da90e74ebe77cd0f",
    title: "کفش و پوشاک",
    href: "/category/shoeProduct/64369234da90e74ebe77cd0f",
    icon: Footprints,
    image: "componentsImages/catagories/shoes.jpg",
  },
];

const otherLinks = [
  {
    id: "shipping",
    title: "پیگیری سفارش",
    href: "/shippingStatus",
    icon: PackageSearch,
    accent: "text-emerald-600",
    bg: "bg-emerald-50",
  },
  {
    id: "userSaticfacion",
    title: "رضایت مشتریان",
    href: "/CustomerTestimonialsPage",
    icon: Flame,
    accent: "text-orange-500",
    bg: "bg-orange-50",
  },
  {
    id: "offers",
    title: "تخفیف‌های ویژه",
    href: "#",
    icon: Percent,
    accent: "text-red-500",
    bg: "bg-red-50",
  },
  {
    id: "contact",
    title: "تماس با ما",
    href: "/connectus",
    icon: Phone,
    accent: "text-sky-600",
    bg: "bg-sky-50",
  },
];

const fetcher = (...args) => fetch(...args).then((res) => res.json());

// =================================================================
// SubCategoryAccordion
// =================================================================

const SubCategoryAccordion = ({ subCategory, subcategoryParts }) => {
  const [isOpen, setIsOpen] = useState(false);

  const gridChildren = subcategoryParts.filter(
    (part) => part.subcategory === subCategory._id
  );

  const hasGridChildren = gridChildren.length > 0;
  const hasListChildren =
    subCategory.children && subCategory.children.length > 0;

  // حالت ۱: گرید
  if (hasGridChildren) {
    return (
      <div className="border-b border-slate-100 last:border-b-0">
        <button
          onClick={() => setIsOpen(!isOpen)}
          aria-expanded={isOpen}
          className="group flex w-full items-center justify-between gap-3 px-4 py-3.5 text-right transition-colors hover:bg-slate-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:px-5 sm:py-4"
        >
          <div className="min-w-0 flex-1">
            <h3 className="truncate text-sm font-bold text-slate-900 sm:text-base">
              {subCategory.title}
            </h3>
            <p className="mt-0.5 text-xs font-medium text-slate-400">
              {gridChildren.length} مورد
            </p>
          </div>

          <div
            className={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border transition-all duration-200 ${
              isOpen
                ? "border-red-100 bg-red-50 text-red-600"
                : "border-slate-200 bg-white text-slate-400 group-hover:text-slate-600"
            }`}
          >
            <ChevronDown
              className={`h-4 w-4 transition-transform duration-200 ${
                isOpen ? "rotate-180" : "rotate-0"
              }`}
            />
          </div>
        </button>

        <div
          className={`overflow-hidden transition-all duration-300 ease-in-out ${
            isOpen ? "max-h-[1400px] opacity-100" : "max-h-0 opacity-0"
          }`}
        >
          <div className="grid grid-cols-3 gap-2 px-3 pb-4 pt-1 sm:grid-cols-4 sm:gap-3 sm:px-5 md:grid-cols-5 lg:grid-cols-6">
            {gridChildren.map((part) => (
              <a
                key={part._id}
                href={`/subcategorypart/${part.title.replace(/ /g, "-")}A/${
                  part._id
                }`}
                className="group flex flex-col items-center rounded-2xl bg-slate-50/70 p-2 text-center transition-all duration-200 hover:bg-red-50 active:scale-95 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:border sm:border-slate-100 sm:bg-white sm:p-3 sm:shadow-sm sm:hover:-translate-y-0.5 sm:hover:border-red-100 sm:hover:shadow-md"
              >
                <img
                  src={
                    part.icon ||
                    `https://placehold.co/100x100/F1F5F9/64748B?text=${part.title.charAt(
                      0
                    )}`
                  }
                  alt={part.title}
                  className="h-12 w-12 rounded-xl border border-slate-100 object-cover sm:h-16 sm:w-16 sm:rounded-2xl"
                />

                <h4 className="mt-2 line-clamp-2 text-[11px] font-semibold leading-5 text-slate-700 group-hover:text-red-600 sm:text-xs sm:font-bold">
                  {part.title}
                </h4>
              </a>
            ))}

            <a
              href={`/subcategory/${subCategory.title.replace(/ /g, "-")}A/${
                subCategory._id
              }`}
              className="group flex flex-col items-center rounded-2xl bg-red-50 p-2 text-center transition-all duration-200 hover:bg-red-100 active:scale-95 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:border sm:border-red-100 sm:bg-white sm:p-3 sm:shadow-sm sm:hover:-translate-y-0.5 sm:hover:shadow-md"
            >
              <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-white text-red-500 ring-1 ring-red-100 sm:h-16 sm:w-16 sm:rounded-2xl sm:bg-red-500 sm:text-white sm:ring-0">
                <ChevronLeft className="h-5 w-5" />
              </div>

              <h4 className="mt-2 line-clamp-2 text-[11px] font-bold leading-5 text-red-600 sm:text-xs">
                همه
              </h4>
            </a>
          </div>
        </div>
      </div>
    );
  }

  // حالت ۲: لیست
  if (hasListChildren) {
    return (
      <div className="border-b border-slate-100 last:border-b-0">
        <button
          onClick={() => setIsOpen(!isOpen)}
          aria-expanded={isOpen}
          className="group flex w-full items-center gap-3 px-4 py-3.5 text-right transition-colors hover:bg-slate-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:gap-4 sm:px-5 sm:py-4"
        >
          <img
            src={
              subCategory.image ||
              `https://placehold.co/100x100/F8FAFC/64748B?text=${subCategory.title
                .charAt(0)
                .toUpperCase()}`
            }
            alt={subCategory.title}
            className="h-12 w-12 flex-shrink-0 rounded-2xl border border-slate-100 object-cover sm:h-16 sm:w-16"
          />

          <div className="min-w-0 flex-1 text-right">
            <h3 className="truncate text-sm font-bold text-slate-900 sm:text-base sm:font-extrabold">
              {subCategory.title}
            </h3>
            <p className="mt-0.5 text-xs font-medium text-slate-400">
              {isOpen ? "بستن" : "مشاهده زیرشاخه‌ها"}
            </p>
          </div>

          <div
            className={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border transition-all duration-200 ${
              isOpen
                ? "border-red-100 bg-red-50 text-red-600"
                : "border-slate-200 bg-white text-slate-400"
            }`}
          >
            <ChevronLeft
              className={`h-4 w-4 transition-transform duration-200 ${
                isOpen ? "-rotate-90" : "rotate-0"
              }`}
            />
          </div>
        </button>

        <div
          className={`overflow-hidden transition-all duration-300 ease-in-out ${
            isOpen ? "max-h-screen opacity-100" : "max-h-0 opacity-0"
          }`}
        >
          <div className="px-4 pb-4 sm:px-5">
            <a
              href={subCategory.href || "#"}
              target="_self"
              className="mb-2 flex w-full items-center justify-between rounded-xl bg-red-50 px-3 py-2.5 text-xs font-bold text-red-600 transition-colors hover:bg-red-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:rounded-2xl sm:bg-red-500 sm:px-4 sm:py-3 sm:text-sm sm:text-white sm:hover:bg-red-600"
            >
              <span>{`همه ${subCategory.title}`}</span>
              <ChevronLeft className="h-4 w-4" />
            </a>

            <ul className="grid gap-1.5 sm:grid-cols-2 sm:gap-2 lg:grid-cols-3">
              {subCategory.children.map((child) => (
                <li key={child._id}>
                  <a
                    href={child.href || "#"}
                    target="_self"
                    className="block w-full rounded-xl bg-slate-50 px-3 py-2.5 text-xs font-semibold text-slate-700 transition-colors hover:bg-red-50 hover:text-red-600 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:border sm:border-slate-100 sm:bg-white sm:px-4 sm:py-3 sm:text-sm sm:hover:border-red-100"
                  >
                    {child.title}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    );
  }

  // حالت ۳: لینک ساده
  return (
    <a
      href={subCategory.href || "#"}
      target="_self"
      className="group flex items-center gap-3 border-b border-slate-100 px-4 py-3.5 transition-colors last:border-b-0 hover:bg-slate-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:gap-4 sm:px-5 sm:py-4"
    >
      <img
        src={`https://www.atenakala.com/${subCategory.icon}`}
        alt={subCategory.title}
        className="h-12 w-12 flex-shrink-0 rounded-2xl border border-slate-100 object-cover sm:h-16 sm:w-16"
      />

      <div className="min-w-0 flex-1">
        <h3 className="truncate text-sm font-bold text-slate-900 sm:text-base sm:font-extrabold">
          {subCategory.title}
        </h3>
        <p className="mt-0.5 text-xs font-medium text-slate-400">
          مشاهده محصولات
        </p>
      </div>

      <ChevronLeft className="h-5 w-5 flex-shrink-0 text-slate-300 group-hover:text-red-500" />
    </a>
  );
};

// =================================================================
// کامپوننت اصلی
// =================================================================

export default function ResponsiveMenu() {
  useEffect(() => {
    document.title = `دسته بندی ها`;
  }, []);

  const { data, error, isLoading } = useSWR(`/api/subcategoriesoomenu`, fetcher);

  const [activeCatId, setActiveCatId] = useState(null);

  const activeCategory = mainCategories.find((c) => c.id === activeCatId);

  const subcategories = data?.subcategories || [];
  const subcategoryParts = data?.subcategoryparts || [];

  const activeSubcategories = subcategories.filter(
    (subcat) => subcat.category === activeCatId
  );

  const renderHeader = () => (
    <div className="sticky top-0 z-30">
      <div className="h-[2px] bg-red-500 sm:bg-gradient-to-l sm:from-red-700 sm:via-red-500 sm:to-orange-400" />

      <div className="border-b border-slate-100 bg-white/95 backdrop-blur-xl sm:shadow-[0_10px_35px_-25px_rgba(15,23,42,0.45)]">
        <div className="mx-auto flex max-w-7xl items-center gap-2 px-3 py-2.5 sm:gap-3 sm:px-6 sm:py-3 lg:px-8">
          <button
            onClick={() =>
              activeCatId ? setActiveCatId(null) : window.history.back()
            }
            aria-label="بازگشت"
            className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full bg-slate-50 text-slate-600 transition-colors hover:bg-red-50 hover:text-red-600 active:scale-95 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:h-auto sm:w-auto sm:gap-1.5 sm:border sm:border-slate-200 sm:bg-white sm:px-3 sm:py-2 sm:shadow-sm"
          >
            <ChevronRight className="h-5 w-5" />
            <span className="hidden text-sm font-bold leading-none sm:inline">
              بازگشت
            </span>
          </button>

          <div className="min-w-0 flex-1 overflow-hidden">
            <AnimatePresence mode="wait">
              {activeCatId && activeCategory ? (
                <motion.div
                  key="breadcrumb"
                  initial={{ opacity: 0, x: 8 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: -8 }}
                  transition={{ duration: 0.16 }}
                  className="flex min-w-0 items-center gap-2"
                >
                  <img
                    src={`https://www.atenakala.com/${activeCategory.image}`}
                    alt=""
                    aria-hidden="true"
                    className="h-8 w-8 flex-shrink-0 rounded-xl border border-slate-100 object-cover sm:h-9 sm:w-9 sm:rounded-2xl"
                  />

                  <div className="min-w-0">
                    <h1 className="truncate text-sm font-extrabold text-slate-900 sm:text-base">
                      {activeCategory.title}
                    </h1>
                    <p className="hidden text-xs font-medium text-slate-400 sm:block">
                      انتخاب زیرشاخه محصول
                    </p>
                  </div>
                </motion.div>
              ) : (
                <motion.div
                  key="brand"
                  initial={{ opacity: 0, x: 8 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: -8 }}
                  transition={{ duration: 0.16 }}
                  className="flex min-w-0 items-center gap-2"
                >
                  <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-xl bg-red-500 text-white sm:h-10 sm:w-10 sm:rounded-2xl sm:bg-gradient-to-br sm:from-red-600 sm:to-red-500 sm:shadow-lg sm:shadow-red-200/60">
                    <span className="text-sm font-black leading-none sm:text-base">
                      آ
                    </span>
                  </div>

                  <div className="min-w-0">
                    <h1 className="truncate text-sm font-extrabold text-slate-900 sm:text-base">
                      دسته‌بندی‌ها
                    </h1>
                    <p className="hidden text-xs font-medium text-slate-400 sm:block">
                      آتناکالا
                    </p>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          <Link
            href="/searchPageTopNav"
            className="flex-shrink-0 rounded-xl focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60"
          >
            <ResponsiveSearchTopNav />
          </Link>
        </div>
      </div>
    </div>
  );

  return (
    <LayoutGroup>
      <div className="flex min-h-screen flex-col bg-slate-50 pb-16 lg:bg-[radial-gradient(circle_at_top_right,#fee2e2_0,transparent_26%),linear-gradient(to_bottom,#f8fafc,#ffffff)] lg:pb-0">
        {renderHeader()}

        {activeCatId && (
          <div className="border-b border-slate-100 bg-white">
            <div
              className="mx-auto max-w-7xl overflow-x-auto px-3 py-2.5 sm:px-6 sm:py-3 lg:px-8"
              style={{
                scrollbarWidth: "none",
                msOverflowStyle: "none",
              }}
            >
              <div className="flex gap-2">
                {mainCategories.map((category) => (
                  <CategoryChip
                    key={category.id}
                    category={category}
                    isSelected={category.id === activeCatId}
                    onClick={() => setActiveCatId(category.id)}
                  />
                ))}
              </div>
            </div>
          </div>
        )}

        <main className="relative flex-1 overflow-y-auto">
          <AnimatePresence mode="wait">
            {!activeCatId && (
              <motion.div
                key="grid"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.18 }}
                className="mx-auto w-full max-w-7xl px-3 py-4 sm:px-6 sm:py-6 lg:px-8 lg:py-8"
              >
                {/* Hero فقط دسکتاپ/تبلت */}
                <section className="mb-5 hidden overflow-hidden rounded-2xl border border-red-100 bg-gradient-to-l from-red-600 to-orange-500 px-5 py-4 text-white shadow-sm sm:block">
                  <div className="flex items-center justify-between gap-4">
                    <div>
                      <div className="mb-2 inline-flex items-center gap-1.5 rounded-full bg-white/15 px-2.5 py-1 text-[11px] font-bold backdrop-blur">
                        <Flame className="h-3.5 w-3.5" />
                        دسته‌بندی‌ها
                      </div>

                      <h2 className="text-xl font-black leading-8 lg:text-2xl">
                        دسته‌بندی محصولات آتناکالا
                      </h2>

                      <p className="mt-1 text-sm font-medium leading-6 text-white/80">
                        سریع‌تر محصول موردنظرت را پیدا کن.
                      </p>
                    </div>

                    <div className="hidden rounded-2xl bg-white/15 p-3 backdrop-blur lg:block">
                      <PackageSearch className="h-10 w-10 text-white" />
                    </div>
                  </div>
                </section>


                <section>
                  <div className="mb-3 sm:mb-4">
                    <h2 className="text-base font-black text-slate-900 sm:text-2xl">
                      دسته‌بندی‌های اصلی
                    </h2>
                    <p className="mt-1 text-xs font-medium text-slate-400 sm:text-sm">
                      یک دسته را انتخاب کنید.
                    </p>
                  </div>

                  <ul className="grid gap-2.5 sm:gap-4 md:grid-cols-4">
                    {mainCategories.map((category) => (
                      <CategoryCard
                        key={category.id}
                        category={category}
                        onClick={() => setActiveCatId(category.id)}
                      />
                    ))}
                  </ul>
                </section>

                <section className="mt-6 rounded-2xl bg-white p-3 shadow-sm ring-1 ring-slate-100 sm:mt-8 sm:rounded-[2rem] sm:p-5 lg:p-6">
                  <div className="mb-3 sm:mb-4">
                    <h2 className="text-base font-black text-slate-900 sm:text-xl">
                      سرویس‌های دیگر
                    </h2>
                    <p className="mt-1 text-xs font-medium text-slate-400 sm:text-sm">
                      دسترسی‌های کاربردی فروشگاه
                    </p>
                  </div>

                  <ul className="grid grid-cols-2 gap-2 sm:gap-3 md:grid-cols-4">
                    {otherLinks.map((link) => (
                      <li key={link.id}>
                        <a
                          href={link.href}
                          target="_self"
                          className="group flex min-h-20 items-center gap-2 rounded-2xl bg-slate-50 px-3 py-3 transition-colors hover:bg-red-50 active:scale-95 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:min-h-32 sm:flex-col sm:justify-center sm:gap-3 sm:border sm:border-slate-100 sm:bg-white sm:p-4 sm:text-center sm:shadow-sm sm:hover:-translate-y-1 sm:hover:border-red-100 sm:hover:shadow-xl sm:hover:shadow-slate-200/70"
                        >
                          <div
                            className={`flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-xl ${link.bg} sm:h-14 sm:w-14 sm:rounded-2xl`}
                          >
                            <link.icon
                              className={`h-5 w-5 ${link.accent} sm:h-7 sm:w-7`}
                            />
                          </div>

                          <span className="text-xs font-bold text-slate-700 transition-colors group-hover:text-red-600 sm:text-sm sm:font-extrabold">
                            {link.title}
                          </span>
                        </a>
                      </li>
                    ))}
                  </ul>
                </section>
              </motion.div>
            )}

            {activeCatId && data && (
              <motion.div
                key="subcategories"
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -8 }}
                transition={{ delay: 0.03, duration: 0.18 }}
                className="mx-auto w-full max-w-7xl px-3 py-4 sm:px-6 sm:py-6 lg:px-8 lg:py-8"
              >
                <div className="grid gap-5 lg:grid-cols-[300px_1fr] xl:grid-cols-[340px_1fr]">
                  {/* Sidebar فقط دسکتاپ */}
                  <aside className="hidden lg:block">
                    <div className="hidden lg:block sticky top-28 rounded-[2rem] border border-slate-100 bg-white p-4 shadow-sm">
                      <h2 className="mb-3 px-2 text-sm font-black text-slate-900">
                        دسته‌بندی‌ها
                      </h2>

                      <div className="space-y-2">
                        {mainCategories.map((category) => (
                          <button
                            key={category.id}
                            onClick={() => setActiveCatId(category.id)}
                            className={`group flex w-full items-center gap-3 rounded-2xl border p-3 text-right transition-all ${
                              category.id === activeCatId
                                ? "border-red-100 bg-red-50 text-red-600 shadow-sm"
                                : "border-transparent bg-white text-slate-700 hover:border-slate-100 hover:bg-slate-50"
                            }`}
                          >
                            <img
                              src={`https://www.atenakala.com/${category.image}`}
                              alt={category.title}
                              className="h-11 w-11 rounded-2xl object-cover shadow-sm"
                            />

                            <span className="flex-1 text-sm font-extrabold">
                              {category.title}
                            </span>

                            <ChevronLeft
                              className={`h-4 w-4 transition-transform group-hover:-translate-x-0.5 ${
                                category.id === activeCatId
                                  ? "text-red-500"
                                  : "text-slate-300"
                              }`}
                            />
                          </button>
                        ))}
                      </div>
                    </div>
                  </aside>

                  <section>
                    <a
                      href={activeCategory.href}
                      target="_self"
                      className="mb-3 flex items-center justify-between rounded-2xl bg-white p-3 text-sm font-bold text-slate-900 shadow-sm ring-1 ring-slate-100 transition-colors hover:bg-red-50 hover:text-red-600 active:scale-[0.98] focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:mb-4 sm:rounded-[1.5rem] sm:bg-gradient-to-l sm:from-red-600 sm:to-red-500 sm:p-5 sm:font-black sm:text-white sm:shadow-xl sm:shadow-red-200/60 sm:hover:from-red-700 sm:hover:to-red-600 sm:hover:text-white"
                    >
                      <div>
                        <span className="block lg:text-white">
                          {`همه ${activeCategory.title}`}
                        </span>
                        <span className="mt-0.5 hidden text-xs font-semibold text-white/80 sm:block">
                          ورود به صفحه کامل این دسته‌بندی
                        </span>
                      </div>

                      <div className="flex h-8 w-8 items-center justify-center rounded-full bg-slate-50 text-slate-400 sm:h-10 sm:w-10 sm:bg-white/15 sm:text-white">
                        <ChevronLeft className="h-5 w-5" />
                      </div>
                    </a>

                    <div className="overflow-hidden rounded-2xl bg-white shadow-sm ring-1 ring-slate-100 sm:rounded-[2rem] sm:border sm:border-slate-100 sm:ring-0">
                      {activeSubcategories.length > 0 ? (
                        activeSubcategories.map((subCat) => (
                          <SubCategoryAccordion
                            key={subCat._id}
                            subCategory={subCat}
                            subcategoryParts={subcategoryParts}
                          />
                        ))
                      ) : (
                        <p className="p-8 text-center text-sm font-semibold text-slate-500">
                          زیرشاخه‌ای یافت نشد.
                        </p>
                      )}
                    </div>
                  </section>
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {isLoading && (
            <div className="absolute inset-0 z-30 flex items-center justify-center bg-white/75 backdrop-blur-sm">
              <div className="flex flex-col items-center gap-3 rounded-2xl bg-white px-6 py-5 shadow-lg ring-1 ring-slate-100 sm:rounded-3xl sm:px-8 sm:py-7">
                <Loader2 className="h-7 w-7 animate-spin text-red-500 sm:h-8 sm:w-8" />
                <span className="text-xs font-bold text-slate-600 sm:text-sm">
                  در حال بارگذاری...
                </span>
              </div>
            </div>
          )}

          {error && !isLoading && (
            <div className="absolute inset-0 z-30 flex items-center justify-center bg-white p-4">
              <div className="flex max-w-sm flex-col items-center rounded-3xl border border-red-100 bg-red-50 p-6 text-center">
                <AlertCircle className="mb-3 h-9 w-9 text-red-500" />
                <span className="text-sm font-black text-red-700 sm:text-base">
                  خطا در بارگذاری
                </span>
                <p className="mt-2 text-xs font-medium leading-6 text-red-600/80 sm:text-sm">
                  لطفاً چند لحظه دیگر دوباره تلاش کنید.
                </p>
              </div>
            </div>
          )}
        </main>
      </div>

      <BottomNavigation />
    </LayoutGroup>
  );
}

// =================================================================
// CategoryCard
// =================================================================

function CategoryCard({ category, onClick }) {
  const Icon = category.icon;

  return (
    <motion.li layoutId={`category-container-${category.id}`}>
      <button
        onClick={onClick}
        className="group w-full overflow-hidden rounded-2xl bg-white text-right shadow-sm ring-1 ring-slate-100 transition-all duration-200 hover:bg-red-50 active:scale-95 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:relative sm:rounded-[1.6rem] sm:shadow-md sm:shadow-slate-200/70 sm:hover:-translate-y-1 sm:hover:bg-white sm:hover:shadow-2xl sm:hover:shadow-red-100/80"
      >
        {/* موبایل: مینیمال و کم‌حجم */}
        <div className="flex items-center gap-3 p-3 sm:hidden">
          <img
            src={category.image}
            alt={category.title}
            className="h-14 w-14 flex-shrink-0 rounded-2xl object-cover"
          />

          <div className="min-w-0 flex-1">
            <h3 className="truncate text-sm font-extrabold text-slate-900">
              {category.title}
            </h3>
            <p className="mt-1 text-xs font-medium text-slate-400">
              مشاهده دسته
            </p>
          </div>

          <ChevronLeft className="h-5 w-5 flex-shrink-0 text-slate-300" />
        </div>

        {/* دسکتاپ/تبلت: تصویری و پرمیوم */}
        <div className="relative hidden aspect-[5/4] sm:block md:aspect-[4/5] lg:aspect-[5/4]">
          <motion.img
            layoutId={`category-image-${category.id}`}
            src={category.image}
            alt={category.title}
            className="absolute inset-0 h-full w-full object-cover transition-transform duration-700 group-hover:scale-110"
          />

          <div className="absolute inset-0 bg-gradient-to-t from-slate-950/80 via-slate-950/25 to-transparent" />
          <div className="absolute inset-0 bg-gradient-to-br from-red-600/20 via-transparent to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100" />

          <div className="absolute right-3 top-3 flex h-10 w-10 items-center justify-center rounded-2xl bg-white/90 text-red-600 shadow-sm backdrop-blur">
            <Icon className="h-5 w-5" />
          </div>

          <div className="absolute bottom-0 right-0 w-full p-4 text-right">
            <motion.h3
              layoutId={`category-title-${category.id}`}
              className="text-lg font-black text-white drop-shadow-sm"
            >
              {category.title}
            </motion.h3>

            <div className="mt-2 inline-flex items-center gap-1.5 rounded-full bg-white/15 px-3 py-1 text-[11px] font-bold text-white backdrop-blur transition-colors group-hover:bg-red-500">
              مشاهده زیرشاخه‌ها
              <ChevronLeft className="h-3.5 w-3.5" />
            </div>
          </div>
        </div>
      </button>
    </motion.li>
  );
}

// =================================================================
// CategoryChip
// =================================================================

function CategoryChip({ category, isSelected, onClick }) {
  return (
    <motion.button
      layoutId={`category-container-${category.id}`}
      onClick={onClick}
      type="button"
      className={`flex flex-shrink-0 items-center gap-2 rounded-full border px-3 py-1.5 transition-all active:scale-95 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/60 sm:px-3 sm:py-2 ${
        isSelected
          ? "border-red-500 bg-red-500 text-white shadow-sm sm:shadow-lg sm:shadow-red-200/60"
          : "border-slate-200 bg-white text-slate-600 hover:border-red-100 hover:bg-red-50 hover:text-red-600"
      }`}
    >
      <motion.img
        layoutId={`category-image-${category.id}`}
        src={`https://www.atenakala.com/${category.image}`}
        alt={category.title}
        className={`h-6 w-6 rounded-full object-cover sm:h-7 sm:w-7 ${
          isSelected ? "ring-1 ring-white/40" : "ring-1 ring-slate-100"
        }`}
      />

      <motion.h3
        layoutId={`category-title-${category.id}`}
        className="whitespace-nowrap text-xs font-bold sm:text-sm sm:font-extrabold"
      >
        {category.title}
      </motion.h3>
    </motion.button>
  );
}
