"use client";

import Link from "next/link";
import { useEffect, useState, useRef, useMemo } from "react";
import { useRouter, usePathname } from "next/navigation";
import useSWR from "swr";

import {
  UserIcon,
  ShoppingBagIcon,
  MagnifyingGlassIcon,
  Bars3Icon,
} from "@heroicons/react/24/outline";

import { useAuth } from "@/context/AuthContext";
import { toPersianDigitsDecimal } from "@/lib/utl/toPersianDigitsDecimal";
import Image from "next/image";

const apiFetch = async (url, options = {}) =>
  fetch(url, {
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    ...options,
  });

const swrFetcher = (url) => apiFetch(url).then((res) => res.json());

// لوگو مینیمال
const Logo = () => {
  return (
    <Link
      href="/"
      className="group flex items-baseline shrink-0 relative outline-none focus-visible:ring-2 focus-visible:ring-rose-500/50"
      aria-label="صفحه اصلی آتناکالا"
    >
      <Image src={'/topNavLogo34.png'} width={100} height={100} alt="لوگو سایت" className=" opacity-85" />
    </Link>
  );
};

const ResponsiveNav = () => {
  const [showNav, setShowNav] = useState(true);
  const [lastScrollY, setLastScrollY] = useState(0);
  const [headerHeight, setHeaderHeight] = useState(0);
  const headerRef = useRef(null);

  const { user, loading: authLoading } = useAuth();
  const router = useRouter();
  const pathname = usePathname();

  const { data: ordersData } = useSWR(
    user ? "/api/orders/my-orders" : null,
    swrFetcher,
    { refreshInterval: 60000 }
  );

  const cartCount = useMemo(() => {
    if (!ordersData?.orders) return 0;
    return ordersData.orders.filter(
      (order) =>
        order.productShippingStatu !== "تحویل شده" ||
        order.productShippingStatu === "جاری"
    ).length;
  }, [ordersData]);

  useEffect(() => {
    const updateHeaderHeight = () => {
      if (headerRef.current) setHeaderHeight(headerRef.current.offsetHeight);
    };
    updateHeaderHeight();
    window.addEventListener("resize", updateHeaderHeight);
    return () => window.removeEventListener("resize", updateHeaderHeight);
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollY = window.scrollY;
      setShowNav(currentScrollY < lastScrollY || currentScrollY < 50);
      setLastScrollY(currentScrollY);
    };
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, [lastScrollY]);

  const renderUserHub = () => {
    if (authLoading) {
      return (
        <div className="w-8 h-8 flex items-center justify-center">
          <div className="w-4 h-4 border-2 border-zinc-200 border-t-rose-500 rounded-full animate-spin" />
        </div>
      );
    }

    return (
      <div className="flex items-center gap-1 sm:gap-1.5">
        {/* سبد خرید (منتقل شد به وسط) */}
        <Link
          href="/dashboard/orders"
          className="relative flex items-center justify-center w-8 h-8 rounded-xl hover:bg-zinc-100 text-zinc-700 transition-all duration-200"
          aria-label="سبد خرید"
        >
          <ShoppingBagIcon className="w-5 h-5 stroke-[1.5]" />
          
          {cartCount > 0 && (
            <span className="absolute top-1 right-1 flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-rose-500 text-[10px] font-bold text-white leading-none border-2 border-white translate-x-1/4 -translate-y-1/4 shadow-sm">
              {cartCount > 99 ? "۹۹+" : toPersianDigitsDecimal(cartCount)}
            </span>
          )}
        </Link>

        {/* خط جداکننده (فاصله‌ها کمتر شد) */}
        <span className="w-px h-5 bg-zinc-200 hidden sm:block mx-0.5" />

        {/* ورود / پروفایل (منتقل شد به چپ) */}
        {!user ? (
          <button
            aria-label="لاگین و ثبت نام"
            onClick={() => router.push(`/signup?redirect=${pathname}`)}
            className="flex items-center gap-1.5 h-10 px-2 sm:px-3 rounded-xl border border-zinc-200 hover:border-zinc-300 text-zinc-700 hover:bg-zinc-50 transition-all duration-200 ml-1"
          >
            <UserIcon className="w-5 h-5 stroke-[1.5]" />
            <span className="text-[13px] font-bold hidden sm:block">ورود | ثبت‌نام</span>
          </button>
        ) : (
          <Link
            href="/dashboard"
            className="flex items-center gap-1.5 h-10 px-2 sm:px-3 rounded-xl hover:bg-zinc-100 text-zinc-700 transition-all duration-200 ml-1"
            title="پروفایل کاربری"
          >
            <div className="relative flex items-center justify-center w-7 h-7 rounded-full bg-zinc-100 border border-zinc-200">
              <UserIcon className="w-4 h-4 stroke-[2]" />
              <span className="absolute bottom-0 -right-0.5 w-2.5 h-2.5 rounded-full bg-emerald-500 border-2 border-white" />
            </div>
            <span className="text-[13px] font-bold hidden sm:block text-zinc-600">پروفایل من</span>
          </Link>
        )}
      </div>
    );
  };

  return (
    <>
      <header
        ref={headerRef}
        className={`fixed top-0 left-0 w-full z-[999] bg-white/95 backdrop-blur-md border-b border-zinc-100 transition-transform duration-300 ease-in-out ${
          showNav ? "translate-y-0" : "-translate-y-full"
        }`}
        dir="rtl"
      >

        <div className="w-full">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 h-[68px] flex items-center justify-between gap-4 sm:gap-6">
            
            {/* بخش راست: منو و لوگو */}
            <div className="flex items-center gap-0 sm:gap-5 shrink-0">
              <Link
                href="/responsive-site-menu"
                className="flex items-center justify-center w-8 h-8 rounded-xl text-zinc-700 hover:bg-zinc-100 transition-all duration-200"
                aria-label="منوی سایت"
              >
                <Bars3Icon className="w-6 h-6 stroke-[1.5]" />
              </Link>
              {/* <Logo /> */}
            </div>

            {/* بخش وسط: جستجو */}
            <div className="hidden md:flex flex-1 max-w-xl">
              <Link
                href="/searchPageTopNav"
                className="group flex items-center w-full h-[42px] px-4 gap-3 bg-zinc-100 hover:bg-zinc-200/60 rounded-xl text-zinc-500 transition-all duration-200 border border-transparent hover:border-zinc-200"
              >
                <MagnifyingGlassIcon className="w-5 h-5 stroke-[1.5] group-hover:text-zinc-700 transition-colors" />
                <span className="text-[13px] font-medium mt-0.5">جستجو در آتناکالا...</span>
              </Link>
            </div>

            {/* بخش چپ: آیکون‌های کاربر، سبد خرید و جستجوی موبایل (فاصله کلی کمتر شد) */}
            <div className="flex items-center gap-0.5 sm:gap-1 shrink-0">
              <Link
                href="/searchPageTopNav"
                className="md:hidden flex items-center justify-center w-8 h-8 rounded-xl text-zinc-700 hover:bg-zinc-100 transition-all duration-200"
                aria-label="جستجو"
              >
                <MagnifyingGlassIcon className="w-5 h-5 stroke-[1.5]" />
              </Link>
              
              {renderUserHub()}
            </div>

          </div>
        </div>
      </header>

      <div
        style={{ height: `${headerHeight}px` }}
        aria-hidden="true"
        className="w-full shrink-0"
      />
    </>
  );
};

export default ResponsiveNav;
