<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useWorkItemsStore } from '@/stores/workitems'
import { calculateSCurve, type CurvePoint, type SCurveData } from '@/services/s-curve'
import { getBlockers } from '@/services/blocker-log'

const props = defineProps<{ projectId: number; compact?: boolean }>()

const workItems = useWorkItemsStore()
const loading = ref(true)
const sCurve = ref<SCurveData | null>(null)

async function load() {
  loading.value = true
  try {
    const blockers = await getBlockers(props.projectId)
    sCurve.value = calculateSCurve(workItems.userStories, blockers)
  } catch (e) {
    console.error('[Alpha] S-Curve error:', e)
  } finally {
    loading.value = false
  }
}

onMounted(load)
watch(() => workItems.userStories.length, load)

const CHART_W = 400
const CHART_H = 150
const PAD = { top: 10, right: 10, bottom: 20, left: 35 }

function buildAreaPath(points: CurvePoint[], maxSp: number, totalDays: number): string {
  if (points.length === 0) return ''
  const w = CHART_W - PAD.left - PAD.right
  const h = CHART_H - PAD.top - PAD.bottom
  const firstDate = points[0].date
  const line = points.map((p, i) => {
    const dx = dayOffset(p.date, firstDate)
    const x = PAD.left + (dx / totalDays) * w
    const y = PAD.top + h - (p.cumulative / maxSp) * h
    return `${i === 0 ? 'M' : 'L'}${x},${y}`
  }).join(' ')
  // Close the area for fill
  const last = points[points.length - 1]
  const lastDx = dayOffset(last.date, firstDate)
  const lastX = PAD.left + (lastDx / totalDays) * w
  const bottomY = PAD.top + h
  return `${line} L${lastX},${bottomY} L${PAD.left},${bottomY} Z`
}

function dayOffset(date: string, from: string): number {
  return Math.max(0, Math.ceil((new Date(date).getTime() - new Date(from).getTime()) / (1000 * 60 * 60 * 24)))
}

const planned = computed(() => sCurve.value?.planned || [])
const actual = computed(() => sCurve.value?.actual || [])
const metrics = computed(() => sCurve.value?.metrics)

const maxSp = computed(() => {
  const all = [...planned.value, ...actual.value]
  return Math.max(...all.map(p => p.cumulative), 1)
})

const totalDays = computed(() => {
  const all = [...planned.value, ...actual.value]
  if (all.length < 2) return 30
  const first = new Date(all[0].date)
  const last = new Date(all[all.length - 1].date)
  return Math.max(1, Math.ceil((last.getTime() - first.getTime()) / (1000 * 60 * 60 * 24)))
})
</script>

<template>
  <div v-if="loading" class="text-[10px] text-muted-foreground text-center py-4">Cargando...</div>
  <div v-else-if="planned.length === 0" class="text-[10px] text-muted-foreground text-center py-4">Sin datos</div>
  <div v-else class="space-y-2">
    <!-- Mini metrics row for compact -->
    <div v-if="metrics && compact" class="flex items-center gap-2 text-[10px] text-muted-foreground px-1">
      <span class="font-mono font-bold text-foreground">{{ metrics.totalSpPlanned }} SP</span>
      <span class="text-muted-foreground/50">|</span>
      <span :class="metrics.spi >= 1 ? 'text-green-500' : 'text-red-500'">SPI {{ metrics.spi }}</span>
    </div>

    <!-- SVG Chart -->
    <svg :viewBox="`0 0 ${CHART_W} ${CHART_H}`" class="w-full h-auto">
      <defs>
        <linearGradient id="planGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stop-color="#3b82f6" stop-opacity="0.3" />
          <stop offset="100%" stop-color="#3b82f6" stop-opacity="0.02" />
        </linearGradient>
        <linearGradient id="actualGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stop-color="#22c55e" stop-opacity="0.25" />
          <stop offset="100%" stop-color="#22c55e" stop-opacity="0.02" />
        </linearGradient>
      </defs>

      <!-- Grid -->
      <line v-for="i in 3" :key="i"
        :x1="PAD.left" :y1="PAD.top + ((i-1)/2) * (CHART_H - PAD.top - PAD.bottom)"
        :x2="CHART_W - PAD.right" :y2="PAD.top + ((i-1)/2) * (CHART_H - PAD.top - PAD.bottom)"
        stroke="currentColor" stroke-opacity="0.08" stroke-dasharray="3,3"
      />

      <!-- Area fills -->
      <path :d="buildAreaPath(planned, maxSp, totalDays)" fill="url(#planGrad)" />
      <path :d="buildAreaPath(actual, maxSp, totalDays)" fill="url(#actualGrad)" />

      <!-- Lines -->
      <path :d="buildAreaPath(planned, maxSp, totalDays).replace(/Z$/, '')" fill="none" stroke="#3b82f6" stroke-width="1.5" />
      <path :d="buildAreaPath(actual, maxSp, totalDays).replace(/Z$/, '')" fill="none" stroke="#22c55e" stroke-width="1.5" />

      <!-- Y labels -->
      <text v-for="i in 3" :key="'y'+i"
        :x="PAD.left - 4"
        :y="PAD.top + ((i-1)/2) * (CHART_H - PAD.top - PAD.bottom) + 3"
        text-anchor="end" class="fill-muted-foreground text-[8px]"
      >{{ Math.round(maxSp * (i-1) / 2) }}</text>

      <!-- X labels -->
      <text :x="PAD.left" :y="CHART_H - 4" text-anchor="middle" class="fill-muted-foreground text-[8px]">{{ planned[0]?.date?.slice(5) || '' }}</text>
      <text :x="CHART_W - PAD.right" :y="CHART_H - 4" text-anchor="middle" class="fill-muted-foreground text-[8px]">{{ planned[planned.length - 1]?.date?.slice(5) || '' }}</text>

      <!-- Mini legend -->
      <circle cx="20" cy="8" r="3" fill="#3b82f6" />
      <text x="27" y="12" class="fill-muted-foreground text-[8px]">Plan</text>
      <circle cx="65" cy="8" r="3" fill="#22c55e" />
      <text x="72" y="12" class="fill-muted-foreground text-[8px]">Real</text>
    </svg>
  </div>
</template>
