import plugin from 'tailwindcss/plugin'
import type { CSSRuleObject } from 'tailwindcss/types/config'
declare let module: any

/**
 * Avatar component for displaying user profile images with fallback support.
 *
 * Class Names:
 *
 *  btu-avatar - Base avatar styles
 *  btu-avatar-[xs|sm|md|lg|xl|xxl] - Size variants
 *  btu-avatar-fallback - Fallback text container
 *
 * Example Usages:
 *
 *  <btu-avatar class="btu-avatar btu-avatar-md">
 *    <div class="btu-avatar-fallback">JP</div>
 *    <img src="..." alt="..." />
 *  </btu-avatar>
 */

type AvatarSize = {
  size: string
  fontSize: 'xs' | 'sm' | 'base' | 'md' | 'lg' | 'xl'
  fontWeight?: 'medium' | 'bold'
}

const className = '.btu-avatar'

module.exports = plugin(function ({ addComponents, theme, e, matchUtilities }) {
  const avatarSizes = theme('avatar.size')
  const fontSizes: Record<string, CSSRuleObject> = theme('fontSize')

  // Custom color utilities for avatar background and ring
  matchUtilities(
    {
      'btu-avatar-background': value => ({
        '--avatar-bg-color': value,
      }),
    },
    { values: theme('colors'), type: ['color', 'any'] },
  )

  matchUtilities(
    {
      'btu-avatar-ring': value => ({
        '--avatar-ring-color': value,
      }),
    },
    { values: theme('colors'), type: ['color', 'any'] },
  )

  // Base avatar styles
  addComponents({
    [className]: {
      '--avatar-bg-color': 'oklch(var(--btu-theme-purple-600))',
      '--avatar-ring-width': '0px',
      display: 'grid',
      placeContent: 'center',
      alignItems: 'center',
      width: 'var(--avatar-size)',
      height: 'var(--avatar-size)',
      borderRadius: 'var(--avatar-corner-rounding, 9999px)',
      backgroundColor: 'var(--avatar-bg-color)',
      textAlign: 'center',
      fontWeight: '500',
      textTransform: 'uppercase',
      color: 'white',
      position: 'relative',
      flexShrink: '0',
      userSelect: 'none',

      // Grid stacking
      '& > *': {
        gridArea: '1 / 1',
      },

      // Hover effect - darken background
      '&:hover': {
        backgroundColor: 'oklch(from var(--avatar-bg-color) calc(l * 0.8) c h)',
      },

      // After pseudo-element for border overlay
      '&::after': {
        content: "''",
        position: 'absolute',
        inset: '0',
        borderRadius: '9999px',
        borderWidth: 'var(--avatar-ring-width, 0px)',
        borderColor: 'var(--avatar-ring-color, transparent)',
        borderStyle: 'solid',
        pointerEvents: 'none',
      },

      // Image styles
      '& img': {
        aspectRatio: '1',
        width: '100%',
        height: '100%',
        borderRadius: '9999px',
        objectFit: 'cover',
      },

      // Hide fallback when image is loaded (prevents showing through transparent images)
      '&.btu-avatar-image-loaded .btu-avatar-fallback': {
        display: 'none',
      },
    },

    // Fallback text container
    [`${className}-fallback`]: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      width: '100%',
      height: '100%',
    },

    // Avatar group styles
    [`${className}-group`]: {
      display: 'flex',
      alignItems: 'center',
    },

    // Overflow avatar ("+N" indicator)
    [`${className}-group-overflow`]: {
      fontWeight: '500',
      backgroundColor: 'oklch(var(--btu-theme-gray-100))',
      color: 'oklch(var(--btu-theme-gray-500))',

      '&:hover': {
        backgroundColor: 'oklch(var(--btu-theme-gray-100))',
      },
    },
  })

  // Size variants
  if (avatarSizes && fontSizes) {
    const sizeVariants: AvatarSize[] = [
      { size: avatarSizes.xs, fontSize: 'xs', fontWeight: 'bold' },
      { size: avatarSizes.sm, fontSize: 'sm' },
      { size: avatarSizes.md, fontSize: 'base' },
      { size: avatarSizes.lg, fontSize: 'base' },
      { size: avatarSizes.xl, fontSize: 'lg' },
      { size: avatarSizes.xxl, fontSize: 'xl' },
    ]

    const sizeKeys = ['xs', 'sm', 'md', 'lg', 'xl', 'xxl']

    sizeKeys.forEach((key, index) => {
      const variant = sizeVariants[index]
      const fontSize = fontSizes[variant.fontSize]

      if (fontSize) {
        addComponents({
          [`${className}-${e(key)}`]: {
            '--avatar-size': variant.size,
            fontSize: fontSize[0],
            lineHeight: fontSize[1],
            ...(variant.fontWeight && { fontWeight: variant.fontWeight === 'bold' ? '700' : '500' }),
          },
        })
      }
    })
  }

  // Container query variants for responsive sizing
  if (avatarSizes) {
    const containerVariants: CSSRuleObject = {}

    Object.keys(avatarSizes).forEach(size => {
      containerVariants[`@container/avatar (min-width: ${avatarSizes[size]})`] = {
        [`${className}-${e(size)}`]: {
          '--avatar-size': avatarSizes[size],
        },
      }
    })

    addComponents(containerVariants)
  }
})
