import type { CSSProperties } from 'react';

import Image from '~/src/components/Image';
import { scaleToWidth } from './utils';

interface InlineImageSectionViewProps {
  src: string;
  srcWidth?: number;
  srcHeight?: number;
  altText?: string;
  scale?: number;
  /** Vertical spacing — horizontal margins are always `auto` to keep it centered. */
  marginTop?: string;
  marginBottom?: string;
  testId?: string;
}

/**
 * Renders an inline image scaled to a fraction of its container width and
 * horizontally centered. Shared by the published page and the edit canvas so
 * both stay in sync; the scale is intentionally not applied in the settings
 * modal preview.
 */
export const InlineImageSectionView = ({
  src,
  srcWidth,
  srcHeight,
  altText,
  scale,
  marginTop,
  marginBottom,
  testId,
}: InlineImageSectionViewProps) => {
  const wrapperStyle: CSSProperties = {
    width: scaleToWidth(scale),
    marginLeft: 'auto',
    marginRight: 'auto',
    marginTop,
    marginBottom,
  };

  return (
    <div data-testid="inlineImageScaleWrapper" style={wrapperStyle}>
      <Image
        testId={testId}
        src={src}
        size={srcWidth && srcHeight ? [srcWidth, srcHeight] : undefined}
        alt={altText}
      />
    </div>
  );
};
