/// <cts-enable />
import { computed, type Default, ifElse, NAME, pattern, UI } from "commontools";

type ImageInput = {
  url: Default<string, "">;
  caption: Default<string, "">;
};

type ImageOutput = {
  [NAME]: unknown;
  [UI]: unknown;
  url: string;
  caption: string;
};

export default pattern<ImageInput, ImageOutput>(({ url, caption }) => {
  const hasCaption = computed(() => !!caption);
  const displayName = computed(() => caption || "Image");

  return {
    [NAME]: displayName,
    [UI]: (
      <ct-screen>
        <ct-vstack gap="2" style={{ alignItems: "center" }}>
          <img
            src={url}
            alt={caption || "Image"}
            style={{
              maxWidth: "100%",
              width: "100%",
              height: "auto",
              borderRadius: "8px",
              objectFit: "contain",
            }}
          />
          {ifElse(
            hasCaption,
            <div
              style={{
                fontSize: "14px",
                color: "var(--ct-color-gray-500)",
                textAlign: "center",
                padding: "4px 0",
              }}
            >
              {caption}
            </div>,
            null,
          )}
        </ct-vstack>
      </ct-screen>
    ),
    url,
    caption,
  };
});
