"use client";

import { useEffect, useRef, useState } from "react";
import NextLink from "next/link";
import Image from "next/image";

// --- Navigation temporarily disabled -------------------------------------
// Every <Link> below is shadowed by this non-navigating stub so all header
// menu items render exactly as before but go nowhere. The logo still uses the
// real link via `NextLink`. To restore full navigation, delete this stub and
// rename `NextLink` back to `Link`.
const Link = ({ href, onClick, children, ...props }) => (
  <a
    href="#"
    onClick={(e) => {
      e.preventDefault();
      onClick?.(e);
    }}
    {...props}
  >
    {children}
  </a>
);
// -------------------------------------------------------------------------
import { usePathname } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import { mainNav, headerCta } from "@/config/navigation";
import { serviceCategories } from "@/data/services";
import { cn } from "@/lib/utils";
import {
  ArrowRight,
  ChevronDown,
  Close,
  Menu,
  Sparkles,
  categoryIcons,
  navIcons,
} from "@/components/ui/icons";
import AnimatedButton from "@/components/ui/AnimatedButton";
import MobileNav from "@/components/layout/MobileNav";

/* ------------------------------------------------------------------ */
/*  Logo                                                               */
/* ------------------------------------------------------------------ */
function Logo() {
  return (
    <NextLink href="/" className="group flex items-center gap-2.5 text-lg font-semibold tracking-tight">
      <span className="relative">
        <Image
          src="/images/CerkelLogo.png"
          alt="Cerkel logo"
          width={32}
          height={32}
          priority
          className="h-8 w-8 transition-transform duration-500 group-hover:rotate-[120deg]"
        />
        <span className="absolute inset-0 -z-10 rounded-full bg-primary/40 opacity-0 blur-lg transition-opacity duration-500 group-hover:opacity-100" />
      </span>
      <span className="font-heading">Cerkel</span>
    </NextLink>
  );
}

