"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Search, ShoppingBag, User, Menu, X, Heart, ChevronDown } from "lucide-react";
import { useState } from "react";
import { useCart } from "@/context/CartContext";
import { useFavorites } from "@/context/FavoritesContext";
import { useAuth } from "@/context/AuthContext";
import { AccountMenu } from "@/components/layout/AccountMenu";
import { NavMegaMenu } from "@/components/layout/NavMegaMenu";
import { SearchOverlay } from "@/components/layout/SearchOverlay";
import { OtClubSeal } from "@/components/brand/OtClubSeal";
import { HOME_REGISTER_EVENT } from "@/components/marketing/SubscribeModal";
import { BrandMarquee } from "@/components/marketing/BrandMarquee";
import { megaMenusByHref } from "@/lib/nav-mega-menu";

function goHomeIfGuest(hasAccount: boolean | object | null) {
  if (!hasAccount && typeof window !== "undefined") {
    window.dispatchEvent(new Event(HOME_REGISTER_EVENT));
  }
}

const links = [
  { href: "/", label: "Inicio" },
  { href: "/shop?cat=mujer", label: "MUJER", mega: true as const },
  { href: "/shop?cat=hombre", label: "HOMBRE", mega: true as const },
  { href: "/collections", label: "CLUB 1976", mega: true as const },
  { href: "/shop?cat=accesorios", label: "Accesorios", mega: true as const },
];

function isNavActive(pathname: string, href: string) {
  if (href === "/") return pathname === "/";
  const pathOnly = href.split("?")[0].split("#")[0];
  if (href.includes("cat=mujer")) {
    return (
      pathname.startsWith("/product/vestido-sporty-elegance") ||
      pathname.startsWith("/product/set-polo-falda-club-1976") ||
      pathname.startsWith("/product/enterizo-deportivo-diagonal") ||
      pathname.startsWith("/product/enterizo-diagonal-falda") ||
      pathname.startsWith("/product/chaqueta-ot-classic") ||
      pathname.startsWith("/product/truzas") ||
      pathname.startsWith("/product/faldas") ||
      (pathname.startsWith("/product/polos") &&
        !pathname.startsWith("/product/polos-hombre"))
    );
  }
  if (href.includes("cat=hombre")) {
    return (
      pathname.startsWith("/product/conjunto-dos-piezas-chaqueta") ||
      pathname.startsWith("/product/bermuda-y-camisa") ||
      pathname.startsWith("/product/polos-hombre")
    );
  }
  if (href === "/collections" || href.startsWith("/collections#")) {
    return (
      pathname.startsWith("/collections") ||
      pathname.startsWith("/product/set-completo-club-1976") ||
      pathname.startsWith("/product/set-pareja-club-1976")
    );
  }
  if (href.includes("cat=accesorios")) {
    return (
      pathname.startsWith("/product/packaging-ot") ||
      pathname.startsWith("/product/visor-ot") ||
      pathname.startsWith("/product/bolso-duffel-ot") ||
      pathname.startsWith("/product/gorra-ot") ||
      pathname.startsWith("/product/neceser-ot")
    );
  }
  return pathname === pathOnly || pathname.startsWith(`${pathOnly}/`);
}

export function AnnouncementBar() {
  const pathname = usePathname();
  if (
    pathname.startsWith("/account/reset-password") ||
    pathname.startsWith("/ops") ||
    pathname.startsWith("/negocio")
  )
    return null;

  return <BrandMarquee className="border-b border-ot-cream/10" />;
}

