import { ReactNode, useState, useEffect, ComponentType, SVGProps } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import {
  ChevronDown,
  Menu,
  X,
  Facebook,
  Linkedin,
  Instagram,
  Youtube,
  Send,
  Star,
  ArrowUp,
  User,
  LayoutDashboard,
  CreditCard,
  TicketCheck,
  LogOut,
  UserCircle2,
  Home,
  Server,
  HardDrive,
  Cloud,
  Globe,
  Mail,
  Inbox,
  MessageSquare,
  Activity,
  Network,
  Settings,
  LifeBuoy,
  Headphones,
  Phone,
  Info,
  Database,
  ShieldCheck,
  Cpu,
  Wrench,
  Monitor,
  BookOpen,
  HelpCircle,
} from "lucide-react";
import { useUserProfile } from "@/hooks/useUserProfile";
import { signOut } from "@/lib/auth";
import { ShoppingCart, Scale } from "lucide-react";
import { useCart } from "@/context/CartContext";
import { useCompare } from "@/context/CompareContext";
import {
  LanguageSwitcher,
  InlineLanguageSwitcher,
} from "@/components/LanguageSwitcher";
import { useLanguage } from "@/context/LanguageContext";
import AutoTranslate from "@/components/AutoTranslate";
import SeoMeta from "@/components/SeoMeta";

type LucideIcon = ComponentType<SVGProps<SVGSVGElement>>;

/**
 * A single dropdown leaf — either a simple row (flat dropdown) or a
 * mega-menu row with an icon + description.
 */
interface NavChild {
  label: string;
  to: string;
  icon?: LucideIcon;
  description?: string;
  match?: string[];
}

interface NavGroup {
  title: string;
  items: NavChild[];
}

/**
 * Optional "featured offer" column rendered on the right side of a mega-menu.
 */
interface NavPromo {
  image: string;
  imageAlt: string;
  eyebrow?: string;
  headline: string;
  description?: string;
  price?: string;
  priceSuffix?: string;
  ctaLabel: string;
  ctaTo: string;
}

interface NavItem {
  label: string;
  to?: string;
  icon?: LucideIcon;
  match?: string[];
  children?: NavChild[];
  mega?: NavGroup[];
  megaWidthClass?: string;
  promo?: NavPromo;
}

const NAV: NavItem[] = [
  { label: "Home", to: "/", icon: Home },
  {
    label: "Hosting Services",
    icon: Server,
    match: [
      "/hosting",
      "/wordpress-hosting",
      "/cloud-vps",
      "/dedicated",
      "/services",
      "/service-catalog",
    ],
    megaWidthClass: "w-[960px]",
    promo: {
      image:
        "https://mgx-backend-cdn.metadl.com/generate/images/1085345/2026-04-30/nux5odaaafma/promo-hosting-cloud-vps.png",
      imageAlt: "Cloud VPS promotional offer",
      eyebrow: "Featured Offer",
      headline: "Cloud VPS — 40% OFF",
      description: "High-performance NVMe VPS with free setup & 24/7 support.",
      price: "$4.99",
      priceSuffix: "/month",
      ctaLabel: "Get the deal",
      ctaTo: "/cloud-vps",
    },
    mega: [
      {
        title: "Web Hosting",
        items: [
          {
            label: "Shared Hosting",
            to: "/shared-hosting",
            icon: Globe,
            match: ["/hosting"],
            description: "cPanel, Plesk, aaPanel, Windows & WordPress panels.",
          },
          {
            label: "WordPress Hosting",
            to: "/wordpress-hosting",
            icon: Monitor,
            description: "Optimized stack for WordPress with 1-click install.",
          },
          {
            label: "Reseller Hosting",
            to: "/hosting",
            icon: Database,
            match: ["/hosting?reseller"],
            description: "Resell hosting plans to your own clients, white-labeled.",
          },
        ],
      },
      {
        title: "Cloud Hosting",
        items: [
          {
            label: "Cloud VPS",
            to: "/cloud-vps",
            icon: Cloud,
            description: "Scalable virtual private servers billed per hour.",
          },
          {
            label: "Dedicated Servers",
            to: "/dedicated",
            icon: HardDrive,
            description: "Bare-metal power with full hardware isolation.",
          },
          {
            label: "VDS",
            to: "/cloud-vps",
            icon: Cpu,
            match: ["/cloud-vps?vds"],
            description: "Guaranteed resources for demanding workloads.",
          },
          {
            label: "Service Catalog",
            to: "/services",
            icon: BookOpen,
            match: ["/service-catalog"],
            description: "Full catalog of DoItEasy enterprise services.",
          },
        ],
      },
    ],
  },
  {
    label: "Web Services",
    icon: Globe,
    match: [
      "/whatsapp-api",
      "/uptime-monitor",
      "/sd-wan",
      "/managed-it",
      "/remote-support",
      "/domain-search",
      "/business-email",
      "/bizmail360",
    ],
    megaWidthClass: "w-[1040px]",
    promo: {
      image:
        "https://mgx-backend-cdn.metadl.com/generate/images/1085345/2026-04-30/nux5ogqaafna/promo-web-services-email.png",
      imageAlt: "Business Email promotional offer",
      eyebrow: "New Launch",
      headline: "Business Email Pro",
      description: "Professional mailboxes on your own domain, with spam & malware protection.",
      price: "$1.99",
      priceSuffix: "/mailbox / mo",
      ctaLabel: "Start free trial",
      ctaTo: "/business-email",
    },
    mega: [
      {
        title: "Communication",
        items: [
          { label: "Bizmail360 Collaboration Mail", to: "/bizmail360", icon: Inbox, description: "All-in-one collaboration suite: mail, chat, meetings & docs." },
          { label: "Business Email", to: "/business-email", icon: Mail, description: "Professional inboxes on your own domain." },
          { label: "WhatsApp API Service", to: "/whatsapp-api", icon: MessageSquare, description: "Send transactional & marketing messages at scale." },
          { label: "Uptime Monitor", to: "/uptime-monitor", icon: Activity, description: "Know the second your site goes down, 24/7." },
        ],
      },
      {
        title: "Networking & IT",
        items: [
          { label: "SD-WAN Services", to: "/sd-wan", icon: Network, description: "Smart routing for multi-site & branch offices." },
          { label: "Managed IT", to: "/managed-it", icon: Settings, description: "Outsource your day-to-day IT operations." },
          { label: "Remote Support", to: "/remote-support", icon: LifeBuoy, description: "On-demand remote troubleshooting for your team." },
        ],
      },
      {
        title: "Managed & Domains",
        items: [
          { label: "Cloud Managed Services", to: "/remote-support#cloud-managed", icon: ShieldCheck, description: "End-to-end management of your cloud workloads." },
          { label: "On-Premises Managed", to: "/remote-support#on-premises", icon: Wrench, description: "Hands-on support for servers inside your office." },
          { label: "Domain Registration", to: "/domain-search", icon: Globe, description: "Search and register domains in 500+ TLDs." },
        ],
      },
    ],
  },
  {
    label: "Shop",
    to: "/shop",
    icon: ShoppingCart,
    match: ["/shop", "/account/orders"],
  },
  {
    label: "Support",
    icon: Headphones,
    match: ["/tickets", "/contact", "/about", "/knowledge-base", "/kb", "/faq"],
    children: [
      { label: "Knowledge Base", to: "/knowledge-base", icon: BookOpen },
      { label: "FAQ", to: "/faq", icon: HelpCircle },
      { label: "Ticket System", to: "/tickets", icon: TicketCheck },
      { label: "Contact Us", to: "/contact", icon: Phone },
      { label: "About Us", to: "/about", icon: Info },
    ],
  },
];

