<template>
  <div class="indicator-item-flat" @click="expanded = !expanded">
    <!-- Collapsed flat row: Label + Value + Status icon -->
    <div class="indicator-row-flat">
      <span class="indicator-label">{{ label }}</span>
      <span class="indicator-value">{{ formattedValue }}{{ unit ? ` ${unit}` : '' }}</span>
      <span class="indicator-status-icon" :class="statusClass">
        <i :class="statusIcon"></i>
      </span>
    </div>

    <!-- Expanded content (tap to reveal) -->
    <div v-if="expanded" class="indicator-expand-flat slide-down">
      <!-- Description -->
      <div v-if="description" class="indicator-description">
        {{ description }}
      </div>

      <!-- Sparkline -->
      <div
        v-if="hasSparklineData"
        class="sparkline-container"
        ref="sparklineContainer"
      >
        <svg
          class="sparkline-svg"
          :viewBox="`0 0 ${svgWidth} ${svgHeight}`"
          preserveAspectRatio="none"
          @mousemove="handleMouseMove"
          @mouseleave="handleMouseLeave"
        >
          <polyline
            :points="sparklinePoints"
            fill="none"
            :stroke="strokeColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            class="sparkline-line"
          />
          <circle
            v-if="hoveredIndex !== null"
            :cx="hoveredPoint.x"
            :cy="hoveredPoint.y"
            r="4"
            :fill="strokeColor"
            class="sparkline-point"
          />
        </svg>
        <div
          v-if="hoveredIndex !== null"
          class="sparkline-tooltip"
          :style="tooltipStyle"
        >
          <div class="tooltip-label">{{ tooltipLabel }}</div>
          <div class="tooltip-value">{{ tooltipValue }}</div>
        </div>
      </div>

      <!-- YoY Trend -->
      <div
        v-if="hasSparklineData && trendInfo.text !== '-'"
        class="yoy-trend"
        :class="trendInfo.class"
      >
        <i :class="trendInfo.icon"></i>
        <span class="trend-value">{{ trendInfo.text }}</span>
        <span class="trend-label">vs 12 luni</span>
      </div>

      <!-- Threshold info -->
      <div v-if="thresholdText" class="indicator-threshold">
        {{ thresholdText }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// Expand/collapse state (tap to expand)
const expanded = ref(false)

const props = defineProps({
  label: {
    type: String,
    required: true
  },
  value: {
    type: Number,
    default: null
  },
  unit: {
    type: String,
    default: ''
  },
  status: {
    type: String,
    default: 'neutral',
    validator: (val) => ['good', 'warning', 'danger', 'safe', 'grey', 'distress', 'neutral'].includes(val)
  },
  sparklineData: {
    type: Array,
    default: () => []
  },
  sparklineLabels: {
    type: Array,
    default: () => []
  },
  thresholds: {
    type: Object,
    default: () => ({})
  },
  decimals: {
    type: Number,
    default: 2
  },
  description: {
    type: String,
    default: ''
  }
})

// SVG dimensions
const svgWidth = 200
const svgHeight = 40
const padding = { top: 4, right: 4, bottom: 4, left: 4 }

// Refs
const sparklineContainer = ref(null)
const hoveredIndex = ref(null)
const mouseX = ref(0)

// Computed: Format the displayed value (locale-aware with thousands separators)
const formattedValue = computed(() => {
  if (props.value === null || props.value === undefined) return '-'
  return Number(props.value).toLocaleString('ro-RO', {
    minimumFractionDigits: 0,
    maximumFractionDigits: props.decimals
  })
})

// Computed: Check if we have sparkline data
const hasSparklineData = computed(() => {
  return props.sparklineData && props.sparklineData.length > 0
})

// Computed: Normalize status values (Z-Score uses safe/grey/distress)
const normalizedStatus = computed(() => {
  const statusMap = {
    'safe': 'good',
    'grey': 'warning',
    'distress': 'danger'
  }
  return statusMap[props.status] || props.status
})

// Computed: Status CSS class
const statusClass = computed(() => {
  return `status-${normalizedStatus.value}`
})

// Computed: Status icon
const statusIcon = computed(() => {
  const iconMap = {
    'good': 'pi pi-check-circle',
    'warning': 'pi pi-exclamation-circle',
    'danger': 'pi pi-times-circle',
    'neutral': 'pi pi-minus-circle'
  }
  return iconMap[normalizedStatus.value] || iconMap['neutral']
})

// Computed: Stroke color for sparkline - uses primary color that adapts to theme
const strokeColor = computed(() => {
  // Use primary-color which automatically adapts to theme (light/dark mode)
  return 'var(--primary-color)'
})

// Computed: Calculate sparkline points from data
const sparklinePoints = computed(() => {
  if (!hasSparklineData.value) return ''

  const data = props.sparklineData.filter(v => v !== null && v !== undefined)
  if (data.length < 2) return ''

  const min = Math.min(...data)
  const max = Math.max(...data)
  const range = max - min || 1 // Avoid division by zero

  const chartWidth = svgWidth - padding.left - padding.right
  const chartHeight = svgHeight - padding.top - padding.bottom

  const points = data.map((value, index) => {
    const x = padding.left + (index / (data.length - 1)) * chartWidth
    const y = padding.top + chartHeight - ((value - min) / range) * chartHeight
    return `${x},${y}`
  })

  return points.join(' ')
})

// Computed: Calculate point positions for hover
const pointPositions = computed(() => {
  if (!hasSparklineData.value) return []

  const data = props.sparklineData.filter(v => v !== null && v !== undefined)
  if (data.length < 2) return []

  const min = Math.min(...data)
  const max = Math.max(...data)
  const range = max - min || 1

  const chartWidth = svgWidth - padding.left - padding.right
  const chartHeight = svgHeight - padding.top - padding.bottom

  return data.map((value, index) => ({
    x: padding.left + (index / (data.length - 1)) * chartWidth,
    y: padding.top + chartHeight - ((value - min) / range) * chartHeight,
    value: value,
    label: props.sparklineLabels?.[index] || `Luna ${index + 1}`
  }))
})

// Computed: Current hovered point
const hoveredPoint = computed(() => {
  if (hoveredIndex.value === null || !pointPositions.value[hoveredIndex.value]) {
    return { x: 0, y: 0 }
  }
  return pointPositions.value[hoveredIndex.value]
})

// Computed: Tooltip label
const tooltipLabel = computed(() => {
  if (hoveredIndex.value === null) return ''
  return pointPositions.value[hoveredIndex.value]?.label || ''
})

// Computed: Tooltip value
const tooltipValue = computed(() => {
  if (hoveredIndex.value === null) return ''
  const value = pointPositions.value[hoveredIndex.value]?.value
  if (value === null || value === undefined) return '-'
  return `${Number(value).toLocaleString('ro-RO', { minimumFractionDigits: 0, maximumFractionDigits: props.decimals })}${props.unit ? ` ${props.unit}` : ''}`
})

// Computed: Tooltip position style
const tooltipStyle = computed(() => {
  if (hoveredIndex.value === null || !sparklineContainer.value) return {}

  const containerRect = sparklineContainer.value.getBoundingClientRect()
  const point = hoveredPoint.value

  // Convert SVG coordinates to container coordinates
  const xRatio = point.x / svgWidth
  const left = xRatio * containerRect.width

  // Position tooltip above the point, centered horizontally
  return {
    left: `${left}px`,
    transform: 'translateX(-50%)'
  }
})

// Computed: Threshold display text
const thresholdText = computed(() => {
  if (!props.thresholds) return ''

  const parts = []
  if (props.thresholds.threshold_min !== null && props.thresholds.threshold_min !== undefined) {
    parts.push(`Min: ${props.thresholds.threshold_min}`)
  }
  if (props.thresholds.threshold_max !== null && props.thresholds.threshold_max !== undefined) {
    parts.push(`Max: ${props.thresholds.threshold_max}`)
  }
  return parts.join(' | ')
})

// Computed: YoY Trend information (comparing first and last sparkline values)
const trendInfo = computed(() => {
  if (!props.sparklineData || props.sparklineData.length < 2) {
    return { text: '-', icon: 'pi pi-minus', class: 'trend-neutral' }
  }

  const validData = props.sparklineData.filter(v => v !== null && v !== undefined)
  if (validData.length < 2) {
    return { text: '-', icon: 'pi pi-minus', class: 'trend-neutral' }
  }

  const first = validData[0]
  const last = validData[validData.length - 1]

  // Handle division by zero
  if (first === 0) {
    if (last > 0) return { text: '+∞', icon: 'pi pi-arrow-up', class: 'trend-up' }
    if (last < 0) return { text: '-∞', icon: 'pi pi-arrow-down', class: 'trend-down' }
    return { text: '0%', icon: 'pi pi-minus', class: 'trend-neutral' }
  }

  const change = ((last - first) / Math.abs(first)) * 100
  const sign = change > 0 ? '+' : ''
  const text = `${sign}${change.toFixed(1)}%`

  if (change > 0) {
    return { text, icon: 'pi pi-arrow-up', class: 'trend-up' }
  } else if (change < 0) {
    return { text, icon: 'pi pi-arrow-down', class: 'trend-down' }
  }
  return { text: '0%', icon: 'pi pi-minus', class: 'trend-neutral' }
})

// Methods
const handleMouseMove = (event) => {
  if (!pointPositions.value.length || !sparklineContainer.value) return

  const containerRect = sparklineContainer.value.getBoundingClientRect()
  const relativeX = event.clientX - containerRect.left
  const xRatio = relativeX / containerRect.width

  // Find the closest point
  const targetX = xRatio * svgWidth
  let closestIndex = 0
  let closestDistance = Infinity

  pointPositions.value.forEach((point, index) => {
    const distance = Math.abs(point.x - targetX)
    if (distance < closestDistance) {
      closestDistance = distance
      closestIndex = index
    }
  })

  hoveredIndex.value = closestIndex
  mouseX.value = relativeX
}

const handleMouseLeave = () => {
  hoveredIndex.value = null
}
</script>

<style scoped>
/* Indicator Item - Flat row design */
.indicator-item-flat {
  border-bottom: 1px solid var(--surface-border);
  display: flex;
  flex-direction: column;
  cursor: pointer;
  transition: background var(--transition-fast);
}

.indicator-item-flat:last-child {
  border-bottom: none;
}

.indicator-item-flat:active {
  background: var(--surface-hover);
}

/* Collapsed flat row */
.indicator-row-flat {
  display: flex;
  align-items: center;
  padding: var(--space-sm) 0;
  min-height: 48px;
  gap: var(--space-sm);
}

/* Label (left, flex-grow) */
.indicator-label {
  flex: 1;
  font-size: var(--text-base);
  font-weight: var(--font-medium);
  color: var(--text-color);
}

/* Expanded content area */
.indicator-expand-flat {
  padding: 0 0 var(--space-sm);
}

/* Description */
.indicator-description {
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
  line-height: 1.4;
  padding: var(--space-xs) var(--space-sm);
  background: var(--surface-hover);
  border-radius: var(--radius-sm);
  margin-bottom: var(--space-xs);
}

/* Slide down animation */
.slide-down {
  animation: slideDown 0.2s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* Value (inline, right of label) */
.indicator-value {
  font-size: var(--text-base);
  font-weight: var(--font-semibold);
  font-variant-numeric: tabular-nums;
  color: var(--text-color);
  white-space: nowrap;
}

/* Status Icon (rightmost) - only element that gets status color */
.indicator-status-icon {
  font-size: var(--text-lg);
  flex-shrink: 0;
}

/* Status Colors - use 600 variants in light mode, 400 variants in dark mode for better contrast */
.status-good {
  color: var(--green-600);
}

.status-warning {
  color: var(--yellow-600);
}

.status-danger {
  color: var(--red-600);
}

.status-neutral {
  color: var(--text-color-secondary);
}

/* Dark mode: use lighter variants (400) for better visibility on dark backgrounds */
[data-theme="dark"] .status-good {
  color: var(--green-400);
}

[data-theme="dark"] .status-warning {
  color: var(--yellow-400);
}

[data-theme="dark"] .status-danger {
  color: var(--red-400);
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) .status-good {
    color: var(--green-400);
  }

  :root:not([data-theme]) .status-warning {
    color: var(--yellow-400);
  }

  :root:not([data-theme]) .status-danger {
    color: var(--red-400);
  }
}

/* Sparkline Container */
.sparkline-container {
  width: 100%;
  height: 40px;
  position: relative;
  margin-top: var(--space-xs);
}

/* SVG Sparkline */
.sparkline-svg {
  width: 100%;
  height: 100%;
  display: block;
}

.sparkline-line {
  vector-effect: non-scaling-stroke;
}

.sparkline-point {
  transition: r 0.15s ease;
}

/* Tooltip */
.sparkline-tooltip {
  position: absolute;
  bottom: calc(100% + 4px);
  background: var(--surface-overlay);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  padding: var(--space-xs) var(--space-sm);
  box-shadow: var(--shadow-md);
  z-index: var(--z-tooltip);
  pointer-events: none;
  white-space: nowrap;
}

.tooltip-label {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
  margin-bottom: 2px;
}

.tooltip-value {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  color: var(--text-color);
  font-family: var(--font-mono);
}

/* YoY Trend indicator */
.yoy-trend {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-xs);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
  margin-top: var(--space-xs);
  padding: var(--space-xs) var(--space-sm);
  border-radius: var(--radius-sm);
  background: var(--surface-hover);
}

