"use strict";
"use client";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var Image_exports = {};
__export(Image_exports, {
  default: () => Image_default
});
module.exports = __toCommonJS(Image_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_controls = require("@makeswift/controls");
var import_placeholders = require("../../utils/placeholders");
var import_Link = require("../../shared/Link");
var import_css = require("@emotion/css");
var import_use_style = require("../../../runtimes/react/use-style");
var import_responsive_style = require("../../utils/responsive-style");
var import_makeswift_api = require("../../../runtimes/react/hooks/makeswift-api");
var import_use_breakpoints = require("../../../runtimes/react/hooks/use-breakpoints");
var import_use_framework_context = require("../../../runtimes/react/components/hooks/use-framework-context");
var import_ts_pattern = require("ts-pattern");
function loadImage(src) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = () => resolve(image);
    image.onerror = reject;
    image.src = src;
  });
}
function imageSizes(breakpoints, width) {
  const baseDevice = breakpoints.find((breakpoint) => breakpoint.maxWidth == null);
  const baseWidth = baseDevice && width && (0, import_controls.findBreakpointOverride)(breakpoints, width, baseDevice.id);
  const baseWidthSize = baseWidth == null || baseWidth.value.unit !== "px" ? "100vw" : `${baseWidth.value.value}px`;
  return breakpoints.map((breakpoint) => {
    const override = (0, import_controls.findBreakpointOverride)(breakpoints, width, breakpoint.id);
    if (override == null || breakpoint.maxWidth == null || override.value.unit !== "px") {
      return null;
    }
    return `(max-width: ${breakpoint.maxWidth}px) ${Math.min(
      breakpoint.maxWidth,
      override.value.value
    )}px`;
  }).filter((size) => size != null).reduce((sourceSizes, sourceSize) => `${sourceSize}, ${sourceSizes}`, baseWidthSize);
}
const ImageComponent = (0, import_react.forwardRef)(function Image2({
  id,
  width,
  margin,
  padding,
  file,
  border,
  borderRadius,
  altText,
  link,
  opacity,
  boxShadow,
  placeholder = import_placeholders.placeholders.image,
  className,
  priority
}, ref) {
  const fileId = (0, import_ts_pattern.match)(file).with(import_ts_pattern.P.string, (v) => v).with({ type: "makeswift-file", version: 1 }, (v) => v.id).otherwise(() => null);
  const fileData = (0, import_makeswift_api.useFile)(fileId);
  const imageSrc = (0, import_ts_pattern.match)([file, fileData]).with([import_ts_pattern.P.any, import_ts_pattern.P.not(import_ts_pattern.P.nullish)], ([, fileData2]) => fileData2.publicUrl).with([{ type: "external-file", version: 1 }, import_ts_pattern.P.any], ([file2]) => file2.url).otherwise(() => placeholder.src);
  const dataDimensions = (0, import_ts_pattern.match)([file, fileData, imageSrc]).with(
    [{ type: "external-file", version: 1, width: import_ts_pattern.P.number, height: import_ts_pattern.P.number }, import_ts_pattern.P.any, import_ts_pattern.P.any],
    ([externalFile]) => ({ width: externalFile.width, height: externalFile.height })
  ).with([import_ts_pattern.P.any, import_ts_pattern.P.not(import_ts_pattern.P.nullish), import_ts_pattern.P.any], ([, data]) => data.dimensions).with([import_ts_pattern.P.any, import_ts_pattern.P.any, placeholder.src], () => placeholder.dimensions).otherwise(() => null);
  const [measuredDimensions, setMeasuredDimensions] = (0, import_react.useState)(null);
  const breakpoints = (0, import_use_breakpoints.useBreakpoints)();
  (0, import_react.useEffect)(() => {
    if (dataDimensions)
      return;
    let cleanedUp = false;
    loadImage(imageSrc).then((image) => {
      if (!cleanedUp) {
        setMeasuredDimensions({ width: image.naturalWidth, height: image.naturalHeight });
      }
    }).catch(console.error);
    return () => {
      cleanedUp = true;
    };
  }, [dataDimensions, imageSrc]);
  const dimensions = dataDimensions ?? measuredDimensions;
  const Container = link ? import_Link.Link : "div";
  const containerClassName = (0, import_css.cx)(
    (0, import_use_style.useStyle)({ lineHeight: 0, overflow: "hidden" }),
    (0, import_use_style.useStyle)((0, import_responsive_style.useResponsiveWidth)(width, dimensions?.width)),
    (0, import_use_style.useStyle)((0, import_responsive_style.useResponsiveStyle)([opacity], ([opacity2 = 1]) => ({ opacity: opacity2 }))),
    margin,
    padding,
    border,
    borderRadius,
    boxShadow,
    className
  );
  const { Image: Image3 } = (0, import_use_framework_context.useFrameworkContext)();
  if (!dimensions)
    return null;
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Container, { link, ref, id, className: containerClassName, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    Image3,
    {
      src: imageSrc,
      priority,
      sizes: imageSizes(breakpoints, width),
      alt: altText ?? "",
      width: dimensions.width,
      height: dimensions.height,
      style: {
        width: "100%",
        height: "auto"
      }
    }
  ) });
});
var Image_default = ImageComponent;
//# sourceMappingURL=Image.js.map