function pathMatches(pathname: string, target?: string, extra?: string[]): boolean {
  if (!target && (!extra || extra.length === 0)) return false;
  const candidates = [target, ...(extra ?? [])].filter(Boolean) as string[];
  for (const raw of candidates) {
    const clean = raw.split("#")[0].split("?")[0];
    if (!clean) continue;
    if (clean === "/") {
      if (pathname === "/") return true;
      continue;
    }
    if (pathname === clean) return true;
    if (pathname.startsWith(clean + "/")) return true;
  }
  return false;
}

function isTopLevelActive(pathname: string, item: NavItem): boolean {
  if (item.to && pathMatches(pathname, item.to)) return true;
  if (item.match && pathMatches(pathname, undefined, item.match)) return true;
  const allChildren: NavChild[] = [
    ...(item.children ?? []),
    ...((item.mega ?? []).flatMap((g) => g.items)),
  ];
  return allChildren.some((c) => pathMatches(pathname, c.to, c.match));
}

function isChildActive(pathname: string, child: NavChild): boolean {
  return pathMatches(pathname, child.to, child.match);
}

/**
 * Site header.
 *
 * Behavior highlights:
 *   - Transparent overlay on the homepage hero while the user is still at
 *     the very top, then solidifies + becomes sticky as soon as the user
 *     scrolls. On every other page, it is always a solid sticky bar.
 *   - Subtle drop shadow appears once scrolled, for a clean "lifted" look.
 *   - Header + logo shrink to a condensed size on scroll.
 *   - Mega-menu and dropdowns fade + slide down smoothly on hover.
 *   - Mobile drawer slides in from the right with a dimmed backdrop,
 *     a sticky user card, and a footer with Cart + Client Area CTAs.
 */
