import React from 'react'
import type { ItemStack } from '../../types'
import { MessageFormattedString } from '../Text/MessageFormattedString'
import styles from './Tooltip.module.css'

function getRarityColor(item: ItemStack): string {
  if (item.enchantments && item.enchantments.length > 0) return '#8080ff'
  return '#ffffff'
}

function formatEnchantment(e: { name: string; level: number }): string {
  const roman = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']
  return e.level <= 10 ? `${e.name} ${roman[e.level]}` : `${e.name} ${e.level}`
}

export function getItemTooltipDisplayName(item: ItemStack): string {
  return item.displayName ?? (item.name ? item.name.replace(/_/g, ' ') : `Item #${item.type}`)
}

/** Item name, enchantments, lore, durability, and type id — shared by desktop tooltip and mobile menu. */
export function ItemTooltipBody({ item }: { item: ItemStack }) {
  const nameColor = getRarityColor(item)
  const hasDurability =
    item.durability !== undefined &&
    item.maxDurability !== undefined &&
    item.durability < item.maxDurability

  return (
    <>
      <div className={styles.name} style={{ color: nameColor }}>
        <MessageFormattedString
          text={getItemTooltipDisplayName(item)}
          fallbackColor={nameColor}
        />
      </div>

      {item.enchantments && item.enchantments.length > 0 && (
        <div className={styles.section}>
          {item.enchantments.map((e, i) => (
            <div key={i} className={styles.enchantment}>
              {formatEnchantment(e)}
            </div>
          ))}
        </div>
      )}

      {item.lore && item.lore.length > 0 && (
        <div className={styles.lore}>
          {item.lore.map((line, i) => (
            <div key={i}>
              <MessageFormattedString text={line} />
            </div>
          ))}
        </div>
      )}

      {hasDurability && (
        <div className={styles.durability}>
          Durability: {item.durability} / {item.maxDurability}
        </div>
      )}

      <div className={styles.typeId}>
        {item.name ?? `#${item.type}`}
        {item.metadata !== undefined && item.metadata > 0 ? `:${item.metadata}` : ''}
      </div>
    </>
  )
}
