import classNames from "classnames";
import React, { useContext } from "react";
import { getNormalizedColSpans } from "./../../../../../ricos-common-plugins/layout/get-normalized-col-spans.js";
import {
  getResolvedLayoutFillColor,
  getResolvedLayoutFillGradient
} from "./../../../../../ricos-common-plugins/layout/layout-fill.js";
import {
  LAYOUT_DEFAULTS,
  normalizePadding
} from "./../../../../../ricos-common-plugins/layout/shared-with-viewer.js";
import { RicosContext, RicosNodeContextProvider } from "./../../../../../ricos-context/index.js";
import { resolveBackwardCompatOverlay } from "./../../../../../_shared/resolve-backward-compat-overlay.js";
import { resolveCssColor } from "./../../../../../_shared/resolve-css-color.js";
import { schemaGradientToCss } from "./../../../../../_shared/schema-gradient-to-css.js";
import { getImageSrc } from "./../../../../../wix-rich-content-common/lib/image-utils.js";
import { LayoutBackgroundLoader } from "./../../../../../ui-components/layout-background-loader/layout-background-loader.js";
import styles from "./layout-scss.js";
const PROMPT_URL_PREFIX = "prompt://";
const isGeneratingImage = (media) => {
  const src = media?.src?.id ?? media?.src?.url ?? "";
  return typeof src === "string" && src.startsWith(PROMPT_URL_PREFIX);
};
const getGridTemplateColumnsTemplate = (node) => {
  const cols = [];
  node.nodes.forEach((cell) => {
    if (cell.type === "LAYOUT_CELL") {
      cols.push(cell.layoutCellData?.colSpan ?? 0);
    }
  });
  return getNormalizedColSpans(cols).map((col) => `minmax(0, ${col}fr)`).join(" ");
};
const getStyleContent = (node) => {
  const responsivenessBehaviour = {
    STACK: "stack",
    WRAP: "wrap"
  }[node.layoutData?.responsivenessBehaviour ?? LAYOUT_DEFAULTS.responsivenessBehaviour];
  const responsivenessBreakpoint = node.layoutData?.responsivenessBreakpoint && !isNaN(node.layoutData?.responsivenessBreakpoint) ? node.layoutData?.responsivenessBreakpoint : LAYOUT_DEFAULTS.responsivenessBreakpoint;
  const scopeValue = encodeURIComponent(
    `layout-${node.id}-${responsivenessBreakpoint}-${responsivenessBehaviour}`
  );
  const isWrapping = responsivenessBehaviour === "wrap";
  const styleContent = `
    [data-layout-scope=${scopeValue}].${styles.layout} {
      --ricos-internal-layout-display: ${isWrapping ? "flex" : "grid"};
      --ricos-internal-layout-justify-content: ${isWrapping ? "center" : "auto"};
      --ricos-internal-layout-grid-template: grid-template-columns: minmax(0, 1fr);
      --ricos-internal-layout-cell-min-width: ${isWrapping ? `${Math.floor(responsivenessBreakpoint / node.nodes.length)}px` : "100%"};
      --ricos-internal-layout-cell-height: ${isWrapping ? "auto" : "100%"};
    }
  `;
  return {
    scopeValue,
    content: `
@supports not (contain: inline-size) {
  @media only screen and (max-width: ${responsivenessBreakpoint}px) {
    ${styleContent}
  }
}

@container (max-width: ${responsivenessBreakpoint}px) {
  ${styleContent}
}
`
  };
};
const Layout = ({ node, nodeIndex, RicosNodesRenderer }) => {
  const { isMobile } = useContext(RicosContext);
  const layoutData = node.type === "LAYOUT" ? node.layoutData : void 0;
  const backgroundMedia = layoutData?.backgroundImage?.media;
  const backdropMedia = layoutData?.backdropImage?.media;
  const isGeneratingBackground = isGeneratingImage(backgroundMedia);
  const isGeneratingBackdrop = isGeneratingImage(backdropMedia);
  const backgroundImageUrl = !isGeneratingBackground && (backgroundMedia?.src?.url ?? (backgroundMedia?.src?.id && getImageSrc({ file_name: backgroundMedia.src.id }, void 0, {
    requiredQuality: 100,
    requiredWidth: Math.min(backgroundMedia?.width ?? 4e3, 4e3),
    requiredHeight: Math.min(backgroundMedia?.height ?? 4e3, 4e3)
  })));
  const backdropImageUrl = !isGeneratingBackdrop && (backdropMedia?.src?.url ?? (backdropMedia?.src?.id && getImageSrc({ file_name: backdropMedia.src.id }, void 0, {
    requiredQuality: 100,
    requiredWidth: Math.min(backdropMedia?.width ?? 4e3, 4e3),
    requiredHeight: Math.min(backdropMedia?.height ?? 4e3, 4e3)
  })));
  const shouldShowLoader = isGeneratingBackground || isGeneratingBackdrop;
  const style = React.useMemo(() => {
    if (node.type !== "LAYOUT") {
      return {};
    }
    const layoutData2 = node.layoutData;
    const cellPadding = normalizePadding(layoutData2?.cellPadding, [...LAYOUT_DEFAULTS.cellPadding]);
    const cellVerticalAlignment = layoutData2?.cellVerticalAlignment ?? LAYOUT_DEFAULTS.cellVerticalAlignment;
    const borderColor = layoutData2?.borderColor ?? LAYOUT_DEFAULTS.borderColor;
    const borderWidth = layoutData2?.borderWidth ?? LAYOUT_DEFAULTS.borderWidth;
    return {
      ...layoutData2?.containerData?.width?.custom ? {
        "--ricos-internal-layout-width": `${layoutData2.containerData.width.custom}px`
      } : {},
      ...(() => {
        const backgroundGradient = getResolvedLayoutFillGradient(
          layoutData2?.background,
          layoutData2?.backgroundColor
        );
        const bgColor = getResolvedLayoutFillColor(
          layoutData2?.background,
          layoutData2?.backgroundColor
        );
        const baseVars = backgroundGradient ? {
          "--ricos-internal-layout-background-gradient": schemaGradientToCss(
            backgroundGradient
          )
        } : bgColor ? { "--ricos-internal-layout-background-color": resolveCssColor(bgColor) } : {};
        const imageVars = layoutData2?.backgroundImage ? {
          "--ricos-internal-layout-background-image-src": `url(${backgroundImageUrl})`,
          ...layoutData2.backgroundImage.scaling ? {
            "--ricos-internal-layout-background-image-scaling": layoutData2.backgroundImage.scaling.toLowerCase()
          } : {},
          ...layoutData2.backgroundImage.position ? {
            "--ricos-internal-layout-background-image-position": layoutData2.backgroundImage.position.toLowerCase().split("_").join(" ")
          } : {},
          // Overlay: only set when image exists, uses same color/gradient as base
          ...backgroundGradient ? {
            "--ricos-internal-layout-background-overlay": schemaGradientToCss(
              backgroundGradient
            )
          } : bgColor ? {
            "--ricos-internal-layout-background-overlay": resolveBackwardCompatOverlay(
              bgColor,
              layoutData2?.backgroundImage?.opacity ?? 100,
              100
            )
          } : {},
          // Blur is independent of the color overlay — both layers stack.
          ...layoutData2.backgroundImage.blur ? {
            "--ricos-internal-layout-background-image-blur": `blur(${layoutData2.backgroundImage.blur}px)`
          } : {}
        } : {};
        return { ...baseVars, ...imageVars };
      })(),
      ...layoutData2?.backgroundImage ? {
        "--ricos-internal-layout-background-image-src": `url(${backgroundImageUrl})`,
        ...layoutData2.backgroundImage.opacity ? {
          "--ricos-internal-layout-background-image-opacity": `${layoutData2.backgroundImage.opacity}%`
        } : {},
        ...layoutData2.backgroundImage.scaling ? {
          "--ricos-internal-layout-background-image-scaling": layoutData2.backgroundImage.scaling.toLowerCase()
        } : {},
        ...layoutData2.backgroundImage.position ? {
          "--ricos-internal-layout-background-image-position": layoutData2.backgroundImage.position.toLowerCase().split("_").join(" ")
        } : {}
      } : {},
      ...borderColor ? {
        "--ricos-internal-layout-border-color": resolveCssColor(borderColor),
        "--ricos-internal-layout-border-width": `${borderWidth}px`
      } : {},
      ...layoutData2?.borderRadius ? {
        "--ricos-internal-layout-border-radius": `${layoutData2.borderRadius}px`
      } : {},
      ...(() => {
        const backdropGradient = getResolvedLayoutFillGradient(
          layoutData2?.backdrop,
          layoutData2?.backdropColor
        );
        const bdColor = getResolvedLayoutFillColor(layoutData2?.backdrop, layoutData2?.backdropColor);
        const baseVars = backdropGradient ? {
          "--ricos-internal-layout-backdrop-gradient": schemaGradientToCss(
            backdropGradient
          )
        } : bdColor ? { "--ricos-internal-layout-backdrop-color": resolveCssColor(bdColor) } : {};
        const imageVars = layoutData2?.backdropImage ? {
          "--ricos-internal-layout-backdrop-image-src": `url(${backdropImageUrl})`,
          ...layoutData2.backdropImage.scaling ? {
            "--ricos-internal-layout-backdrop-image-scaling": layoutData2.backdropImage.scaling.toLowerCase()
          } : {},
          ...layoutData2.backdropImage.position ? {
            "--ricos-internal-layout-backdrop-image-position": layoutData2.backdropImage.position.toLowerCase().split("_").join(" ")
          } : {},
          // Overlay: only set when image exists, uses same color/gradient as base
          ...backdropGradient ? {
            "--ricos-internal-layout-backdrop-overlay": schemaGradientToCss(
              backdropGradient
            )
          } : bdColor ? {
            "--ricos-internal-layout-backdrop-overlay": resolveBackwardCompatOverlay(
              bdColor,
              layoutData2?.backdropImage?.opacity ?? 100,
              100
            )
          } : {},
          // Blur is independent of the color overlay — both layers stack.
          ...layoutData2.backdropImage.blur ? {
            "--ricos-internal-layout-backdrop-image-blur": `blur(${layoutData2.backdropImage.blur}px)`
          } : {}
        } : {};
        return { ...baseVars, ...imageVars };
      })(),
      ...typeof layoutData2?.gap === "number" ? {
        "--ricos-internal-layout-gap": `${layoutData2.gap}px`
      } : {},
      ...layoutData2?.backdropPaddingTop && layoutData2.backdropPaddingTop > 0 ? {
        "--ricos-internal-layout-backdrop-padding-top": `${layoutData2.backdropPaddingTop}px`
      } : {},
      ...layoutData2?.backdropPaddingBottom && layoutData2.backdropPaddingBottom > 0 ? {
        "--ricos-internal-layout-backdrop-padding-bottom": `${layoutData2.backdropPaddingBottom}px`
      } : {},
      ...cellPadding && cellPadding.length > 0 ? {
        "--ricos-internal-layout-cell-padding-top": `${cellPadding[0]}px`,
        "--ricos-internal-layout-cell-padding-right": `${cellPadding[1] ?? cellPadding[0]}px`,
        "--ricos-internal-layout-cell-padding-bottom": `${cellPadding[2] ?? cellPadding[0]}px`,
        "--ricos-internal-layout-cell-padding-left": `${cellPadding[3] ?? cellPadding[1] ?? cellPadding[0]}px`
      } : {},
      ...cellVerticalAlignment ? {
        "--ricos-internal-layout-cell-vertical-alignment": cellVerticalAlignment === "TOP" ? "flex-start" : cellVerticalAlignment === "BOTTOM" ? "flex-end" : "center"
      } : {}
    };
  }, [node, backgroundImageUrl, backdropImageUrl]);
  const styleContent = React.useMemo(() => getStyleContent(node), [node]);
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: styles.layoutWrapper,
      style,
      ...node.layoutData?.banner ? {
        "data-layout-banner": node.layoutData.banner.position === "TOP" ? "top" : "bottom"
      } : {}
    },
    shouldShowLoader && /* @__PURE__ */ React.createElement(
      LayoutBackgroundLoader,
      {
        backgroundColor: resolveCssColor(
          layoutData?.backdropColor ?? layoutData?.backgroundColor ?? void 0
        )
      }
    ),
    /* @__PURE__ */ React.createElement("style", { "data-layout-style": node.id }, styleContent.content),
    /* @__PURE__ */ React.createElement("div", { "data-breakout": "normal" }, /* @__PURE__ */ React.createElement(
      "div",
      {
        "data-layout-scope": styleContent.scopeValue,
        className: classNames(styles.layout, {
          [styles.mobile]: isMobile,
          [styles.designOnLayout]: !node.layoutData?.designTarget || node.layoutData?.designTarget === "LAYOUT",
          [styles.designOnCell]: node.layoutData?.designTarget === "CELL"
        }),
        style: {
          "--ricos-internal-layout-column-template": getGridTemplateColumnsTemplate(node)
        }
      },
      /* @__PURE__ */ React.createElement(RicosNodeContextProvider, { parentNode: node, parentIndex: nodeIndex }, /* @__PURE__ */ React.createElement(RicosNodesRenderer, { key: `children-${node.id}`, nodes: node.nodes ?? [] }))
    ))
  );
};
const LayoutRenderer = ({ node, ...props }) => {
  return /* @__PURE__ */ React.createElement(Layout, { key: node.id, node, ...props });
};
export {
  Layout,
  LayoutRenderer
};
//# sourceMappingURL=layout.js.map
