<script setup lang="ts">
import { CDRAGON_BASE, mapPath } from '~/utils/cdragon'
import {
  parseItemDescription,
  type TextSegment,
  type ItemEffect,
  type ParsedDescription
} from 'dragon-item-parser'

import type { Item } from '~/types/cdragon'
import type { ItemTag } from 'match_collector'

interface Props {
  item: Item | null
  show: boolean
  x: number
  y: number
  tags?: ItemTag[]
}

const props = withDefaults(defineProps<Props>(), {
  tags: () => []
})

// Tag display helpers
function getTagLabel(tag: ItemTag): string {
  const labels: Record<ItemTag, string> = {
    ahead: 'Ahead',
    behind: 'Behind',
    region_euw: 'EUW',
    region_eun: 'EUN',
    region_na: 'NA',
    region_kr: 'KR'
  }
  return labels[tag] || tag
}

function getTagTooltip(tag: ItemTag): string {
  const tooltips: Record<ItemTag, string> = {
    ahead: 'This item is typically bought when ahead in gold',
    behind: 'This item is typically bought when behind in gold',
    region_euw: 'Popular in EU West region',
    region_eun: 'Popular in EU Nordic & East region',
    region_na: 'Popular in North America region',
    region_kr: 'Popular in Korea region'
  }
  return tooltips[tag] || tag
}

function getTagClass(tag: ItemTag): string {
  return `tag-${tag}`
}

// Parse the item description once
const parsedDescription = computed<ParsedDescription | null>(() => {
  if (!props.item?.description) return null
  return parseItemDescription(props.item.description)
})

// Format stats for display
const formattedStats = computed(() => {
  const stats = parsedDescription.value?.stats
  if (!stats) return []

  const statLabels: Record<string, string> = {
    attackDamage: 'Attack Damage',
    abilityPower: 'Ability Power',
    attackSpeed: 'Attack Speed',
    criticalStrikeChance: 'Critical Strike Chance',
    criticalStrikeDamage: 'Critical Strike Damage',
    lifeSteal: 'Life Steal',
    omnivamp: 'Omnivamp',
    physicalVamp: 'Physical Vamp',
    spellVamp: 'Spell Vamp',
    health: 'Health',
    armor: 'Armor',
    magicResist: 'Magic Resist',
    mana: 'Mana',
    baseManaRegen: 'Base Mana Regen',
    baseHealthRegen: 'Base Health Regen',
    moveSpeed: 'Move Speed',
    abilityHaste: 'Ability Haste',
    armorPenetration: 'Armor Penetration',
    magicPenetration: 'Magic Penetration',
    lethality: 'Lethality',
    healAndShieldPower: 'Heal and Shield Power',
    tenacity: 'Tenacity',
    slowResist: 'Slow Resist'
  }

  const percentageStats = [
    'attackSpeed',
    'criticalStrikeChance',
    'criticalStrikeDamage',
    'lifeSteal',
    'omnivamp',
    'physicalVamp',
    'spellVamp',
    'baseManaRegen',
    'baseHealthRegen',
    'armorPenetration',
    'magicPenetration',
    'healAndShieldPower',
    'tenacity',
    'slowResist'
  ]

  return Object.entries(stats)
    .filter(([_, value]) => value !== undefined)
    .map(([key, value]) => ({
      key,
      label: statLabels[key] || key,
      value: percentageStats.includes(key) ? `${value}%` : value
    }))
})

// Get CSS class for text segment type
function getSegmentClass(segment: TextSegment): string {
  const classMap: Record<TextSegment['type'], string> = {
    text: '',
    highlight: 'stat-highlight',
    passive: 'tag-passive',
    active: 'tag-active',
    keyword: 'tag-keyword',
    keywordMajor: 'tag-keyword-major',
    keywordStealth: 'tag-keyword-stealth',
    status: 'tag-status',
    speed: 'tag-speed',
    scaleMana: 'tag-scaling',
    scaleHealth: 'tag-scaling',
    scaleAP: 'tag-scaling',
    scaleAD: 'tag-scaling',
    scaleArmor: 'tag-scaling',
    scaleMR: 'tag-scaling',
    scaleLevel: 'tag-scaling',
    scaleBonusHealth: 'tag-scaling',
    scaleBonusMana: 'tag-scaling',
    scaleMaxHealth: 'tag-scaling',
    spellName: 'tag-spellname',
    unique: 'tag-unique',
    rarityMythic: 'tag-rarity-mythic',
    rarityLegendary: 'tag-rarity-legendary',
    rarityGeneric: 'tag-rarity-generic',
    magicDamage: 'tag-magic-damage',
    physicalDamage: 'tag-physical-damage',
    trueDamage: 'tag-true-damage',
    healing: 'tag-healing',
    shield: 'tag-shield',
    attention: 'stat-highlight',
    onHit: 'tag-onhit',
    color: ''
  }
  return classMap[segment.type] || ''
}

