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

const getAlignmentCSSVar = (alignment: DividerAlignment) => {
  switch (alignment) {
    case 'start':
      return `flex-${alignment}`;
    case 'end':
      return `flex-${alignment}`;
    case 'center':
      return alignment;
    default:
      return 'stretch';
  }
};

const DividerComponent = ({
  orientation = 'horizontal',
  alignment = 'stretch',
  spacing,
  borderStyle = 'solid',
  length = 100,
  thickness = 1,
  variant = 'primary', // !todo: not used atm but keeping for when we need to add variant system.
  className = '',
  style = {},
}: DividerProps) => {
  const variantClass = styles[`hscl-divider-${variant}`];
  const orientationClass =
    orientation === 'horizontal' ? styles.horizontal : styles.vertical;

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

  const cssVariables: CSSVariables = {
    '--hscl-divider-alignment': getAlignmentCSSVar(alignment),
    '--hscl-divider-borderStyle': borderStyle,
    [`--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 & {
  ContentFields: typeof ContentFields;
  StyleFields: typeof StyleFields;
};

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

export default Divider;