.yoy-trend i {
  font-size: var(--text-sm);
}

.yoy-trend .trend-value {
  font-family: var(--font-mono);
  font-weight: var(--font-semibold);
}

.yoy-trend .trend-label {
  color: var(--text-color-secondary);
  font-size: var(--text-2xs);
}

/* Trend colors */
.yoy-trend.trend-up {
  color: var(--green-600);
  background: var(--green-50);
}

.yoy-trend.trend-down {
  color: var(--red-600);
  background: var(--red-50);
}

.yoy-trend.trend-neutral {
  color: var(--text-color-secondary);
}

/* Dark mode for YoY trend */
[data-theme="dark"] .yoy-trend.trend-up {
  color: var(--green-400);
  background: rgba(34, 197, 94, 0.15);
}

[data-theme="dark"] .yoy-trend.trend-down {
  color: var(--red-400);
  background: rgba(239, 68, 68, 0.15);
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) .yoy-trend.trend-up {
    color: var(--green-400);
    background: rgba(34, 197, 94, 0.15);
  }

  :root:not([data-theme]) .yoy-trend.trend-down {
    color: var(--red-400);
    background: rgba(239, 68, 68, 0.15);
  }
}

/* Threshold info */
.indicator-threshold {
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
  text-align: center;
  margin-top: var(--space-xs);
}

/* Responsive */
@media (max-width: 768px) {
  .sparkline-container {
    height: 32px;
  }
}

/* Dark mode adjustments */
[data-theme="dark"] .sparkline-tooltip {
  background: var(--surface-card);
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) .sparkline-tooltip {
    background: var(--surface-card);
  }
}
</style>