// Get effect type label
function getEffectTypeLabel(type: ItemEffect['type']): string {
  const labels: Record<ItemEffect['type'], string> = {
    passive: 'Passive',
    active: 'Active',
    unique: 'Unique',
    mythic: 'Mythic',
    legendary: 'Legendary',
    epic: 'Epic'
  }
  return labels[type] || ''
}

// Get effect type class
function getEffectTypeClass(type: ItemEffect['type']): string {
  const classMap: Record<ItemEffect['type'], string> = {
    passive: 'effect-passive',
    active: 'effect-active',
    unique: 'effect-unique',
    mythic: 'effect-mythic',
    legendary: 'effect-legendary',
    epic: 'effect-epic'
  }
  return classMap[type] || ''
}

// Render text segments to HTML
function renderSegments(segments: TextSegment[]): string {
  return segments
    .map(segment => {
      const cssClass = getSegmentClass(segment)

      if (segment.type === 'color' && segment.color) {
        return `<span style="color: ${segment.color}">${segment.content}</span>`
      }

      if (cssClass) {
        return `<span class="${cssClass}">${segment.content}</span>`
      }

      return segment.content
    })
    .join('')
}

// Render effect description
function renderEffect(effect: ItemEffect): string {
  return renderSegments(effect.description)
}

// Render rules
function renderRules(segments: TextSegment[] | undefined): string {
  if (!segments) return ''
  return renderSegments(segments)
}

// Render flavor text
function renderFlavorText(segments: TextSegment[] | undefined): string {
  if (!segments) return ''
  return renderSegments(segments)
}

// Check if we should show the effects section
const hasEffects = computed(() => {
  return parsedDescription.value?.effects?.length
})

// Check if we should show rules
const hasRules = computed(() => {
  return parsedDescription.value?.rules?.length
})

// Check if we should show flavor text
const hasFlavorText = computed(() => {
  return parsedDescription.value?.flavorText?.length
})
</script>

<template>
  <Teleport to="body">
    <Transition name="fade">
      <div
        v-if="show && item"
        class="item-tooltip"
        :style="{
          left: x + 'px',
          top: y + 'px'
        }"
        @mouseenter.stop
      >
        <!-- Header -->
        <div class="tooltip-header">
          <NuxtImg class="tooltip-icon" :src="CDRAGON_BASE + mapPath(item.iconPath)" />
          <div class="tooltip-title">
            <h3>{{ item.name || 'Unknown Item' }}</h3>
            <span v-if="item.priceTotal" class="tooltip-gold">{{ item.priceTotal }} Gold</span>
          </div>
        </div>

        <!-- Plaintext (brief description) -->
        <div v-if="item.plaintext" class="tooltip-plaintext">
          {{ item.plaintext }}
        </div>

        <!-- Item Tags -->
        <div v-if="tags && tags.length > 0" class="tooltip-tags-section">
          <div class="tooltip-tags">
            <span
              v-for="tag in tags"
              :key="tag"
              :class="['item-tag', getTagClass(tag)]"
              :title="getTagTooltip(tag)"
            >
              {{ getTagLabel(tag) }}
            </span>
          </div>
        </div>

        <!-- Stats Section -->
        <div v-if="formattedStats.length > 0" class="tooltip-stats">
          <div v-for="stat in formattedStats" :key="stat.key" class="stat-row">
            <span class="stat-value">{{ stat.value }}</span>
            <span class="stat-label">{{ stat.label }}</span>
          </div>
        </div>

        <!-- Effects Section -->
        <div v-if="hasEffects" class="tooltip-effects">
          <div
            v-for="(effect, index) in parsedDescription?.effects"
            :key="index"
            :class="['effect-item', getEffectTypeClass(effect.type)]"
          >
            <div class="effect-header">
              <span class="effect-type">{{ getEffectTypeLabel(effect.type) }}</span>
              <span v-if="effect.name" class="effect-name">{{ effect.name }}</span>
            </div>
            <!-- eslint-disable vue/no-v-html -->
            <div class="effect-description" v-html="renderEffect(effect)"></div>
            <!-- eslint-enable vue/no-v-html -->
          </div>
        </div>

        <!-- Rules Section -->
        <div v-if="hasRules" class="tooltip-rules">
          <!-- eslint-disable vue/no-v-html -->
          <div v-html="renderRules(parsedDescription?.rules)"></div>
          <!-- eslint-enable vue/no-v-html -->
        </div>

        <!-- Flavor Text -->
        <div v-if="hasFlavorText" class="tooltip-flavor">
          <!-- eslint-disable vue/no-v-html -->
          <div v-html="renderFlavorText(parsedDescription?.flavorText)"></div>
          <!-- eslint-enable vue/no-v-html -->
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<style scoped>
.item-tooltip {
  position: fixed;
  z-index: 1000;
  background: var(--tooltip-bg);
  border: 1px solid var(--tooltip-border);
  border-radius: 8px;
  padding: 12px;
  max-width: 320px;
  min-width: 250px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
  pointer-events: none;
  font-family: 'Inter', sans-serif;
}

