<script setup lang="ts">
import { computed } from "vue"

function formatDate(d: Date): string {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, "0")
  const day = String(d.getDate()).padStart(2, "0")
  return `${y}-${m}-${day}`
}

const props = defineProps<{
  days: string[]
  activeDate?: string
}>()

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

/** Stable density per day — computed once, reused across renders. */
const densityMap = computed(() => {
  const map = new Map<string, number>()
  for (const date of props.days) {
    map.set(date, Math.floor(Math.random() * 3) + 1)
  }
  return map
})

function density(date: string): number {
  return densityMap.value.get(date) ?? 1
}

function label(date: string): string {
  const d = new Date(`${date}T12:00:00`)
  const today = formatDate(new Date())
  const yesterday = formatDate(new Date(Date.now() - 86400000))
  if (date === today) return "Today"
  if (date === yesterday) return "Yesterday"
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric" })
}
</script>

<template>
  <div class="flex flex-col gap-0.5 py-4">
    <button
      v-for="date in days"
      :key="date"
      class="flex items-center gap-2 px-3 py-1.5 text-left rounded-md transition-colors hover:bg-elevated"
      :class="date === activeDate ? 'bg-elevated' : ''"
      @click="emit('select', date)"
    >
      <span class="flex gap-0.5">
        <span
          v-for="i in density(date)"
          :key="i"
          class="size-1 rounded-full transition-colors"
          :class="date === activeDate ? 'bg-(--ui-primary)' : 'bg-(--ui-text-muted)/40'"
        />
      </span>
      <span
        class="text-xs font-medium transition-colors"
        :class="date === activeDate ? 'text-(--ui-primary)' : 'text-(--ui-text-muted)'"
      >
        {{ label(date) }}
      </span>
    </button>
  </div>
</template>