/* ------------------------------------------------------------------ */
/*  Services mega menu — 4 category columns + featured promo card      */
/* ------------------------------------------------------------------ */
function ServicesMega() {
  return (
    <div className="w-[82rem] max-w-[calc(100vw-2rem)] overflow-hidden rounded-2xl border border-border bg-background/95 shadow-2xl shadow-black/60 backdrop-blur-2xl">
      <div className="h-px w-full bg-gradient-to-r from-transparent via-primary/60 to-transparent" />

      <div className="grid lg:grid-cols-[17rem_1fr]">
        {/* Intro rail */}
        <div className="relative hidden flex-col overflow-hidden border-r border-border bg-gradient-to-b from-primary/15 via-surface/60 to-accent/10 p-6 lg:flex">
          <div className="pointer-events-none absolute -right-10 -top-10 h-32 w-32 rounded-full bg-primary/25 blur-3xl" />

          <p className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wider text-primary">
            <span className="h-1.5 w-1.5 rounded-full bg-primary" />
            Our services
          </p>
          <h3 className="mt-3 font-heading text-xl font-semibold leading-snug">
            Everything you need to build &amp; scale.
          </h3>
          <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
            Strategy, engineering, AI and operations — one senior team, end to end.
          </p>
          <Link
            href="/services"
            className="group/all mt-4 inline-flex w-fit items-center gap-1.5 text-sm font-semibold text-primary"
          >
            <span className="relative">
              View all services
              <span className="absolute -bottom-0.5 left-0 h-px w-0 bg-primary transition-all duration-300 group-hover/all:w-full" />
            </span>
            <ArrowRight className="h-3.5 w-3.5 transition-transform group-hover/all:translate-x-1" />
          </Link>

          {/* Featured card */}
          <Link
            href="/services/ai-development"
            className="group relative mt-auto block overflow-hidden rounded-xl border border-border"
          >
            <span
              className="block h-28 bg-cover bg-center transition-transform duration-700 group-hover:scale-110"
              style={{ backgroundImage: "url(/images/opt/HeroBanner3.png)" }}
            />
            <span className="absolute inset-0 bg-gradient-to-t from-background via-background/40 to-transparent" />
            <span className="absolute inset-x-0 bottom-0 p-3.5">
              <span className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-primary">
                <Sparkles className="h-3 w-3" />
                Featured
              </span>
              <span className="mt-1 flex items-center gap-1.5 font-heading text-sm font-semibold text-foreground">
                Cerkel AI
                <ArrowRight className="h-3.5 w-3.5 text-primary transition-transform group-hover:translate-x-1" />
              </span>
            </span>
          </Link>

          <div className="mt-4">
            <AnimatedButton href="/contact" size="sm" className="w-full justify-center">
              Talk to an expert
            </AnimatedButton>
          </div>
        </div>

        {/* Category columns — one category per column. Each category now has
            six services, so the menu stays short and fits the viewport without
            wrapping or scrolling. */}
        <div className="grid gap-x-7 gap-y-8 px-7 py-7 sm:grid-cols-2 lg:grid-cols-4">
          {serviceCategories.map((cat, ci) => {
            const Icon = categoryIcons[cat.slug];
            return (
              <div key={cat.slug}>
                <Link
                  href={`/services/${cat.overviewSlug || cat.slug}`}
                  className="group/cat mb-2 flex items-center gap-2 border-b border-border/60 px-2 pb-2 text-[11px] font-semibold uppercase tracking-wider text-primary transition-colors hover:text-accent"
                >
                  {Icon ? <Icon className="h-3.5 w-3.5" /> : null}
                  {cat.title}
                  <ArrowRight className="h-3 w-3 -translate-x-1 opacity-0 transition-all group-hover/cat:translate-x-0 group-hover/cat:opacity-100" />
                </Link>
                <div>
                  {cat.services.map((svc, si) => (
                    <Link
                      key={svc.slug}
                      href={`/services/${svc.slug}`}
                      className="menu-in group relative flex items-start rounded-xl px-3 py-2 transition-colors hover:bg-surface"
                      style={{ animationDelay: `${80 + ci * 50 + si * 25}ms` }}
                    >
                      {/* left accent grows on hover */}
                      <span className="absolute left-0 top-1/2 h-0 w-0.5 -translate-y-1/2 rounded-full bg-gradient-to-b from-primary to-accent transition-all duration-300 group-hover:h-3/5" />
                      <span className="min-w-0 flex-1">
                        <span className="flex items-center gap-1 text-sm font-semibold text-foreground transition-colors group-hover:text-primary">
                          {svc.name}
                          <ArrowRight className="h-3.5 w-3.5 shrink-0 -translate-x-1 text-primary opacity-0 transition-all group-hover:translate-x-0 group-hover:opacity-100" />
                        </span>
                        {svc.description && (
                          <span className="mt-0.5 block text-xs leading-snug text-muted-foreground">
                            {svc.description}
                          </span>
                        )}
                      </span>
                    </Link>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Simple dropdown panel — 2 columns for long lists + view-all footer */
/* ------------------------------------------------------------------ */
const DROPDOWN_FOOTER = {
  Portfolio: { href: "/portfolio", label: "View all work" },
  "About Us": { href: "/about", label: "More about Cerkel" },
  Insights: { href: "/blog", label: "Visit the blog" },
};

/* Featured image panel shown alongside wide dropdowns. */
const DROPDOWN_PROMO = {
  Industries: {
    href: "/industries",
    image: "/images/opt/HeroBanner2.webp",
    title: "Industry expertise",
    text: "Software tailored to the users, rules and economics of your sector.",
    cta: "Explore industries",
  },
};

function Dropdown({ items, title }) {
  const wide = items.length > 4;
  const footer = DROPDOWN_FOOTER[title];
  const promo = DROPDOWN_PROMO[title];

  return (
    <div
      className={cn(
        "relative overflow-hidden rounded-2xl border border-border bg-background/95 shadow-2xl shadow-black/60 backdrop-blur-2xl",
        promo ? "w-[46rem]" : wide ? "w-[36rem]" : "w-80"
      )}
    >
      <div className="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/60 to-transparent" />

      <div className={cn(promo && "grid grid-cols-[1fr_15rem]")}>
        <div className={cn("p-2", wide && "grid grid-cols-2 gap-x-1 self-start")}>
          {items.map((item, i) => {
            const Icon = navIcons[item.icon];
            return (
              <Link
                key={`${item.href}-${item.title}`}
                href={item.href}
                className="menu-in group flex items-start gap-3 rounded-xl p-2.5 transition-colors hover:bg-surface"
                style={{ animationDelay: `${60 + i * 30}ms` }}
              >
                <span className="mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-primary/20 bg-primary/10 text-primary transition-colors group-hover:bg-primary group-hover:text-primary-foreground">
                  {Icon ? <Icon className="h-4 w-4" /> : null}
                </span>
                <span className="min-w-0 flex-1">
                  <span className="flex items-center gap-1 text-sm font-semibold text-foreground transition-colors group-hover:text-primary">
                    {item.title}
                    <ArrowRight className="h-3.5 w-3.5 shrink-0 -translate-x-1 text-primary opacity-0 transition-all group-hover:translate-x-0 group-hover:opacity-100" />
                  </span>
                  {item.description && (
                    <span className="mt-0.5 block text-xs leading-snug text-muted-foreground">
                      {item.description}
                    </span>
                  )}
                </span>
              </Link>
            );
          })}
        </div>

        {/* Featured image panel */}
        {promo && (
          <Link href={promo.href} className="group relative m-2 overflow-hidden rounded-xl border border-border">
            <Image src={promo.image} alt="" fill sizes="15rem" className="object-cover transition-transform duration-500 group-hover:scale-105" />
            <span className="absolute inset-0 bg-gradient-to-t from-background via-background/70 to-background/20" />
            <div className="absolute inset-0 flex flex-col justify-end p-5">
              <h4 className="font-heading text-base font-semibold text-foreground">{promo.title}</h4>
              <p className="mt-1 text-xs leading-snug text-muted-foreground">{promo.text}</p>
              <span className="mt-3 inline-flex items-center gap-1.5 text-xs font-semibold text-primary">
                {promo.cta}
                <ArrowRight className="h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5" />
              </span>
            </div>
          </Link>
        )}
      </div>

      {footer && (
        <div className="border-t border-border bg-surface/60 px-4 py-3">
          <Link
            href={footer.href}
            className="group/foot inline-flex items-center gap-1.5 text-sm font-semibold text-primary"
          >
            <span className="relative">
              {footer.label}
              <span className="absolute -bottom-0.5 left-0 h-px w-0 bg-primary transition-all duration-300 group-hover/foot:w-full" />
            </span>
            <ArrowRight className="h-3.5 w-3.5 transition-transform group-hover/foot:translate-x-1" />
          </Link>
        </div>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Header                                                             */
/* ------------------------------------------------------------------ */
export default function Header() {
  const [scrolled, setScrolled] = useState(false);
  const [hidden, setHidden] = useState(false);
  const [openMenu, setOpenMenu] = useState(null);
  const [hovered, setHovered] = useState(null);
  const [mobileOpen, setMobileOpen] = useState(false);
  const closeTimer = useRef(null);
  const lastY = useRef(0);
  const pathname = usePathname();

  // Solidify on scroll; hide on scroll-down, reveal on scroll-up.
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      setScrolled(y > 8);
      if (y > lastY.current + 6 && y > 140) setHidden(true);
      else if (y < lastY.current - 6 || y <= 140) setHidden(false);
      lastY.current = y;
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    setOpenMenu(null);
    setMobileOpen(false);
  }, [pathname]);

  const open = (title) => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setOpenMenu(title);
  };
  const scheduleClose = () => {
    closeTimer.current = setTimeout(() => setOpenMenu(null), 120);
  };

  const isActive = (href) => href && (href === "/" ? pathname === "/" : pathname.startsWith(href));
  const reveal = !hidden || openMenu || mobileOpen;

  return (
    <header
      className={cn(
        "fixed inset-x-0 top-0 z-50 transition-transform duration-500 ease-out",
        reveal ? "translate-y-0" : "-translate-y-full"
      )}
    >
      <div
        className={cn(
          "border-b transition-all duration-300",
          scrolled || openMenu || mobileOpen
            ? "border-border bg-background/85 shadow-lg shadow-black/20 backdrop-blur-xl"
            : "border-transparent bg-background/40 backdrop-blur-md"
        )}
      >
        <div className="container flex h-[4.5rem] items-center justify-between gap-4">
          <motion.div
            initial={{ y: -18, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ duration: 0.5, ease: "easeOut" }}
          >
            <Logo />
          </motion.div>

          {/* Desktop nav — always visible, no hamburger */}
          <nav className="hidden items-center gap-1 lg:flex" onMouseLeave={() => setHovered(null)}>
            {mainNav.map((item, idx) => {
              const hasMenu = item.type === "mega" || item.type === "dropdown";
              const menuOpen = openMenu === item.title;
              const active = hasMenu ? menuOpen : isActive(item.href);
              const lit = hovered === item.title || active;

              const inner = (
                <>
                  <span className={cn("transition-colors", lit && "text-foreground")}>
                    {item.title}
                  </span>
                  {hasMenu && (
                    <ChevronDown
                      className={cn(
                        "h-3.5 w-3.5 transition-transform duration-300",
                        menuOpen && "rotate-180"
                      )}
                    />
                  )}
                  {/* spring gradient underline */}
                  {lit && (
                    <motion.span
                      layoutId="nav-underline"
                      transition={{ type: "spring", stiffness: 480, damping: 40 }}
                      className="absolute inset-x-3 -bottom-0.5 h-0.5 rounded-full bg-gradient-to-r from-primary to-accent"
                    />
                  )}
                </>
              );

              const triggerClass =
                "relative flex items-center gap-1.5 px-4 py-2 text-base font-medium text-muted-foreground transition-colors hover:text-foreground";

              const entrance = {
                initial: { y: -18, opacity: 0 },
                animate: { y: 0, opacity: 1 },
                transition: { delay: 0.1 + idx * 0.06, duration: 0.5, ease: "easeOut" },
              };

              if (!hasMenu) {
                return (
                  <motion.div key={item.title} {...entrance}>
                    <Link
                      href={item.href}
                      onMouseEnter={() => setHovered(item.title)}
                      className={triggerClass}
                    >
                      {inner}
                    </Link>
                  </motion.div>
                );
              }

              return (
                <motion.div
                  key={item.title}
                  {...entrance}
                  className={item.type === "mega" ? "static" : "static lg:relative"}
                  onMouseEnter={() => {
                    setHovered(item.title);
                    open(item.title);
                  }}
                  onMouseLeave={scheduleClose}
                >
                  <button className={triggerClass} aria-expanded={menuOpen}>
                    {inner}
                  </button>

                  <AnimatePresence>
                    {menuOpen && (
                      <motion.div
                        initial={{ opacity: 0, y: 14, scale: 0.985, x: item.type === "mega" ? 0 : "-50%" }}
                        animate={{ opacity: 1, y: 0, scale: 1, x: item.type === "mega" ? 0 : "-50%" }}
                        exit={{ opacity: 0, y: 14, scale: 0.985, x: item.type === "mega" ? 0 : "-50%" }}
                        transition={{ duration: 0.22, ease: "easeOut" }}
                        className={cn(
                          "absolute top-full pt-3",
                          item.type === "mega" ? "inset-x-0 flex justify-center px-4" : "left-1/2"
                        )}
                      >
                        {item.type === "mega" ? (
                          <ServicesMega />
                        ) : (
                          <Dropdown items={item.items} title={item.title} />
                        )}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </motion.div>
              );
            })}
          </nav>

          {/* Right cluster */}
          <motion.div
            initial={{ y: -18, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ delay: 0.4, duration: 0.5, ease: "easeOut" }}
            className="flex items-center gap-3"
          >
            <AnimatedButton href={headerCta.href} size="sm" className="hidden sm:inline-flex">
              {headerCta.title}
            </AnimatedButton>
            {/* mobile-only menu toggle */}
            <button
              onClick={() => setMobileOpen((v) => !v)}
              className="rounded-xl p-2 text-foreground lg:hidden"
              aria-label="Toggle menu"
            >
              {mobileOpen ? <Close /> : <Menu />}
            </button>
          </motion.div>
        </div>
      </div>

      <MobileNav open={mobileOpen} onClose={() => setMobileOpen(false)} />
    </header>
  );
}
