"use client";

import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { AnimatePresence, m } from "framer-motion";
import { AgentSidebar } from "@/components/agent/AgentSidebar";
import { AgentHeader } from "@/components/agent/AgentHeader";
import { useAgentAuth } from "@/hooks/useAgentAuth";

export default function AgentAppLayout({ children }: { children: React.ReactNode }) {
  const { user, hydrated } = useAgentAuth();
  const router = useRouter();
  const pathname = usePathname();

  // Below 1440px the sidebar is an overlay drawer, closed by default. At 1440px+
  // it's a permanent push panel — forced by CSS (`min-[1440px]:` variants on the
  // sidebar, backdrop, hamburger, and grid columns) independent of this state, so
  // there's no JS/viewport-timing race that could flash the collapsed layout.
  const [sidebarOpen, setSidebarOpen] = useState(false);

  useEffect(() => {
    if (hydrated && !user) {
      router.replace(`/agent/login?redirect=${encodeURIComponent(pathname)}`);
    }
  }, [hydrated, user, pathname, router]);

  if (!hydrated || !user) {
    return (
      <div className="grid min-h-screen place-items-center bg-white dark:bg-slate-950">
        <div className="flex items-center gap-3 text-slate-500 dark:text-slate-400">
          <span className="h-2 w-2 animate-pulse rounded-full bg-brand-500" />
          <span className="h-2 w-2 animate-pulse rounded-full bg-brand-500 [animation-delay:120ms]" />
          <span className="h-2 w-2 animate-pulse rounded-full bg-brand-500 [animation-delay:240ms]" />
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50/60 dark:bg-slate-950">
      <div className="min-[1440px]:grid min-[1440px]:grid-cols-[18rem_1fr]">
        <AgentSidebar open={sidebarOpen} onClose={() => setSidebarOpen(false)} />
        <div className="flex min-h-screen flex-col">
          <AgentHeader sidebarOpen={sidebarOpen} onMenuClick={() => setSidebarOpen((v) => !v)} />
          {/* pt-4 mirrors the sidebar nav's own p-4 top offset (AgentSidebar.tsx) so the
              first row of main content lines up with the "Dashboard" nav item, instead
              of sitting lower under the header. Bottom keeps the roomier pb-8 rhythm. */}
          <main id="main-content" className="flex-1 pt-4 pb-8">
            <AnimatePresence mode="wait" initial={false}>
              <m.div
                key={pathname}
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -4 }}
                transition={{ duration: 0.18, ease: "easeOut" }}
              >
                {children}
              </m.div>
            </AnimatePresence>
          </main>
        </div>
      </div>
    </div>
  );
}
