"use client";

import usePreference from "@/hooks/helpers/usePreference";
import useToggle from "@/hooks/helpers/useToggle";
import { glassSurface } from "@/lib/styles/glassSurface";
import clsx from "clsx";
import { usePathname, useRouter } from "next/navigation";
import React, { useEffect, useRef } from "react";
import SideMenu from "../menu/SideMenu";
import BottomNavBar from "../navigation/BottomNavBar";
import PagerModal from "../pager/PagerModal";
import TopBar from "../topbar/TopBar";

type Props = {} & React.AllHTMLAttributes<HTMLBodyElementEventMap>;

function ClientMenuRouteWrapper({ children }: Props) {
  const { state: profileDrop, toggle: _toggleProfileDrop } = useToggle(false);
  const { state: menuState, toggle: _toggleMenuState, set: setMenuState } = useToggle(false);
  const { state: searchModal, toggle: _toggleSearchModal } = useToggle(false);
  const { state: nightMode, toggle: _toggleNightMode } = usePreference<boolean>("night-mode", false);
  const { state: pagerOpen, toggle: togglePager, set: setPagerOpen } = useToggle(false);
  const router = useRouter();
  const pathname = usePathname();

  const toggleProfileDrop = () => {
    _toggleProfileDrop();
  };

  const toggleNightMode = () => {
    _toggleNightMode();
  };

  const toggleMenuState = () => {
    _toggleMenuState();
  };

  const toggleSearchModal = () => {
    _toggleSearchModal();
  };

  const handleClosePager = () => {
    setPagerOpen(false);
  };

  const location = usePathname();
  const hideBottomNav = pathname.endsWith("/cart") || pathname.endsWith("/ai");
  const mainRef = useRef<HTMLElement>(null);

  // Refs for the scroll-driven animation — kept outside React state so scroll
  // events never trigger re-renders. The RAF+lerp loop writes directly to the DOM.
  const navContainerRef = useRef<HTMLDivElement>(null);
  const targetProgressRef = useRef(0);
  const currentProgressRef = useRef(0);
  const rafIdRef = useRef(0);

  useEffect(() => {
    if (menuState) {
      setMenuState(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location]);

  useEffect(() => {
    const scrollEl = mainRef.current;
    const navEl = navContainerRef.current;

    if (!navEl) return;

    if (!scrollEl || hideBottomNav) {
      cancelAnimationFrame(rafIdRef.current);
      navEl.style.transform = "";
      targetProgressRef.current = 0;
      currentProgressRef.current = 0;
      return;
    }

    const SCROLL_RANGE = 150; // px of scroll to reach full compact state
    const LERP_FACTOR = 0.1; // per-frame smoothing (lower = smoother, higher = snappier)
    const MIN_SCALE = 0.82; // scale floor (18% smaller at full scroll)

    const tick = () => {
      const diff = targetProgressRef.current - currentProgressRef.current;
      if (Math.abs(diff) < 0.0005) {
        currentProgressRef.current = targetProgressRef.current;
      } else {
        currentProgressRef.current += diff * LERP_FACTOR;
        rafIdRef.current = requestAnimationFrame(tick);
      }
      const scale = 1 - (1 - MIN_SCALE) * currentProgressRef.current;
      navEl.style.transform = `scale(${scale.toFixed(4)})`;
    };

    const onScroll = () => {
      targetProgressRef.current = Math.min(1, Math.max(0, scrollEl.scrollTop / SCROLL_RANGE));
      cancelAnimationFrame(rafIdRef.current);
      rafIdRef.current = requestAnimationFrame(tick);
    };

    scrollEl.addEventListener("scroll", onScroll, { passive: true });

    return () => {
      scrollEl.removeEventListener("scroll", onScroll);
      cancelAnimationFrame(rafIdRef.current);
    };
  }, [hideBottomNav, location]);

  return (
    <div className="h-svh overflow-hidden pt-10 flex flex-col pb-4 xl:pt-12">
      <div data-menu-topbar className={glassSurface("z-50 fixed right-4 left-4 xl:right-71.25 top-4 xl:h-16 h-12 flex items-center px-4 justify-between rounded-4xl xl:w-[calc(100%-305px)]")}>
        <TopBar
          profileDropState={profileDrop}
          toggleProfileDropState={toggleProfileDrop}
          menuState={menuState}
          toggleMenuState={toggleMenuState}
          searchModalState={searchModal}
          toggleSearchModalState={toggleSearchModal}
          nightModeState={nightMode}
          toggleNightModeState={toggleNightMode}
        />
      </div>

      {!hideBottomNav && (
        <div ref={navContainerRef} data-menu-bottom-nav className="fixed bottom-7 left-0 right-0 z-45 px-4" style={{ willChange: "transform", transformOrigin: "center bottom" }}>
          <BottomNavBar onPagerClick={togglePager} />
        </div>
      )}

      <SideMenu nightModeState={nightMode} togglenightModeState={toggleNightMode} menuState={menuState} toggleMenuState={toggleMenuState} />

      <main ref={mainRef} className={clsx("relative noscrollbar overflow-y-auto h-svh pt-6 xl:pt-8 px-4 xl:pr-0 xl:pl-5 w-full xl:w-[calc(100%-285px)] md:self-end", hideBottomNav ? "pb-4" : "pb-12")}>
        {children}
      </main>

      <PagerModal visible={pagerOpen} onClose={handleClosePager} />
    </div>
  );
}

export default ClientMenuRouteWrapper;
