"use client";

import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import { usePathname } from "next/navigation";
import { isFullBleedMainRoute } from "@/app/(main)/isFullBleedMainRoute";
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.
 */
/** Height lives in `sx` when full-bleed workbench so it matches MUI flex chain (avoids Tailwind vs % rounding gaps). */
const WORKBENCH_MAIN = "bg-slate-50 dark:bg-slate-900 p-0 overflow-hidden";
const MAIN_PADDING = "p-4 sm:p-4 md:p-6 lg:p-8";

/**
 * 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 = isFullBleedMainRoute(pathname);

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