<script setup lang="ts">
import { ref, computed } from 'vue'
import { Panel } from 'soleprint-ui'
import type { DataSource } from 'soleprint-ui'
import type { Detection } from '../types/sse-contract'

const props = defineProps<{
  source: DataSource
  status?: 'idle' | 'live' | 'processing' | 'error'
  embedded?: boolean
}>()

interface TimelineEntry {
  brand: string
  timestamp: number
  duration: number
  confidence: number
  source: string
}

const entries = ref<TimelineEntry[]>([])

props.source.on<Detection>('detection', (e) => {
  entries.value.push({
    brand: e.brand,
    timestamp: e.timestamp,
    duration: e.duration || 0.5,
    confidence: e.confidence,
    source: e.source,
  })
})

// One row per unique brand, sorted by first appearance
const brands = computed(() => {
  const seen = new Map<string, number>()
  for (const e of entries.value) {
    if (!seen.has(e.brand)) seen.set(e.brand, e.timestamp)
  }
  return [...seen.entries()]
    .sort((a, b) => a[1] - b[1])
    .map(([brand]) => brand)
})

const maxTime = computed(() => {
  if (entries.value.length === 0) return 60
  return Math.max(...entries.value.map((e) => e.timestamp + e.duration)) * 1.1
})

// Ruler ticks — nice intervals based on duration
const rulerTicks = computed(() => {
  const max = maxTime.value
  const intervals = [1, 2, 5, 10, 15, 30, 60, 120, 300]
  const targetTicks = 8
  const rawStep = max / targetTicks
  const step = intervals.find((i) => i >= rawStep) || Math.ceil(rawStep / 60) * 60
  const ticks: number[] = []
  for (let t = 0; t <= max; t += step) {
    ticks.push(t)
  }
  return ticks
})

const sourceColor: Record<string, string> = {
  ocr: '#3ecf8e',
  local_vlm: '#f5a623',
  cloud_llm: '#e05252',
  logo_match: '#4f9cf9',
}

function barStyle(entry: TimelineEntry) {
  const left = (entry.timestamp / maxTime.value) * 100
  const width = Math.max((entry.duration / maxTime.value) * 100, 1)
  const color = sourceColor[entry.source] || '#a78bfa'
  const opacity = 0.4 + entry.confidence * 0.6
  return {
    left: `${left}%`,
    width: `${width}%`,
    background: color,
    opacity,
  }
}
</script>

<template>
  <Panel v-if="!embedded" title="Detection Timeline" :status="status">
    <div class="timeline" v-if="brands.length > 0">
      <div class="ruler">
        <span class="ruler-label" />
        <div class="ruler-track">
          <span
            v-for="t in rulerTicks" :key="t"
            class="ruler-tick"
            :style="{ left: (t / maxTime) * 100 + '%' }"
          >{{ t }}s</span>
        </div>
      </div>
      <div class="rows">
        <div class="row" v-for="brand in brands" :key="brand">
          <span class="brand-label">{{ brand }}</span>
          <div class="track">
            <div
              v-for="(entry, i) in entries.filter((e) => e.brand === brand)"
              :key="i"
              class="bar"
              :style="barStyle(entry)"
              :title="`${entry.brand} — ${entry.source} (${(entry.confidence * 100).toFixed(0)}%) @ ${entry.timestamp.toFixed(1)}s`"
            />
          </div>
        </div>
      </div>
      <div class="legend">
        <span v-for="(color, source) in sourceColor" :key="source" class="legend-item">
          <span class="legend-dot" :style="{ background: color }" />
          {{ source }}
        </span>
      </div>
    </div>
    <div v-else class="empty">Waiting for detections...</div>
  </Panel>
  <div v-else class="timeline" v-show="brands.length > 0">
    <div class="ruler">
      <span class="ruler-label" />
      <div class="ruler-track">
        <span
          v-for="t in rulerTicks" :key="t"
          class="ruler-tick"
          :style="{ left: (t / maxTime) * 100 + '%' }"
        >{{ t }}s</span>
      </div>
    </div>
    <div class="rows">
      <div class="row" v-for="brand in brands" :key="brand">
        <span class="brand-label">{{ brand }}</span>
        <div class="track">
          <div
            v-for="(entry, i) in entries.filter((e) => e.brand === brand)"
            :key="i"
            class="bar"
            :style="barStyle(entry)"
            :title="`${entry.brand} — ${entry.source} (${(entry.confidence * 100).toFixed(0)}%) @ ${entry.timestamp.toFixed(1)}s`"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.timeline {
  padding: var(--space-2);
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: auto;
}

.ruler {
  display: flex;
  align-items: flex-end;
  gap: var(--space-2);
  flex-shrink: 0;
  height: 20px;
  margin-bottom: var(--space-1);
}

.ruler-label {
  width: 100px;
  flex-shrink: 0;
}

.ruler-track {
  flex: 1;
  position: relative;
  height: 100%;
  border-bottom: 1px solid var(--surface-3);
}

.ruler-tick {
  position: absolute;
  bottom: 0;
  transform: translateX(-50%);
  font-size: 9px;
  color: var(--text-dim);
  padding-bottom: 2px;
}

.ruler-tick::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  width: 1px;
  height: 6px;
  background: var(--surface-3);
}

.rows {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}

.row {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  height: 24px;
}

.brand-label {
  width: 100px;
  flex-shrink: 0;
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  text-align: right;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.track {
  flex: 1;
  position: relative;
  height: 16px;
  background: var(--surface-2);
  border-radius: 3px;
}

.bar {
  position: absolute;
  top: 2px;
  height: 12px;
  border-radius: 2px;
  min-width: 4px;
}

.legend {
  display: flex;
  gap: var(--space-3);
  padding-left: 108px;
  margin-top: var(--space-2);
  font-size: var(--font-size-sm);
  color: var(--text-dim);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.legend-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
}

.empty {
  color: var(--text-dim);
  padding: var(--space-6);
  text-align: center;
}
</style>