export function Navbar() {
  const pathname = usePathname();
  const router = useRouter();
  const { count } = useCart();
  const { count: favCount } = useFavorites();
  const { customer, logout } = useAuth();
  const [open, setOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  /** Href del mega menú abierto en mobile (mujer/hombre) */
  const [mobileMegaHref, setMobileMegaHref] = useState<string | null>(null);
  const [mobileMegaSection, setMobileMegaSection] = useState<string | null>(
    null
  );
  if (
    pathname.startsWith("/account/reset-password") ||
    pathname.startsWith("/ops") ||
    pathname.startsWith("/negocio")
  )
    return null;

  return (
    <>
    <header className="sticky top-0 z-50 bg-ot-cream/95 backdrop-blur border-b border-black/5">
      <div className="ot-container flex items-center justify-between gap-4 py-4">
        <button className="lg:hidden" onClick={() => setOpen((v) => !v)} aria-label="Menú">
          {open ? <X size={22} /> : <Menu size={22} />}
        </button>
        <Link
          href="/"
          className="font-serif text-2xl tracking-[0.08em]"
          onClick={() => goHomeIfGuest(customer)}
        >
          OT <span className="text-sm tracking-[0.28em] ml-1">OLD TENNIS</span>
        </Link>
        <nav className="hidden lg:flex items-center gap-6 text-[12px] tracking-[0.16em] uppercase">
          {links.map((l) => {
            const mega = megaMenusByHref[l.href];
            if (mega) {
              return (
                <NavMegaMenu
                  key={l.href}
                  section={mega}
                  active={isNavActive(pathname, l.href)}
                  onNavigateHomeGuest={() => goHomeIfGuest(customer)}
                />
              );
            }
            return (
              <Link
                key={l.href}
                href={l.href}
                onClick={() => {
                  if (l.href === "/") goHomeIfGuest(customer);
                }}
                className={
                  isNavActive(pathname, l.href)
                    ? "text-ot-gold border-b border-ot-gold pb-0.5"
                    : "text-ot-ink/80 hover:text-ot-ink"
                }
              >
                {l.label}
              </Link>
            );
          })}
        </nav>
        <div className="flex items-center gap-3">
          <button
            type="button"
            aria-label="Buscar"
            className="hover:text-ot-gold"
            onClick={() => setSearchOpen(true)}
          >
            <Search size={18} />
          </button>
          {customer ? (
            <AccountMenu />
          ) : (
            <Link href="/account" aria-label="Cuenta" className="hover:text-ot-gold">
              <User size={18} />
            </Link>
          )}
          <Link
            href={customer ? "/account/favorites" : "/account"}
            aria-label="Favoritos"
            className="relative hover:text-ot-gold"
          >
            <Heart
              size={18}
              fill={favCount > 0 ? "currentColor" : "none"}
              className={favCount > 0 ? "text-ot-green" : undefined}
            />
            {favCount > 0 && (
              <span className="absolute -top-2 -right-2 bg-ot-gold text-white text-[10px] w-4 h-4 rounded-full grid place-items-center">
                {favCount > 9 ? "9+" : favCount}
              </span>
            )}
          </Link>
          <Link href="/cart" aria-label="Carrito" className="relative hover:text-ot-gold">
            <ShoppingBag size={18} />
            {count > 0 && (
              <span className="absolute -top-2 -right-2 bg-ot-gold text-white text-[10px] w-4 h-4 rounded-full grid place-items-center">
                {count}
              </span>
            )}
          </Link>
        </div>
      </div>
      {open && (
        <nav className="lg:hidden border-t border-black/5 px-4 py-4 flex flex-col gap-3 text-sm tracking-[0.14em] uppercase bg-ot-cream max-h-[70vh] overflow-y-auto">
          {links.map((l) => {
            const mega = megaMenusByHref[l.href];
            if (mega) {
              const megaOpen = mobileMegaHref === l.href;
              return (
                <div key={l.href} className="border-b border-black/5 pb-3">
                  <button
                    type="button"
                    className="w-full flex items-center justify-between text-left"
                    onClick={() => {
                      setMobileMegaHref((cur) => {
                        if (cur === l.href) {
                          setMobileMegaSection(null);
                          return null;
                        }
                        setMobileMegaSection(null);
                        return l.href;
                      });
                    }}
                    aria-expanded={megaOpen}
                  >
                    <span>{mega.label}</span>
                    <ChevronDown
                      size={16}
                      className={`transition-transform ${megaOpen ? "rotate-180" : ""}`}
                    />
                  </button>
                  {megaOpen ? (
                    <div className="mt-3 space-y-1 normal-case tracking-normal">
                      {mega.columns.map((col) => {
                        const expanded = mobileMegaSection === col.id;
                        return (
                          <div
                            key={col.id}
                            className="border-b border-black/5 last:border-b-0"
                          >
                            <button
                              type="button"
                              className="w-full flex items-center justify-between py-2.5 text-left"
                              onClick={() =>
                                setMobileMegaSection((cur) =>
                                  cur === col.id ? null : col.id
                                )
                              }
                              aria-expanded={expanded}
                            >
                              <span className="text-[11px] tracking-[0.16em] uppercase text-ot-ink">
                                {col.title}
                              </span>
                              <ChevronDown
                                size={14}
                                className={`text-ot-muted transition-transform ${
                                  expanded ? "rotate-180" : ""
                                }`}
                              />
                            </button>
                            {expanded ? (
                              <div className="flex flex-col gap-2.5 pb-3 pl-1">
                                {col.items.map((item) => (
                                  <Link
                                    key={item.label}
                                    href={item.href}
                                    className="text-[13px] text-ot-ink/80"
                                    onClick={() => setOpen(false)}
                                  >
                                    {item.label}
                                    {item.soon ? (
                                      <span className="ml-1 text-[9px] uppercase text-ot-gold">
                                        pronto
                                      </span>
                                    ) : null}
                                  </Link>
                                ))}
                              </div>
                            ) : null}
                          </div>
                        );
                      })}
                      <Link
                        href={mega.href}
                        className="mt-3 inline-flex text-[11px] tracking-[0.16em] uppercase text-ot-green underline underline-offset-4"
                        onClick={() => setOpen(false)}
                      >
                        Ver todo
                      </Link>
                    </div>
                  ) : null}
                </div>
              );
            }
            return (
              <Link
                key={l.href}
                href={l.href}
                onClick={() => {
                  setOpen(false);
                  if (l.href === "/") goHomeIfGuest(customer);
                }}
              >
                {l.label}
              </Link>
            );
          })}
          {customer ? (
            <>
              <Link href="/account" onClick={() => setOpen(false)}>
                Mi cuenta
              </Link>
              <Link href="/account/orders" onClick={() => setOpen(false)}>
                Mis pedidos
              </Link>
              <Link href="/account/favorites" onClick={() => setOpen(false)}>
                Mis favoritos
              </Link>
              <Link href="/account/returns" onClick={() => setOpen(false)}>
                Cambio y devolución
              </Link>
              <button
                type="button"
                className="text-left"
                onClick={async () => {
                  setOpen(false);
                  await logout();
                  router.push("/account");
                  router.refresh();
                }}
              >
                Cerrar sesión
              </button>
            </>
          ) : (
            <Link href="/account" onClick={() => setOpen(false)}>
              Bienvenido
            </Link>
          )}
        </nav>
      )}
    </header>
    <SearchOverlay open={searchOpen} onClose={() => setSearchOpen(false)} />
    </>
  );
}

export function Footer() {
  const pathname = usePathname();
  if (
    pathname.startsWith("/account/reset-password") ||
    pathname.startsWith("/ops") ||
    pathname.startsWith("/negocio")
  )
    return null;
  return (
    <footer className={pathname.startsWith("/account") ? "mt-0" : "mt-16"}>
      <div className="bg-ot-cream border-t border-black/10">
        <div className="ot-container py-7 md:py-8 flex justify-start">
          <OtClubSeal />
        </div>
      </div>
      <div className="bg-ot-green text-ot-cream">
        <div className="ot-container py-16 grid gap-10 md:grid-cols-4">
          <div className="md:col-span-2">
            <p className="font-serif text-3xl tracking-[0.12em]">OT</p>
            <p className="mt-2 text-sm tracking-[0.2em] uppercase text-ot-gold">
              Old Tennis — Club 1976
            </p>
            <p className="mt-4 max-w-md text-ot-cream/75 leading-relaxed">
              El arte de jugar con estilo. Ropa de tenis clásica, elegante y
              atemporal para la cancha y después del partido.
            </p>
          </div>
          <div>
            <p className="ot-eyebrow mb-4">Tienda</p>
            <div className="flex flex-col gap-2 text-sm text-ot-cream/80">
              <Link href="/shop">Catálogo</Link>
              <Link href="/collections">Colecciones</Link>
              <Link href="/lookbook">Lookbook</Link>
              <Link href="/cart">Carrito</Link>
            </div>
          </div>
          <div>
            <p className="ot-eyebrow mb-4">Ayuda</p>
            <div className="flex flex-col gap-2 text-sm text-ot-cream/80">
              <span>Envíos a todo Colombia</span>
              <Link href="/cambios-y-devoluciones">Cambios y devoluciones</Link>
              <span>Pagos seguros (Wompi)</span>
              <a href="mailto:hola@ot.azulado.cloud">hola@ot.azulado.cloud</a>
            </div>
          </div>
        </div>
        <div className="border-t border-white/10 py-4 text-center text-xs tracking-[0.16em] uppercase text-ot-cream/55">
          © {new Date().getFullYear()} Old Tennis · ot.azulado.cloud
        </div>
      </div>
    </footer>
  );
}