/* Header */
.tooltip-header {
  display: flex;
  gap: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--tooltip-header-border);
  margin-bottom: 10px;
}

.tooltip-icon {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  border: 2px solid var(--tooltip-border);
  flex-shrink: 0;
  background: rgba(0, 0, 0, 0.3);
}

.tooltip-title {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 4px;
}

.tooltip-title h3 {
  margin: 0;
  font-size: 1rem;
  font-weight: 600;
  color: var(--tooltip-text);
  line-height: 1.2;
}

.tooltip-gold {
  font-size: 0.85rem;
  color: var(--color-gold);
  font-weight: 500;
}

/* Plaintext */
.tooltip-plaintext {
  font-size: 0.8rem;
  color: var(--tooltip-text-dim);
  margin-bottom: 8px;
  font-style: italic;
  line-height: 1.4;
}

/* Item Tags Section */
.tooltip-tags-section {
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--tooltip-header-border);
}

.tooltip-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tooltip-tags .item-tag {
  font-size: 0.65rem;
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  white-space: nowrap;
}

.tooltip-tags .tag-ahead {
  background-color: #22c55e;
  color: white;
}

.tooltip-tags .tag-behind {
  background-color: #ef4444;
  color: white;
}

.tooltip-tags .tag-region_euw {
  background-color: #3b82f6;
  color: white;
}

.tooltip-tags .tag-region_eun {
  background-color: #8b5cf6;
  color: white;
}

.tooltip-tags .tag-region_na {
  background-color: #f59e0b;
  color: white;
}

.tooltip-tags .tag-region_kr {
  background-color: #ec4899;
  color: white;
}

/* Stats Section */
.tooltip-stats {
  margin-bottom: 10px;
}

.stat-row {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 3px;
}

.stat-value {
  color: var(--tooltip-stat-value);
  font-weight: 600;
  font-size: 0.85rem;
  min-width: 45px;
  text-align: right;
}

.stat-label {
  color: var(--tooltip-stat-label);
  font-size: 0.85rem;
}

/* Effects Section */
.tooltip-effects {
  padding-top: 8px;
  border-top: 1px solid var(--tooltip-header-border);
}

.effect-item {
  margin-bottom: 8px;
  padding-left: 10px;
  border-left: 3px solid var(--tooltip-border);
}

.effect-item:last-child {
  margin-bottom: 0;
}

.effect-item.effect-passive {
  border-left-color: var(--tooltip-effect-passive);
}

.effect-item.effect-active {
  border-left-color: var(--tooltip-effect-active);
}

.effect-item.effect-unique {
  border-left-color: var(--tooltip-effect-unique);
}

.effect-item.effect-mythic {
  border-left-color: var(--tooltip-effect-mythic);
}

.effect-item.effect-legendary {
  border-left-color: var(--tooltip-effect-legendary);
}

.effect-item.effect-epic {
  border-left-color: var(--tooltip-effect-epic);
}

.effect-header {
  display: flex;
  align-items: baseline;
  gap: 6px;
  margin-bottom: 3px;
}

