import styles from './index.module.scss';
import cx from '../utils/classname.js';
import type { CSSVariables } from '../utils/types.js';
import { DividerOrientation, DividerProps } from './types.js';
import StyleFields from './StyleFields.js';

const getAlignmentCSSVar = (
  alignment: DividerProps['alignment'],
  orientation: DividerOrientation
): string => {
  if (!alignment) return 'stretch';

  if (orientation === 'horizontal') {
    switch (alignment.horizontal_align) {
      case 'LEFT':
        return 'flex-start';
      case 'CENTER':
        return 'center';
      case 'RIGHT':
        return 'flex-end';
    }
  } else {
    switch (alignment.vertical_align) {
      case 'TOP':
        return 'flex-start';
      case 'MIDDLE':
        return 'center';
      case 'BOTTOM':
        return 'flex-end';
    }
  }

  return 'stretch';
};

const DividerComponent = ({
  orientation = 'horizontal',
  alignment,
  spacing,
  borderStyle = 'solid',
  length = 100,
  thickness = 1,
  color,
  className = '',
  style = {},
}: DividerProps) => {
  const orientationClass =
    orientation === 'horizontal' ? styles.horizontal : styles.vertical;

  const defaultClasses = cx(styles.divider, orientationClass);
  const combinedClasses = cx(defaultClasses, className);

  const cssVariables: CSSVariables = {
    '--hscl-divider-alignment': getAlignmentCSSVar(alignment, orientation),
    '--hscl-divider-borderStyle': borderStyle,
    '--hscl-divider-borderColor': color?.rgba ?? color?.color,
    [`--hscl-divider-margin${
      orientation === 'horizontal' ? 'Block' : 'Inline'
    }`]: spacing,
    [`--hscl-divider-${
      orientation === 'horizontal' ? 'width' : 'height'
    }`]: `${length}%`,
    '--hscl-divider-borderWidth': `${thickness}px`,
    ...style,
  };

  const sharedProps = {
    className: combinedClasses,
    style: cssVariables,
  };

  if (orientation === 'horizontal') {
    return <hr {...sharedProps} />;
  }

  return <div {...sharedProps} role="separator" />;
};

// Create compound component with proper typing
type DividerComponentType = typeof DividerComponent & {
  StyleFields: typeof StyleFields;
};

const Divider = DividerComponent as DividerComponentType;
Divider.StyleFields = StyleFields;

export default Divider;
