/**
 * Stack Component - Lynx 版 MUI Stack
 * 一比一对应 MUI Stack
 * 
 * 用于管理子元素之间间距的 Flex 布局组件
 * 支持：
 * - direction: row, column, row-reverse, column-reverse
 * - spacing: 间距值
 * - divider: 分隔元素
 * - useFlexGap: 使用 CSS gap 属性
 */
import './Stack.css'

// =============================================
// Stack 类型定义
// =============================================
export type StackDirection = 'row' | 'column' | 'row-reverse' | 'column-reverse'

export interface StackProps {
  /** 子元素 */
  children?: any
  /** 自定义类名 */
  className?: string
  /** 内联样式 */
  style?: Record<string, any>
  /** 排列方向 */
  direction?: StackDirection
  /** 间距 */
  spacing?: number | string
  /** 分隔元素 */
  divider?: any
  /** 是否使用 flex gap */
  useFlexGap?: boolean
  /** 对齐方式 */
  alignItems?: 'flex-start' | 'flex-end' | 'center' | 'stretch' | 'baseline'
  /** 主轴对齐 */
  justifyContent?: 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'space-evenly'
  /** 是否换行 */
  flexWrap?: 'nowrap' | 'wrap' | 'wrap-reverse'
  /** sx 属性 */
  sx?: Record<string, any>
}

// =============================================
// Stack 类名
// =============================================
export const stackClasses = {
  root: 'MuiStack-root',
}

// =============================================
// 间距单位
// =============================================
const spacingUnit = 8

// =============================================
// Stack 组件实现
// =============================================
export function Stack(props: StackProps) {
  const {
    children,
    className,
    style,
    direction = 'column',
    spacing = 0,
    divider,
    useFlexGap = true,
    alignItems,
    justifyContent,
    flexWrap,
    sx,
    ...other
  } = props

  // 计算间距值
  const spacingValue = typeof spacing === 'number' 
    ? `${spacing * spacingUnit}px` 
    : spacing

  // 构建类名
  const classes = [
    stackClasses.root,
    `MuiStack-direction-${direction}`,
    className,
  ].filter(Boolean).join(' ')

  // 计算样式
  const computedStyle: Record<string, any> = {
    display: 'flex',
    flexDirection: direction,
    ...(useFlexGap && spacing && { gap: spacingValue }),
    ...(alignItems && { alignItems }),
    ...(justifyContent && { justifyContent }),
    ...(flexWrap && { flexWrap }),
    ...sx,
    ...style,
  }

  // 如果有 divider，需要在子元素之间插入分隔符
  if (divider && Array.isArray(children)) {
    const childrenWithDivider: any[] = []
    children.forEach((child: any, index: number) => {
      if (index > 0) {
        childrenWithDivider.push(
          <view key={`divider-${index}`} className="MuiStack-divider">
            {divider}
          </view>
        )
      }
      childrenWithDivider.push(child)
    })
    return (
      <view className={classes} style={computedStyle} {...other}>
        {childrenWithDivider}
      </view>
    )
  }

  return (
    <view className={classes} style={computedStyle} {...other}>
      {children}
    </view>
  )
}

export default Stack
