import plugin from 'tailwindcss/plugin'
declare let module: any

/**
 * Tailwind plugin that automatically adds more-contrast variants for ring utilities.
 *
 * This plugin adds global CSS rules that override ring colors and offsets in high-contrast mode.
 *
 * Behavior:
 * - Adds default focus-visible ring styles (4px primary-100 ring)
 * - Any ring color (ring-primary-100, etc.) → automatically maps to higher contrast (400 shade)
 * - Any ring-offset → automatically resets to 0px/transparent in high-contrast mode to prevent double rings
 *
 */
module.exports = plugin(function ({ addBase, theme, e }) {
  const baseStyles: Record<string, any> = {}

  // Add default focus-visible ring styles
  baseStyles[':focus-visible'] = {
    '--tw-ring-opacity': '1',
    '--tw-ring-color': 'oklch(var(--btu-theme-primary-100))',
    '--tw-ring-offset-shadow':
      'var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width, 0px) var(--tw-ring-offset-color, transparent)',
    '--tw-ring-shadow': 'var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width, 0px)) var(--tw-ring-color)',
    'box-shadow': 'var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 transparent)',
    outline: 'none',
  }

  const colors = theme('colors') as Record<string, any>

  // Build high-contrast ring color overrides (100 → 400 shade)
  // Only process primary, success, and error theme colors
  const allowedThemeColors = ['primary', 'success', 'error']
  const ringColorOverrides: Record<string, string> = {}

  Object.entries(colors).forEach(([colorName, colorValue]) => {
    if (!allowedThemeColors.includes(colorName)) return
    if (typeof colorValue !== 'object') return

    Object.entries(colorValue).forEach(([shade, color]) => {
      if (shade === '100' && colorValue['400'] && typeof colorValue['400'] === 'string') {
        const className = `.${e(`ring-${colorName}-${shade}`)}`
        const resolvedColor = (colorValue['400'] as string).replace(/<alpha-value>/g, 'var(--tw-ring-opacity)')
        ringColorOverrides[className] = resolvedColor
      }
    })
  })

  const defaultHighContrastColor = ringColorOverrides['.ring-primary-100'] || null
  const ringOffsetWidths = theme('ringOffsetWidth') as Record<string, string>
  const ringOffsetSelectors = Object.keys(ringOffsetWidths).map(key => `.${e(`ring-offset-${key}`)}`)

  const buildContrastRules = (rootSelector: string): Record<string, any> => {
    const rules: Record<string, any> = {}

    // Default focus-visible ring color
    if (defaultHighContrastColor) {
      rules[`${rootSelector} :focus-visible`] = {
        '--tw-ring-color': defaultHighContrastColor,
      }
    }

    // Specific ring color overrides
    Object.entries(ringColorOverrides).forEach(([className, color]) => {
      rules[`${rootSelector} ${className}`] = {
        '--tw-ring-color': color,
      }
    })

    // Reset all ring offsets (width and color)
    if (ringOffsetSelectors.length > 0) {
      const selector = ringOffsetSelectors.map(cls => `${rootSelector} ${cls}`).join(',\n')
      rules[selector] = {
        '--tw-ring-offset-width': '0px !important',
        '--tw-ring-offset-color': 'transparent !important',
      }
    }

    return rules
  }

  // Merge high-contrast rules
  Object.assign(baseStyles, buildContrastRules(':root.is-moreContrast'))

  // Merge media query rules
  const mediaQueryRules = buildContrastRules(':root:not(.is-normalContrast)')
  baseStyles['@media screen and (prefers-contrast: more) and (forced-colors: none)'] = mediaQueryRules

  addBase(baseStyles)
})
