"use client";

import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import { usePathname } from "next/navigation";
import { NAVIGATION_CONTENT_WIDTH } from "@/config/uiConfig";

const MAIN_SURFACE = "min-h-screen bg-slate-50 dark:bg-slate-900";
/**
 * Workbench route: fixed height under the AppBar (`100dvh` minus toolbar min-height).
 * Avoids `min-h-screen` on `<main>`, which would stack below the bar and introduce body scroll.
 */
const WORKBENCH_MAIN =
  "bg-slate-50 dark:bg-slate-900 p-0 overflow-hidden h-[calc(100dvh-56px)] max-h-[calc(100dvh-56px)] sm:h-[calc(100dvh-64px)] sm:max-h-[calc(100dvh-64px)]";
const MAIN_PADDING = "p-4 sm:p-4 md:p-6 lg:p-8";

/** Returns true when `pathname` is `/po/workbench` or a nested path under it. */
function isPoWorkbenchRoute(pathname: string | null): boolean {
  if (!pathname) return false;
  return pathname === "/po/workbench" || pathname.startsWith("/po/workbench/");
}

/**
 * Wraps authenticated app content in `<main>` with responsive padding.
 *
 * For the PO Workbench route, padding is removed so the grid can use the full content width
 * without applying compensating negative margins.
 */
export default function MainContentArea({
  children,
}: {
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  /** True when the active route is PO Workbench (full-bleed main area). */
  const fullBleedWorkbench = isPoWorkbenchRoute(pathname);

  return (
    <Box
      component="main"
      sx={{
        marginInlineStart: { xs: 0, xl: NAVIGATION_CONTENT_WIDTH },
      }}
      className={
        fullBleedWorkbench
          ? WORKBENCH_MAIN
          : `${MAIN_SURFACE} ${MAIN_PADDING}`
      }
    >
      <Stack
        spacing={fullBleedWorkbench ? 0 : 2}
        sx={
          fullBleedWorkbench
            ? { height: "100%", minHeight: 0, overflow: "hidden" }
            : undefined
        }
      >
        {children}
      </Stack>
    </Box>
  );
}
