"use client";
import { jsxs, jsx } from "react/jsx-runtime";
import { useRef, useState, useCallback } from "react";
import { HEADER_HEIGHT_DESKTOP } from "./constants.js";
import { CONTAINER_PADDING_DESKTOP, CONTAINER_PADDING_MOBILE, CONTAINER_MAX_WIDTH_DEFAULT } from "./Container.js";
import { useIsomorphicLayoutEffect } from "../hooks/useIsomorphicLayoutEffect.js";
import { classNames } from "../utils/classNames.js";
const Layout = ({
  preheader,
  header,
  headerSticky = false,
  headerOverlay = false,
  footer,
  footerOverlay = false,
  container = true,
  className,
  children,
  ...props
}) => {
  const rootRef = useRef(null);
  const innerGridRef = useRef(null);
  const headerRangeRef = useRef(null);
  const headerRangeHeight = useRef(HEADER_HEIGHT_DESKTOP);
  const lastScrollY = useRef(0);
  const lastScrollDirection = useRef("down");
  const headerRef = useRef(null);
  const [headerStuck, setHeaderStuck] = useState(false);
  const [headerOutsideViewport, setHeaderOutsideViewport] = useState(false);
  const refreshStickyHeader = useCallback(() => {
    const scrollDirection = window.scrollY > lastScrollY.current ? "down" : "up";
    lastScrollY.current = window.scrollY;
    const headerDistanceFromViewportTop = getDistanceFromViewportTop(headerRef.current);
    if (scrollDirection !== lastScrollDirection.current && (headerDistanceFromViewportTop <= -80 || headerDistanceFromViewportTop >= 0)) {
      headerRangeHeight.current = Math.max(0, -getDistanceFromViewportTop(innerGridRef.current)) + (scrollDirection === "down" ? HEADER_HEIGHT_DESKTOP : -32);
      headerRangeRef.current.style.setProperty("height", `${headerRangeHeight.current}px`);
    }
    lastScrollDirection.current = scrollDirection;
    setHeaderStuck(headerRef.current.offsetTop > 0);
    setHeaderOutsideViewport(headerDistanceFromViewportTop <= -80);
    const headerHiddenAmount = Math.max(0, Math.min(HEADER_HEIGHT_DESKTOP, -headerDistanceFromViewportTop));
    rootRef.current.style.setProperty("--gds-header-hidden-amount", `${headerHiddenAmount}px`);
  }, []);
  useIsomorphicLayoutEffect(() => {
    var _a, _b;
    if (!headerSticky || typeof window === "undefined") {
      setHeaderStuck(false);
      setHeaderOutsideViewport(false);
      (_a = rootRef.current) == null ? void 0 : _a.style.removeProperty("--gds-header-hidden-amount");
      (_b = headerRangeRef.current) == null ? void 0 : _b.style.removeProperty("height");
      return;
    }
    refreshStickyHeader();
    window.addEventListener("scroll", refreshStickyHeader);
    return () => {
      window.removeEventListener("scroll", refreshStickyHeader);
    };
  }, [headerSticky, refreshStickyHeader]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: rootRef,
      className: classNames(["gds-layout grid", className]),
      style: {
        "--gds-header-height-visible": "max(0px, calc(var(--gds-header-height) - var(--gds-header-hidden-amount)))",
        "--gds-header-stuck": headerStuck ? 1 : 0,
        "--gds-header-hidden-amount": "0px",
        gridTemplateAreas: `
            "preheader"
            "header"
            "main"
            "footer"
          `,
        gridTemplateRows: `
            max-content
            max-content
            1fr
            max-content
          `,
        // Together with the 1fr for the `main` area (above), ensure the layout fills the viewport's height (no empty space below the footer)
        minHeight: "100vh",
        // Prevent horizontal scrolling when elements accidentally (or intentionally) overflow the page
        overflow: "clip",
        // Create a stacking context so that no element outside this layout (e.g. portaled elements from Radix) can appear behind any element inside it
        isolation: "isolate"
      },
      ...props,
      children: [
        /* @__PURE__ */ jsx("div", { style: { gridArea: "preheader / 1 / main / -1", minHeight: "min(100vh, 1024px)", visibility: "hidden" } }),
        preheader ? /* @__PURE__ */ jsx("div", { style: { gridArea: "preheader", zIndex: 100 }, children: preheader }) : null,
        /* @__PURE__ */ jsxs(
          "div",
          {
            ref: innerGridRef,
            className: `
          grid grid-rows-subgrid
          ${/* Fallback for browsers that don't support subgrid: */
            ""}
          [grid-template-areas:inherit]
          -:grid-rows-[inherit]
        `,
            style: { gridArea: "header / 1 / footer / -1" },
            children: [
              /* @__PURE__ */ jsx(
                "header",
                {
                  className: "gds-layout-header",
                  style: {
                    gridArea: "header",
                    pointerEvents: "none",
                    zIndex: 100,
                    position: headerOverlay ? "absolute" : "relative",
                    left: 0,
                    right: 0,
                    top: 0,
                    height: headerOverlay ? 0 : "var(--gds-header-height)",
                    // Fix issue where selecting text in the sticky header causes the page to scroll
                    // (except in Safari due to this bug: https://bugs.webkit.org/show_bug.cgi?id=208682)
                    userSelect: "none"
                  },
                  children: /* @__PURE__ */ jsx("div", { ref: headerRangeRef, children: /* @__PURE__ */ jsx(
                    "div",
                    {
                      ref: headerRef,
                      "data-header-sticky": headerSticky || void 0,
                      "data-header-stuck": headerStuck || void 0,
                      "data-header-outside-viewport": headerOutsideViewport || void 0,
                      className: `
                top-0 flex h-[var(--gds-header-height)] flex-col justify-center border-b border-transparent transition pointer-events-auto
                data-[header-outside-viewport]:invisible
                data-[header-sticky]:sticky
                data-[header-stuck]:border-white/8
                data-[header-stuck]:bg-midnight/88
                data-[header-stuck]:backdrop-blur-2xl
              `,
                      children: container ? /* @__PURE__ */ jsx(Container, { className: "static", children: header }) : /* @__PURE__ */ jsx("div", { className: "static", children: header })
                    }
                  ) })
                }
              ),
              /* @__PURE__ */ jsx(
                "main",
                {
                  className: "gds-layout-main static",
                  style: {
                    gridArea: "main",
                    /**
                     * Give the main area a minimum height just in case there's almost no content, notably to ensure the footer never overlaps
                     * the header if `footerOverlay` is set.
                     */
                    minHeight: "256px"
                  },
                  children: container ? /* @__PURE__ */ jsx(Container, { className: "static", children }) : children
                }
              ),
              /* @__PURE__ */ jsx(
                "footer",
                {
                  className: "gds-layout-footer",
                  style: {
                    gridArea: "footer",
                    zIndex: 100,
                    position: footerOverlay ? "absolute" : "relative",
                    left: 0,
                    right: 0,
                    bottom: 0
                  },
                  children: container ? /* @__PURE__ */ jsx(Container, { className: "static", children: footer }) : footer
                }
              )
            ]
          }
        )
      ]
    }
  );
};
function getDistanceFromViewportTop(element) {
  let currentElement = element;
  let distance = 0;
  while (currentElement) {
    distance += currentElement.offsetTop;
    currentElement = currentElement.offsetParent;
  }
  return distance - window.scrollY;
}
function Container({ className, children, ...props }) {
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: classNames([
        `gds-container mx-auto w-[calc(var(--gds-container-max-width)+2*var(--gds-container-padding))] max-w-[100vw] px-[var(--gds-container-padding)]
        [--gds-container-max-width:var(--max-width)]
        [--gds-container-padding:var(--padding-mobile)]
        *:[--gds-container-max-width-parent:var(--max-width)]
        *:[--gds-container-padding-parent:var(--padding-mobile)]
        md:[--gds-container-padding:var(--padding-desktop)]
        md:*:[--gds-container-padding-parent:var(--padding-desktop)]`,
        className
      ]),
      style: {
        "--max-width": `${CONTAINER_MAX_WIDTH_DEFAULT}px`,
        "--padding-mobile": `${CONTAINER_PADDING_MOBILE}px`,
        "--padding-desktop": `${CONTAINER_PADDING_DESKTOP}px`
      },
      ...props,
      children
    }
  );
}
export {
  Layout
};
