import { useMemo } from 'react';
import { useBrandSettings } from '@hubspot/cms-components';
import { dummyLogoData } from './_dummyLogoData.js';
import { LogoData, LogoProps } from './types.js';
import styles from './index.module.scss';
import cx from '../utils/classname.js';
import Link from '../Link/index.js';
import Image from '../Image/index.js';
import type { CSSVariables } from '../utils/types.js';

export const Logo = ({
  useDummyLogo = false,
  className = '',
  style = {},
  loading = 'eager',
  maxWidth,
  maxHeight,
}: LogoProps) => {
  const { primaryLogo } = useBrandSettings() ?? {};

  const logo: LogoData | undefined = useMemo(() => {
    return useDummyLogo ? dummyLogoData.logo : primaryLogo;
  }, [useDummyLogo, primaryLogo]);

  if (!logo?.src) {
    return null;
  }

  const hasOnlyMaxHeight = maxHeight && !maxWidth;

  const defaultClasses = styles.logo;
  const combinedClasses = cx(defaultClasses, className);
  const imageClasses = styles.logoImage;

  const wrapperStyle: CSSVariables = {
    ...(maxWidth && { '--hscl-logo-maxWidth': maxWidth }),
    ...(maxHeight && { '--hscl-logo-maxHeight': maxHeight }),
    ...(hasOnlyMaxHeight && { '--hscl-logo-maxWidth': 'fit-content' }),
    ...style,
  };

  const imageStyle: CSSVariables = {
    ...(hasOnlyMaxHeight && {
      inlineSize: 'auto',
      blockSize: 'auto',
    }),
  };

  const content = (
    <Image
      src={logo.src}
      alt={logo.alt ?? 'Logo'}
      loading={loading}
      width={logo.width}
      height={logo.height}
      className={imageClasses}
      style={imageStyle}
      responsive={true}
    />
  );

  return logo.link ? (
    <Link href={logo.link} className={combinedClasses} style={wrapperStyle}>
      {content}
    </Link>
  ) : (
    <div className={combinedClasses} style={wrapperStyle}>
      {content}
    </div>
  );
};

export default Logo;
