import { useLocation } from "react-router-dom";
import { Outlet } from "react-router-dom";
import { AppMenuTabs } from "./AppMenuTabs";
import { useSidebar } from "@/shared/common/ui/sidebar";
import Top from "@/record-management/components/common/Top";
import { useAuth } from "@/shared/context/AuthContext";

export const AppLayout = () => {
  const { pathname } = useLocation();
  const isAuthPage = pathname === "/";
  const { toggleSidebar } = useSidebar();
  const { user } = useAuth();
  
  const userRoles = user?.roles?.map((role) => role.key) || [];
  const isSuperAdmin = userRoles.includes("super_admin");
  
  // html/body/#root are `overflow: hidden` (index.css) — the host chrome
  // scrolls inside FreightDashboardLayout. This subtree renders its own
  // full-page layout instead, so it must be its own scroll container or
  // nothing scrolls. Top/AppMenuTabs are `fixed`, unaffected by the scroller.
  if (isAuthPage) {
    return (
      <div className="h-dvh w-full overflow-y-auto bg-gray-50">
        <Outlet />
      </div>
    );
  }

  return (
    // pt-16 clears the fixed 64px <Top>; AppMenuTabs is sticky and in flow,
    // so content starts right below it at any tabs height (mobile/desktop).
    <div className="w-full h-dvh overflow-y-auto flex flex-col pt-16 bg-background text-foreground">
      <Top onToggleSidebar={toggleSidebar} showRecordManagementShortcut={!isSuperAdmin} />
      <AppMenuTabs />
      <div className="px-2 pb-2 pt-4 sm:px-4 sm:pb-4 sm:pt-6 flex-1">
        <div className="w-full overflow-x-auto">
          <Outlet />
        </div>
      </div>
    </div>
  );
};
