"use client";

import { usePathname } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import NavItem from "./NavItems";
import { SquareButton } from "./SquareButton";
import { BalancePill } from "./BalancePill";
import { XPBadge } from "./XPBadge";
import { Burger } from "./BurgerMenu";
import { useSelector } from "react-redux";
import GameModesSubMenus from "./GameModesSubMenus";
import { User } from "@/constants/types";
import PacksModes from "./PacksModes";
import PackSubMenus from "./PackSubMenus";

const MOBILE_GAMES = [
  { label: "Roll", href: "/games/roll" },
  { label: "Crash", href: "/games/crash" },
  { label: "Coinflip", href: "/games/coinflip" },
  { label: "Mystery Slabs", href: "/games/mystery-packs" },
  { label: "Spin", href: "/games/spin" },
];

const MOBILE_PACKS = [
  { label: "Shop", href: "/shop" },
  { label: "Boxes", href: "/mystery-boxes" },
  { label: "Mystery Slabs", href: "/games/mystery-packs" },
];

export default function Header() {
  const [open, setOpen] = useState(false);
  const user = useSelector((state: any) => state.auth.user) as User | null;
  const status = useSelector((state: any) => state.auth.status);
  const [gamesOpen, setGamesOpen] = useState(false);
  const closeTimer = useRef<number | null>(null);
  const [instantClose, setInstantClose] = useState(false);
  const [mobileGamesOpen, setMobileGamesOpen] = useState(false);
  const [gamesMobileOpen, setGamesMobileOpen] = useState(false);
  const [packsOpen, setPacksOpen] = useState(false);
  const [mobilePacksOpen, setMobilePacksOpen] = useState(false);
  const [packsLock, setPacksLock] = useState(false);
  const [gamesLock, setGamesLock] = useState(false);
  const pathname = usePathname();

  const NAV = [
    {
      href: "/shop",
      label: "Shop",
      icon: "/images/header/lock.svg",
      ActiveIcon: "/images/header/lockBlue.svg",
    },
    ...(user?.is_deposit
      ? [
          {
            href: "/games/roll",
            label: "Games",
            icon: "/images/header/game-i.svg",
            ActiveIcon: "/images/header/game-ac.svg",
          },
          {
            href: "/sports",
            label: "Sports",
            icon: "/images/header/tyre-i.svg",
            ActiveIcon: "/images/header/tyre-ac.svg",
          },
          {
            href: "/rewards",
            label: "Rewards",
            icon: "/images/header/start-i.svg",
            ActiveIcon: "/images/header/star-ac.svg",
          },
        ]
      : []),

    ...(!user?.is_deposit
      ? [
          {
            href: "/mystery-boxes",
            label: "Mystery Boxes",
            icon: "/images/header/box-i.svg",
            ActiveIcon: "/images/header/box-ac.svg",
          },
          {
            href: "/games/mystery-packs",
            label: "SLABS",
            icon: "/images/header/slab.svg",
            ActiveIcon: "/images/header/star-ac.svg",
          },
          {
            href: "/faqs",
            label: "Faqs",
            icon: "/images/header/faqs.svg",
            ActiveIcon: "/images/header/star-ac.svg",
          },
        ]
      : []),
  ];

  const openPacks = () => {
    if (packsLock) return; // ✅ prevent instant re-open after click
    if (closeTimer.current) window.clearTimeout(closeTimer.current);
    setGamesOpen(false);
    setPacksOpen(true);
  };

  const closePacks = () => {
    if (closeTimer.current) window.clearTimeout(closeTimer.current);
    closeTimer.current = window.setTimeout(() => setPacksOpen(false), 140);
  };

  const closePacksFromClick = () => {
    if (closeTimer.current) window.clearTimeout(closeTimer.current);
    setPacksLock(true);
    setInstantClose(true); // ✅ no animation frame
    setPacksOpen(false);
    window.setTimeout(() => {
      setPacksLock(false);
      setInstantClose(false);
    }, 250);
  };

  const closeAllMobile = () => {
    setOpen(false);
    setGamesMobileOpen(false);
  };

  const openGames = () => {
    if (gamesLock) return;
    if (closeTimer.current) window.clearTimeout(closeTimer.current);
    setPacksOpen(false);
    setGamesOpen(true);
  };

  const closeGames = () => {
    if (closeTimer.current) window.clearTimeout(closeTimer.current);
    closeTimer.current = window.setTimeout(() => setGamesOpen(false), 140);
  };

  const closeGamesFromClick = () => {
    if (closeTimer.current) window.clearTimeout(closeTimer.current);
    setGamesLock(true);
    setGamesOpen(false);
    window.setTimeout(() => setGamesLock(false), 250);
  };

  useEffect(() => {
    setPacksOpen(false);
    setGamesOpen(false);
    setInstantClose(true); // optional: route change pe animation na ho
    const t = setTimeout(() => setInstantClose(false), 0);
    return () => clearTimeout(t);
  }, [pathname]);

  useEffect(() => {
    const onScroll = () => {
      setInstantClose(true);
      setGamesOpen(false);
      setPacksOpen(false);
      // next tick pe wapas smooth allow
      requestAnimationFrame(() => setInstantClose(false));
    };

    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    if (!open) setMobileGamesOpen(false);
  }, [open]);

  useEffect(() => {
    if (!open) {
      setMobileGamesOpen(false);
      setMobilePacksOpen(false);
    }
  }, [open]);

  return (
    <header className="sticky border-b border-(--color-gray) bg-(--color-naviBlue) md:py-3 z-9999 px-2 top-0 tracking-tighter ">
      <div className="max-w-400 mx-auto px-3 2xl:px-6">
        <div className=" flex items-center gap-4 2xl:gap-10">
          <Link href="/">
            <Image
              src="/images/header/tcg.svg"
              alt="Open That Pack"
              width={96}
              height={28}
              placeholder="empty"
              className="w-15 md:w-17.5 h-auto"
            />
          </Link>

          {/* Desktop Nav */}

          <nav className="hidden xl:flex items-center gap-5 2xl:gap-8 2xl:ml-2">
            {NAV.map((item, index) => {
              const isActive =
                item.label === "Games"
                  ? pathname.startsWith("/games")
                  : pathname === item.href ||
                    pathname.startsWith(item.href + "/");

              if (item.label === "Games") {
                return (
                  <div
                    key={index}
                    className="relative"
                    onMouseEnter={openGames}
                    onMouseLeave={closeGames}
                  >
                    <NavItem
                      href={item.href}
                      label={item.label}
                      icon={item.icon}
                      ActiveIcon={item.ActiveIcon}
                      active={isActive}
                      hasDropdown
                    />

                    <div
                      onMouseEnter={openGames}
                      onMouseLeave={closeGames}
                      className={`
  fixed left-1/2 ${user ? "top-[62px]" : "top-[50px] 2xl:top-[53px]"}  bg-(--color-naviBlue) -translate-x-1/2 mt-4 w-full z-9999
  transition-all ${instantClose ? "duration-0" : "duration-200"}
  ${
    gamesOpen
      ? "opacity-100 translate-y-0 pointer-events-auto"
      : "opacity-0 -translate-y-2 pointer-events-none"
  }
`}
                    >
                      <div className="bg container  mx-auto">
                        <GameModesSubMenus closeGames={closeGamesFromClick} />
                      </div>
                    </div>
                  </div>
                );
              }

              if (item.label === "Shop") {
                const isActive =
                  item.label === "Shop"
                    ? pathname.startsWith("/shop")
                    : pathname === item.href ||
                      pathname.startsWith(item.href + "/");
                return (
                  <div
                    key={index}
                    className="relative"
                    onMouseEnter={openPacks}
                    onMouseLeave={closePacks}
                  >
                    <NavItem
                      href={item.href}
                      label={item.label}
                      icon={item.icon}
                      ActiveIcon={item.ActiveIcon}
                      active={isActive}
                      hasDropdown
                    />

                    <div
                      onMouseEnter={openPacks}
                      onMouseLeave={closePacks}
                      className={`
    fixed left-1/2 ${user ? "top-[62px]" : "top-[50px] 2xl:top-[53px]"}
    -translate-x-1/2 mt-4 w-full z-9999 bg-(--color-naviBlue)
    ${packsOpen ? "block" : "hidden"}   // ✅ IMPORTANT
    ${instantClose ? "" : "transition-all duration-200"}
    ${packsOpen ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-2"}
  `}
                    >
                      <div className="bg container mx-auto">
                        <PackSubMenus closePacks={closePacksFromClick} />
                      </div>
                    </div>
                  </div>
                );
              }

              return (
                <NavItem
                  key={item.href}
                  href={item.href}
                  label={item.label}
                  icon={item.icon}
                  ActiveIcon={item.ActiveIcon}
                  active={isActive}
                />
              );
            })}
          </nav>

          {/* Spacer */}
          <div className="flex-1" />

          {/* CTA Buttons */}
          <div className="hidden xl:flex items-center gap-2 2xl:gap-3">
            <SquareButton
              href="/trade"
              label="Trade"
              ActiveIcon="/images/header/lock-ac.svg"
              className="px-5"
              active={pathname === "/trade" || pathname.startsWith("/trade/")}
            />

            <>
              {status == "authenticated" ? (
                <SquareButton
                  href="/inventory"
                  label="Inventory"
                  icon="/images/header/lock-i.svg"
                  ActiveIcon="/images/header/lock-ac.svg"
                  active={
                    pathname === "/inventory" ||
                    pathname.startsWith("/inventory/")
                  }
                />
              ) : null}

              {status == "authenticated" ? (
                <BalancePill
                  activeMode={user?.activeMode ?? "coins"}
                  coins={user?.coins ?? 0}
                  gems={user?.gems ?? 0}
                  value={user?.balance ?? 0}
                />
              ) : null}

              <XPBadge
                status={status}
                user={user}
                xp={1000}
                level={7}
                avatarSrc="/images/profile/img.svg"
                username="Umar"
              />
            </>
          </div>

          {/* Mobile toggles */}
          <button
            className="xl:hidden inline-flex items-center justify-center w-10 h-10 rounded-md hover:bg-white/5 focus:outline-none"
            onClick={() => setOpen((v) => !v)}
            aria-label="Toggle menu"
          >
            <Burger open={open} />
          </button>
        </div>
      </div>

      {/* Mobile Drawer */}
      <div
        className={`xl:hidden overflow-y-auto relative z-9999 md:overflow-hidden transition-all duration-200 ${
          open ? "max-h-full" : "hidden"
        }`}
      >
        <div className="px-4 pt-4 pb-6 bg-navy-900/90">
          <div className="grid gap-3">
            {NAV.map((item, index) => {
              const isActive =
                pathname === item.href || pathname.startsWith(item.href + "/");

              // ✅ Mobile Games dropdown
              if (item.label === "Games") {
                return (
                  <div key={index} className="rounded-md md:overflow-hidden">
                    {/* Top row: Games button */}
                    <div
                      onClick={() => setMobileGamesOpen((v) => !v)}
                      className="w-full"
                    >
                      <NavItem
                        // href={item?.href}
                        label={item.label}
                        icon={item.icon}
                        ActiveIcon={item.ActiveIcon}
                        active={isActive}
                      />
                    </div>

                    {/* Dropdown */}
                    <div
                      className={`transition-all duration-200 ${
                        mobileGamesOpen
                          ? "max-h-96 opacity-100"
                          : "max-h-0 opacity-0"
                      } overflow-hidden`}
                    >
                      <div className="mt-2 ml-10 grid gap-2 pb-2">
                        {MOBILE_GAMES.map((g) => {
                          const gameActive =
                            pathname === g.href ||
                            pathname.startsWith(g.href + "/");

                          return (
                            <Link
                              key={g.href}
                              href={g.href}
                              onClick={() => {
                                setOpen(false); // close mobile drawer
                                setMobileGamesOpen(false); // close dropdown
                              }}
                              className={`text-sm font-sofia ${
                                gameActive ? "text-white" : "text-white/70"
                              } hover:text-white`}
                            >
                              {g.label}
                            </Link>
                          );
                        })}
                      </div>
                    </div>
                  </div>
                );
              }
              if (item.label === "Shop") {
                const isActive =
                  pathname === "/shop" || pathname.startsWith("/shop/");

                return (
                  <div key={index} className="rounded-md md:overflow-hidden">
                    {/* Top row: Shop button */}
                    <div
                      onClick={() => {
                        setMobilePacksOpen((v) => !v);
                        setMobileGamesOpen(false); // ✅ (optional) games close
                      }}
                      className="w-full"
                    >
                      <NavItem
                        label={item.label}
                        icon={item.icon}
                        ActiveIcon={item.ActiveIcon}
                        active={isActive}
                      />
                    </div>

                    {/* Dropdown */}
                    <div
                      className={`transition-all duration-200 ${
                        mobilePacksOpen
                          ? "max-h-96 opacity-100"
                          : "max-h-0 opacity-0"
                      } overflow-hidden`}
                    >
                      <div className="mt-2 ml-10 grid gap-2 pb-2">
                        {MOBILE_PACKS.map((p) => {
                          const packActive =
                            pathname === p.href ||
                            pathname.startsWith(p.href + "/");

                          return (
                            <Link
                              key={p.href}
                              href={p.href}
                              onClick={() => {
                                setOpen(false);
                                setMobilePacksOpen(false);
                              }}
                              className={`text-sm font-sofia ${
                                packActive ? "text-white" : "text-white/70"
                              } hover:text-white`}
                            >
                              {p.label}
                            </Link>
                          );
                        })}
                      </div>
                    </div>
                  </div>
                );
              }

              // normal items
              return (
                <NavItem
                  key={item.href}
                  href={item.href}
                  label={item.label}
                  icon={item.icon}
                  ActiveIcon={item.ActiveIcon}
                  active={isActive}
                  onClick={closeAllMobile}
                />
              );
            })}
          </div>

          <div className="mt-4 grid gap-3">
            <SquareButton
              href="/trade"
              label="Trade"
              className="w-full justify-center "
              ActiveIcon="/images/header/lock-ac.svg"
              onClick={() => setOpen(false)}
            />
            {status == "authenticated" ? (
              <SquareButton
                href="/inventory"
                label="Inventory"
                icon="/images/header/lock-i.svg"
                className="w-full justify-center"
                ActiveIcon="/images/header/lock-ac.svg"
                active={
                  pathname === "/inventory" ||
                  pathname.startsWith("/inventory/")
                }
                onClick={() => setOpen(false)}
              />
            ) : null}

            {status == "authenticated" ? (
              <BalancePill
                activeMode={user?.activeMode ?? "coins"}
                coins={user?.coins ?? 0}
                gems={user?.gems ?? 0}
                value={user?.balance ?? 0}
                className="w-full"
              />
            ) : null}

            <div className="">
              <XPBadge
                status={status}
                user={user}
                xp={1000}
                level={7}
                avatarSrc="/images/header/profile.svg"
                username="Umar"
              />
            </div>
          </div>
        </div>
      </div>
    </header>
  );
}
