"use client";

import { ThemeProvider } from "next-themes";
import { MotionConfig } from "framer-motion";
import { CartProvider } from "@/context/CartContext";
import { usePathname } from "next/navigation";
import SiteHeader from "@/components/layout/SiteHeader";
import SiteFooter from "@/components/layout/SiteFooter";
import CartToast from "@/components/storefront/CartToast";
import CartRestoredToast from "@/components/cart/CartRestoredToast";

export function Providers({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const isBrandRoute = pathname?.startsWith("/tuxedo") || pathname?.startsWith("/indian-river-direct");
  const isLandingPage = pathname === "/" || pathname === "/brands";
  const isAuthPage = pathname === "/login" || pathname === "/admin/login";
  // Admin routes have their own AdminSidebar + design-system shell; suppress
  // the public SiteHeader/SiteFooter to avoid a duplicate header on every
  // admin page.
  const isAdminRoute = pathname?.startsWith("/admin");
  // Cart + checkout + wholesale pages render their own StorefrontHeader/Footer
  // (or wholesale-specific layout) — skip the public chrome to avoid doubles.
  const isStandalonePage =
    pathname?.startsWith("/cart") ||
    pathname?.startsWith("/checkout") ||
    pathname?.startsWith("/wholesale") ||
    pathname?.startsWith("/water");
  // Suppress hydration flash for theme (next-themes handles this gracefully)
  // The visibility:hidden pattern was causing click handling issues on hidden elements
  return (
    <ThemeProvider attribute="class" defaultTheme="light" enableSystem={false} disableTransitionOnChange>
      {/*
       * MotionConfig caps every framer-motion animation in the tree:
       *   - default transition is 0.2s easeOut (was usually 0.6-1s with custom cubic-bezier eases)
       *   - `reducedMotion="user"` makes framer-motion automatically strip x/y/scale/rotate
       *     from animations when the user has prefers-reduced-motion: reduce set, leaving
       *     only opacity. This is the single most important lever for vestibular comfort —
       *     it overrides the 71 `initial={{ y: 48 }}` / `initial={{ scale: 0 }}` reveals
       *     across the public site without touching each file.
       * Combined with the prefers-reduced-motion block in globals.css, this means a user
       * with motion sensitivity gets the same content with zero positional movement.
       */}
      <MotionConfig transition={{ duration: 0.2, ease: "easeOut" }} reducedMotion="user">
        <CartProvider>
          {!isBrandRoute && !isLandingPage && !isAuthPage && !isAdminRoute && !isStandalonePage && <SiteHeader />}
          {children}
          {!isBrandRoute && !isLandingPage && !isAuthPage && !isAdminRoute && !isStandalonePage && <SiteFooter />}
          <CartToast />
          <CartRestoredToast />
        </CartProvider>
      </MotionConfig>
    </ThemeProvider>
  );
}