"use client";
import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { AnimatePresence } from "framer-motion";
import { useAppSelector, useAppDispatch } from "@/store/hooks";
import { stopAll } from "@/store/slices/playerSlice";
import { validateAuth } from "@/store/slices/authSlice";
import { useLoginPrompt } from "@/lib/LoginPromptContext";
import { Header } from "@/components/layout/Header";
import { Sidebar } from "@/components/layout/Sidebar";
import { BottomPlayer } from "@/components/layout/BottomPlayer";
import { MiniVideoPlayer } from "@/components/layout/MiniVideoPlayer";
import { MobileBottomNav } from "@/components/layout/MobileBottomNav";
import { Footer } from "@/components/layout/Footer";
import { useSidebar } from "@/lib/SidebarContext";
import { cn } from "@/utils/cn";
import { PageTransition } from "@/components/motion/PageTransition";

// Pages that are meaningless without an account — show login prompt when visited as a guest
const PERSONAL_ROUTES = [
  "/profile",
  "/history",
  "/liked",
  "/watch-later",
  "/upload",
  "/wallet",
  "/subscriptions",
  "/notifications",
];

// Routes where all background media (video mini-player + audio) must stop
const STOP_MEDIA_ROUTES = ["/shorts", "/reel"];

export function AppShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const dispatch = useAppDispatch();
  const isAuthenticated = useAppSelector((s) => s.auth.isAuthenticated);
  const { open: openLoginPrompt } = useLoginPrompt();
  const { collapsed, mobileOpen, toggle, closeMobile } = useSidebar();

  const isPersonalRoute = PERSONAL_ROUTES.some((r) => pathname.startsWith(r));
  const isShortRoute = STOP_MEDIA_ROUTES.some((r) => pathname.startsWith(r));

  const currentTrack = useAppSelector((s) => s.player.currentTrack);
  const playerType = useAppSelector((s) => s.player.type);
  const hasAudioPlayer =
    !isShortRoute && !!currentTrack && playerType === "audio";

  useEffect(() => {
    dispatch(validateAuth());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (isShortRoute) {
      dispatch(stopAll());
    }
  }, [isShortRoute, pathname, dispatch]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (isPersonalRoute && !isAuthenticated) {
      openLoginPrompt();
      router.replace("/");
    }
  }, [isPersonalRoute, isAuthenticated, openLoginPrompt, router]);

  return (
    <div
      className="h-screen overflow-hidden flex flex-col"
      style={{ background: "var(--bg)" }}
    >
      <Header onMenuToggle={toggle} />
      <div
        className={cn(
          "flex-1 min-h-0 overflow-hidden transition-all duration-200",
          "md:grid",
          collapsed ? "md:grid-cols-[56px_1fr]" : "md:grid-cols-[200px_1fr]",
        )}
      >
        <Sidebar
          collapsed={collapsed}
          mobileOpen={mobileOpen}
          onClose={closeMobile}
        />
        <main
          className={cn(
            "min-w-0",
            // Shorts/reels: lock to viewport — prevent scroll, fill parent height
            isShortRoute
              ? "overflow-hidden h-full"
              : // h-full gives main a bounded height so overflow-y-auto actually scrolls
                // (on mobile the inner container is block, not grid, so height is otherwise auto)
                hasAudioPlayer
                ? "h-full overflow-y-auto pb-32 md:pb-24"
                : "h-full overflow-y-auto pb-16 md:pb-4",
          )}
        >
          <AnimatePresence mode="wait" initial={false}>
            <PageTransition key={pathname}>{children}</PageTransition>
          </AnimatePresence>
          {/* <Footer /> */}
        </main>
      </div>
      {/* Hide persistent players on shorts/reels — they manage their own playback */}
      {!isShortRoute && <BottomPlayer collapsed={collapsed} />}
      {!isShortRoute && <MiniVideoPlayer />}
      {/* Mobile bottom navigation — always visible including on shorts */}
      <MobileBottomNav />
    </div>
  );
}