.effect-type {
  font-size: 0.65rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  padding: 1px 5px;
  border-radius: 2px;
  background: rgba(255, 255, 255, 0.1);
}

.effect-passive .effect-type {
  color: var(--tooltip-effect-passive);
}

.effect-active .effect-type {
  color: var(--tooltip-effect-active);
}

.effect-unique .effect-type {
  color: var(--tooltip-effect-unique);
}

.effect-mythic .effect-type {
  color: var(--tooltip-effect-mythic);
}

.effect-legendary .effect-type {
  color: var(--tooltip-effect-legendary);
}

.effect-epic .effect-type {
  color: var(--tooltip-effect-epic);
}

.effect-name {
  font-weight: 600;
  color: var(--tooltip-text);
  font-size: 0.85rem;
}

.effect-description {
  font-size: 0.8rem;
  color: var(--tooltip-text-dim);
  line-height: 1.5;
}

/* Rules Section */
.tooltip-rules {
  margin-top: 8px;
  padding: 6px 8px;
  background: rgba(0, 0, 0, 0.2);
  border-left: 2px solid var(--tooltip-border);
  font-size: 0.75rem;
  font-style: italic;
  color: var(--tooltip-text-dim);
}

/* Flavor Text */
.tooltip-flavor {
  margin-top: 8px;
  padding: 6px 8px;
  background: rgba(74, 222, 255, 0.05);
  border-left: 2px solid var(--tooltip-flavor);
  font-size: 0.75rem;
  font-style: italic;
  color: var(--tooltip-flavor);
}

/* Text segment styles inside effects */
.effect-description :deep(.stat-highlight) {
  color: var(--tooltip-highlight);
  font-weight: 600;
}

.effect-description :deep(.tag-passive) {
  color: var(--tooltip-effect-passive);
  font-weight: 600;
}

.effect-description :deep(.tag-active) {
  color: var(--tooltip-effect-active);
  font-weight: 600;
}

.effect-description :deep(.tag-keyword) {
  color: var(--tooltip-keyword);
  font-weight: 600;
}

.effect-description :deep(.tag-keyword-major) {
  color: var(--tooltip-keyword-major);
  font-weight: 700;
  font-style: italic;
}

.effect-description :deep(.tag-keyword-stealth) {
  color: var(--tooltip-keyword-stealth);
  font-weight: 600;
}

.effect-description :deep(.tag-status) {
  color: var(--tooltip-status);
  font-weight: 500;
  font-style: italic;
}

.effect-description :deep(.tag-speed),
.effect-description :deep(.tag-scaling) {
  color: var(--tooltip-scaling);
  font-style: italic;
  font-weight: 500;
}

.effect-description :deep(.tag-healing) {
  color: var(--tooltip-healing);
  font-weight: 500;
}

.effect-description :deep(.tag-shield) {
  color: var(--tooltip-shield);
  font-weight: 500;
}

.effect-description :deep(.tag-magic-damage) {
  color: var(--tooltip-magic-damage);
  font-weight: 500;
}

.effect-description :deep(.tag-physical-damage) {
  color: var(--tooltip-physical-damage);
  font-weight: 500;
}

.effect-description :deep(.tag-true-damage) {
  color: var(--tooltip-true-damage);
  font-weight: 600;
}

.effect-description :deep(.tag-onhit) {
  background: rgba(52, 152, 219, 0.2);
  color: var(--tooltip-onhit);
  padding: 1px 4px;
  border-radius: 3px;
  font-size: 0.75rem;
  font-weight: 500;
}

.effect-description :deep(.tag-spellname) {
  color: var(--tooltip-spellname);
  font-weight: 600;
  font-style: italic;
}

.effect-description :deep(.tag-unique) {
  color: var(--tooltip-effect-unique);
  font-weight: 700;
  font-size: 0.75rem;
  letter-spacing: 0.5px;
}

.effect-description :deep(.tag-rarity-mythic) {
  color: var(--tooltip-effect-mythic);
  font-weight: 700;
  font-size: 0.85rem;
}

.effect-description :deep(.tag-rarity-legendary) {
  color: var(--tooltip-effect-legendary);
  font-weight: 600;
  font-size: 0.85rem;
}

.effect-description :deep(.tag-rarity-generic) {
  color: var(--tooltip-effect-epic);
  font-weight: 500;
  font-size: 0.85rem;
}

/* Transition */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.15s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
