"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { ChevronsLeft, ChevronsRight } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
import { Button } from "../../primitives/button.js";
import { IconButton } from "../../primitives/icon-button.js";
import { useZoneCollapse } from "./useZoneCollapse.js";
const SIDE_BY_SIDE_MIN_WIDTH = 1280;
function subscribeViewport(callback) {
  const mediaQuery = window.matchMedia("(min-width: 1024px)");
  mediaQuery.addEventListener("change", callback);
  return () => mediaQuery.removeEventListener("change", callback);
}
function getViewportSnapshot() {
  return window.matchMedia("(min-width: 1024px)").matches;
}
function getViewportServerSnapshot() {
  return false;
}
function CollapsibleZoneLayout({
  zone1,
  zone2,
  entityName,
  pageType,
  zone1DefaultWidth,
  errorCount = 0,
  isDirty = false,
  sections
}) {
  const t = useT();
  const { collapsed, setCollapsed, isHydrated } = useZoneCollapse(pageType);
  const canCollapse = React.useSyncExternalStore(
    subscribeViewport,
    getViewportSnapshot,
    getViewportServerSnapshot
  );
  const layoutRef = React.useRef(null);
  const expandButtonRef = React.useRef(null);
  const [containerWidth, setContainerWidth] = React.useState(() => typeof window === "undefined" ? 0 : window.innerWidth);
  const [expandedWhileConstrained, setExpandedWhileConstrained] = React.useState(false);
  React.useEffect(() => {
    const node = layoutRef.current;
    if (!node) return;
    const updateWidth = (nextWidth) => {
      setContainerWidth((prev) => Math.abs(prev - nextWidth) < 1 ? prev : nextWidth);
    };
    const measure = () => {
      updateWidth(node.getBoundingClientRect().width || window.innerWidth);
    };
    measure();
    if (typeof ResizeObserver === "undefined") {
      window.addEventListener("resize", measure);
      return () => window.removeEventListener("resize", measure);
    }
    const observer = new ResizeObserver((entries) => {
      const entry = entries[0];
      if (!entry) return;
      updateWidth(entry.contentRect.width);
    });
    observer.observe(node);
    return () => observer.disconnect();
  }, []);
  const canShowSideBySide = containerWidth >= SIDE_BY_SIDE_MIN_WIDTH;
  React.useEffect(() => {
    if (canShowSideBySide) {
      setExpandedWhileConstrained(false);
    }
  }, [canShowSideBySide]);
  const showCollapsedRail = canCollapse && (collapsed || !canShowSideBySide && !expandedWhileConstrained);
  const showStackedExpanded = !showCollapsedRail && !canShowSideBySide;
  const layoutMode = showCollapsedRail ? "collapsed" : showStackedExpanded ? "stacked" : "side-by-side";
  const zone1SideBySideStyle = zone1DefaultWidth ? { width: zone1DefaultWidth, flexBasis: zone1DefaultWidth } : void 0;
  const handleExpand = React.useCallback(() => {
    if (!canCollapse) return;
    setCollapsed(false);
    setExpandedWhileConstrained(!canShowSideBySide);
  }, [canCollapse, canShowSideBySide, setCollapsed]);
  const handleSectionActivate = React.useCallback((section) => {
    if (!canCollapse) return;
    setCollapsed(false);
    setExpandedWhileConstrained(!canShowSideBySide);
    requestAnimationFrame(() => {
      const target = document.getElementById(section.targetId ?? `collapsible-group-wrapper-${section.id}`) ?? document.getElementById(`collapsible-group-${section.id}`);
      if (!target) return;
      const headingButton = target.querySelector("button[aria-controls]");
      if (headingButton?.getAttribute("aria-expanded") === "false") {
        headingButton.click();
      }
      target.scrollIntoView({ behavior: "smooth", block: "start" });
      requestAnimationFrame(() => {
        const focusables = Array.from(
          target.querySelectorAll(
            'input:not([type="hidden"]), textarea, select, [contenteditable="true"]'
          )
        );
        const firstInput = focusables.find((el) => {
          if (el.hasAttribute("disabled") || el.getAttribute("aria-hidden") === "true") return false;
          if (el instanceof HTMLInputElement && el.readOnly) return false;
          return true;
        });
        if (firstInput) {
          firstInput.focus({ preventScroll: true });
          return;
        }
        headingButton?.focus({ preventScroll: true });
      });
    });
  }, [canCollapse, canShowSideBySide, setCollapsed]);
  const handleCollapse = React.useCallback(() => {
    if (!canCollapse) return;
    setExpandedWhileConstrained(false);
    setCollapsed(true);
    requestAnimationFrame(() => {
      expandButtonRef.current?.focus();
    });
  }, [canCollapse, setCollapsed]);
  return /* @__PURE__ */ jsx(
    "div",
    {
      ref: layoutRef,
      "data-zone-layout-mode": layoutMode,
      "data-persistence-hydrated": isHydrated ? "true" : "false",
      "aria-hidden": isHydrated ? void 0 : true,
      className: cn(
        "flex gap-4",
        !isHydrated && "invisible",
        showStackedExpanded ? "flex-col" : "flex-col lg:flex-row"
      ),
      children: showCollapsedRail ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs("div", { className: "hidden lg:flex shrink-0 flex-col items-center gap-3", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              ref: expandButtonRef,
              type: "button",
              variant: "default",
              size: "sm",
              onClick: handleExpand,
              className: "h-auto rounded-[10px] px-1.5 py-2 shadow-sm",
              "aria-label": t("ui.zone.expand", "Expand form panel"),
              children: /* @__PURE__ */ jsx(ChevronsRight, { className: "size-4" })
            }
          ),
          sections?.length ? /* @__PURE__ */ jsx("div", { className: "flex flex-col items-center gap-2 rounded-[14px] border border-border/70 bg-card px-2 py-3", children: sections.map((section) => {
            const SectionIcon = section.icon;
            const hasErrors = Boolean(section.errorCount && section.errorCount > 0);
            return /* @__PURE__ */ jsxs(
              IconButton,
              {
                type: "button",
                variant: "ghost",
                size: "default",
                onClick: () => handleSectionActivate(section),
                className: "relative size-9 rounded-[10px] border border-transparent bg-muted/70 text-muted-foreground hover:border-border hover:bg-accent hover:text-accent-foreground",
                title: section.label,
                "aria-label": section.ariaLabel ?? section.label,
                children: [
                  /* @__PURE__ */ jsx(SectionIcon, { className: "size-4" }),
                  hasErrors ? /* @__PURE__ */ jsx("span", { className: "absolute right-1.5 top-1.5 size-1.5 rounded-full bg-destructive" }) : null
                ]
              },
              section.id
            );
          }) }) : null
        ] }),
        /* @__PURE__ */ jsx("div", { className: "min-w-0 flex-1", children: zone2 })
      ] }) : showStackedExpanded ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs("div", { className: "w-full space-y-2", children: [
          canCollapse ? /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              onClick: handleCollapse,
              className: "h-auto rounded-[6px] border bg-card px-1.5 py-2",
              "aria-label": t("ui.zone.collapse", "Collapse form panel"),
              children: /* @__PURE__ */ jsx(ChevronsLeft, { className: "size-4" })
            }
          ) }) : null,
          /* @__PURE__ */ jsx("div", { className: "w-full", children: zone1 })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "min-w-0 w-full", children: zone2 })
      ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          "div",
          {
            className: cn("w-full lg:shrink-0", zone1DefaultWidth ? void 0 : "lg:w-[40%]"),
            style: zone1SideBySideStyle,
            children: zone1
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "hidden lg:flex relative shrink-0 w-8 items-start justify-center pt-4", children: [
          /* @__PURE__ */ jsx("div", { className: "absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-border" }),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              onClick: handleCollapse,
              className: "relative z-10 h-auto rounded-[6px] border bg-card px-1.5 py-2",
              "aria-label": t("ui.zone.collapse", "Collapse form panel"),
              children: /* @__PURE__ */ jsx(ChevronsLeft, { className: "size-4" })
            }
          )
        ] }),
        /* @__PURE__ */ jsx("div", { className: "min-w-0 w-full lg:flex-1", children: zone2 })
      ] })
    }
  );
}
export {
  CollapsibleZoneLayout
};
//# sourceMappingURL=CollapsibleZoneLayout.js.map
