import styles from './index.module.scss';
import cx from '../utils/classname.js';
import type { CSSVariables } from '../utils/types.js';
import { FlexProps } from './types.js';

const FlexComponent = ({
  as: Component = 'div',
  direction = 'row',
  wrap = 'nowrap',
  justifyContent = 'flex-start',
  alignItems = 'stretch',
  alignContent = 'stretch',
  gap,
  paddingInline,
  paddingBlock,
  marginInline,
  marginBlock,
  maxWidth,
  maxHeight,
  inline = false,
  className = '',
  style = {},
  children,
}: FlexProps) => {
  const defaultClasses = styles.flex;
  const combinedClasses = cx(defaultClasses, className);

  const customStyle: CSSVariables = {
    ...style,
    '--hscl-flex-direction': direction,
    '--hscl-flex-wrap': wrap,
    '--hscl-flex-justifyContent': justifyContent,
    '--hscl-flex-alignItems': alignItems,
    '--hscl-flex-alignContent': alignContent,
    '--hscl-flex-display': inline ? 'inline-flex' : 'flex',
  };

  const propertyMap: Record<string, string | undefined> = {
    '--hscl-flex-gap': gap,
    '--hscl-flex-maxWidth': maxWidth,
    '--hscl-flex-maxHeight': maxHeight,
    '--hscl-flex-paddingInline': paddingInline,
    '--hscl-flex-paddingBlock': paddingBlock,
    '--hscl-flex-marginInline': marginInline,
    '--hscl-flex-marginBlock': marginBlock,
  };

  Object.entries(propertyMap).forEach(([cssVar, value]) => {
    if (value) {
      customStyle[cssVar] = value;
    }
  });

  return (
    <Component className={combinedClasses} style={customStyle}>
      {children}
    </Component>
  );
};

const Flex = FlexComponent as typeof FlexComponent;

export default Flex;
