<script setup>
import { onMounted, ref } from 'vue'
import MusicCard from '../components/MusicCard.vue'
import DetailModal from '../components/DetailModal.vue'

const batches = ref([])
const selected = ref(null)
const loading = ref(false)
const openDetail = ref(null)

async function load() {
  const res = await fetch('/api/suggest/batches')
  batches.value = await res.json()
  if (batches.value.length && !selected.value) pick(batches.value[0].id)
}

async function pick(id) {
  loading.value = true
  try {
    const res = await fetch(`/api/suggest/batches/${id}`)
    if (res.ok) selected.value = await res.json()
  } finally {
    loading.value = false
  }
}

function fmt(iso) {
  return new Date(iso).toLocaleString('sv-SE', { dateStyle: 'medium', timeStyle: 'short' })
}

onMounted(load)
</script>

<template>
  <section class="wrap">
    <aside>
      <h2>Förslag</h2>
      <p v-if="!batches.length" class="dim">Inga batcher ännu — generera från Upptäck-sidan.</p>
      <button
        v-for="b in batches"
        :key="b.id"
        class="batch"
        :class="{ active: selected?.id === b.id }"
        @click="pick(b.id)"
      >
        <strong>#{{ b.id }}</strong> — {{ fmt(b.createdAt) }}
        <span class="dim">{{ { tracks: 'låtar', singers: 'sångare', genres: 'genrer' }[b.type] ?? 'artister/album' }} · {{ b.count }} förslag · {{ b.trigger }}</span>
      </button>
    </aside>

    <div class="content">
      <template v-if="selected">
        <p class="dim">
          Batch #{{ selected.id }} ({{ fmt(selected.createdAt) }}) — signaler:
          {{ Object.entries(selected.signalCounts ?? {}).map(([k, v]) => `${k}: ${v}`).join(', ') }}
        </p>
        <div class="grid">
          <MusicCard
            v-for="(r, i) in selected.items"
            :key="`${selected.id}-${r.mbid ?? i}`"
            :item="r"
            @detail="openDetail = $event"
          />
        </div>
      </template>
      <p v-else-if="loading" class="dim">Laddar…</p>
    </div>
    <DetailModal v-if="openDetail" :item="openDetail" @close="openDetail = null" />
  </section>
</template>

<style scoped>
.wrap {
  display: grid;
  grid-template-columns: 16rem 1fr;
  gap: 1.5rem;
  align-items: start;
}

@media (max-width: 50rem) {
  .wrap {
    grid-template-columns: 1fr;
  }
}

h2 {
  margin: 0 0 0.8rem;
}

aside {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  position: sticky;
  top: 5rem;
}

.batch {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 0.15rem;
  text-align: left;
  background: var(--card);
  border: 1px solid rgba(255, 255, 255, 0.06);
  color: var(--text);
  padding: 0.6rem 0.8rem;
}

.batch:hover {
  background: var(--card-hover);
}

.batch.active {
  border-color: var(--accent);
}

.dim {
  color: var(--text-dim);
  font-size: 0.85rem;
}

.content .dim {
  margin: 0 0 1rem;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(10.5rem, 1fr));
  gap: 1rem;
}
</style>
