<script setup lang="ts">
import type { SessionInfo } from '@/types/transcript-debug'

defineProps<{
  sessions: SessionInfo[]
  selectedId: string | null
  loading: boolean
}>()

const emit = defineEmits<{
  select: [sessionId: string]
}>()

function formatSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

function formatDate(iso: string): string {
  const d = new Date(iso)
  const now = new Date()
  const diff = now.getTime() - d.getTime()
  if (diff < 60000) return 'just now'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`
  if (diff < 86400000) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  return d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

function truncate(text: string, max: number): string {
  if (text.length <= max) return text
  return text.slice(0, max) + '...'
}
</script>

<template>
  <div class="session-selector">
    <label class="selector-label">Session</label>
    <select
      class="session-select"
      :value="selectedId || ''"
      @change="emit('select', ($event.target as HTMLSelectElement).value)"
      :disabled="loading"
    >
      <option value="" disabled>Select a transcript session...</option>
      <option
        v-for="s in sessions"
        :key="s.id"
        :value="s.id"
      >
        {{ s.firstUserMessage ? truncate(s.firstUserMessage, 60) : s.id.slice(0, 8) + '...' }} &mdash; {{ formatDate(s.mtimeISO) }} ({{ formatSize(s.size) }})
      </option>
    </select>
    <span v-if="loading" class="loading-indicator">
      <span class="spinner-sm"></span>
    </span>
  </div>
</template>

<style scoped>
.session-selector {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex: 1;
  min-width: 0;
}

.selector-label {
  font-size: 13px;
  font-weight: 500;
  color: var(--text-secondary);
  white-space: nowrap;
}

.session-select {
  flex: 1;
  min-width: 0;
  padding: 0.4rem 0.75rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-primary);
  font-size: 12px;
  cursor: pointer;
}

.session-select:focus {
  outline: none;
  border-color: var(--accent);
}

.loading-indicator {
  display: flex;
  align-items: center;
}

.spinner-sm {
  width: 16px;
  height: 16px;
  border: 2px solid var(--border-color);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>
