import styles from './Skeleton.module.css'

interface SkeletonProps {
  variant?: 'text' | 'circular' | 'rectangular'
  width?: string | number
  height?: string | number
  lines?: number
  className?: string
}

function normalizeSize(value: string | number | undefined): string | undefined {
  if (value === undefined) return undefined
  return typeof value === 'number' ? `${value}px` : value
}

export function Skeleton({
  variant = 'rectangular',
  width,
  height,
  lines,
  className,
}: SkeletonProps) {
  const w = normalizeSize(width)
  const h = normalizeSize(height)

  if (variant === 'text') {
    const lineCount = lines && lines > 1 ? lines : 1
    if (lineCount === 1) {
      return (
        <div
          className={[styles.skeleton, styles.text, styles.shimmer, className ?? ''].filter(Boolean).join(' ')}
          style={{ width: w, height: h }}
          aria-hidden="true"
        />
      )
    }
    return (
      <div className={[styles.textGroup, className ?? ''].filter(Boolean).join(' ')} aria-hidden="true">
        {Array.from({ length: lineCount }, (_, i) => (
          <div
            key={i}
            className={[styles.skeleton, styles.text, styles.shimmer].join(' ')}
            style={{
              width: i === lineCount - 1 ? '70%' : (w ?? '100%'),
              height: h,
            }}
          />
        ))}
      </div>
    )
  }

  if (variant === 'circular') {
    return (
      <div
        className={[styles.skeleton, styles.circular, styles.shimmer, className ?? ''].filter(Boolean).join(' ')}
        style={{ width: w ?? '40px', height: h ?? '40px' }}
        aria-hidden="true"
      />
    )
  }

  // rectangular (default)
  return (
    <div
      className={[styles.skeleton, styles.rectangular, styles.shimmer, className ?? ''].filter(Boolean).join(' ')}
      style={{ width: w ?? '100%', height: h ?? '80px' }}
      aria-hidden="true"
    />
  )
}