export function Header() {
  const { tr, t } = useLanguage();
  const [open, setOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState<string | null>(null);
  const [scrolled, setScrolled] = useState(false);
  const { pathname } = useLocation();
  const navigate = useNavigate();
  const isHome = pathname === "/";
  const transparent = isHome && !scrolled;
  const { authed, user, avatarUrl } = useUserProfile();
  const { itemCount } = useCart();
  // Header quick-access to the product comparison drawer. Shows a live count
  // badge that mirrors the cart badge styling so the two controls read as a
  // pair in the top-right of the site header.
  const { items: compareItems, openDrawer: openCompareDrawer } = useCompare();
  const compareCount = compareItems.length;
  const displayName = user?.name || user?.email || tr("Guest User");
  const greeting = authed ? t("nav.welcome_back") : t("nav.welcome");

  // Lock body scroll while the mobile drawer is open.
  useEffect(() => {
    if (typeof document === "undefined") return;
    if (open) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => {
        document.body.style.overflow = prev;
      };
    }
  }, [open]);

  // Track scroll to toggle the condensed + solid header state.
  useEffect(() => {
    if (typeof window === "undefined") return;
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [pathname]);

  // Close the mobile drawer on route change.
  useEffect(() => {
    setOpen(false);
    setMobileOpen(null);
  }, [pathname]);

  const handleLogin = () => {
    navigate("/login");
  };
  const handleLogout = () => {
    signOut("/login");
  };

  const headerClass = transparent
    ? "absolute top-0 left-0 right-0 z-50 bg-transparent border-b border-transparent"
    : [
        "sticky top-0 z-50 bg-white/90 backdrop-blur-md supports-[backdrop-filter]:bg-white/75",
        "border-b",
        scrolled
          ? "border-slate-200 shadow-[0_2px_16px_-6px_rgba(15,23,41,0.18)]"
          : "border-slate-100 shadow-none",
      ].join(" ");

  const rowHeightClass = scrolled
    ? "h-16 3xl:h-20 5xl:h-24"
    : "h-20 3xl:h-24 5xl:h-28";
  const logoHeightClass = scrolled ? "h-10 md:h-11" : "h-12 md:h-14";

  return (
    <header className={`${headerClass} transition-[background-color,box-shadow,border-color] duration-300`}>
      <div
        className={`max-w-7xl 3xl:max-w-[1680px] 4xl:max-w-[2000px] 5xl:max-w-[2400px] mx-auto px-4 sm:px-6 lg:px-8 3xl:px-12 5xl:px-16 ${rowHeightClass} flex items-center justify-between transition-[height] duration-300`}
      >
        <Link to="/" className="flex items-center shrink-0" aria-label="DoItEasy home">
          <img
            src="/logo.svg"
            alt="DoItEasy"
            className={`${logoHeightClass} w-auto transition-all duration-300 ${transparent ? "brightness-0 invert" : ""}`}
          />
        </Link>

        <nav className="hidden lg:flex items-center gap-6 xl:gap-8">
          {NAV.map((item) => {
            const active = isTopLevelActive(pathname, item);
            const topBase = transparent
              ? active
                ? "text-[#f5c400] drop-shadow"
                : "text-white hover:text-[#f5c400] drop-shadow"
              : active
              ? "text-[#0b6e3e]"
              : "text-slate-800 hover:text-[#0b6e3e]";
            const TopIcon = item.icon;

            return (
              <div key={item.label} className="relative group">
                {item.to ? (
                  <Link
                    to={item.to}
                    className={`site-nav-link relative flex items-center gap-1.5 font-semibold transition ${topBase}`}
                  >
                    {TopIcon ? <TopIcon className="w-4 h-4" /> : null}
                    <span>{tr(item.label)}</span>
                    {active && (
                      <span
                        className={`absolute -bottom-2 left-0 right-0 h-[3px] rounded-full ${
                          transparent ? "bg-[#f5c400]" : "bg-[#0b6e3e]"
                        }`}
                      />
                    )}
                  </Link>
                ) : (
                  <button
                    type="button"
                    className={`site-nav-link relative flex items-center gap-1.5 font-semibold transition ${topBase}`}
                  >
                    {TopIcon ? <TopIcon className="w-4 h-4" /> : null}
                    <span>{tr(item.label)}</span>
                    <ChevronDown className="w-4 h-4 transition-transform duration-200 group-hover:rotate-180" />
                    {active && (
                      <span
                        className={`absolute -bottom-2 left-0 right-0 h-[3px] rounded-full ${
                          transparent ? "bg-[#f5c400]" : "bg-[#0b6e3e]"
                        }`}
                      />
                    )}
                  </button>
                )}

                {/* Mega-menu dropdown */}
                {item.mega && (
                  <div
                    className="absolute top-full left-1/2 -translate-x-1/2 pt-4 opacity-0 invisible translate-y-2 group-hover:opacity-100 group-hover:visible group-hover:translate-y-0 transition-all duration-200 ease-out z-40"
                  >
                    <div
                      className={`bg-white rounded-2xl shadow-[0_24px_64px_-16px_rgba(15,23,41,0.28)] ring-1 ring-slate-900/5 border border-slate-100 p-5 ${
                        item.megaWidthClass ?? "w-[720px]"
                      }`}
                    >
                      {(() => {
                        const hasPromo = !!item.promo;
                        const groupCols = item.mega!.length;
                        const gridTemplate = hasPromo
                          ? `repeat(${groupCols}, minmax(0, 1fr)) 260px`
                          : `repeat(${groupCols}, minmax(0, 1fr))`;
                        return (
                          <div
                            className="grid gap-5"
                            style={{ gridTemplateColumns: gridTemplate }}
                          >
                            {item.mega!.map((group) => (
                              <div key={group.title}>
                                <h4 className="text-[11px] font-bold uppercase tracking-wider text-slate-400 mb-2 px-2">
                                  {group.title}
                                </h4>
                                <ul className="flex flex-col gap-1">
                                  {group.items.map((c) => {
                                    const ChildIcon = c.icon;
                                    const cActive = isChildActive(pathname, c);
                                    return (
                                      <li key={c.label}>
                                        <Link
                                          to={c.to}
                                          className={`site-nav-link group/item flex items-start gap-3 px-2 py-2 rounded-lg transition ${
                                            cActive
                                              ? "bg-emerald-50 text-[#0b6e3e]"
                                              : "text-slate-700 hover:bg-slate-50 hover:text-[#0b6e3e]"
                                          }`}
                                        >
                                          <span
                                            className={`w-8 h-8 rounded-md flex items-center justify-center shrink-0 transition ${
                                              cActive
                                                ? "bg-[#0b6e3e] text-white"
                                                : "bg-slate-100 text-[#0b6e3e] group-hover/item:bg-[#0b6e3e] group-hover/item:text-white"
                                            }`}
                                          >
                                            {ChildIcon ? (
                                              <ChildIcon className="w-4 h-4" />
                                            ) : (
                                              <ChevronDown className="w-4 h-4" />
                                            )}
                                          </span>
                                          <span className="min-w-0">
                                            <span className="block text-sm font-semibold leading-tight">
                                              {tr(c.label)}
                                            </span>
                                            {c.description && (
                                              <span className="block text-xs text-slate-500 mt-0.5 leading-snug">
                                                {c.description}
                                              </span>
                                            )}
                                          </span>
                                        </Link>
                                      </li>
                                    );
                                  })}
                                </ul>
                              </div>
                            ))}

                            {item.promo && (
                              <div className="relative rounded-xl overflow-hidden bg-gradient-to-br from-[#0b6e3e] to-[#22c55e] text-white flex flex-col shadow-lg">
                                <div className="relative h-32 w-full overflow-hidden">
                                  <img
                                    src={item.promo.image}
                                    alt={item.promo.imageAlt}
                                    className="w-full h-full object-cover opacity-90"
                                    loading="lazy"
                                  />
                                  <div className="absolute inset-0 bg-gradient-to-b from-transparent to-[#0b6e3e]/70" />
                                  {item.promo.eyebrow && (
                                    <span className="absolute top-2 left-2 bg-[#f5c400] text-slate-900 text-[10px] font-bold uppercase tracking-wider px-2 py-1 rounded">
                                      {item.promo.eyebrow}
                                    </span>
                                  )}
                                </div>
                                <div className="p-4 flex flex-col flex-1">
                                  <h4 className="text-base font-bold leading-tight">
                                    {item.promo.headline}
                                  </h4>
                                  {item.promo.description && (
                                    <p className="text-xs text-white/85 mt-1.5 leading-snug">
                                      {item.promo.description}
                                    </p>
                                  )}
                                  {item.promo.price && (
                                    <div className="mt-3 flex items-baseline gap-1">
                                      <span className="text-2xl font-extrabold text-[#f5c400]">
                                        {item.promo.price}
                                      </span>
                                      {item.promo.priceSuffix && (
                                        <span className="text-xs text-white/80">
                                          {item.promo.priceSuffix}
                                        </span>
                                      )}
                                    </div>
                                  )}
                                  <Link to={item.promo.ctaTo} className="mt-auto pt-3">
                                    <span className="inline-flex w-full items-center justify-center gap-1 bg-[#f5c400] hover:bg-yellow-400 text-slate-900 text-sm font-bold px-4 py-2 rounded-md transition shadow">
                                      {item.promo.ctaLabel}
                                      <ChevronDown className="w-4 h-4 -rotate-90" />
                                    </span>
                                  </Link>
                                </div>
                              </div>
                            )}
                          </div>
                        );
                      })()}
                    </div>
                  </div>
                )}

                {/* Classic single-column dropdown */}
                {item.children && (
                  <div className="absolute top-full left-0 pt-4 opacity-0 invisible translate-y-2 group-hover:opacity-100 group-hover:visible group-hover:translate-y-0 transition-all duration-200 ease-out z-40">
                    <div className="bg-white rounded-xl shadow-[0_20px_48px_-16px_rgba(15,23,41,0.24)] ring-1 ring-slate-900/5 border border-slate-100 py-2 min-w-[260px]">
                      {item.children.map((c) => {
                        const ChildIcon = c.icon;
                        const cActive = isChildActive(pathname, c);
                        return (
                          <Link
                            key={c.label}
                            to={c.to}
                            className={`site-nav-link flex items-center gap-3 px-4 py-2 transition ${
                              cActive
                                ? "bg-emerald-50 text-[#0b6e3e]"
                                : "text-slate-700 hover:bg-slate-50 hover:text-[#0b6e3e]"
                            }`}
                          >
                            {ChildIcon ? (
                              <ChildIcon
                                className={`w-4 h-4 shrink-0 ${
                                  cActive ? "text-[#0b6e3e]" : "text-slate-500"
                                }`}
                              />
                            ) : null}
                            <span>{tr(c.label)}</span>
                          </Link>
                        );
                      })}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </nav>

        <div className="hidden lg:flex items-center gap-4">
          <LanguageSwitcher transparent={transparent} />
          {!authed && (
            <button
              type="button"
              onClick={handleLogin}
              className={`site-nav-link font-semibold tracking-wide ${
                transparent ? "text-white hover:text-[#f5c400] drop-shadow" : "text-slate-800 hover:text-[#0b6e3e]"
              }`}
            >
              {tr("LOGIN")}
            </button>
          )}
          {/* Compare + Cart icons are hidden on the home page — the user
              wants these shopping controls to appear only on store/shop
              pages, not in the marketing home header. */}
          {!isHome && (
            <>
              <button
                type="button"
                onClick={openCompareDrawer}
                aria-label={
                  compareCount > 0
                    ? `Compare ${compareCount} selected products`
                    : "Open product comparison"
                }
                title="Compare products"
                className={`relative w-10 h-10 rounded-full border-2 flex items-center justify-center transition-all duration-200 hover:scale-105 ${
                  transparent
                    ? "border-white/70 text-white hover:bg-white hover:text-[#0b6e3e] hover:border-white"
                    : "border-[#0b6e3e] text-[#0b6e3e] hover:bg-[#0b6e3e] hover:text-white"
                }`}
              >
                <Scale className="w-5 h-5" />
                {compareCount > 0 && (
                  <span className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1 rounded-full bg-[#f5c400] text-slate-900 text-[10px] font-extrabold flex items-center justify-center shadow">
                    {compareCount}
                  </span>
                )}
              </button>
              <Link
                to="/shop/cart"
                data-cart-icon
                aria-label="View cart"
                title="Shopping Cart"
                className={`relative w-10 h-10 rounded-full border-2 flex items-center justify-center transition-all duration-200 hover:scale-105 ${
                  transparent
                    ? "border-white/70 text-white hover:bg-white hover:text-[#0b6e3e] hover:border-white"
                    : "border-[#0b6e3e] text-[#0b6e3e] hover:bg-[#0b6e3e] hover:text-white"
                }`}
              >
                <ShoppingCart className="w-5 h-5" />
                {itemCount > 0 && (
                  <span className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1 rounded-full bg-[#f5c400] text-slate-900 text-[10px] font-extrabold flex items-center justify-center shadow">
                    {itemCount > 99 ? "99+" : itemCount}
                  </span>
                )}
              </Link>
            </>
          )}
          <div className="relative group">
            <button
              type="button"
              aria-label="Account menu"
              title="My Account"
              className={`w-10 h-10 rounded-full border-2 flex items-center justify-center overflow-hidden transition-all duration-200 hover:scale-105 ${
                transparent
                  ? "border-white/70 text-white hover:bg-white hover:text-[#0b6e3e] hover:border-white"
                  : "border-[#0b6e3e] text-[#0b6e3e] hover:bg-[#0b6e3e] hover:text-white"
              }`}
            >
              {avatarUrl ? (
                <img src={avatarUrl} alt="Profile" className="w-full h-full object-cover" />
              ) : (
                <User className="w-5 h-5" />
              )}
            </button>
            <div className="absolute top-full right-0 pt-4 opacity-0 invisible translate-y-2 group-hover:opacity-100 group-hover:visible group-hover:translate-y-0 transition-all duration-200 ease-out z-50">
              <div className="bg-white rounded-xl shadow-[0_20px_48px_-16px_rgba(15,23,41,0.24)] ring-1 ring-slate-900/5 border border-slate-100 py-2 min-w-[240px]">
                <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full border border-slate-200 overflow-hidden bg-slate-100 flex items-center justify-center shrink-0">
                    {avatarUrl ? (
                      <img src={avatarUrl} alt="Profile" className="w-full h-full object-cover" />
                    ) : (
                      <User className="w-5 h-5 text-[#0b6e3e]" />
                    )}
                  </div>
                  <div className="min-w-0">
                    <p className="text-xs text-slate-500">{greeting}</p>
                    <p className="text-sm font-semibold text-slate-900 truncate">{displayName}</p>
                  </div>
                </div>
                <Link to="/account/profile" className="flex items-center gap-3 px-4 py-2 text-slate-700 hover:bg-slate-50 hover:text-[#0b6e3e] transition">
                  <UserCircle2 className="w-4 h-4" />
                  <span className="text-sm font-medium">Account Settings</span>
                </Link>
                <Link to="/client" className="flex items-center gap-3 px-4 py-2 text-slate-700 hover:bg-slate-50 hover:text-[#0b6e3e] transition">
                  <LayoutDashboard className="w-4 h-4" />
                  <span className="text-sm font-medium">Dashboard</span>
                </Link>
                <Link to="/client" className="flex items-center gap-3 px-4 py-2 text-slate-700 hover:bg-slate-50 hover:text-[#0b6e3e] transition">
                  <CreditCard className="w-4 h-4" />
                  <span className="text-sm font-medium">Billing</span>
                </Link>
                <Link to="/tickets" className="flex items-center gap-3 px-4 py-2 text-slate-700 hover:bg-slate-50 hover:text-[#0b6e3e] transition">
                  <TicketCheck className="w-4 h-4" />
                  <span className="text-sm font-medium">Tickets</span>
                </Link>
                <div className="border-t border-slate-100 mt-1 pt-1">
                  {authed ? (
                    <button
                      type="button"
                      onClick={handleLogout}
                      className="w-full flex items-center gap-3 px-4 py-2 text-red-600 hover:bg-red-50 transition text-left"
                    >
                      <LogOut className="w-4 h-4" />
                      <span className="text-sm font-medium">{tr("Logout")}</span>
                    </button>
                  ) : (
                    <button
                      type="button"
                      onClick={handleLogin}
                      className="w-full flex items-center gap-3 px-4 py-2 text-[#0b6e3e] hover:bg-emerald-50 transition text-left"
                    >
                      <LogOut className="w-4 h-4 rotate-180" />
                      <span className="text-sm font-medium">{tr("Sign in")}</span>
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
          <Link
            to="/client"
            className="px-3.5 py-1.5 rounded-md bg-[#f5c400] text-slate-900 text-xs font-semibold tracking-wide shadow-md hover:bg-yellow-400 hover:shadow-lg hover:-translate-y-0.5 hover:scale-[1.03] transition-all duration-200"
          >
            {tr("CLIENT AREA")}
          </Link>
        </div>

        <button
          type="button"
          className={`lg:hidden w-10 h-10 rounded-md flex items-center justify-center transition ${
            transparent
              ? "text-white hover:bg-white/10"
              : "text-slate-800 hover:bg-slate-100"
          }`}
          onClick={() => setOpen(!open)}
          aria-label={open ? "Close menu" : "Open menu"}
          aria-expanded={open}
        >
          {open ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
        </button>
      </div>

      {/* Mobile drawer */}
      <div
        className={`lg:hidden fixed inset-0 z-[60] ${open ? "pointer-events-auto" : "pointer-events-none"}`}
        aria-hidden={!open}
      >
        <div
          className={`absolute inset-0 bg-slate-900/50 backdrop-blur-[2px] transition-opacity duration-300 ${
            open ? "opacity-100" : "opacity-0"
          }`}
          onClick={() => setOpen(false)}
        />
        <aside
          className={`absolute top-0 right-0 h-full w-[86%] max-w-sm bg-white shadow-2xl flex flex-col transform transition-transform duration-300 ease-out ${
            open ? "translate-x-0" : "translate-x-full"
          }`}
          role="dialog"
          aria-modal="true"
          aria-label="Mobile navigation"
        >
          {/* Drawer header */}
          <div className="flex items-center justify-between px-5 h-16 border-b border-slate-100 shrink-0">
            <Link to="/" onClick={() => setOpen(false)} className="flex items-center">
              <img src="/logo.svg" alt="DoItEasy" className="h-9 w-auto" />
            </Link>
            <button
              type="button"
              onClick={() => setOpen(false)}
              aria-label="Close menu"
              className="w-10 h-10 rounded-full flex items-center justify-center text-slate-600 hover:bg-slate-100 transition"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Drawer user card */}
          <div className="px-5 py-4 border-b border-slate-100 shrink-0">
            <div className="flex items-center gap-3">
              <div className="w-11 h-11 rounded-full border border-slate-200 overflow-hidden bg-emerald-50 flex items-center justify-center shrink-0">
                {avatarUrl ? (
                  <img src={avatarUrl} alt="Profile" className="w-full h-full object-cover" />
                ) : (
                  <User className="w-5 h-5 text-[#0b6e3e]" />
                )}
              </div>
              <div className="min-w-0 flex-1">
                <p className="text-xs text-slate-500">{greeting}</p>
                <p className="text-sm font-semibold text-slate-900 truncate">{displayName}</p>
              </div>
              {authed ? (
                <button
                  type="button"
                  onClick={handleLogout}
                  className="text-xs font-semibold text-red-600 hover:text-red-700"
                >
                  {tr("Logout")}
                </button>
              ) : (
                <button
                  type="button"
                  onClick={() => {
                    setOpen(false);
                    handleLogin();
                  }}
                  className="text-xs font-semibold text-[#0b6e3e] hover:text-emerald-700"
                >
                  {tr("Sign in")}
                </button>
              )}
            </div>
            <div className="mt-3 flex items-center justify-between">
              <span className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                {t("lang.label")}
              </span>
              <InlineLanguageSwitcher />
            </div>
          </div>

          {/* Scrollable nav area */}
          <div className="flex-1 overflow-y-auto">
            {NAV.map((item) => {
              const active = isTopLevelActive(pathname, item);
              const TopIcon = item.icon;
              const megaGroups = item.mega ?? null;
              const flatChildren = item.children ?? null;

              return (
                <div key={item.label} className="border-b border-slate-100">
                  {item.to ? (
                    <Link
                      to={item.to}
                      className={`flex items-center gap-3 px-6 py-3 font-semibold ${
                        active ? "text-[#0b6e3e] bg-emerald-50" : "text-slate-800"
                      }`}
                      onClick={() => setOpen(false)}
                    >
                      {TopIcon ? <TopIcon className="w-4 h-4" /> : null}
                      <span>{tr(item.label)}</span>
                    </Link>
                  ) : (
                    <>
                      <button
                        type="button"
                        className={`flex w-full items-center justify-between px-6 py-3 font-semibold ${
                          active ? "text-[#0b6e3e] bg-emerald-50" : "text-slate-800"
                        }`}
                        onClick={() =>
                          setMobileOpen(mobileOpen === item.label ? null : item.label)
                        }
                        aria-expanded={mobileOpen === item.label}
                      >
                        <span className="flex items-center gap-3">
                          {TopIcon ? <TopIcon className="w-4 h-4" /> : null}
                          <span>{tr(item.label)}</span>
                        </span>
                        <ChevronDown
                          className={`w-4 h-4 transition ${
                            mobileOpen === item.label ? "rotate-180" : ""
                          }`}
                        />
                      </button>
                      {mobileOpen === item.label && (
                        <div className="bg-slate-50 py-1">
                          {megaGroups ? (
                            <>
                              {megaGroups.map((group) => (
                                <div key={group.title} className="py-1">
                                  <div className="px-6 pt-2 pb-1 text-[11px] font-bold uppercase tracking-wider text-slate-400">
                                    {group.title}
                                  </div>
                                  {group.items.map((c) => {
                                    const ChildIcon = c.icon;
                                    const cActive = isChildActive(pathname, c);
                                    return (
                                      <Link
                                        key={c.label}
                                        to={c.to}
                                        className={`flex items-start gap-3 px-8 py-2 text-sm ${
                                          cActive
                                            ? "text-[#0b6e3e] bg-emerald-50"
                                            : "text-slate-700"
                                        }`}
                                        onClick={() => setOpen(false)}
                                      >
                                        {ChildIcon ? (
                                          <ChildIcon className="w-4 h-4 mt-0.5 shrink-0" />
                                        ) : null}
                                        <span className="min-w-0">
                                          <span className="block font-semibold">{tr(c.label)}</span>
                                          {c.description && (
                                            <span className="block text-xs text-slate-500 mt-0.5">
                                              {c.description}
                                            </span>
                                          )}
                                        </span>
                                      </Link>
                                    );
                                  })}
                                </div>
                              ))}
                              {item.promo && (
                                <Link
                                  to={item.promo.ctaTo}
                                  onClick={() => setOpen(false)}
                                  className="mx-6 my-3 flex items-center gap-3 rounded-xl overflow-hidden bg-gradient-to-br from-[#0b6e3e] to-[#22c55e] text-white shadow"
                                >
                                  <img
                                    src={item.promo.image}
                                    alt={item.promo.imageAlt}
                                    className="w-20 h-20 object-cover shrink-0"
                                    loading="lazy"
                                  />
                                  <div className="py-2 pr-3 min-w-0 flex-1">
                                    {item.promo.eyebrow && (
                                      <span className="inline-block bg-[#f5c400] text-slate-900 text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded mb-1">
                                        {item.promo.eyebrow}
                                      </span>
                                    )}
                                    <div className="text-sm font-bold leading-tight truncate">
                                      {item.promo.headline}
                                    </div>
                                    <div className="flex items-center gap-2 mt-1">
                                      {item.promo.price && (
                                        <span className="text-sm font-extrabold text-[#f5c400]">
                                          {item.promo.price}
                                          <span className="text-[10px] text-white/80 font-normal ml-0.5">
                                            {item.promo.priceSuffix}
                                          </span>
                                        </span>
                                      )}
                                      <span className="text-[10px] font-semibold uppercase tracking-wide text-white ml-auto">
                                        {item.promo.ctaLabel} →
                                      </span>
                                    </div>
                                  </div>
                                </Link>
                              )}
                            </>
                          ) : (
                            flatChildren?.map((c) => {
                              const ChildIcon = c.icon;
                              const cActive = isChildActive(pathname, c);
                              return (
                                <Link
                                  key={c.label}
                                  to={c.to}
                                  className={`flex items-center gap-3 px-10 py-2 text-sm ${
                                    cActive
                                      ? "text-[#0b6e3e] bg-emerald-50"
                                      : "text-slate-700"
                                  }`}
                                  onClick={() => setOpen(false)}
                                >
                                  {ChildIcon ? (
                                    <ChildIcon className="w-4 h-4 shrink-0" />
                                  ) : null}
                                  <span>{tr(c.label)}</span>
                                </Link>
                              );
                            })
                          )}
                        </div>
                      )}
                    </>
                  )}
                </div>
              );
            })}
          </div>

          {/* Drawer footer CTAs — Cart button also hidden on the home page
              so the mobile drawer matches the desktop header behavior. */}
          <div className="p-4 border-t border-slate-100 shrink-0 flex gap-3">
            {!isHome && (
              <Link
                to="/shop/cart"
                onClick={() => setOpen(false)}
                className="relative flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg border-2 border-[#0b6e3e] text-[#0b6e3e] font-semibold hover:bg-emerald-50 transition"
              >
                <ShoppingCart className="w-4 h-4" />
                <span>{tr("Cart")}</span>
                {itemCount > 0 && (
                  <span className="ml-1 min-w-[20px] h-5 px-1.5 rounded-full bg-[#f5c400] text-slate-900 text-[10px] font-extrabold flex items-center justify-center">
                    {itemCount > 99 ? "99+" : itemCount}
                  </span>
                )}
              </Link>
            )}
            <Link
              to="/client"
              className="flex-1 text-center py-2.5 rounded-lg bg-[#f5c400] text-slate-900 font-bold hover:bg-yellow-400 transition shadow"
              onClick={() => setOpen(false)}
            >
              {tr("CLIENT AREA")}
            </Link>
          </div>
        </aside>
      </div>

    </header>
  );
}

export function Footer() {
  const { t, tr } = useLanguage();
  const [showTop, setShowTop] = useState(false);

  useEffect(() => {
    const onScroll = () => setShowTop(window.scrollY > 400);
    window.addEventListener("scroll", onScroll);
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const scrollToTop = () => window.scrollTo({ top: 0, behavior: "smooth" });

  const socials: { label: string; Icon: typeof Facebook; href: string }[] = [
    { label: "YouTube", Icon: Youtube, href: "#" },
    { label: "Telegram", Icon: Send, href: "#" },
    { label: "Facebook", Icon: Facebook, href: "#" },
    { label: "Instagram", Icon: Instagram, href: "#" },
    { label: "LinkedIn", Icon: Linkedin, href: "#" },
  ];

  return (
    <footer className="relative bg-black text-slate-200 text-sm overflow-hidden">
      <div className="max-w-7xl 3xl:max-w-[1680px] 4xl:max-w-[2000px] 5xl:max-w-[2400px] mx-auto px-4 sm:px-6 lg:px-8 3xl:px-12 5xl:px-16 pt-16 pb-10">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-10">
          <div>
            <div className="flex flex-col items-center md:items-start">
              <img
                src="/logo.svg"
                alt="DoItEasy"
                className="h-14 md:h-16 w-auto brightness-0 invert"
              />
            </div>

            <div className="flex gap-3 mt-5">
              {socials.map(({ label, Icon, href }) => (
                <a
                  key={label}
                  href={href}
                  aria-label={label}
                  className="w-9 h-9 rounded-md bg-white/5 hover:bg-[#22c55e] hover:text-black text-white flex items-center justify-center transition"
                >
                  <Icon className="w-4 h-4" />
                </a>
              ))}
            </div>

            <div className="flex flex-col gap-3 mt-6 max-w-[200px]">
              <a
                href="#"
                className="inline-flex items-center gap-3 bg-black border border-white/30 rounded-lg px-3 py-2 hover:border-[#22c55e] transition"
              >
                <svg viewBox="0 0 384 512" className="w-6 h-6 text-white fill-current" aria-hidden="true">
                  <path d="M318.7 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7C63.3 141.2 4 184.8 4 273.5q0 39.3 14.4 81.2c12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zm-56.6-164.2c27.3-32.4 24.8-61.9 24-72.5-24.1 1.4-52 16.4-67.9 34.9-17.5 19.8-27.8 44.3-25.6 71.9 26.1 2 49.9-11.4 69.5-34.3z" />
                </svg>
                <div className="leading-tight text-left">
                  <div className="text-[9px] text-white/70 uppercase">Download on the</div>
                  <div className="text-sm font-semibold text-white">App Store</div>
                </div>
              </a>
              <a
                href="#"
                className="inline-flex items-center gap-3 bg-black border border-white/30 rounded-lg px-3 py-2 hover:border-[#22c55e] transition"
              >
                <svg viewBox="0 0 512 512" className="w-6 h-6" aria-hidden="true">
                  <path fill="#34a853" d="M325.3 234.3L104.6 13l280.8 161.2-60.1 60.1z" />
                  <path fill="#fbbc04" d="M104.6 499L325.3 277.7l60.1 60.1L104.6 499z" />
                  <path fill="#4285f4" d="M447 256.3c17.4 10.1 17.4 37.3 0 47.4l-61.7 35.6-60.1-60.1 60.1-60.1L447 256.3z" />
                  <path fill="#ea4335" d="M104.6 13v486c-9.4-5.4-15.6-15.6-15.6-27.7V40.7c0-12.1 6.2-22.3 15.6-27.7z" />
                </svg>
                <div className="leading-tight text-left">
                  <div className="text-[9px] text-white/70 uppercase">Get it on</div>
                  <div className="text-sm font-semibold text-white">Google Play</div>
                </div>
              </a>
            </div>
          </div>

          <div>
            <h4 className="font-bold text-white text-base mb-4">{t("footer.about_title")}</h4>
            <ul className="space-y-2 text-slate-300 leading-relaxed">
              <li>{t("footer.country")}</li>
              <li>{t("footer.address_line1")}</li>
              <li>{t("footer.address_line2")}</li>
              <li>{t("footer.address_line3")}</li>
              <li className="keep-ltr">{t("footer.phone")}</li>
            </ul>
          </div>

          <div>
            <h4 className="font-bold text-white text-base mb-4">{t("footer.terms_title")}</h4>
            <ul className="space-y-2 text-slate-300">
              <li><Link to="/service-terms" className="hover:text-[#22c55e] transition">{t("footer.service_terms")}</Link></li>
              <li><Link to="/refund-policy" className="hover:text-[#22c55e] transition">{t("footer.refund_policy")}</Link></li>
              <li><Link to="/privacy-center" className="hover:text-[#22c55e] transition">{t("footer.privacy_center")}</Link></li>
              <li><Link to="/tickets" className="hover:text-[#22c55e] transition">{t("footer.customer_support")}</Link></li>
              <li><Link to="/knowledge-base" className="hover:text-[#22c55e] transition">{t("footer.knowledge_base")}</Link></li>
              <li><Link to="/faq" className="hover:text-[#22c55e] transition">{t("footer.faq")}</Link></li>
              <li><Link to="/services" className="hover:text-[#22c55e] transition">{t("footer.services_catalog")}</Link></li>
            </ul>
          </div>

          <div>
            <h4 className="font-bold text-white text-base mb-4">{t("footer.clients_title")}</h4>
            <ul className="space-y-2 text-slate-300">
              <li><Link to="/client" className="hover:text-[#22c55e] transition">{t("footer.account_dashboard")}</Link></li>
              <li><Link to="/register" className="hover:text-[#22c55e] transition">{t("footer.new_client")}</Link></li>
              <li><a href="#" className="hover:text-[#22c55e] transition">{t("footer.affiliate_program")}</a></li>
              <li><Link to="/tickets" className="hover:text-[#22c55e] transition">{t("footer.customer_support")}</Link></li>
              <li><Link to="/services" className="hover:text-[#22c55e] transition">{t("footer.services_catalog")}</Link></li>
            </ul>
          </div>
        </div>

        <div className="flex justify-center mt-12">
          <a
            href="#"
            className="inline-flex items-center gap-2 bg-black border border-white/40 hover:border-[#22c55e] rounded-md px-5 py-2.5 text-white text-sm font-medium transition"
          >
            <Star className="w-4 h-4 fill-white" />
            <span>{t("footer.rate_us")}</span>
          </a>
        </div>

        <div className="text-center mt-8 text-slate-400 text-sm relative z-10">
          {t("footer.copyright").replace("{year}", String(new Date().getFullYear()))}
        </div>
      </div>

      <div className="absolute bottom-0 left-0 right-0 pointer-events-none" aria-hidden="true">
        <svg
          viewBox="0 0 1440 120"
          preserveAspectRatio="none"
          className="w-full h-20 md:h-24"
        >
          <path fill="#16a34a" fillOpacity="0.85">
            <animate
              attributeName="d"
              dur="8s"
              repeatCount="indefinite"
              values="
                M0,60 C240,110 480,0 720,40 C960,90 1200,20 1440,60 L1440,120 L0,120 Z;
                M0,70 C240,20 480,100 720,60 C960,20 1200,90 1440,50 L1440,120 L0,120 Z;
                M0,60 C240,110 480,0 720,40 C960,90 1200,20 1440,60 L1440,120 L0,120 Z
              "
            />
          </path>

          <path fill="#22c55e" fillOpacity="0.95">
            <animate
              attributeName="d"
              dur="6s"
              repeatCount="indefinite"
              values="
                M0,80 C240,40 480,110 720,70 C960,30 1200,100 1440,70 L1440,120 L0,120 Z;
                M0,70 C240,110 480,40 720,80 C960,120 1200,50 1440,90 L1440,120 L0,120 Z;
                M0,80 C240,40 480,110 720,70 C960,30 1200,100 1440,70 L1440,120 L0,120 Z
              "
            />
          </path>
        </svg>
      </div>

      {showTop && (
        <button
          type="button"
          onClick={scrollToTop}
          aria-label={tr("Back to top")}
          className="fixed bottom-6 right-6 z-50 w-11 h-11 rounded-full bg-white text-[#16a34a] shadow-lg border border-slate-200 hover:bg-[#16a34a] hover:text-white transition flex items-center justify-center"
        >
          <ArrowUp className="w-5 h-5" />
        </button>
      )}
    </footer>
  );
}

export default function SiteLayout({ children }: { children: ReactNode }) {
  const { pathname } = useLocation();
  const transparentHeader = pathname === "/";

  useEffect(() => {
    if (typeof window === "undefined") return;

    requestAnimationFrame(() =>
      window.scrollTo({ top: 0, behavior: "instant" as ScrollBehavior })
    );

    if (pathname !== "/") {
      document.documentElement.classList.remove("onepage-mode");
      document.body.classList.remove("onepage-mode");
    }
  }, [pathname]);

  return (
    <div className="min-h-screen flex flex-col bg-white" key={pathname}>
      <SeoMeta />
      <AutoTranslate />
      <Header />
      <main className={`flex-1 ${transparentHeader ? "-mt-20" : ""}`}>{children}</main>
      <Footer />
    </div>
  );
}